@byteplus/vepusher 2.0.4-rc.13 → 2.0.4-rc.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -63,7 +63,7 @@ registerProcessor('vumeter', class extends AudioWorkletProcessor {
63
63
  cursor: pointer;
64
64
  z-index:100;
65
65
  background-size: 45px;
66
- }`,t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.appendChild(document.createTextNode(e)),t.appendChild(n);var i=document.createElement("div");i.innerHTML='<div id="debugger-applog-web" class="debugger-applog-web"></div>';var o=document.createElement("div");o.innerHTML='<div id="debugger-container" class="debugger-container"></div>',document.getElementsByTagName("body")[0].appendChild(i),document.getElementsByTagName("body")[0].appendChild(o);var a=document.getElementById("debugger-applog-web");a&&a.addEventListener("click",function(){window&&window.postMessage({type:"devtool:web:open-draw"},location.origin)})},r}(),ho={autotrack:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/autotrack.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/autotrack.js"},object:"LogAutoTrack"},ab:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/ab.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/ab.js"},object:"LogAb"},stay:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/stay.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/stay.js"},object:"LogStay"},route:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/route.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/route.js"},object:"LogRoute"},tracer:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/tracer.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/tracer.js"},object:"LogTracer"},retry:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/retry.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/retry.js"},object:"LogRetry"},visual:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/visual.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/visual.js"},object:"LogVisual"}},__=["ab","autotrack","Stay","store","et","profile","cep","heartbeat","monitor","route","tracer"],et=function(){function r(e){this.disableAutoPageView=!1,this.bridgeReport=!1,this.staging=!1,this.pluginInstances=[],this.sended=!1,this.started=!1,this.destroy=!1,this.sdkReady=!1,this.adapters={},this.loadType="base",this.sdkStop=!1,this.name=e,this.hook=new $m,this.remotePlugin=new Map,this.Types=F,this.adapters.storage=Xt,this.loadType="full"}return r.usePlugin=function(e,t,n){if(t){for(var i=!1,o=0,a=r.plugins.length;o<a;o++)if(r.plugins[o].name===t){r.plugins[o].plugin=e,r.plugins[o].options=n||{},i=!0;break}i||r.plugins.push({name:t,plugin:e,options:n})}else r.plugins.push({plugin:e})},r.prototype.usePlugin=function(e,t,n){e&&(this.loadType==="full"&&__.includes(e)?console.info("your sdk version has "+e+" already ~"):t?typeof t=="string"?this.remotePlugin.get(e)||this.remotePlugin.set(e,{src:t,call:n}):this.remotePlugin.get(e)||this.remotePlugin.set(e,{instance:t}):this.remotePlugin.get(e)||this.remotePlugin.set(e,"sdk"))},r.prototype.init=function(e){var t,n,i=this;try{t=JSON.parse(JSON.stringify(e))}catch{t=e}if(this.logger=new ag(this.name,t.log),this.inited)this.logger.warn("[instance: "+this.name+"], every instance's api: init, can be call only one time!");else if(t&&Gr(t))if(t.app_id&&typeof(n=t.app_id)=="number"&&!isNaN(n))if(!t.app_key||function(o){return typeof o=="string"}(t.app_key)){if(t.channel_domain||(t.report_channel!=="eu_ttp_ie"&&t.channel!=="ie"||this.logger.error("ie dc will be deprecated in the future, please use other dc instead"),t.report_channel&&!Ga().has(t.report_channel)?(this.logger.warn("your report_channel: "+t.report_channel+" is not exist. report_channel must be one of "+qi().join(",")+", use default report_channel: us_east instead, please check!!!"),t.report_channel="us_east"):t.report_channel||["sg","va","in","my","ie","ie2"].indexOf(t.channel)!==-1||(this.logger.warn("your channel: "+t.channel+" is not exist. use report_channel instead and report_channel must be one of "+qi().join(",")+", use default report_channel: us_east instead, please check!!!"),t.report_channel="us_east"),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK set channel warning",level:"error",time:Date.now(),data:"your report_channel: "+t.channel+" is not exist. report_channel must be one of "+qi().join(",")+", use us_east instead, please check!!!",infoType:"sdk"})),this.spider=new cg,this.spider.checkSpider(t))return this.logger.warn("The current environment may be a spider, can not report!"),void this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK hit spider",level:"error",time:Date.now(),data:"The current environment may be a spider, can not report!",infoType:"sdk"});this.appBridge=new ug(this,t.enable_native),this.requestManager=new m_(this,t),this.bridgeReport=this.appBridge.bridgeInject(),this.configManager=new sg(this,t),this.debugger=new g_(this,t),this.initConfig=t,this.emit(F.Init),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Init",data:t,level:"info",time:Date.now(),infoType:"cus"}),t.disable_auto_pv&&(this.disableAutoPageView=!0),this.bridgeReport||(this.configManager.setAppid(t.app_id),this.eventManager=new lg,this.tokenManager=new hg,this.sessionManager=new fg,Promise.all([new Promise(function(o){i.once(F.TokenComplete,function(){o(!0)})}),new Promise(function(o){i.once(F.Start,function(){o(!0)})}),new Promise(function(o){i.once(F.LogSettingReady,function(){o(!0)})})]).then(function(){try{r.plugins.reduce(function(o,a){var s=a.plugin,u=a.options,c=Object.assign(i.initConfig,u);i.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Load "+a.name+" Plugin",level:"info",time:Date.now(),infoType:"sdk"});var d=new s;return d.apply(i,c),o.push(d),o},i.pluginInstances)}catch(o){console.warn("load plugin error, "+o.message),i.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Load Plugin Error",level:"error",time:Date.now(),data:o.message,infoType:"sdk"})}i.sdkReady=!0,i.emit(F.Ready),i.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK UserInfo Init Completed",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"}),i.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Initialization Completed",time:Date.now(),level:"info",data:i.configManager.get("user"),infoType:"sdk"}),i.logger.info("appid: "+t.app_id+", userInfo:"+JSON.stringify(i.configManager.get("user"))),i.logger.info("appid: "+t.app_id+", sdk is ready, version is "+Vr+", you can report now !!!"),t.disable_auto_pv&&(i.disableAutoPageView=!0);try{(i.loadType==="full"&&t.enable_ab_test||t.autotrack)&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")}catch(o){i.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"Something Error",level:"error",time:Date.now(),data:o.message,infoType:"sdk"})}i.pageView(),i.on(F.TokenChange,function(o){o==="webid"&&i.pageView(),i.logger.info("appid: "+t.app_id+" token change, new userInfo:"+JSON.stringify(i.configManager.get("user"))),i.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Set UserInfo",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(F.TokenReset,function(){i.logger.info("appid: "+t.app_id+" token reset, new userInfo:"+JSON.stringify(i.configManager.get("user"))),i.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Reset UserInfo",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(F.RouteChange,function(o){o.init||t.disable_route_report||i.pageView()})}),this.tokenManager.apply(this,t),this.eventManager.apply(this,t),this.sessionManager.apply(this,t)),this.inited=!0}else this.logger.warn("app_key param is error, must be string, please check!");else this.logger.warn("app_id param is error, must be number, please check!");else this.logger.warn("init params error,please check")},r.prototype.config=function(e){if(!this.inited)return console.warn("config must be use after function init"),void this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Config Error",level:"error",time:Date.now(),data:"config must be use after function init",infoType:"sdk"});if(!e||!Gr(e))return console.warn("config params is error, please check"),void this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Config Error",level:"error",time:Date.now(),data:"config params is error, please check",infoType:"sdk"});var t;try{t=JSON.parse(JSON.stringify(t))}catch{t=e}if(this.bridgeReport)this.appBridge.setConfig(t);else{t._staging_flag&&t._staging_flag===1&&(this.staging=!0),t.disable_auto_pv&&(this.disableAutoPageView=!0,delete t.disable_auto_pv);var n=me({},t);if(this.initConfig&&this.initConfig.configPersist){var i=this.configManager.getStore();i&&(n=Object.assign(i,t)),this.configManager.setStore(t)}n.web_id,n.user_unique_id,n.device_id;var o=function(a,s){var u={};for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&s.indexOf(c)<0&&(u[c]=a[c]);if(a!=null&&typeof Object.getOwnPropertySymbols=="function"){var d=0;for(c=Object.getOwnPropertySymbols(a);d<c.length;d++)s.indexOf(c[d])<0&&(u[c[d]]=a[c[d]])}return u}(n,["web_id","user_unique_id","device_id"]);n.hasOwnProperty("web_id")&&this.emit(F.ConfigWebId,n.web_id),n.hasOwnProperty("user_unique_id")&&this.emit(F.ConfigUuid,n.user_unique_id),n.hasOwnProperty("device_id")&&this.emit(F.ConfigDiD,n.device_id),this.configManager.set(o),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Config",level:"info",time:Date.now(),data:n,infoType:"cus"})}},r.prototype.setDomain=function(e){this.configManager&&this.configManager.setDomain(e),this.emit(F.ConfigDomain)},r.prototype.getConfig=function(e){return this.configManager.get(e)},r.prototype.send=function(){this.start()},r.prototype.start=function(){this.inited&&!this.sended&&(this.sended=!0,this.emit(F.Start),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Start",level:"info",time:Date.now(),infoType:"cus"}),this.bridgeReport&&(this.pageView(),this.emit(F.Ready)))},r.prototype.event=function(e,t){var n=this;try{var i=[];if(Array.isArray(e))e.forEach(function(a){var s=n.processEvent(a[0],a[1]||{});s&&i.push(s)});else{var o=this.processEvent(e,t);if(!o)return;i.push(o)}this.bridgeReport?i.forEach(function(a){var s=a.event,u=a.params;n.appBridge.onEventV3(s,JSON.stringify(u))}):i.length&&(this.emit(F.Event,i),this.emit(F.SessionResetTime)),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Event",level:"info",time:Date.now(),data:e,infoType:"cus"})}catch(a){this.logger.warn("something error, please check"),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Event Something Error",level:"error",time:Date.now(),data:a.message,infoType:"sdk"})}},r.prototype.beconEvent=function(e,t){if(Array.isArray(e))return this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK BeconEvent Error",level:"error",time:Date.now(),data:"beconEvent not support batch report, please check",infoType:"sdk"}),void this.logger.warn("beconEvent not support batch report, please check");var n=[],i=this.processEvent(e,t||{});i&&(n.push(i),n.length&&(this.emit(F.BeconEvent,n),this.emit(F.SessionResetTime)),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Beacon Event",level:"info",time:Date.now(),data:e,infoType:"sdk"}))},r.prototype.beaconEvent=function(e,t){this.beconEvent(e,t)},r.prototype.processEvent=function(e,t){t===void 0&&(t={});try{if(!e)return console.warn("eventName is null, please check"),null;var n=e;/^event\./.test(e)&&(n=e.slice(6));var i=t;typeof i!="object"&&(i={}),i.profile?delete i.profile:i.event_index=qm();var o=void 0;return i.local_ms?(o=i.local_ms,delete i.local_ms):o=+new Date,{event:n,params:i,local_time_ms:o,is_bav:this.initConfig&&this.initConfig.autotrack?1:0}}catch(a){return this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:a.message,infoType:"sdk"}),{event:e,params:t}}},r.prototype.filterEvent=function(e){this.eventFilter=e},r.prototype.on=function(e,t){this.hook.on(e,t)},r.prototype.once=function(e,t){this.hook.once(e,t)},r.prototype.off=function(e,t){this.hook.off(e,t)},r.prototype.emit=function(e,t,n){this.hook.emit(e,t,n)},r.prototype.set=function(e){this.hook.set(e)},r.prototype.stop=function(){this.sdkStop=!0},r.prototype.reStart=function(){this.sdkStop=!1},r.prototype.pageView=function(){this.disableAutoPageView||this.predefinePageView()},r.prototype.predefinePageView=function(e){if(e===void 0&&(e={}),this.inited){var t={title:document.title||location.pathname,url:location.href,url_path:location.pathname,time:Date.now(),referrer:window.document.referrer,$is_first_time:""+(this.configManager&&this.configManager.is_first_time||!1)},n=me(me({},t),e);this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Report PV",level:"info",time:Date.now(),infoType:"sdk"}),this.event("predefine_pageview",n)}else console.warn("predefinePageView should call after init")},r.prototype.clearEventCache=function(){this.emit(F.CleanEvents)},r.prototype.setWebId=function(e){this.config({web_id:""+e})},r.prototype.setNativeAppId=function(e){this.bridgeReport&&this.appBridge.setNativeAppId(e)},r.prototype.getSessionId=function(){return jr()},r.prototype.setSessionId=function(e){this.emit(F.SessionReset,e)},r.prototype.resetStayDuration=function(e,t,n){this.emit(F.ResetStay,{url_path:e,title:t,url:n},F.Stay)},r.prototype.resetStayParams=function(e,t,n){e===void 0&&(e=""),t===void 0&&(t=""),n===void 0&&(n=""),this.emit(F.SetStay,{url_path:e,title:t,url:n},F.Stay)},r.prototype.getToken=function(e,t){var n=this;if(this.inited){var i=!1,o=function(s){if(!i){i=!0;var u=n.configManager.get().user;return s&&(u.tobid=s,u["diss".split("").reverse().join("")]=s),e(me({},u))}},a=function(){n.tokenManager.getTobId().then(function(s){o(s)})};this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute GetToken",level:"info",time:Date.now(),infoType:"cus"}),this.sdkReady?a():(t&&setTimeout(function(){o()},t),this.on(F.Ready,function(){a()}))}else console.warn("predefinePageView should call after init")},r.prototype.startTrackEvent=function(e){e&&this.emit(F.TrackEventDurationStart,e,F.TrackEventDuration)},r.prototype.endTrackEvent=function(e,t){t===void 0&&(t={}),e&&this.emit(F.TrackEventDurationEnd,{eventName:e,params:t},F.TrackEventDuration)},r.prototype.pauseTrackEvent=function(e){e&&this.emit(F.TrackEventDurationPause,e,F.TrackEventDuration)},r.prototype.resumeTrackEvent=function(e){e&&this.emit(F.TrackEventDurationResume,e,F.TrackEventDuration)},r.prototype.profileSet=function(e){this.bridgeReport?this.appBridge.profileSet(JSON.stringify(e)):this.emit(F.ProfileSet,e,F.Profile),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileSet",level:"info",time:Date.now(),data:e})},r.prototype.profileSetOnce=function(e){this.bridgeReport?this.appBridge.profileSetOnce(JSON.stringify(e)):this.emit(F.ProfileSetOnce,e,F.Profile),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileSetOnce",level:"info",time:Date.now(),data:e})},r.prototype.profileIncrement=function(e){this.bridgeReport?this.appBridge.profileIncrement(JSON.stringify(e)):this.emit(F.ProfileIncrement,e,F.Profile),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileIncrement",level:"info",time:Date.now(),data:e})},r.prototype.profileUnset=function(e){this.bridgeReport?this.appBridge.profileUnset(e):this.emit(F.ProfileUnset,e,F.Profile),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileUnset",level:"info",time:Date.now(),data:e})},r.prototype.profileAppend=function(e){this.bridgeReport?this.appBridge.profileAppend(JSON.stringify(e)):this.emit(F.ProfileAppend,e,F.Profile),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileAppend",level:"info",time:Date.now(),data:e})},r.prototype.setExternalAbVersion=function(e){this.emit(F.AbExternalVersion,typeof e=="string"&&e?(""+e).trim():null,F.Ab)},r.prototype.getVar=function(e,t,n,i){this.emit(F.AbVar,{name:e,defaultValue:t,callback:n,uuid:i},F.Ab)},r.prototype.getABconfig=function(e,t){this.emit(F.AbConfig,{params:e,callback:t},F.Ab)},r.prototype.getABConfig=function(e,t){this.emit(F.AbConfig,{params:e,callback:t},F.Ab)},r.prototype.getAbSdkVersion=function(){return this.configManager.getAbVersion()},r.prototype.onAbSdkVersionChange=function(e){var t=this;return this.emit(F.AbVersionChangeOn,e,F.Ab),function(){t.emit(F.AbVersionChangeOff,e,F.Ab)}},r.prototype.offAbSdkVersionChange=function(e){this.emit(F.AbVersionChangeOff,e,F.Ab)},r.prototype.openOverlayer=function(){this.emit(F.AbOpenLayer,"",F.Ab)},r.prototype.closeOverlayer=function(){this.emit(F.AbCloseLayer,"",F.Ab)},r.prototype.getAllVars=function(e,t){this.emit(F.AbAllVars,{callback:e,timeout:t},F.Ab)},r.prototype.destoryInstace=function(){this.destroy||(this.destroy=!0,this.off(F.TokenComplete),this.emit(F.DestoryInstance))},r.prototype.destroyInstance=function(){this.destroy||(this.destroy=!0,this.off(F.TokenComplete),this.emit(F.DestoryInstance))},r.plugins=[],r}(),on={},Rc=[];function Ac(r,e,t,n){var i=r&&r.source||window.opener||window.parent,o=r&&r.origin||n||window.location.origin,a={type:e,payload:t};i.postMessage(JSON.stringify(a),o)}function v_(r){if(Rc.some(function(i){return r.origin.indexOf(i)>-1})){var e=r.data;if(typeof r.data=="string")try{e=JSON.parse(r.data)}catch{e=void 0}if(!e)return;var t=e.type,n=e.payload;on[t]&&on[t].forEach(function(i){typeof i=="function"&&i(r,n)})}}var sn,fo="__rangers_ab_style__";(function(r){r[r.Var=0]="Var",r[r.All=1]="All"})(sn||(sn={}));var y_=function(){function r(){this.fetchStatus="no",this.refreshFetchStatus="no",this.versions=[],this.extVersions=[],this.mulilinkVersions=[],this.enable_multilink=!1,this.enable_ab_visual=!1,this.editMode=!1,this.callbacks=[],this.data={},this.changeListener=new Map,this.readyStatus=!1,this.exposureCache=[],this.fetchQueueMap=new Map}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,this.config.enable_ab_test){var i=t.enable_multilink,o=t.ab_channel_domain,a=t.enable_ab_visual,s=t.ab_cross,u=t.ab_cookie_domain,c=t.ab_timeout,d=t.disable_auto_ab,f=Ki[t.channel||"sg"]||Ki.sg,h=o||Nr(f),g=e.adapters.storage;this.cacheStorgae=new g(!1),this.timeout=c||3e3,this.enable_multilink=i,this.enable_ab_visual=a,this.abKey="__tea_sdk_ab_version_"+t.app_id,this.ab_cross=s,this.ab_cookie_domain=u||"",this.fetchUrl=h+"/service/2/abtest_config/",this.reportUrl=this.collect.configManager.getUrl("event"),this.exposureLimit=t.exposure_limit||20,this.ab_batch_time=t.ab_batch_time||500,this.ab_user_mode=t.ab_user_mode||"user_unique_id",this.callbackMap=new Map,this.fetchQueueMap=new Map;var k=this.collect.Types;this.types=k,this.collect.on(k.TokenChange,function(z){z==="uuid"&&n.readyStatus&&(n.clearCache(),n.fetchAB())}),this.collect.on(k.AbVar,function(z){var w=z.name,b=z.defaultValue,T=z.callback;n.getVar(w,b,T)}),this.collect.on(k.AbAllVars,function(z){var w=z.callback,b=z.timeout;n.getAllVars(w,b)}),this.collect.on(k.AbConfig,function(z){var w=z.params,b=z.callback;n.getABconfig(w,b)}),this.collect.on(k.AbExternalVersion,function(z){n.setExternalAbVersion(z)}),this.collect.on(k.AbOpenLayer,function(){n.openOverlayer()}),this.collect.on(k.AbCloseLayer,function(){n.closeOverlayer()}),this.collect.on(k.AbVersionChangeOn,function(z){n.changeListener.set(z,z)}),this.collect.on(k.AbVersionChangeOff,function(z){n.changeListener.get(z)&&n.changeListener.delete(z)}),this.loadMode(),(this.enable_ab_visual||this.enable_multilink)&&this.openOverlayer(this.config.multilink_timeout_ms||500),this.checkLocal(),this.ready("ab"),this.readyStatus||(!d&&this.fetchAB(),this.readyStatus=!0),this.collect.emit(k.AbReady)}},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var n=this.collect.hook._hooksCache[e];if(!Object.keys(n).length)return;var i=function(a){n[a].length&&n[a].forEach(function(s){t.collect.hook.emit(a,s)})};for(var o in n)i(o)}},r.prototype.loadMode=function(){var e=function(){try{var o=JSON.parse(atob(window.name));return o||void 0}catch{return}}(),t="";if(e){var n=e.scenario,i=e.href;n?(this.editMode=!0,t=n):!i||i.indexOf("datatester")===-1&&i.indexOf("visual-editor")===-1||(this.editMode=!0,t="visual-editor")}this.enable_ab_visual&&t==="visual-editor"&&this.collect.destoryInstace()},r.prototype.checkLocal=function(){var e=this.getABCache(),t=e.ab_version,n=e.ab_ext_version,i=e.ab_version_multilink,o=(e.data,this.checkFromUrl());o?this.mulilinkVersions.push(o):this.mulilinkVersions=i||[],this.extVersions=n||[],this.versions=t||[];var a=this.versions.concat(this.extVersions);this.enable_multilink&&(a=a.concat(this.mulilinkVersions))},r.prototype.checkFromUrl=function(){var e=On(window.location.href);return e&&e.vid?e.vid:""},r.prototype.updateVersions=function(){var e=this.extVersions.length?this.versions.concat(this.extVersions):this.versions;this.enable_multilink&&(e=e.concat(this.mulilinkVersions)),this.configVersions(e.join(",")),this.updateABCache(),this.changeListener.size>0&&this.changeListener.forEach(function(t){typeof t=="function"&&t(e)})},r.prototype.configVersions=function(e){this.collect.configManager.setAbVersion(e)},r.prototype.getVar=function(e,t,n,i){if(!e)throw new Error("getVar key must not be empty");if(t===void 0&&console.warn("getVar defaultValue is illegal, please check!"),typeof n!="function")throw new Error("getVar callback must be a function");var o={name:e,defaultValue:t,callback:n,type:sn.Var};this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetVar",level:"info",time:Date.now(),data:e,infoType:"cus"}),this.fetchStatus==="complete"&&this.refreshFetchStatus==="complete"?this.getRealVar(o,e,i):this.callbackMap.set(e,o)},r.prototype.setAbUuid=function(e,t){this.collect.configManager.setAbUuidCache(e,t)},r.prototype.getRealVar=function(e,t,n){var i=e.name,o=e.defaultValue,a=e.callback,s=this.data;if(s){var u=s[i];if(u&&Gr(u)){var c=u.vid;return t==="$ab_url"?this.mulilinkVersions.includes(c)||this.mulilinkVersions.push(c):this.versions.includes(c)||this.versions.push(c),this.setAbUuid(c,n),this.updateVersions(),this.fechEvent(c,t||i,o,a,u.val),void this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetVar, Exposure Experiment "+i,level:"info",time:Date.now(),data:s[i],infoType:"sdk"})}this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GerVar Default Callback",level:"info",time:Date.now(),data:this.data,infoType:"sdk"}),a(o)}else a(o)},r.prototype.getAllVars=function(e,t){var n=this;if(typeof e!="function")throw new Error("getAllVars callback must be a function");var i=null,o={callback:e,type:sn.All,timer:i};this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetAllVars",level:"info",time:Date.now(),infoType:"cus"}),t&&(i=setTimeout(function(){o.timer=null,n.getRealAllVars(o),clearTimeout(i)},t),o.timer=i),this.fetchStatus==="complete"&&this.refreshFetchStatus==="complete"?(o.timer=null,this.getRealAllVars(o),i&&clearTimeout(i)):this.callbackMap.set("allVars",o)},r.prototype.getRealAllVars=function(e,t){var n=e.callback,i=e.timer;i&&(clearTimeout(i),e.timer=null);var o=(t??this.data)||{};try{n(JSON.parse(JSON.stringify(o)))}catch{n(o)}this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetAllVars Callback",level:"info",time:Date.now(),data:this.data,infoType:"sdk"})},r.prototype.fechEvent=function(e,t,n,i,o){try{if(this.config.disable_track_event||!e)return;var a=this.collect.configManager.get(),s=a.header,u=a.user,c=this.getABCache(),d=u[this.ab_user_mode]||u.user_unique_id;if(c&&c.uuid&&c.uuid!==d)return;var f={event:"abtest_exposure",ab_sdk_version:""+e,params:JSON.stringify({app_id:this.config.appId,ab_url:t==="$ab_url"?n:window.location.href,data:this.data}),local_time_ms:Date.now()};s.custom=JSON.stringify(s.custom);var h={events:[f],user:u,header:s};this.reportExposure(h,t),i&&i(o)}catch(g){this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:g.message,infoType:"sdk"})}},r.prototype.reportExposure=function(e,t){var n=this;this.exposureCache.push(e),this.reportTimeout&&clearTimeout(this.reportTimeout),this.exposureCache.length>=this.exposureLimit?this.report(t):this.reportTimeout=setTimeout(function(){n.report(t),clearTimeout(n.reportTimeout)},this.ab_batch_time)},r.prototype.report=function(e){var t=this;this.collect.requestManager.useRequest({url:this.reportUrl,data:this.exposureCache,timeout:2e4,useBeacon:e==="$ab_url",zip:!0}),this.exposureCache.forEach(function(n){t.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_EVENT,info:"SDK Report Exposure Event Success",time:Date.now(),data:[n],code:200,status:"success",infoType:"sdk"})}),this.collect.emit(this.types.AbVerify,[this.exposureCache]),this.exposureCache=[]},r.prototype.setExternalAbVersion=function(e){this.extVersions=[e],this.updateVersions()},r.prototype.getABconfig=function(e,t){var n=Object.keys(e);n&&n.length&&this.collect.configManager.set(e),this.fetchAB(t)},r.prototype.get=function(e){return this.cacheStorgae.getItem(e)},r.prototype.set=function(e,t){this.cacheStorgae.setItem(e,t),this.collect.configManager.setAbCache(t)},r.prototype.getABCache=function(e){var t={ab_version:[],ab_ext_version:[],ab_version_multilink:[],data:null,timestamp:+new Date,uuid:""};return t=this.get(this.abKey)||t,e?t[e]:t},r.prototype.updateABCache=function(){var e=this.getABCache();e.ab_version_multilink=this.mulilinkVersions,e.ab_ext_version=this.extVersions,e.ab_version=this.versions,e.timestamp=Date.now(),this.set(this.abKey,e)},r.prototype.setAbCache=function(e){var t=this.getABCache();t.data=this.data,t.uuid=e,t.timestamp=Date.now(),this.set(this.abKey,t)},r.prototype.clearCache=function(){this.refreshFetchStatus="ing",this.data={},this.extVersions=[],this.mulilinkVersions=[],this.versions=[],this.collect.configManager.clearAbCache()},r.prototype.openOverlayer=function(e){var t=this;if(function(){if(!document.getElementById(fo)){var i="body { opacity: 0 !important; }",o=document.head||document.getElementsByTagName("head")[0],a=document.createElement("style");a.id=fo,a.type="text/css",a.styleSheet?a.styleSheet.cssText=i:a.appendChild(document.createTextNode(i)),o.appendChild(a)}}(),e)var n=setTimeout(function(){t.closeOverlayer(),clearTimeout(n)},e)},r.prototype.closeOverlayer=function(){var e;(e=document.getElementById(fo))&&e.parentElement.removeChild(e)},r.prototype.fetchComplete=function(e,t){var n=this;this.changeFetchQueueStatus(t);try{if(e&&Object.prototype.toString.call(e)=="[object Object]"){var i=this.collect.configManager.get().user;if(t&&t!==i.user_unique_id)return;this.data=e,this.setAbCache(t);var o=[];Object.keys(e).forEach(function(d){var f=e[d].vid;f&&o.push(f)}),this.versions=this.versions.filter(function(d){return o.includes(d)});var a=e.$ab_url,s=e.$ab_modification;if(s&&s.val&&this.enable_ab_visual){if(this.collect.destroy)return}else if(a&&this.enable_multilink){this.mulilinkVersions=this.mulilinkVersions.filter(function(d){return o.includes(d)});var u=a.val,c=a.vid;u&&c&&this.getVar("$ab_url",u,function(){n.editMode||(u!==window.location.href?setTimeout(function(){if(!n.collect.destroy){var d=""+u;d=d.indexOf("http")===-1?"https://"+d:d,Ni(d).host!==location.host?d=d+"&vid="+c:window.history.replaceState("","",d),window.location.href=d}},100):n.closeOverlayer())})}this.updateVersions()}else this.closeOverlayer();this.callbackMap.forEach(function(d){d.type===sn.Var?n.getRealVar(d,""):n.getRealAllVars(d,e)})}catch{}},r.prototype.pushFetchToQueue=function(e){var t=e,n=this.fetchQueueMap.get(t);n?n.fetchStatus="ing":n={current_user_id:t,fetchStatus:"ing"},this.fetchQueueMap.set(t,n)},r.prototype.changeFetchQueueStatus=function(e){var t=this.fetchQueueMap.get(e);t&&(t.fetchStatus="complete",this.fetchQueueMap.set(e,t))},r.prototype.checkFetchQueueStatus=function(){if(this.fetchQueueMap.size===0)return!1;var e=!0;return this.fetchQueueMap.forEach(function(t){t.fetchStatus!=="complete"&&(e=!1)}),e},r.prototype.clearFetchQueue=function(e){this.fetchQueueMap.delete(e)},r.prototype.fetchAB=function(e){var t=this,n=this.collect.configManager.get(),i={header:me(me(me({aid:this.config.app_id},n.user||{}),n.header||{}),{ab_sdk_version:this.collect.configManager.getAbVersion(),ab_url:window.location.href})};this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch AB Request",level:"info",logType:"fetch",time:Date.now(),data:i,infoType:"sdk"});var o=n.user[this.ab_user_mode]||n.user.user_unique_id;this.pushFetchToQueue(o),this.collect.requestManager.useRequest({url:this.fetchUrl,data:i,success:function(a){t.fetchStatus="complete",t.refreshFetchStatus="complete";var s=a.data;a.message==="success"?(t.fetchComplete(s,o),e&&e(s)):(t.fetchComplete(null,o),e&&e(null)),t.collect.emit(t.types.AbComplete,s),t.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Fetch AB Request Success",level:"info",logType:"fetch",time:Date.now(),data:s,infoType:"sdk"})},fail:function(){t.fetchStatus="complete",t.refreshFetchStatus="complete",t.fetchComplete(null,o),t.collect.emit(t.types.AbTimeout),e&&e(null),t.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Fetch AB Request Network Error",level:"error",logType:"fetch",time:Date.now(),infoType:"sdk"})},timeout:this.timeout})},r.prototype.filterUrl=function(e){try{var t="";e.indexOf("&multilink=true")!==-1?t="&multilink=true[\0-ÿ]*":e.indexOf("?multilink=true")!==-1&&(t="\\?multilink=true[\0-ÿ]*");var n=new RegExp(t,"g");e=e.replace(n,"")}catch{}return e},r}(),S_=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,t.event_verify_url)if(typeof t.event_verify_url=="string"){if(this.url=t.event_verify_url+"/v1/list_test",this.url){var i=e.Types;e.on(i.SubmitVerify,function(o){n.verify(o)}),e.on(i.AbVerify,function(o){n.verify(o)})}}else console.log("please use correct et_test url")},r.prototype.verify=function(e){var t=this;e.forEach(function(n){try{var i=JSON.parse(JSON.stringify(n));t.config.filter&&((i=t.config.filter(i))||console.warn("filter must return data !!")),t.collect.eventFilter&&i&&((i=t.collect.eventFilter(i))||console.warn("filterEvent api must return data !!"));var o=i||n,a=JSON.parse(JSON.stringify(o));if(!o.length)return;var s=!0;if(o.forEach(function(u){u.events.length||(s=!1)}),!s)return;t.collect.requestManager.useBeacon({url:t.url,data:o}),t.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_EVENT,info:"SDK Report ByteIo Verify Request",time:Date.now(),data:a,code:200,status:"success",verifyType:!0})}catch(u){console.warn("something error, "+JSON.stringify(u.stack)),t.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Report ByteIo Verify Request Error",level:"error",time:Date.now(),data:u.message})}})},r}(),b_=function(){function r(e,t){this.maxDuration=432e5,this.aliveDTime=6e4,this.options={aliveName:"predefine_page_alive",params:{}},this.focusState=!0,this.collect=e,this.config=t,this.pageStartTime=Date.now(),this.sessionStartTime=this.pageStartTime,this.timerHandler=null,Gr(t.enable_stay_duration)&&(this.options=Object.assign(this.options,t.enable_stay_duration)),this.hard=this.options.mode&&this.options.mode==="hard",this.focusState=document.hasFocus()}return r.prototype.setParams=function(e,t,n){this.set_path=e,this.set_url=n,this.set_title=t},r.prototype.enable=function(e,t,n){this.url_path=e,this.url=n,this.title=t,this.disableCallback=this.enablePageAlive(),this.hard&&(this.removeMode=this.hardMode())},r.prototype.disable=function(){this.disableCallback(),this.pageStartTime=Date.now()},r.prototype.sendEvent=function(e,t){t===void 0&&(t=!1);var n=t?this.aliveDTime:Date.now()-this.sessionStartTime;n<0||n>this.aliveDTime||Date.now()-this.pageStartTime>this.maxDuration||t&&document.visibilityState==="hidden"||this.hard&&!this.focusState||(this.collect.beconEvent(this.options.aliveName,me({url_path:this.getParams("url_path"),title:this.getParams("title"),url:this.getParams("url"),duration:n,is_support_visibility_change:Pa(),startTime:this.sessionStartTime,hidden:document.visibilityState,leave:e,mode:this.hard?"hard":"normal",focusState:this.focusState},this.options.params)),this.sessionStartTime=Date.now())},r.prototype.getParams=function(e){switch(e){case"url_path":return this.set_path||this.url_path||location.pathname;case"title":return this.set_title||this.title||document.title||location.pathname;case"url":return this.set_url||this.url||location.href}},r.prototype.setUpTimer=function(){var e=this;return this.timerHandler&&clearInterval(this.timerHandler),setInterval(function(){Date.now()-e.sessionStartTime>e.aliveDTime&&e.sendEvent(!1,!0)},1e3)},r.prototype.visibilitychange=function(){document.visibilityState==="hidden"?this.timerHandler&&(clearInterval(this.timerHandler),this.sendEvent(!1)):document.visibilityState==="visible"&&(this.sessionStartTime=Date.now(),this.timerHandler=this.setUpTimer())},r.prototype.beforeunload=function(){document.hidden||this.sendEvent(!0)},r.prototype.enablePageAlive=function(){var e=this;this.timerHandler=this.setUpTimer();var t=this.visibilitychange.bind(this),n=this.beforeunload.bind(this);return document.addEventListener("visibilitychange",t),Br(n),function(){e.beforeunload(),document.removeEventListener("visibilitychange",t),window.removeEventListener("beforeunload",n),window.removeEventListener("pagehide",n)}},r.prototype.hardMode=function(){var e=this,t=function(){e.timerHandler&&(clearInterval(e.timerHandler),e.sendEvent(!1)),e.focusState=!1},n=function(){e.focusState=!0,e.sessionStartTime=Date.now(),e.timerHandler=e.setUpTimer()};return window.addEventListener("blur",t),window.addEventListener("focus",n),function(){window.removeEventListener("blur",t),window.removeEventListener("focus",n)}},r}(),E_=function(){function r(e,t){var n=this;this.maxDuration=432e5,this.aliveDTime=6e4,this.options={closeName:"predefine_page_close",params:{}},this.focusState=!0,this.visibilitychange=function(){document.visibilityState==="hidden"?n.activeEndTime=Date.now():document.visibilityState==="visible"&&(n.activeEndTime&&(n.totalTime+=n.activeEndTime-n.activeStartTime,n.activeTimes+=1),n.activeEndTime=void 0,n.activeStartTime=Date.now())},this.beforeunload=function(){if(n.totalTime+=(n.activeEndTime||Date.now())-n.activeStartTime,n.config.autotrack)try{window.sessionStorage.setItem("_tea_cache_duration",JSON.stringify({duration:n.totalTime,page_title:document.title||location.pathname}))}catch{}n.sendEventPageClose()},this.collect=e,this.config=t,this.maxDuration=t.maxDuration||864e5,this.pageStartTime=Date.now(),Gr(t.enable_stay_duration)&&(this.options=Object.assign(this.options,t.enable_stay_duration)),this.hard=this.options.mode&&this.options.mode==="hard",this.focusState=document.hasFocus(),this.resetData()}return r.prototype.setParams=function(e,t,n){this.set_path=e,this.set_url=n,this.set_title=t},r.prototype.resetParams=function(e,t,n){this.url_path=e,this.url=n,this.title=t},r.prototype.enable=function(e,t,n){this.url_path=e,this.url=n,this.title=t,this.disableCallback=this.enablePageClose(),this.hard&&(this.removeMode=this.hardMode())},r.prototype.disable=function(){this.disableCallback()},r.prototype.resetData=function(){this.activeStartTime=this.activeStartTime===void 0?this.pageStartTime:Date.now(),this.activeEndTime=void 0,this.activeTimes=1,this.totalTime=0,this.resetParams(location.pathname,document.title,location.href)},r.prototype.sendEventPageClose=function(){var e=Date.now()-this.pageStartTime;this.totalTime<0||e<0||this.totalTime>=this.maxDuration||this.hard&&!this.focusState||(this.collect.beconEvent(this.options.closeName,me({url_path:this.getParams("url_path"),title:this.getParams("title"),url:this.getParams("url"),active_times:this.activeTimes,duration:this.totalTime,total_duration:e,is_support_visibility_change:Pa(),mode:this.hard?"hard":"normal",focusState:this.focusState},this.options.params)),this.pageStartTime=Date.now(),this.resetData())},r.prototype.getParams=function(e){switch(e){case"url_path":return this.set_path||this.url_path||location.pathname;case"title":return this.set_title||this.title||document.title||location.pathname;case"url":return this.set_url||this.url||location.href}},r.prototype.enablePageClose=function(){var e=this,t=this.visibilitychange.bind(this),n=this.beforeunload.bind(this);return document.addEventListener("visibilitychange",t),Br(n),function(){e.beforeunload(),document.removeEventListener("visibilitychange",t),window.removeEventListener("beforeunload",n),window.removeEventListener("pagehide",n)}},r.prototype.hardMode=function(){var e=this,t=function(){e.focusState=!1},n=function(){e.focusState=!0};return window.addEventListener("blur",t),window.addEventListener("focus",n),function(){window.removeEventListener("blur",t),window.removeEventListener("focus",n)}},r}(),w_=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,this.config.enable_stay_duration){this.title=document.title||location.pathname,this.url=location.href,this.url_path=location.pathname,this.pageAlive=new b_(e,t),this.pageClose=new E_(e,t);var i=this.collect.Types;this.collect.on(i.ResetStay,function(o){var a=o.url_path,s=o.title,u=o.url;n.resetStayDuration(a,s,u)}),this.collect.on(i.RouteChange,function(o){o.init||t.disable_route_report||n.resetStayDuration()}),this.collect.on(i.SetStay,function(o){var a=o.url_path,s=o.title,u=o.url;n.setStayParmas(a,s,u)}),this.enable(this.url_path,this.title,this.url),this.ready(i.Stay),this.collect.emit(i.StayReady)}},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var n=this.collect.hook._hooksCache[e];if(!Object.keys(n).length)return;var i=function(a){n[a].length&&n[a].forEach(function(s){t.collect.hook.emit(a,s)})};for(var o in n)i(o)}},r.prototype.enable=function(e,t,n){this.pageAlive.enable(e,t,n),this.pageClose.enable(e,t,n)},r.prototype.disable=function(){this.pageAlive.disable(),this.pageClose.disable()},r.prototype.setStayParmas=function(e,t,n){e===void 0&&(e=""),t===void 0&&(t=""),n===void 0&&(n=""),this.pageAlive.setParams(e,t,n),this.pageClose.setParams(e,t,n),this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute resetStayParams",level:"info",time:Date.now(),data:{url_path:e,title:t,url:n}})},r.prototype.reset=function(e,t,n){this.disable(),this.enable(e,t,n)},r.prototype.resetStayDuration=function(e,t,n){this.reset(e,t,n),this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute resetStayDuration",level:"info",time:Date.now(),data:{url_path:e,title:t,url:n}})},r}(),C_=function(){function r(){var e=this;this.setInterval=function(){e.clearIntervalFunc=function(t,n){t===void 0&&(t=function(){}),n===void 0&&(n=1e3);var i,o=Date.now()+n;return i=window.setTimeout(function a(){var s=Date.now()-o;t(),o+=n,i=window.setTimeout(a,Math.max(0,n-s))},n),function(){window.clearTimeout(i)}}(function(){e.isSessionhasEvent&&e.endCurrentSession()},e.sessionInterval)},this.clearInterval=function(){e.clearIntervalFunc&&e.clearIntervalFunc()}}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,!t.disable_heartbeat){this.sessionInterval=6e4,this.startTime=0,this.lastTime=0,this.setInterval();var i=this.collect.Types;this.collect.on(i.SessionReset,function(){n.process()})}},r.prototype.endCurrentSession=function(){this.collect.event("_be_active",{start_time:this.startTime,end_time:this.lastTime,url:window.location.href,referrer:window.document.referrer,title:document.title||location.pathname}),this.isSessionhasEvent=!1,this.startTime=0},r.prototype.process=function(){this.isSessionhasEvent||(this.isSessionhasEvent=!0,this.startTime=+new Date);var e=this.lastTime||+new Date;this.lastTime=+new Date,this.lastTime-e>this.sessionInterval&&(this.clearInterval(),this.endCurrentSession(),this.setInterval())},r}(),k_=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,!this.config.channel_domain&&!t.disable_track_event&&!t.disable_sdk_monitor){this.url=e.configManager.getUrl("event");var i=this.collect.Types;this.collect.on(i.Ready,function(){n.sdkOnload()}),this.collect.on(i.SubmitError,function(o){var a=o.type,s=o.eventData,u=o.errorCode,c=o.response;a==="f_data"&&n.sdkError(s,u,c)}),this.collect.on(e.Types.SDKInnerError,function(o){var a=o.type,s=o.eventData,u=o.errorCode,c=o.msg;n.sdkInnerError(a,s,u,c)})}},r.prototype.sdkOnload=function(){var e=this;try{var t=this.collect.configManager.get(),n=t.header,i=t.user,o=n.app_id,a=n.app_name,s=n.sdk_version,u=(i.web_id,{events:[{event:"onload",params:JSON.stringify({app_id:o,app_name:a||"",sdk_version:s,sdk_type:"npm",sdk_config:this.config,sdk_desc:"TOC_OVERSEA",url:location.href,is_setting:this.config.enable_logsetting||!1,enable_logsetting_params:this.config.enable_logsetting_params||!1,enable_logsetting_header_custom:this.config.enable_logsetting_header_custom||!1}),local_time_ms:Date.now()}],user:{user_unique_id:i.user_unique_id},header:{app_id:6656}});setTimeout(function(){e.collect.requestManager.useRequest({url:e.url,data:[u],timeout:3e4,forceXhr:!0})},16)}catch{}},r.prototype.sdkError=function(e,t,n){var i=this;try{var o=e[0],a=o.user,s=o.header,u=[];e.forEach(function(d){d.events.forEach(function(f){u.push(f)})});var c={events:u.map(function(d){return{event:"on_error",params:JSON.stringify({type:"sdk_event_error",error_code:t,app_id:s.app_id,app_name:s.app_name||"",error_event:d.event,sdk_version:s.sdk_version,local_time_ms:d.local_time_ms,tea_event_index:Date.now(),params:d.params,header:s,user:a,err_msg:n.m||""}),local_time_ms:Date.now()}}),user:{user_unique_id:a.user_unique_id},header:{app_id:6656}};setTimeout(function(){i.collect.requestManager.useRequest({url:i.url,data:[c],timeout:3e4,forceXhr:!0})},16)}catch{}},r.prototype.sdkInnerError=function(e,t,n,i){var o=this;try{var a=t[0],s=a.user,u=a.header,c=[];t.forEach(function(f){f.events.forEach(function(h){c.push(h)})});var d={events:c.map(function(f){return{event:"on_error",params:JSON.stringify({type:e,error_code:n,app_id:u.app_id,app_name:u.app_name||"",error_event:f.event,sdk_version:u.sdk_version,local_time_ms:f.local_time_ms,tea_event_index:Date.now(),params:f.params,header:u,user:s,ua:window.navigator.userAgent,err_msg:i}),local_time_ms:Date.now()}}),user:s,header:{}};setTimeout(function(){o.collect.requestManager.useRequest({url:o.url,data:[d],timeout:3e4,app_key:"566f58151b0ed37e",forceXhr:!0})},16)}catch{}},r}();function po(r,e){if(e===void 0&&(e="list"),!r)return!1;if(e&&e==="list"){if(["LI","TR","DL"].includes(r.nodeName)||r.dataset&&r.dataset.hasOwnProperty("teaIdx")||r.hasAttribute&&r.hasAttribute("data-tea-idx"))return!0}else if(["A","BUTTON"].includes(r.nodeName)||r.dataset&&r.dataset.hasOwnProperty("teaContainer")||r.hasAttribute&&r.hasAttribute("data-tea-container"))return!0;return!1}function mo(r){for(var e=r;e&&!po(e,"container");){if(e.nodeName==="HTML"||e.nodeName==="BODY")return r;e=e.parentElement}return e||r}function Dc(r){var e="";return r.nodeType===3?e=r.textContent.trim():r.dataset&&r.dataset.hasOwnProperty("teaTitle")||r.hasAttribute("ata-tea-title")?e=r.getAttribute("data-tea-title"):r.hasAttribute("title")?e=r.getAttribute("title"):r.nodeName==="INPUT"&&["button","submit"].includes(r.getAttribute("type"))?e=r.getAttribute("value"):r.nodeName==="IMG"&&r.getAttribute("alt")&&(e=r.getAttribute("alt")),e.slice(0,200)}function Ic(r){for(var e=r;e&&e.parentNode;){if(e.hasAttribute("data-tea-ignore"))return!0;if(e.nodeName==="HTML"||e.nodeName==="body")return!1;e=e.parentNode}return!1}var jn=function(r,e){return r.hasAttribute?r.hasAttribute(e):r.attributes?!(!r.attributes[e]||!r.attributes[e].specified):void 0},T_=function(r,e){if(typeof e=="string")return jn(r,e);if(Gi(e)){for(var t=!1,n=0;n<e.length;n++)if(jn(r,e[n])){t=!0;break}return t}},z_=function(){function r(e,t,n){var i=this;this.statistics=!1,this.pageView=!1,this.clickEvent=function(o){(function(a,s){if(a.nodeType!==1||!s.svg&&function(c){if(c.tagName.toLowerCase()==="svg")return!0;for(var d=c.parentElement,f=!1;d;)d.tagName.toLowerCase()==="svg"?(d=null,f=!0):d=d.parentElement;return f}(a)||["HTML","BODY"].includes(a.tagName.toUpperCase()))return!1;var u=a;return u.style.display!=="none"&&(!!po(u,"container")||!(!function(c){if(c.children.length){var d=c.children;return![].slice.call(d).some(function(f){return f.children.length>0})}return!0}(u)&&!s.svg))})(o.target,i.options)&&i.eventHandel({eventType:"dom",eventName:"click"},o)},this.changeEvent=function(o){i.eventHandel({eventType:"dom",eventName:"change"},o)},this.submitEvent=function(o){i.eventHandel({eventType:"dom",eventName:"submit"},o)},this.getPageViewEvent=function(o,a){a&&a==="pushState"&&i.eventHandel({eventType:"dom",eventName:"beat"},me({beat_type:0},o)),i.eventHandel({eventType:"dom",eventName:"page_view"},o)},this.getPageLoadEvent=function(o){i.eventHandel({eventType:"dom",eventName:"page_statistics"},{lcp:o})},this.config=n.getConfig().eventConfig,this.collect=t,this.options=e,this.beatTime=e.beat}return r.prototype.init=function(e){this.eventHandel=e;var t=this.config.mode;this.addListener(t)},r.prototype.addListener=function(e){var t=this;if(e==="proxy-capturing"){if(this.config.click&&window.document.addEventListener("click",this.clickEvent,!0),this.config.change&&window.document.addEventListener("change",this.changeEvent,!0),this.config.submit&&window.document.addEventListener("submit",this.submitEvent,!0),this.config.pv){this.collect.on("route-change",function(u){var c=u.config,d=u.name;t.getPageViewEvent(c,d),t.pageView=!0});var n=setTimeout(function(){t.pageView||(t.getPageViewEvent(t.getDefaultConfig()),t.pageView=!0,clearTimeout(n))},2e3)}if(this.config.beat){try{document.readyState==="complete"?this.beatEvent(this.beatTime):window.addEventListener("load",function(){t.beatEvent(t.beatTime)});var i=0,o=null;window.addEventListener("scroll",function(){clearTimeout(o),o=setTimeout(a,500),i=document.documentElement.scrollTop||document.body.scrollTop});var a=function(){(document.documentElement.scrollTop||document.body.scrollTop)==i&&t.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:1})}}catch{}try{var s=window.performance&&window.performance.getEntriesByType("paint");s&&s.length?(new PerformanceObserver(function(u){var c=u.getEntries(),d=c[c.length-1],f=d.renderTime||d.loadTime;t.statistics||(t.getPageLoadEvent(f),t.statistics=!0)}).observe({entryTypes:["largest-contentful-paint"]}),setTimeout(function(){t.statistics||(t.getPageLoadEvent(s[0].startTime||0),t.statistics=!0)},2e3)):this.getPageLoadEvent(0)}catch{this.getPageLoadEvent(0)}}}},r.prototype.removeListener=function(){window.document.removeEventListener("click",this.clickEvent,!0),window.document.removeEventListener("change",this.changeEvent,!0),window.document.removeEventListener("submit",this.submitEvent,!0)},r.prototype.beatEvent=function(e){var t=this;try{var n;this.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:3}),this.beatTime&&(n=setInterval(function(){t.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:2})},e)),Br(function(){t.eventHandel({eventType:"dom",eventName:"beat",eventSend:"becon"},{beat_type:0}),t.beatTime&&clearInterval(n)})}catch{}},r.prototype.getDefaultConfig=function(){return{is_html:1,url:location.href,referrer:document.referrer,page_key:location.href,refer_page_key:document.referrer,page_title:document.title||location.pathname,page_manual_key:"",refer_page_manual_key:"",refer_page_title:"",page_path:location.pathname,page_host:location.host}},r}(),R_={eventConfig:{mode:"proxy-capturing",submit:!1,click:!0,change:!1,pv:!0,beat:!0,hashTag:!1,impr:!1},scoutConfig:{mode:"xpath"}},A_=function(){function r(e,t){this.config=e,this.config.eventConfig=Object.assign(this.config.eventConfig,t)}return r.prototype.getConfig=function(){return this.config},r.prototype.setConfig=function(e){return this.config=e},r}();function D_(r){for(var e=[];r.parentElement!==null;)e.push(r),r=r.parentElement;var t=[],n=[];return e.forEach(function(i){var o=function(u){if(u===null)return{str:"",index:0};var c=0,d=u.parentElement;if(d)for(var f=d.children,h=0;h<f.length&&f[h]!==u;h++)f[h].nodeName===u.nodeName&&c++;return{str:[u.nodeName.toLowerCase(),po(u,"list")?"[]":""].join(""),index:c}}(i),a=o.str,s=o.index;t.unshift(a),n.unshift(s)}),{element_path:"/"+t.join("/"),positions:n}}function I_(r,e,t,n){var i={},o=function(I){if(I){var U=I.getBoundingClientRect(),L=U.width,j=U.height;return{left:U.left,top:U.top,element_width:L,element_height:j}}}(e),a=function(I,U){I===void 0&&(I={}),U===void 0&&(U={});var L=I.clientX,j=I.clientY,$=U.left,K=U.top,Z=L-$>=0?L-$:0,W=j-K>=0?j-K:0;return{touch_x:Math.floor(Z),touch_y:Math.floor(W)}}(r,o),s=o.element_width,u=o.element_height,c=a.touch_x,d=a.touch_y,f=D_(e),h=f.element_path,g=f.positions,k=function(I){var U=mo(I),L=[];return function j($){var K=Dc($);if(K&&L.indexOf(K)===-1&&L.push(K),$.childNodes.length>0)for(var Z=$.childNodes,W=0;W<Z.length;W++)Z[W].nodeType!==8&&j(Z[W])}(U),L}(e),z=window.performance.timing.navigationStart,w=Date.now()-z,b=g.map(function(I){return""+I}),T=null;if(window.TEAVisualEditor&&window.TEAVisualEditor.getOriginXpath&&(T=window.TEAVisualEditor.getOriginXpath({xpath:h,positions:b})),i.element_path=T&&T.xpath||h,i.positions=T&&T.positions||b,n&&!n.text&&(i.texts=k,i.element_title=function(I){var U=mo(I),L="";return function j($){var K=Dc($);if(K&&(L+=K),$.childNodes.length>0)for(var Z=$.childNodes,W=0;W<Z.length;W++)Z[W].nodeType===3&&j(Z[W])}(U),L}(e)),i.element_id=e.getAttribute("id")||"",i.element_class_name=e.getAttribute("class")||"",i.element_type=e.nodeType,i.element_width=Math.floor(s),i.element_height=Math.floor(u),i.touch_x=c,i.touch_y=d,i.page_manual_key="",i.elememt_manual_key="",i.since_page_start_ms=w,i.page_start_ms=z,i.page_path=location.pathname,i.page_host=location.host,t.track_attr&&function(I,U){return!!T_(I,U)}(e,t.track_attr)){var E=function(I,U){var L={};if(typeof U=="string")jn(I,U)&&(L.attrs=I.getAttribute(U));else if(Gi(U))for(var j=0;j<U.length;j++)jn(I,U[j])&&(L[U[j]]=I.getAttribute(U[j]));return L}(e,t.track_attr);for(var O in E)i[O]=E[O]}var G=mo(e);return G.tagName==="A"&&(i.href=G.getAttribute("href")),e.tagName==="IMG"&&(i.src=e.getAttribute("src")),i}var an=function(r,e,t,n,i){return me(me({event:r},I_(e,t,n,i)),{is_html:1,page_key:window.location.href,page_title:document.title})},x_=function(){function r(e,t){this.ignore={text:!0},this.initConfig=e,this.options=t,this.eventName=t&&t.custom==="tea"?{click:"__bav_click",page:"__bav_page",beat:"__bav_beat",static:"__bav_page_statistics",exposure:"__bav_page_exposure"}:{click:"bav2b_click",page:"bav2b_page",beat:"bav2b_beat",static:"bav2b_page_statistics",exposure:"bav2b_exposure"},t&&t.text===!0&&(this.ignore.text=!1),t&&t.exposure&&t.exposure.eventName&&(this.eventName.exposure=t.exposure.eventName)}return r.prototype.handleEvent=function(e,t){try{if(Ic(e.target))return null;var n="bav2b_click";switch(t){case"click":return n=e.target.getAttribute("data-applog-click-event")||this.eventName.click,an(n,e,e.target,this.options,this.ignore);case"change":return me(me({},an(n="bav2b_change",e,e.target,this.options)),function(i,o){try{if(i==="bav2b_change")return o.hasAttribute("data-tea-track")?{value:o.value}:{}}catch{return{}}}(n,e.target));case"submit":return an(n="bav2b_submit",e,e.target,this.options)}}catch(i){return console.error(i),null}},r.prototype.handleViewEvent=function(e){e.event=this.eventName.page,e.page_title=document.title,e.page_total_width=window.innerWidth,e.page_total_height=window.innerHeight;try{var t=window.sessionStorage.getItem("_tea_cache_duration");if(t){var n=JSON.parse(t);e.refer_page_duration_ms=n?n.duration:""}e.scroll_width=document.documentElement.scrollLeft?document.documentElement.scrollLeft+window.innerWidth:window.innerWidth,e.scroll_height=document.documentElement.scrollTop?document.documentElement.scrollTop+window.innerHeight:window.innerHeight,e.page_start_ms=window.performance.timing.navigationStart}catch(i){console.log("page event error "+JSON.stringify(i))}return e},r.prototype.handleStatisticsEvent=function(e){var t={};t.event=this.eventName.static,t.is_html=1,t.page_key=location.href,t.refer_page_key=document.referrer||"",t.page_title=document.title,t.page_manual_key=this.initConfig.autotrack.page_manual_key||"",t.refer_page_manual_key="";try{var n=e.lcp,i=window.performance.timing,o=i.loadEventEnd-i.navigationStart;t.page_init_cost_ms=parseInt(n||(o>0?o:0)),t.page_start_ms=i.navigationStart}catch(a){console.log("page_statistics event error "+JSON.stringify(a))}return t},r.prototype.handleBeadtEvent=function(e){e.event=this.eventName.beat,e.page_key=window.location.href,e.is_html=1,e.page_title=document.title,e.page_manual_key=this.initConfig.autotrack.page_manual_key||"";try{e.page_viewport_width=window.innerWidth,e.page_viewport_height=window.innerHeight,e.page_total_width=document.documentElement.scrollWidth,e.page_total_height=document.documentElement.scrollHeight,e.scroll_width=document.documentElement.scrollLeft+window.innerWidth,e.scroll_height=document.documentElement.scrollTop+window.innerHeight,e.since_page_start_ms=Date.now()-window.performance.timing.navigationStart,e.page_start_ms=window.performance.timing.navigationStart}catch(t){console.log("beat event error "+JSON.stringify(t))}return e},r.prototype.handleExposureEvent=function(e,t){if(Ic(t.target))return null;var n=an(e.event||this.eventName.exposure,t,t.target||t,this.options,this.ignore);if(n.$exposure_type=e.exposureType,this.options.exposure.callback){var i=this.options.exposure.callback(n);return i||Object.keys(i).length?i:(console.warn("exposure callback must return data!"),n)}return n},r.prototype.handleScrollEvent=function(e,t){var n=an(e.event||this.eventName.scroll,t,t.target||t,this.options,this.ignore);if(n=Object.assign(n,e.params),!this.options.scroll.callback||(n=this.options.scroll.callback(n))||Object.keys(n).length)return n;console.warn("scroll callback must return data!")},r}(),M_=function(){function r(e){this.collect=e,this.eventNameList=["report_click_event","report_change_event","report_submit_event","report_exposure_event","report_page_view_event","report_page_statistics_event","report_beat_event"]}return r.prototype.send=function(e,t){var n=e.eventSend,i=t.event;delete t.event,n&&n==="becon"?this.collect.beconEvent(i,t):this.collect.event(i,t)},r.prototype.get=function(e,t){var n=Object.assign({headers:{"content-type":"application/json"},method:"GET"},t);fetch(e,n)},r.prototype.post=function(e,t){var n=Object.assign({headers:{"content-type":"application/json"},method:"POST"},t);fetch(e,n)},r}(),go=!1;function O_(r){var e,t,n,i,o=r.event,a=r.editorUrl,s=r.autoTrackInstance;go||(go=!0,e=a,t=function(){Ac(o,"editorScriptloadSuccess"),s.destroy()},n=function(){o&&Ac(o,"editorScriptloadError"),go=!1},(i=document.createElement("script")).src=e,i.onerror=function(){n(e)},i.onload=function(){t()},document.getElementsByTagName("head")[0].appendChild(i))}function P_(r,e){window.TEAVisualEditor=window.TEAVisualEditor||{},window.TEAVisualEditor.appId=e.app_id;var t,n,i,o=e.channel_domain,a="";if((t=ng).length&&t.forEach(function(h){Rc.push(h)}),o){var s=void 0,u="";try{var c=window.performance.getEntriesByType("resource");if(c&&c.length&&(c.forEach(function(h){h.initiatorType==="script"&&h.name&&h.name.indexOf("collect")!==-1&&(u=h.name)}),u&&(s=u.split("/"))&&s.length)){a="https:/";for(var d=2;d<s.length&&d!==s.length-1;d++)a=a+"/"+s[d];if(a&&a.indexOf("/5.0")){var f=a.split("/5.0");a=f[0]||a}}}catch{}}window.addEventListener("message",v_,!1);try{i=function(h){var g=h.data.app_id;g&&g!==e.app_id||O_({event:h,editorUrl:"https://sf16-website-login.neutral.ttwstatic.com/obj/tiktok_web_login_static/log-sdk/collect/heatmap-core.js?query="+Date.now(),autoTrackInstance:r})},on[n="tea:openHeatMapCore"]=on[n]||[],on[n].push(i)}catch{console.log("openHeatMapCore error")}}var gt,L_=function(){function r(e,t){this._instance=null,this._intersection=e,this.config=t,this._intersection&&this.init()}return r.prototype.init=function(){var e=this;if(window.MutationObserver)try{if(this._instance=new MutationObserver(function(n){n.forEach(function(i){i.type==="attributes"&&e.attributeChangeObserve(i),i.type==="childList"&&e.modifyNodeObserve(i)})}),!document||!document.body)return void console.warn("please use sdk api init after body element");var t=this.config.autotrack.exposure.attributes!==!1;this._instance.observe(document.body,{childList:!0,attributes:t,subtree:!0,attributeOldValue:!1})}catch{console.log("your browser cannot support MutationObserver,so cannot report exposure event, please update")}else console.log("your browser cannot support MutationObserver,so cannot report exposure event, please update")},r.prototype.attributeChangeObserve=function(e){e.target.hasAttribute("data-exposure")?this.exposureAdd(e,"mutation"):this.exposureRemove(e)},r.prototype.modifyNodeObserve=function(e){var t=this;Array.prototype.forEach.call(e.addedNodes,function(n){n.nodeType===1&&n.hasAttribute("data-exposure")&&t.exposureAdd(n,"intersect"),t.mapChild(n,t.exposureAdd.bind(t))}),Array.prototype.forEach.call(e.removedNodes,function(n){n.nodeType===1&&n.hasAttribute("data-exposure")&&t.exposureRemove(n),t.mapChild(n,t.exposureRemove.bind(t))})},r.prototype.mapChild=function(e,t){var n=this;e.nodeType===1&&e.children.length&&Array.prototype.forEach.call(e.children,function(i){i.nodeType===1&&i.hasAttribute("data-exposure")&&t(i),n.mapChild(i,t)})},r.prototype.exposureAdd=function(e,t){try{this._intersection&&this._intersection.exposureAdd(e,t)}catch(n){console.log("intersection error",JSON.stringify(n.message))}},r.prototype.exposureRemove=function(e){try{this._intersection&&this._intersection.exposureRemove(e)}catch(t){console.log("intersection error",JSON.stringify(t.message))}},r._exposure_observer=null,r}();(function(r){r[r.EXPOSURE_ONCE=0]="EXPOSURE_ONCE",r[r.LIFECYCLE_SHOW_NEW=3]="LIFECYCLE_SHOW_NEW",r[r.RESUME_FORM_PAGE=6]="RESUME_FORM_PAGE",r[r.RESUME_FORM_BACK=7]="RESUME_FORM_BACK",r[r.NOT_EXPOSURE=-1]="NOT_EXPOSURE"})(gt||(gt={}));var rr,U_=function(){function r(e,t,n){var i=this;this.backStatus=!1,this.instance=this.buildObserver(),this.collect=e,this.observeMap=r._observer_map,t.autotrack.exposure.ratio?this.ratio=t.autotrack.exposure.ratio:t.autotrack.exposure.ratio===0?this.ratio=0:this.ratio=.5,this.timeLimit=t.autotrack.exposure.stay||0,this.exposureType=gt.NOT_EXPOSURE,this.eventHandle=n,this.hashMap=new Map,this.backStatus=!1,this.lastState=null,this.collect.on("re-start-sdk",function(){i.visibilitychange()}),this.addListen()}return r.prototype.buildObserver=function(){var e=this;if(r._observer_instance)return console.log("your browser cannot support IntersectionObserver, so cannot report exposure event, please update"),null;if(window.IntersectionObserver){for(var t=[],n=0;n<=1;n+=.01)t.push(n);t.push(1);try{r._observer_instance=new IntersectionObserver(function(i){i.forEach(function(o){var a=o.target.observeId,s=e.observeMap.get(a),u=(o.target,o.isIntersecting,o.intersectionRatio);if(s.intersectionRatio=u,u<=.1&&(o.target.backStatus=!1),e.observeMap.set(a,s),u<e.ratio)return s.isIntersecting=!1,s.added=!1,s.exposured=!1,s.startTime=Date.now(),void e.observeMap.set(a,s);if(!s.added){if(s.startTime=Date.now(),s.added=!0,s.isIntersecting=!0,e.timeLimit){var c=setTimeout(function(){try{if(s.isIntersecting&&!s.exposured&&e.observeMap.get(a)){var d=e.observeMap.get(a).intersectionRatio;e.exposureEvent(o,d,a,s)}}catch(f){console.log("IntersectionObserver setTimeout error,msg: "+JSON.stringify(f))}},e.timeLimit);s.wait=c}e.observeMap.set(a,s)}Date.now()-s.startTime>=e.timeLimit&&!s.exposured&&e.exposureEvent(o,u,a,s)})},{threshold:t})}catch(i){console.log("IntersectionObserver error,msg: "+JSON.stringify(i))}return r._observer_instance}return console.log("your browser cannot support IntersectionObserver, so cannot report exposure event, please update"),null},r.prototype.exposureAdd=function(e,t){var n=t==="mutation"?e.target:e,i=n.observeId,o=Ln();if(i||this.observeMap.has(i)){var a=this.observeMap.get(i);if(a&&n!==a.instance)this.unobserve(n),this.observeMap.delete(i),n.observeId=o,n.visible=!1,this.observeMap.set(o,{instance:n.cloneNode(!0),isIntersecting:!1}),this.observe(n);else{if(n.visible===!0)return;this.handleBoundingExposure(n)}}else n.observeId=o,n.visible=!1,this.observeMap.set(o,{instance:n.cloneNode(!0),isIntersecting:!1}),this.observe(n)},r.prototype.exposureRemove=function(e){this.observeMap.has(e.observeId)&&(this.observeMap.delete(e.observeId),this.unobserve(e),e.observeId="",e.visible=!1)},r.prototype.exposureEvent=function(e,t,n,i){if(t>=this.ratio){if(e.target.style.opacity==="0"||e.target.style.visibility==="hidden"||i.exposured===!0)return;i.startWait&&clearTimeout(i.startWait);var o=e.target.getAttribute("data-applog-exposure-event");this.eventHandle({eventType:"dom",eventName:"exposure",event:o,exposureType:this.getExposureType(e.target)},e),e.target.visible=!0,e.target.hasExposure=!0,i.startTime=Date.now(),i.exposured=!0}else i.startTime=Date.now(),i.exposured=!1;this.observeMap.set(n,i)},r.prototype.observe=function(e){this.instance&&this.instance.observe(e)},r.prototype.unobserve=function(e){this.instance&&this.instance.unobserve(e)},r.prototype.getExposureDomToExposure=function(){var e=this;Array.prototype.forEach.call(document.querySelectorAll("[data-exposure]"),function(t){e.handleBoundingExposure(t)})},r.prototype.visibilitychange=function(){var e=this,t=null;document.visibilityState==="visible"?this.timeLimit?t=setTimeout(function(){e.getExposureDomToExposure()},this.timeLimit):this.getExposureDomToExposure():(clearTimeout(t),this.customType=void 0)},r.prototype.handleBoundingExposure=function(e){if(this.getBoundingRatio(e)>=this.ratio){e.visible=!0;var t=e.getAttribute&&e.getAttribute("data-exposure-event");this.eventHandle({eventType:"dom",eventName:"exposure",event:t,exposureType:this.customType||gt.RESUME_FORM_BACK},e)}},r.prototype.getBoundingRatio=function(e){var t=e.getBoundingClientRect(),n=t.top,i=t.left,o=t.width,a=t.height,s=window.innerWidth||document.documentElement.clientWidth,u=window.innerHeight||document.documentElement.clientHeight;return n>=0&&i>=0&&n<=u&&i<=s?(o>s?s:o)*(u-n)/(o*a):0},r.prototype.getExposureType=function(e){return e.visible?e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=gt.RESUME_FORM_PAGE:this.exposureType=gt.LIFECYCLE_SHOW_NEW:(e.hasExposure,e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=gt.RESUME_FORM_PAGE:this.exposureType=gt.EXPOSURE_ONCE),this.exposureType},r.prototype.addListen=function(){var e=this;this.collect.on("set-exposure-type",function(s){e.customType=s});var t,n,i,o,a=this.visibilitychange.bind(this);return t=document,n="visibilitychange",i=a,o=!1,t.addEventListener?t.addEventListener(n,i,o):t.attachEven?t.attachEven("on"+n,i):t["on"+n]=i,window.addEventListener("hashchange",function(s){var u=e.hashMap.get(s.oldURL);u&&location.href===u.prev?(e.backStatus=!0,e.exposureType=gt.RESUME_FORM_PAGE):(e.backStatus=!1,e.hashMap.set(location.href,{current:s.newURL,prev:s.oldURL}))}),this.collect.on("STATE_CHANGE",function(s){e.lastState=s}),window.addEventListener("popstate",function(s){var u=s.state;u&&u.current&&e.lastState&&e.lastState.back&&u.current===e.lastState.back?(e.backStatus=!0,e.exposureType=gt.RESUME_FORM_PAGE):e.backStatus=!1}),function(){(function(s,u,c,d){s.addEventListener?s.removeEventListener(u,c,d):s.attachEven&&s.detachEven("on"+u,c)})(document,"visibilitychange",a,!1)}},r._observer_instance=null,r._observer_map=new Map,r}(),G_=function(){function r(e,t,n){t.autotrack&&t.autotrack.exposure&&(this._intersection=new U_(e,t,n),this._observer=new L_(this._intersection,t),this._intersection&&this._observer?this.initObserver():console.log("your browser version cannot support exposure event, please update~"))}return r.prototype.initObserver=function(){var e=this;Array.prototype.forEach.call(document.querySelectorAll("[data-exposure]"),function(t){e._intersection.exposureAdd(t,"intersect")})},r}();(function(r){r[r.SCROLL_UP=1]="SCROLL_UP",r[r.SCROLL_DOWN=2]="SCROLL_DOWN",r[r.SCROLL_LEFT=3]="SCROLL_LEFT",r[r.SCROLL_RIGHT=4]="SCROLL_RIGHT",r[r.NOT_SCROLL=-1]="NOT_SCROLL"})(rr||(rr={}));var xc,N_=function(){function r(e,t){this.distance=30,e.autotrack&&e.autotrack.scroll&&(e.autotrack.scroll.distance&&(this.distance=e.autotrack.scroll.distance),this.eventHandle=t,this.addLinstenr(),this.mutation())}return r.prototype.addLinstenr=function(){var e=this;Array.prototype.forEach.call(document.querySelectorAll("[data-scroll]"),function(t){e.scrollHandle(t)})},r.prototype.mutation=function(){var e=this;if(window.MutationObserver)try{var t=new MutationObserver(function(n){n.forEach(function(i){i.type==="childList"&&e.modifyNodeObserve(i)})});if(!document||!document.body)return void console.warn("please use sdk api init after body element");t.observe(document.body,{childList:!0,attributes:!0,subtree:!0,attributeOldValue:!1})}catch{console.log("your browser cannot support MutationObserver")}else console.log("your browser cannot support MutationObserver")},r.prototype.modifyNodeObserve=function(e){var t=this;Array.prototype.forEach.call(e.addedNodes,function(n){n.nodeType===1&&n.hasAttribute("data-scroll")&&t.scrollHandle(n),t.mapChild(n,t.scrollHandle.bind(t))}),Array.prototype.forEach.call(e.removedNodes,function(n){n.nodeType===1&&n.hasAttribute("data-scroll")&&t.scrollHandle(n,"remove"),t.mapChild(n,t.scrollHandle.bind(t))})},r.prototype.mapChild=function(e,t){var n=this;e.nodeType===1&&e.children.length&&Array.prototype.forEach.call(e.children,function(i){i.nodeType===1&&i.hasAttribute("data-scroll")&&t(i),n.mapChild(i,t)})},r.prototype.scrollHandle=function(e,t){var n=this;try{var i=e.scrollTop,o=e.scrollLeft,a=null,s=0,u=0,c=function(d){clearTimeout(a),a=setTimeout(function(){var k=e.scrollTop,z=e.scrollLeft,w=d.target&&d.target.getAttribute("data-scroll-event")||"";g===1||g===2?k===f&&(u=f-i,Math.abs(u)>=n.distance&&n.distance&&n.eventHandle({eventType:"dom",eventName:"scroll",event:w,params:{$direction:g,$offsetY:u,$offsetX:s}},d)):g!==3&&g!==4||z===h&&(s=h-o,Math.abs(s)>=n.distance&&n.distance&&n.eventHandle({eventType:"dom",eventName:"scroll",event:w,params:{$direction:g,$offsetY:u,$offsetX:s}},d)),i=f,o=h},100);var f=e.scrollTop,h=e.scrollLeft,g=rr.NOT_SCROLL;f>i?g=rr.SCROLL_DOWN:f<i?g=rr.SCROLL_UP:h>o?g=rr.SCROLL_LEFT:h<o&&(g=rr.SCROLL_RIGHT)};return t==="remove"?e.removeEventListener("scroll",c,!1):e.addEventListener("scroll",c,!1),function(){e.removeEventListener("scroll",c,!1)}}catch(d){console.warn("scroll event error",JSON.stringify(d))}},r}(),B_={hashTag:!1,impr:!1},F_=function(){function r(){}return r.prototype.apply=function(e,t){if(this.autoTrackStart=!1,this.collect=e,this.config=t,t.autotrack){var n=e.Types;this.ready(n.Autotrack),this.collect.emit(n.AutotrackReady)}},r.prototype.ready=function(e){this.collect.set(e);var t=this.config.autotrack;t=typeof t=="object"?t:{},t=Object.assign(B_,t),this.destroyed=!1,this.options=t,this.Config=new A_(R_,this.options),this.Exposure=new G_(this.collect,this.config,this.handle.bind(this)),this.Scroll=new N_(this.config,this.handle.bind(this)),this.Listener=new z_(t,this.collect,this.Config),this.EventHandle=new x_(this.config,t),this.Request=new M_(this.collect),this.autoTrackStart=!0,this.init(),P_(this,this.config)},r.prototype.init=function(){this.Listener.init(this.handle.bind(this)),this.collect.loadType==="base"&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")},r.prototype.handle=function(e,t){try{if(this.config.autotrack.collect_url&&!this.config.autotrack.collect_url())return}catch{}e.eventType==="dom"&&this.handleDom(e,t)},r.prototype.handleDom=function(e,t){try{var n=e.eventName;if(n==="click"||n==="change"||n==="submit")(s=this.EventHandle.handleEvent(t,n))&&this.Request.send({eventType:"custom"},s);else if(n==="page_view"||n==="page_statistics"){var i=void 0;(i=n==="page_view"?this.EventHandle.handleViewEvent(t):this.EventHandle.handleStatisticsEvent(t))&&this.Request.send({eventType:"custom"},i)}else if(n==="beat"){var o=this.EventHandle.handleBeadtEvent(t),a=e.eventSend;o&&this.Request.send({eventType:"custom",eventSend:a},o)}else if(n==="exposure")(s=this.EventHandle.handleExposureEvent(e,t))&&this.Request.send({eventType:"custom"},s);else if(n==="scroll"){var s;(s=this.EventHandle.handleScrollEvent(e,t))&&this.Request.send({eventType:"custom"},s)}}catch(u){console.log("handel dom event error "+JSON.stringify(u))}},r.prototype.destroy=function(){if(!this.autoTrackStart)return console.warn("engine is undefined, make sure you have called autoTrack.start()");this.autoTrackStart=!1,this.Listener.removeListener()},r}();(function(r){r.Net="net",r.FailNet="f_net",r.FailData="f_data"})(xc||(xc={}));var Mc={pv:["predefine_pageview"],sdk:["_be_active","predefine_page_alive","predefine_page_close","__profile_set","__profile_set_once","__profile_increment","__profile_unset","__profile_append"],autotrack:["bav2b_click","bav2b_page","bav2b_beat","bav2b_page_statistics","__bav_click","__bav_page","__bav_beat","__bav_page_statistics"]},V_=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.ready=t.app_id&&t.enable_tracer&&!t.disable_track_event,this.ready){this.limit={pv:1,sdk:3,autotrack:3,log:3},this.errorCode={f_net:0,f_data:0},this.tracerCache=new Map,this.collect=e,this.appid=t.app_id,this.reportUrl=e.configManager.getUrl("event");var i=this.collect.Types;e.adapters.fetch,this.collect.on(i.Event,function(o){Gi(o)?o.forEach(function(a){n.addCount("log")}):n.addCount("log")}),this.collect.on(i.SubmitError,function(o){var a=o.type,s=o.eventDate,u=o.errorCode,c=o.response;n.addErrorCount(s,a,u,c)}),this.listener(),this.collect.emit(i.TracerReady)}},r.prototype.addCount=function(e,t,n){t===void 0&&(t="net"),n===void 0&&(n=1);try{this.tracerCache||(this.tracerCache=new Map);var i=void 0;if(this.tracerCache.has(e))(o=this.tracerCache.get(e)).has(t)?(i=o.get(t).params.count,i++,o.set(t,this.processTracer(i,e,t))):(i=n,o.set(t,this.processTracer(n,e,t)));else{var o=new Map;i=n,o.set(t,this.processTracer(n,e,t)),this.tracerCache.set(e,o)}t==="net"&&i>=this.limit[e]&&this.report(!1)}catch(a){console.log(a)}},r.prototype.addErrorCount=function(e,t,n,i){var o=this;try{if(e&&e.length){var a=e[0].events;a&&a.length&&(t==="f_data"?(i&&i.hasOwnProperty("sc")?this.addCount("log",t,a.length-i.sc):this.addCount("log",t,a.length),this.errorCode[t]=n):a.forEach(function(s){var u="log";for(var c in Mc)if(Mc[c].indexOf(s.event)!==-1){u=c;break}o.addCount(u,t,1),o.errorCode[t]=n}))}}catch{}},r.prototype.report=function(e){if(this.tracerCache){var t=[];this.tracerCache.forEach(function(n){console.log(n),n.forEach(function(i){t.push(i)})}),t&&t.length&&this.sendTracer(t,e)}},r.prototype.sendTracer=function(e,t){try{var n=this.collect.eventManager.merge(e);this.collect.requestManager.useRequest({url:this.reportUrl,data:n,useBeacon:t}),this.tracerCache=null}catch{}},r.prototype.processTracer=function(e,t,n){try{var i={count:e,state:n,key:t,params_for_special:"applog_trace",aid:this.appid,platform:"web",_staging_flag:1,sdk_version:Vr};n!=="f_net"&&n!=="f_data"||(i.errorCode=this.errorCode[n]);var o=this.collect.processEvent("applog_trace",i);if(o&&o.event)return delete o.is_bav,o}catch{console.warn("something error")}},r.prototype.listener=function(){var e=this;document.addEventListener("visibilitychange",function(){document.visibilityState==="hidden"&&e.leavePage()}),Br(function(){e.leavePage()})},r.prototype.leavePage=function(){this.report(!0)},r}(),j_=function(){function r(){this.retryWaitTime=3e3,this.retryStatus=!1,this.retryCacheStatus=!1}return r.prototype.apply=function(e,t){var n=this;if(t.enable_storage&&!t.disable_storage&&(this.collect=e,this.config=t,!this.collect.destroy)){var i=e.Types,o=e.adapters.storage;this.storage=new o(!1),this.eventUrl=this.collect.configManager.getUrl("event"),this.eventKey="__tea_cache_events_"+t.app_id,this.storageNum=t.storage_num||50,this.retryNum=t.retry_num||3,this.retryInterval=1e3,e.on(i.SubmitError,function(a){a.type!=="f_data"&&n.storeData(a)}),e.on(i.Ready,function(){n.checkStorage()})}},r.prototype.retryRightNow=function(e){var t=this;if(this.retryStatus)this.errorCache.push(e);else{var n=0;this.retryStatus=!0;var i=setInterval(function(){if(n===3)return t.storeData(t.errorCache),t.retryStatus=!1,void clearInterval(i);var o=e.eventData;t.fetchData(o,function(){t.retryStatus=!1,clearInterval(i),t.retryCacheStatus&&t.errorCache.splice(0,1),t.errorCache.length&&(t.retryCacheStatus=!0,t.retryRightNow(t.errorCache[0]))},function(){n++})},this.retryInterval)}},r.prototype.storeData=function(e){var t=this.storage.getItem(this.eventKey),n=e.eventData;Object.keys(t).length!==this.storageNum&&(t[Date.now()]=n,this.storage.setItem(this.eventKey,t))},r.prototype.checkStorage=function(){var e=this;try{if(!window.navigator.onLine)return;var t=this.storage.getItem(this.eventKey);if(!t||!Object.keys(t).length)return;var n={events:[{event:"ontest",params:{app_id:this.config.app_id},local_time_ms:Date.now()}],user:{user_unique_id:this.collect.configManager.get("web_id")},header:{}};this.fetchData([n],function(){var i=JSON.parse(JSON.stringify(t)),o=function(s){e.fetchData(t[s],function(){delete i[s],e.storage.setItem(e.eventKey,i)},function(){},!1)};for(var a in t)o(a)},function(){},!0)}catch{console.warn("error check storage")}},r.prototype.fetchData=function(e,t,n,i){this.collect.requestManager.useRequest({url:this.eventUrl,data:e,timeout:3e4,success:t,fail:n,app_key:i?"566f58151b0ed37e":""})},r}(),_o=typeof window<"u"?(window.LogPluginObject||(window.LogPluginObject={}),window.LogPluginObject):null,H_=function(){function r(){}return r.prototype.apply=function(e,t){this._plugin={},this.config=t,this.collect=e,this.channel="va",this.loadExtend()},r.prototype.loadExtend=function(){var e=this;try{this.collect.remotePlugin.forEach(function(t,n){if(t==="sdk")if(ho.hasOwnProperty(n)){var i=ho[n].object,o=""+ho[n].src[e.channel];e.exist(n,i,o)}else console.warn("your "+n+" is not exist,please check plugin name");else typeof t=="object"&&(t.src?e.exist(n,t.call,t.src):e.process(n,t.instance,"INSTANCE"))})}catch(t){this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"LoadExtend Fail",level:"error",time:Date.now(),data:t.message}),console.log("load extend error")}},r.prototype.exist=function(e,t,n){var i=this;_o[t]?(this.process(e,_o[t]),console.log("already has "+e+" plugin~")):this.loadPlugin(e,n,function(){i.process(e,_o[t]),console.log(" %c %s %s %s","color: yellow; background-color: black;","–","load plugin:"+e+" success","-")},function(){console.log(" %c %s %s %s","color: red; background-color: yellow;","–","load plugin:"+e+" error","-")})},r.prototype.process=function(e,t,n){try{if(n){var i=new t;i.apply&&i.apply(this.collect,this.config),console.log("excude "+e+" success")}else t&&t(this.collect,this.config)}catch(o){this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"Extend Process Fail",level:"error",time:Date.now(),data:o.message}),console.log("excude "+e+" error, message:"+o.message)}},r.prototype.loadPlugin=function(e,t,n,i){var o=this;try{var a=document.createElement("script");a.src=t,this._plugin[e]||(this._plugin[e]=[]),this._plugin[e].push(n),a.onerror=function(){i(t)},a.onload=function(){o._plugin[e].forEach(function(s){s()})},document.getElementsByTagName("head")[0].appendChild(a)}catch(s){this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"Extend LoadPlugin Fail",level:"error",time:Date.now(),data:s.message})}},r}(),$_=function(){function r(){this.autotrack=!1,this.spa=!1,this.cache={},this.allowHash=!1}return r.prototype.apply=function(e,t){if(t.spa||t.autotrack){var n=e.Types;this.collect=e,this.config=t,this.appid=t.app_id,this.allowHash=t.allow_hash,this.fncArray=new Map,this.setKey(),this.setLocation(),this.hack(),this.init(),this.listener(),e.emit(n.RouteReady)}},r.prototype.setKey=function(){var e=this.collect.adapters.storage;this.storage=new e(!1),this.cache_key="__tea_cache_refer_"+this.appid,this.cache={refer_key:"",refer_title:document.title||location.pathname,refer_manual_key:"",routeChange:!1},this.config.autotrack&&typeof this.config.autotrack=="object"&&this.config.autotrack.page_manual_key&&(this.cache.refer_manual_key=this.config.autotrack.page_manual_key),this.storage.setItem(this.cache_key,this.cache)},r.prototype.hack=function(){var e=this,t=window.history.pushState;history.pushState=function(i){for(var o=[],a=1;a<arguments.length;a++)o[a-1]=arguments[a];typeof history.onpushstate=="function"&&history.onpushstate({state:i});var s=t.call.apply(t,Ur([history,i],o));if(e.collect.sdkStop||e.collect.destroy)return s;if(!(e.lastLocation===location.href||e.config.disable_spa_query&&e.pathEquel())){e.setReferCache(e.lastLocation);var u=e.getPopStateChangeEventData();return e.lastLocation=location.href,e.sendPv(u,"pushState"),s}};var n=history.replaceState;history.replaceState=function(i){for(var o=[],a=1;a<arguments.length;a++)o[a-1]=arguments[a];typeof history.onreplacestate=="function"&&history.onreplacestate({state:i});var s=n.call.apply(n,Ur([history,i],o));if(e.collect.sdkStop||e.collect.destroy)return s;if(!(e.lastLocation===location.href||e.config.disable_spa_query&&e.pathEquel())){e.setReferCache(e.lastLocation);var u=e.getPopStateChangeEventData();return e.lastLocation=location.href,e.sendPv(u),s}}},r.prototype.setLocation=function(){typeof window<"u"&&(this.lastLocation=window.location.href)},r.prototype.getLocation=function(){return this.lastLocation},r.prototype.pathEquel=function(){try{return new URL(this.lastLocation).origin+new URL(this.lastLocation).pathname===new URL(location.href).origin+new URL(location.href).pathname}catch{return!1}},r.prototype.init=function(){var e=this.getPopStateChangeEventData();this.collect.emit("route-change",{config:e,init:!0})},r.prototype.listener=function(){var e=this;window.addEventListener("hashchange",function(t){if(!e.collect.sdkStop&&!e.collect.destroy&&e.lastLocation!==window.location.href&&(!e.config.disable_spa_query||!e.pathEquel())&&e.allowHash){e.setReferCache(e.lastLocation),e.lastLocation=window.location.href;var n=e.getPopStateChangeEventData();e.sendPv(n)}}),window.addEventListener("popstate",function(t){if(!e.collect.sdkStop&&!e.collect.destroy&&!(e.lastLocation===window.location.href||e.config.disable_spa_query&&e.pathEquel())){e.setReferCache(e.lastLocation),e.lastLocation=window.location.href;var n=e.getPopStateChangeEventData();e.sendPv(n)}})},r.prototype.getPopStateChangeEventData=function(){var e=this.pageConfig();return e.is_back=0,e},r.prototype.pageConfig=function(){try{var e=this.storage.getItem(this.cache_key)||{},t=!1,n=this.storage.getItem("__tea_cache_first_"+this.appid);return t=!n||n!=1,{is_html:1,url:location.href,referrer:this.handleRefer(),page_key:location.href,refer_page_key:this.handleRefer(),page_title:document.title||location.pathname,page_manual_key:this.config.autotrack&&this.config.autotrack.page_manual_key||"",refer_page_manual_key:e&&e.refer_manual_key||"",refer_page_title:e&&e.refer_title||"",page_path:location.pathname,page_host:location.host,is_first_time:""+t}}catch(i){return this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"something error",level:"error",time:Date.now(),data:i.message}),{}}},r.prototype.sendPv=function(e,t){this.collect.emit("route-change",{config:e,init:!1})},r.prototype.handleRefer=function(){var e="";try{var t=this.storage.getItem(this.cache_key)||{};e=t.routeChange?t.refer_key:this.collect.configManager.get("referrer")}catch{e=document.referrer}return e},r.prototype.removeQuery=function(e){try{var t=new URL(e);return t.search="",t.href}catch{return e.split(/[?#]/)[0]}},r.prototype.setReferCache=function(e){var t=this.storage.getItem(this.cache_key)||{},n=this.removeQuery(e);t.refer_key=n,t.routeChange=!0,this.storage.setItem(this.cache_key,t)},r}(),q_=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;this.collect=e,this.config=t;var i=e.Types;e.on(i.TrackDurationStart,function(o){n.trackEventStart(o)}),e.on(i.TrackDurationEnd,function(o){n.trackEventEnd(o)}),e.on(i.TrackDurationPause,function(o){n.trackEventPause(o)}),e.on(i.TrackDurationResume,function(o){n.trackEventResume(o)}),this.Types=i,this.TrackEventMap=new Map,this.ready(i.TrackDuration)},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var n=this.collect.hook._hooksCache[e];if(!Object.keys(n).length)return;var i=function(a){n[a].length&&n[a].forEach(function(s){t.collect.hook.emit(a,s)})};for(var o in n)i(o)}},r.prototype.trackEventStart=function(e){this.TrackEventMap.set(e,{startTime:Date.now(),isPause:!1,pauseTime:0,resumeTime:0})},r.prototype.trackEventEnd=function(e){var t=e.eventName,n=e.params;if(this.TrackEventMap.has(t)){var i=this.TrackEventMap.get(t),o=0;o=i.isPause?i.pauseTime-i.startTime:i.resumeTime?i.pauseTime-i.startTime+(Date.now()-i.resumeTime):Date.now()-i.startTime;var a=Object.assign(n,{event_duration:o});this.collect.event(t,a),this.cleanEventTrack(t)}},r.prototype.trackEventPause=function(e){if(this.TrackEventMap.has(e)){var t=this.TrackEventMap.get(e);t.isPause||(t.isPause=!0,t.pauseTime=Date.now(),this.TrackEventMap.set(e,t))}},r.prototype.trackEventResume=function(e){if(this.TrackEventMap.has(e)){var t=this.TrackEventMap.get(e);t.isPause&&(t.isPause=!1,t.resumeTime=Date.now(),this.TrackEventMap.set(e,t))}},r.prototype.cleanEventTrack=function(e){this.TrackEventMap.delete(e)},r}();et.usePlugin(H_,"extend"),et.usePlugin(S_,"et"),et.usePlugin(j_,"retry"),et.usePlugin(y_,"ab"),et.usePlugin(w_,"stay"),et.usePlugin(F_,"autotrack"),et.usePlugin(q_,"trackeventduration"),et.usePlugin(C_,"heartbeat"),et.usePlugin(k_,"monitor"),et.usePlugin($_,"route"),et.usePlugin(V_,"tracer");var cn=new et("default");const vo="VEPUSHER_DEVICE_ID",yo="VEPUSHER_USER_ID",Oc=r=>Math.floor((Math.random()*9+1)*Math.pow(10,r-1)).toString();function K_(r){const e={};if(!(r instanceof Object))throw new Error("params type error");for(const[t,n]of Object.entries(r))if(["string","number","boolean"].includes(typeof n))e[t]=n;else try{e[t]=JSON.stringify(n)}catch(i){console.error("serialize error",i)}return e}function W_(r){if(r)return localStorage.setItem(yo,r),r;const e=localStorage.getItem(yo);if(e)return e;const t=Oc(12);return localStorage.setItem(yo,t),r}function J_(r){if(r)return localStorage.setItem(vo,r),r;const e=localStorage.getItem(vo);if(e)return e;const t=Oc(11);return localStorage.setItem(vo,t),t}const J={PUSHER_INIT:"pusher_init",SET_PROPERTY_CALL:"set_property_call",SET_VIDEO_QUALITY:"set_video_quality",SET_AUDIO_QUALITY:"set_audio_quality",PAGE_VISIBLE_CHANGE:"page_visible_change",PUSHER_DESTROY:"pusher_destroy",...{GET_DEVICES_RESULT:"get_devices_result",CAMERA_CAPTURE_RESULT:"camera_capture_result",MICROPHONE_CAPTURE_RESULT:"microphone_capture_result",SCREEN_CAPTURE_RESULT:"screen_capture_result",VIDEO_FILE_CAPTURE_RESULT:"video_file_capture_result",AUDIO_FILE_CAPTURE_RESULT:"audio_file_capture_result",IMAGE_FILE_CAPTURE_RESULT:"image_file_capture_result",VOLUME_DETECTOR_START_RESULT:"volume_detector_start_result",STOP_CAPTURE:"stop_capture"},...{SWITCH_ENABLE_MIXING:"switch_enable_mixing",SET_MIXING_CONFIG:"set_mixing_config",ADD_VIDEO_STREAM:"add_video_stream",UPDATE_VIDEO_STREAM:"update_video_stream",DELETE_VIDEO_STREAM:"delete_video_stream",CHANGE_VIDEO_STREAM_MUTE:"change_video_stream_mute",ADD_AUDIO_STREAM:"add_audio_stream",UPDATE_AUDIO_STREAM:"update_audio_stream",DELETE_AUDIO_STREAM:"delete_audio_stream",CHANGE_AUDIO_STREAM_MUTE:"change_audio_stream_mute"},...{START_PUSH:"start_push",STOP_PUSH_STREAM:"stop_push_stream",STOP_PUSH_STREAM_API_CALL:"stop_push_stream_api_call",START_PUSH_STATUS:"start_push_status",PUSH_RECONNECT_START:"push_reconnect_start",PUSH_RECONNECT_STATUS:"push_reconnect_status",PUSH_STATS:"push_stats",PUSH_AUDIO_CONTEXT_START_FAILED:"push_audio_context_start_failed",PUSH_RTC_STATE_CHANGE:"push_rtc_state_change",PUSH_SDP_INFO:"push_sdp_info"}};class X_{constructor({showLogInConsole:e=!1}){this._showLogInConsole=!1,this.markCollectTeaEventReady=()=>{this.isReady=!0,cn.start(),this.queueTeaEvent.forEach(t=>this.sendTeaEvent(...t)),this.queueTeaEvent=[]},this.configTea=(t,n)=>{const i={...t,evtParams:{page_url_fe:encodeURIComponent(window.location.href)||"",page_path_fe:window.location.pathname||"unknown",page_host_fe:window.location.hostname||"unknown",sdk_version:"2.0.3",build_version:"1.0.0.127",...n}};cn.config(i),this.markCollectTeaEventReady()},this.isReady=!1,this.queueTeaEvent=[],cn.init({app_id:778494,channel:"sg"}),this._showLogInConsole=e}sendTeaEvent(e,t,n=!1){if(e)if(this.isReady)try{const i={...K_(t||{})};cn.event(e,i),this._showLogInConsole&&!n&&console.log("[VePusher logger]:",e,i)}catch(i){console.error(i)}else this._showLogInConsole&&!n&&console.log("[VePusher logger]:",e,t),this.queueTeaEvent.push([e,t])}getIsReady(){return this.isReady}getRawTea(){return cn}}let un;function Z_({showLogInConsole:r}){un=new X_({showLogInConsole:r})}function X(r,e,t=!1){un&&un.sendTeaEvent(r,e,t)}function Y_(r,e){un&&un.configTea(r,e)}const Pc=()=>{X(J.PAGE_VISIBLE_CHANGE,{page_visible:!document.hidden})},Q_=()=>{document.addEventListener("visibilitychange",Pc)},ev=()=>{document.removeEventListener("visibilitychange",Pc)};function vr(r){var e;return{error:r,error_code:r.code,error_message:r.message,original_error_message:(e=r.error)==null?void 0:e.message}}class tv extends Mt{constructor(e){super(),this._videoConstraints={width:1080,height:720,frameRate:30},this._cameraStreams={},this._screenStreams={},this._videoFileStreams={},this._microphoneStreams={},this._audioFileStreams={},this._imageStreams={},this._customVideoStreams={},this._customAudioStreams={};const{width:t,height:n,frameRate:i}=pr(vs,"video"),{sampleRate:o}=pr(ys,"audio");this._videoConstraints={width:t,height:n,frameRate:i},this._audioConstraints={sampleRate:o,enableAutoGainControl:!0,enableNoiseSuppression:!0,enableEchoCancellation:!0},this._livePusher=e}_notifyCaptured(e){this.emit(dt.DeviceCaptured,e)}_notifyStopCapture(e){this.emit(dt.DeviceStopCapture,e)}_bindStreamEvent(e){e.bindTrackEnd(()=>{this.emit(dt.Interrupted,e),this.stopCapture({streamId:e.id,type:e.type})})}_handleError(e,t){const n=new fr(t,e.message);this.emit(dt.Error,n)}setVideoResolution(e){this._videoConstraints={...this._videoConstraints,...e}}setVideoFps(e){this._videoConstraints={...this._videoConstraints,frameRate:e}}setAudioSampleRate(e){this._audioConstraints={...this._audioConstraints,sampleRate:e}}async getDevicesList(e){try{const t=await El(e?[e]:["audioinput","videoinput"]);return X(J.GET_DEVICES_RESULT,{type:e,is_success:!0,devices:t}),t}catch(t){return X(J.GET_DEVICES_RESULT,{type:e,is_success:!1,error:t,origin_error:t.error,error_code:t.code,error_message:t.message}),[]}}async getMicrophones(){return this.getDevicesList("audioinput")}async getCameras(){return this.getDevicesList("videoinput")}stopCapture({streamId:e,type:t}){let n;switch(t){case ae.Camera:n="_cameraStreams";break;case ae.Screen:n="_screenStreams";break;case ae.VideoFile:n="_videoFileStreams";break;case ae.Microphone:n="_microphoneStreams";break;case ae.AudioFile:n="_audioFileStreams";break;case ae.Image:n="_imageStreams";break;case ae.CustomVideo:n="_customVideoStreams";break;case ae.CustomAudio:n="_customAudioStreams";break}if(n){let i=[];if(e){const o=this[n][e];i.push(o)}else i=kt(this[n]);X(J.STOP_CAPTURE,{stream_id:e,type:t,number:i.length}),i.forEach(o=>{this._notifyStopCapture(o),o.destroy(),delete this[n][o.id]})}}async startCameraCapture(e){let t={};Bm.includes(e)?t={facingMode:e}:e&&(t={deviceId:{exact:e}});const n={...t,...this._videoConstraints};try{const i=await wl(n,!this._livePusher.isEnableMixing),o=new Jl(i,{frameRate:this._videoConstraints.frameRate});return this._cameraStreams[o.id]=o,this._notifyCaptured(o),this._bindStreamEvent(o),X(J.CAMERA_CAPTURE_RESULT,{is_success:!0,stream_id:o.id,device_id:e,capture_params:n}),o.id}catch(i){throw X(J.CAMERA_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:n,...vr(i)}),this._handleError(i,qe.OPEN_CAMERA_FAILED),i}}async startMicrophoneCapture(e){let t={};e&&(t={deviceId:{exact:e}});const n={...this._audioConstraints,...t};try{const i=await kl(n),o=new Mm(i);return this._microphoneStreams[o.id]=o,this._notifyCaptured(o),this._bindStreamEvent(o),X(J.MICROPHONE_CAPTURE_RESULT,{is_success:!0,stream_id:o.id,device_id:e,capture_params:n}),o.id}catch(i){throw X(J.MICROPHONE_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:n,...vr(i)}),this._handleError(i,qe.OPEN_MICROPHONE_FAILED),i}}async startScreenCapture(e){const t={audio:e,video:this._videoConstraints};try{const n=await Tl(t,void 0,!this._livePusher.isEnableMixing),i=new Pm(n,{frameRate:this._videoConstraints.frameRate});return this._screenStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),X(J.SCREEN_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,capture_params:t}),i.id}catch(n){throw X(J.SCREEN_CAPTURE_RESULT,{is_success:!1,capture_params:t,...vr(n)}),this._handleError(n,qe.OPEN_SCREEN_FAILED),n}}async startVideoFileCapture(e){try{const t=await Gs({url:e,video:!0,audio:!0,loop:!0}),n=new Om(t);return this._videoFileStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),X(J.VIDEO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,file_url:e}),n.id}catch(t){throw this._handleError(t,qe.VIDEO_FILE_CAPTURE_FAILED),X(J.VIDEO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...vr(t)}),t}}async startAudioFileCapture(e){try{const t=await Gs({url:e,video:!1,audio:!0,loop:!0}),n=new Lm(t);return this._audioFileStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),X(J.AUDIO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,file_url:e}),n.id}catch(t){throw X(J.AUDIO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...vr(t)}),this._handleError(t,qe.AUDIO_FILE_CAPTURE_FAILED),t}}async startImageCapture(e){try{const t=await Cl({url:e,width:0,height:0,frameRate:30}),n=new Um(t);return this._imageStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),X(J.IMAGE_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,file_url:e}),n.id}catch(t){throw X(J.IMAGE_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...vr(t)}),this._handleError(t,qe.IMAGE_FILE_CAPTURE_FAILED),t}}startCustomVideoCapture(e){const t=Rl(e);if(t){const n=new Gm(t);return this._customVideoStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),n.id}}startCustomAudioCapture(e){const t=Al(e);if(t){const n=new Nm(t);return this._customAudioStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),n.id}}async startVolumeDetect(e){const t=this.getStreamById(e);if(t)try{await t.startVolumeDetect(),X(J.VOLUME_DETECTOR_START_RESULT,{is_success:!0,stream_id:t.id})}catch(n){X(J.VOLUME_DETECTOR_START_RESULT,{is_success:!1,stream_id:t.id,error_message:n.message}),this._handleError(n,qe.VOLUME_DETECT_FAILED)}}stopVolumeDetect(e){const t=this.getStreamById(e);t&&t.stopVolumeDetect()}getDefaultVideoStream(){return kt(this._cameraStreams)[0]||kt(this._screenStreams)[0]||kt(this._videoFileStreams)[0]||kt(this._imageStreams)[0]||kt(this._customVideoStreams)[0]}getDefaultAudioStream(){return kt(this._microphoneStreams)[0]||kt(this._audioFileStreams)[0]||kt(this._customAudioStreams)[0]}getVideoStream(e){return this._cameraStreams[e]||this._screenStreams[e]||this._videoFileStreams[e]||this._imageStreams[e]||this._customVideoStreams[e]}getAudioStream(e){return this._microphoneStreams[e]||this._audioFileStreams[e]||this._customAudioStreams[e]}getStreamById(e){return this.getAudioStream(e)||this.getVideoStream(e)}getVolume(e){const t=this.getStreamById(e);return(t==null?void 0:t.volume)||0}destroy(){Object.values(ae).forEach(e=>{this.stopCapture({type:e})})}}let Bt=class{constructor(e){this._enabled=!1,this.group=(...t)=>{this._enabled&&console.group(`[${this._prefix}]: `,...t)},this.groupCollapsed=(...t)=>{this._enabled&&console.groupCollapsed(`[${this._prefix}]: `,...t)},this.groupEnd=()=>{this._enabled&&console.groupEnd()},this.log=(...t)=>{this._enabled&&console.log(`[${this._prefix}]: `,...t)},this.warn=(...t)=>{this._enabled&&console.warn(`[${this._prefix}]: `,...t)},this.error=(...t)=>{this._enabled&&console.error(`[${this._prefix}]: `,...t)},this.table=(...t)=>{this._enabled&&console.table(...t)},this._prefix=e;try{this._enabled=location.href.indexOf("rtmdebug")!==-1}catch{}}};class So{constructor({streamManagerController:e,composedStream:t,streamComposeController:n}){this._streamManagerController=e,this._composedStream=t,this._streamComposeController=n,this._active=!1,this.bindStreamManagerControllerEvent()}bindStreamManagerControllerEvent(){this._streamManagerController.on(dt.DeviceCaptured,e=>{this._active&&this.onStreamCapture(e)}),this._streamManagerController.on(dt.DeviceStopCapture,e=>{this._active&&this.onStreamStopCapture(e)})}getComposedStream(){return this._composedStream}enable(){this._active=!0}disable(){this._active=!1}}const Lc=new Bt("SingleComposer");class rv extends So{onStreamCapture(e){e.isVideoStream?this._handleVideoStreamCapture(e):this._handleAudioStreamCapture(e)}onStreamStopCapture(e){e&&(e.isVideoStream?this._handleVideoStreamStopCapture(e):this._handleAudioStreamStopCapture(e))}enable(){if(super.enable(),this._composedStream.videoStream){const e=this._streamManagerController.getDefaultVideoStream();e&&this._handleVideoStreamCapture(e)}}async setVideoQuality({width:e,height:t,frameRate:n}){var i,o;if(this._active)try{await((o=(i=this._composedStream.videoStream)==null?void 0:i.videoTrack)==null?void 0:o.applyConstraints({width:{min:e,ideal:e},height:{min:t,ideal:t},frameRate:{min:n,ideal:n}}))}catch(a){Lc.error("setVideoQuality error",a)}}_handleVideoStreamCapture(e){const t=this._composedStream.videoStream;t!=null&&t.id&&this._streamComposeController.getMixerComposer().haveMixedStream(t.id)&&this._streamComposeController.removeAudioStream(t.id),e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100}),this._composedStream.setVideoStream(e)}_handleAudioStreamCapture(e){const t=this._streamComposeController.getMixerComposer().getMixedStreamByType(e.type);t.length>0&&t.forEach(n=>{this._streamComposeController.removeAudioStream(n.id)}),this._streamComposeController.addAudioStream({streamId:e.id,volume:100})}_handleVideoStreamStopCapture(e){const t=this._composedStream.videoStream;if((t==null?void 0:t.id)===e.id){const n=this._streamManagerController.getDefaultVideoStream();n?this._handleVideoStreamCapture(n):Lc.error("all video stream stop capture")}}muteVideoStream(){var e;(e=this._composedStream.videoStream)!=null&&e.videoTrack&&(this._composedStream.videoStream.videoTrack.enabled=!1)}unmuteVideoStream(){var e;(e=this._composedStream.videoStream)!=null&&e.videoTrack&&(this._composedStream.videoStream.videoTrack.enabled=!0)}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class nv extends Mt{constructor(e,{width:t,height:n,x:i,y:o,zOrder:a,keepRatio:s,mirrorType:u}){super(),this._rect={x:0,y:0,width:0,height:0,zOrder:0},this._isHidden=!1,this._paintSize={width:0,height:0},this._rect.width=t??e.width,this._rect.height=n??e.height,this._rect.x=i??0,this._rect.y=o??0,this._rect.zOrder=a??0,this._rect.sourceHeight=e.height,this._rect.sourceWidth=e.width,this._rect.keepRatio=s??!1,this._rect.mirrorType=u,this._stream=e,this._bindVideoTrackSizeChange()}_getPaintSize({elementWidth:e,elementHeight:t}){const n=this._rect.width,i=this._rect.height;if(n===0&&i===0)return{width:0,height:0};if(n===0)return{height:i,width:e*(i/t)};if(i===0)return{width:n,height:t*(n/e)};const o=e/t,a=n/i;let s=n,u=i;return o>a?(s=n,u=2*Math.round(n/o/2)):o<a&&(s=2*Math.round(i*o/2),u=i),{width:s,height:u}}_bindVideoTrackSizeChange(){this._stream.on(_s.SizeChange,({width:e,height:t})=>{this.setBaseProps("sourceWidth",e),this.setBaseProps("sourceHeight",t)})}getViewNode(){var i;if(!this._stream)return;let e={width:this._rect.width,height:this._rect.height};this._rect.keepRatio&&(e=this._getPaintSize({elementWidth:this._stream.width,elementHeight:this._stream.height})),this._paintSize=e;const t=(i=this._stream.viewNode)==null?void 0:i.size(e.width,e.height);let n;return this._rect.mirrorType!==void 0&&this._rect.mirrorType!==hs.None?n=t==null?void 0:t.mirror(this._rect.mirrorType):n=t,n=n==null?void 0:n.position(this._rect.x,this._rect.y),n}get x(){return this._rect.x}set x(e){this.setBaseProps("x",e)}get y(){return this._rect.y}set y(e){this.setBaseProps("y",e)}get width(){return this._rect.width}set width(e){this.setBaseProps("width",e)}get height(){return this._rect.height}set height(e){this.setBaseProps("height",e)}get zOrder(){return this._rect.zOrder}set zOrder(e){this.setBaseProps("zOrder",e)}get keepRatio(){return this._rect.keepRatio??!1}set keepRatio(e){this.setBaseProps("keepRatio",e)}set mirrorType(e){this.setBaseProps("mirrorType",e)}get paintSize(){return this._paintSize}setBaseProps(e,t){const n=this._rect[e]!==t;switch(e){case"width":this._rect.width=t;break;case"height":this._rect.height=t;break;case"x":this._rect.x=t;break;case"y":this._rect.y=t;break;case"zOrder":this._rect.zOrder=t;break;case"keepRatio":this._rect.keepRatio=t;break;case"mirrorType":this._rect.mirrorType=t;break}n&&this.emit("propsChange",{[e]:t})}show(){this._isHidden=!1}hide(){this._isHidden=!0}get stream(){return this._stream}get isHidden(){return this._isHidden}destroy(){}}class Uc extends ur{constructor(e,t){super({type:ae.MixVideo,stream:e}),this._trackMap.video=e,this._frameRate=(t==null?void 0:t.frameRate)??1}get source(){return this._source}replaceVideoTrack(e){this._trackMap.video=e,this._source=e}get viewNode(){return null}get mixerNode(){return null}bindTrackEnd(e){this.source.onended=e}destroy(){this.source.stop(),delete this._trackMap.video}}var iv=Object.defineProperty,ov=Object.getOwnPropertyDescriptor,dn=(r,e,t,n)=>{for(var i=ov(e,t),o=r.length-1,a;o>=0;o--)(a=r[o])&&(i=a(e,t,i)||i);return i&&iv(e,t,i),i};const Gc=new Bt("composition-composer");function ln(r,e,t){const n=t.value;return t.value=function(...i){return this._active||Gc.error("composer is not active"),n.apply(this,i)},t}class yr extends So{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new Hl}onStreamCapture(e){}onStreamStopCapture(e){e&&e.isVideoStream&&this.removeVideoStream(e.id)}enable(){var n;if(this._active)return;super.enable();const e=this._videoMixer.track(),t=this._mixedVideoStream;this._mixedVideoStream=new Uc(e,{frameRate:this._compositionViewConfig.frameRate}),this._composedStream.setVideoStream(this._mixedVideoStream),t&&((n=t.videoTrack)==null?void 0:n.id)!==e.id&&t.destroy()}disable(){super.disable(),this._videoMixer.stop()}_updateSpriteToMixer(){const e=xa(this._sprites.map(t=>t.isHidden?null:t.getViewNode()));this._videoMixer.draw(e)}_removeSprite(e){this._sprites=this._sprites.filter(t=>t!==e),e.destroy(),this._updateSpriteToMixer()}_addSprite(e){this._sprites.push(e),this._sprites=this._sprites.sort((t,n)=>t.zOrder-n.zOrder),e.on("propsChange",t=>{xm(t.zOrder)||(this._sprites=this._sprites.sort((n,i)=>n.zOrder-i.zOrder)),this._updateSpriteToMixer()}),this._updateSpriteToMixer()}setMixingConfig(e){const t=e.frameRate&&e.frameRate!==this._compositionViewConfig.frameRate;if(this._compositionViewConfig={...this._compositionViewConfig,...e},this._compositionViewConfig.frameRate<1&&(this._compositionViewConfig.frameRate=1),this._videoMixer.updateConfig(this._compositionViewConfig),t&&this._mixedVideoStream){const n=this._mixedVideoStream,i=this._videoMixer.updateFps();this._mixedVideoStream=new Uc(i,{frameRate:this._compositionViewConfig.frameRate}),this._composedStream.setVideoStream(this._mixedVideoStream),n.destroy()}}getMixingConfig(){return this._compositionViewConfig}addVideoStream(e,t){if(!e.viewNode){Gc.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const n=new nv(e,t);this._addSprite(n)}_updateSingleVideoStream(e){const t=e.streamId;if(!t)return;const n=this._sprites.find(i=>i.stream.id===t);n&&(n.height=e.height,n.width=e.width,n.x=e.x,n.y=e.y,n.zOrder=e.zOrder,n.keepRatio=e.keepRatio??!1,n.mirrorType=e.mirrorType)}updateVideoStream(e){e.forEach(t=>{this._updateSingleVideoStream(t)}),this._updateSpriteToMixer()}removeVideoStream(e){if(!e)return;const t=this._sprites.find(n=>n.stream.id===e);t&&this._removeSprite(t)}muteVideoStream(e){if(e){const t=this._sprites.find(n=>n.stream.id===e);t&&t.hide()}else this._sprites.forEach(t=>{t.hide()});this._updateSpriteToMixer()}unmuteVideoStream(e){if(e){const t=this._sprites.find(n=>n.stream.id===e);t&&t.show()}else this._sprites.forEach(t=>{t.show()});this._updateSpriteToMixer()}setMixerWorkerScript(e){this._videoMixer.setWorkerTimerScriptUrl(e)}getVideoStreamRenderConfig(e){const t=this._sprites.find(n=>n.stream.id===e);if(t)return{width:t.width,height:t.height,paintWidth:t.paintSize.width,paintHeight:t.paintSize.height,x:t.x,y:t.y,zOrder:t.zOrder}}getDrawCountPerSecond(){return this._videoMixer.getDrawCountPerSecond()}}dn([ln],yr.prototype,"addVideoStream"),dn([ln],yr.prototype,"updateVideoStream"),dn([ln],yr.prototype,"removeVideoStream"),dn([ln],yr.prototype,"muteVideoStream"),dn([ln],yr.prototype,"unmuteVideoStream");class sv extends Mt{constructor(e,{volume:t}){super(),this._volume=100,this._isMute=!1,this._volume=t??100,this._stream=e}get volume(){return this._volume}set volume(e){const t=this._volume!==e;this._volume=e,t&&this.emit("propsChange",{volume:e})}getMixerNode(){var e;return(e=this._stream.mixerNode)==null?void 0:e.gain(this._volume/100)}mute(){this._isMute=!0}unmute(){this._isMute=!1}get isMute(){return this._isMute}get stream(){return this._stream}}class av extends kn{constructor(e){super({type:ae.MixAudio,stream:e}),this._trackMap.audio=e}get source(){return this._source}hasVideoTrack(){return!1}get mixerNode(){return null}bindTrackEnd(e){this.source.onended=e}destroy(){var e;(e=this._trackMap.audio)==null||e.stop(),delete this._trackMap.audio}}class cv extends So{constructor(e){super(e),this._spriteList=[],this._audioMixer=new Il({keepAlive:!0})}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=xa(this._spriteList.map(t=>t.isMute?null:t.getMixerNode()));this._audioMixer.mix(e)}_updateSingleAudioStream(e){const{streamId:t,volume:n}=e,i=this._spriteList.find(o=>o.stream.id===t);i?n!==void 0&&(i.volume=n):console.error("can not find stream"+t)}enable(){super.enable();const e=this._audioMixer.track(),t=new av(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}resumeMixer(){this._audioMixer.resume()}addAudioStream(e,t){const n=new sv(e,t);this._spriteList.push(n),this._updateSpriteToMixer()}tryResume(){return this._audioMixer.resume()}removeAudioStream(e){const t=this._spriteList.find(n=>n.stream.id===e);t&&(this._spriteList=this._spriteList.filter(n=>n!==t),this._updateSpriteToMixer())}updateAudioStream(e){e.forEach(t=>{this._updateSingleAudioStream(t)}),this._updateSpriteToMixer()}muteAudioStream(e){if(e){const t=this._spriteList.find(n=>n.stream.id===e);t&&t.mute()}else this._spriteList.forEach(t=>{t.mute()});this._updateSpriteToMixer()}unmuteAudioStream(e){if(e){const t=this._spriteList.find(n=>n.stream.id===e);t&&t.unmute()}else this._spriteList.forEach(t=>{t.unmute()});this._updateSpriteToMixer()}haveMixedStream(e){return this._spriteList.some(t=>t.stream.id===e)}getMixedStreamByType(e){return this._spriteList.filter(t=>t.stream.type===e).map(t=>t.stream)}}class uv extends Mt{constructor({videoStream:e,audioStream:t}={}){super(),this._videoStream=e,this._audioStream=t}setVideoStream(e){var t;((t=this._videoStream)==null?void 0:t.id)!==(e==null?void 0:e.id)&&(this._videoStream=e,this.emit(qt.VideoStreamChange,e))}setAudioStream(e){var t;((t=this._audioStream)==null?void 0:t.id)!==e.id&&(this._audioStream=e,this.emit(qt.AudioStreamChange,e))}get audioStream(){return this._audioStream}get videoStream(){return this._videoStream}get videoTrack(){var e;return(e=this._videoStream)==null?void 0:e.videoTrack}get audioTrack(){var e;return(e=this._audioStream)==null?void 0:e.audioTrack}}const dv=new Bt("streamComposeController");class lv{constructor(e){this._streamManagerController=e,this._composedStream=new uv,this.singleComposer=new rv({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new yr({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new cv({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.singleComposer.enable(),this.mixerComposer.enable()}enableMixing(e){e?(this.compositionComposer.enable(),this.singleComposer.disable()):(this.compositionComposer.disable(),this.singleComposer.enable())}setVideoQuality({width:e,height:t,frameRate:n}){this.singleComposer.setVideoQuality({width:e,height:t,frameRate:n}),this.compositionComposer.setMixingConfig({width:e,height:t,frameRate:n})}setMixingConfig(e){this.compositionComposer.setMixingConfig(e)}getMixingConfig(){return this.compositionComposer.getMixingConfig()}addAudioStream(e){const t=this._streamManagerController.getStreamById(e.streamId);this.mixerComposer.addAudioStream(t,{volume:e.volume??100})}removeAudioStream(e){return this.mixerComposer.removeAudioStream(e)}updateAudioStream(e){this.mixerComposer.updateAudioStream(e)}addVideoStream(e){const t=this._streamManagerController.getVideoStream(e.streamId);if(!t){dv.error("can not find video stream"+e.streamId);return}this.compositionComposer.addVideoStream(t,e)}updateVideoStream(e){this.compositionComposer.updateVideoStream(e);const t=e.map(n=>({streamId:n.streamId,volume:n.volume}));this.mixerComposer.updateAudioStream(t)}removeVideoStream(e){this.compositionComposer.removeVideoStream(e),this.mixerComposer.removeAudioStream(e)}getComposer(){return this.isEnableMixing?this.compositionComposer:this.singleComposer}getComposedStream(){return this._composedStream}muteVideoStream(e){this.isEnableMixing?this.compositionComposer.muteVideoStream(e):this.singleComposer.muteVideoStream()}unmuteVideoStream(e){this.isEnableMixing?this.compositionComposer.unmuteVideoStream(e):this.singleComposer.unmuteVideoStream()}muteAudioStream(e){this.mixerComposer.muteAudioStream(e)}unmuteAudioStream(e){this.mixerComposer.unmuteAudioStream(e)}get isEnableMixing(){return this.compositionComposer._active}getMixerComposer(){return this.mixerComposer}setMixerWorkerScript(e){this.compositionComposer.setMixerWorkerScript(e)}getVideoStreamRenderConfig(e){if(this.compositionComposer._active)return this.compositionComposer.getVideoStreamRenderConfig(e)}resumeMixer(){return this.mixerComposer.tryResume()}getCompositionDrawCountPerSecond(){return this.compositionComposer.getDrawCountPerSecond()}}class Nc{constructor(e){this._hasBindComposedStreamEvent=!1,this._composedStream=e}bindComposedStreamEvent(){this._hasBindComposedStreamEvent||(this._composedStream.on(qt.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.on(qt.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!0)}unbindComposedStreamEvent(){this._hasBindComposedStreamEvent&&(this._composedStream.off(qt.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.off(qt.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!1)}}const Sr=new Bt("PreviewConsumer");class hv extends Nc{constructor(e,{streamConsumeController:t}){super(e),this._isPreviewing=!1,this._previewElement=null,this.handleAudioStreamChange=n=>{this.startPreview()},this.handleVideoStreamChange=n=>{this.startPreview()},this._streamConsumeController=t}start(){this.bindComposedStreamEvent()}stop(){this.unbindComposedStreamEvent()}setRenderView(e){if(!e)return;const t=document.getElementById(e);if(!t)throw new Error(`can not found element with id ${e}`);if(t===this._previewElement)return;if(this._previewElement){if(t.contains(this._previewElement))return;t.appendChild(this._previewElement);return}const n=document.createElement("video");n.style.width="100%",n.style.height="100%",n.autoplay=!0,n.playsInline=!0,n.setAttribute("webkit-playsinline",""),n.setAttribute("x5-playsinline",""),this._previewElement=n;const i={video:null,audio:null};n.addEventListener("loadeddata",()=>{const o=n.srcObject.getVideoTracks()[0],a=n.srcObject.getAudioTracks()[0];o&&o!==i.video&&(this._streamConsumeController.emit(Ee.CaptureFirstVideoFrame),i.video=o),a&&a!==i.audio&&(this._streamConsumeController.emit(Ee.CaptureFirstAudioFrame),i.audio=a)}),t.appendChild(n)}startPreview(){if(Sr.log("startPreview"),!this._previewElement){Sr.warn("preview element not found");return}this._isPreviewing||this.start();const e=this._composedStream.audioTrack,t=this._composedStream.videoTrack;e&&(this._appendTrack(this._previewElement,e),this._removeTrack(this._previewElement,null)),t&&(this._appendTrack(this._previewElement,t),this._removeTrack(this._previewElement,null)),this._previewElement.play().catch(n=>{this._streamConsumeController.emit(Ee.NotAllowedAutoPlay)}),this._isPreviewing=!0}stopPreview(){this._isPreviewing=!1;const e=this._composedStream.audioTrack,t=this._composedStream.videoTrack;e&&this._removeTrack(this._previewElement,e),t&&this._removeTrack(this._previewElement,t),this.stop()}destroy(){this.stopPreview(),this._previewElement=null,this.unbindComposedStreamEvent()}_appendTrack(e,t){if(!e||!t)return;const n=e.srcObject||new MediaStream;n.getTracks().find(i=>i.id===t.id)||(t.kind==="audio"&&n.getTracks().forEach(i=>{i.kind==="audio"&&(Sr.log(`remove preview track, ${i.label}, readyState=${i.readyState}`),n.removeTrack(i))}),t.kind==="video"&&n.getTracks().forEach(i=>{i.kind==="video"&&(n.removeTrack(i),Sr.log(`remove preview track, ${i.label}, readyState=${i.readyState}`))}),n.addTrack(t),e.srcObject?e.load():e.srcObject=n)}_removeTrack(e,t){if(!e)return;const n=e.srcObject;n&&(n.getTracks().forEach(i=>{(i.id===(t==null?void 0:t.id)||i.readyState==="ended")&&(Sr.log(`remove preview track ${i.label}`),n.removeTrack(i))}),n.getTracks().length===0&&(e.srcObject=null,Sr.log("set srcObject null")))}getPreviewElement(){if(this.isPreviewing)return this._previewElement}get isPreviewing(){return this._isPreviewing}}var ot={},bo={},Eo={exports:{}},Bc;function wo(){if(Bc)return Eo.exports;Bc=1;var r=Eo.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(r).forEach(function(e){var t=r[e];t.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),Eo.exports}var Fc;function fv(){return Fc||(Fc=1,function(r){var e=function(s){return String(Number(s))===s?Number(s):s},t=function(s,u,c,d){if(d&&!c)u[d]=e(s[1]);else for(var f=0;f<c.length;f+=1)s[f+1]!=null&&(u[c[f]]=e(s[f+1]))},n=function(s,u,c){var d=s.name&&s.names;s.push&&!u[s.push]?u[s.push]=[]:d&&!u[s.name]&&(u[s.name]={});var f=s.push?{}:d?u[s.name]:u;t(c.match(s.reg),f,s.names,s.name),s.push&&u[s.push].push(f)},i=wo(),o=RegExp.prototype.test.bind(/^([a-z])=(.*)/);r.parse=function(s){var u={},c=[],d=u;return s.split(/(\r\n|\r|\n)/).filter(o).forEach(function(f){var h=f[0],g=f.slice(2);h==="m"&&(c.push({rtp:[],fmtp:[]}),d=c[c.length-1]);for(var k=0;k<(i[h]||[]).length;k+=1){var z=i[h][k];if(z.reg.test(g))return n(z,d,g)}}),u.media=c,u};var a=function(s,u){var c=u.split(/=(.+)/,2);return c.length===2?s[c[0]]=e(c[1]):c.length===1&&u.length>1&&(s[c[0]]=void 0),s};r.parseParams=function(s){return s.split(/;\s?/).reduce(a,{})},r.parseFmtpConfig=r.parseParams,r.parsePayloads=function(s){return s.toString().split(" ").map(Number)},r.parseRemoteCandidates=function(s){for(var u=[],c=s.split(" ").map(e),d=0;d<c.length;d+=3)u.push({component:c[d],ip:c[d+1],port:c[d+2]});return u},r.parseImageAttributes=function(s){return s.split(" ").map(function(u){return u.substring(1,u.length-1).split(",").reduce(a,{})})},r.parseSimulcastStreamList=function(s){return s.split(";").map(function(u){return u.split(",").map(function(c){var d,f=!1;return c[0]!=="~"?d=e(c):(d=e(c.substring(1,c.length)),f=!0),{scid:d,paused:f}})})}}(bo)),bo}var Co,Vc;function pv(){if(Vc)return Co;Vc=1;var r=wo(),e=/%[sdv%]/g,t=function(a){var s=1,u=arguments,c=u.length;return a.replace(e,function(d){if(s>=c)return d;var f=u[s];switch(s+=1,d){case"%%":return"%";case"%s":return String(f);case"%d":return Number(f);case"%v":return""}})},n=function(a,s,u){var c=s.format instanceof Function?s.format(s.push?u:u[s.name]):s.format,d=[a+"="+c];if(s.names)for(var f=0;f<s.names.length;f+=1){var h=s.names[f];s.name?d.push(u[s.name][h]):d.push(u[s.names[f]])}else d.push(u[s.name]);return t.apply(null,d)},i=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];return Co=function(a,s){s=s||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(f){f.payloads==null&&(f.payloads="")});var u=s.outerOrder||i,c=s.innerOrder||o,d=[];return u.forEach(function(f){r[f].forEach(function(h){h.name in a&&a[h.name]!=null?d.push(n(f,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(g){d.push(n(f,h,g))})})}),a.media.forEach(function(f){d.push(n("m",r.m[0],f)),c.forEach(function(h){r[h].forEach(function(g){g.name in f&&f[g.name]!=null?d.push(n(h,g,f)):g.push in f&&f[g.push]!=null&&f[g.push].forEach(function(k){d.push(n(h,g,k))})})})}),d.join(`\r
66
+ }`,t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.appendChild(document.createTextNode(e)),t.appendChild(n);var i=document.createElement("div");i.innerHTML='<div id="debugger-applog-web" class="debugger-applog-web"></div>';var o=document.createElement("div");o.innerHTML='<div id="debugger-container" class="debugger-container"></div>',document.getElementsByTagName("body")[0].appendChild(i),document.getElementsByTagName("body")[0].appendChild(o);var a=document.getElementById("debugger-applog-web");a&&a.addEventListener("click",function(){window&&window.postMessage({type:"devtool:web:open-draw"},location.origin)})},r}(),ho={autotrack:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/autotrack.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/autotrack.js"},object:"LogAutoTrack"},ab:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/ab.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/ab.js"},object:"LogAb"},stay:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/stay.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/stay.js"},object:"LogStay"},route:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/route.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/route.js"},object:"LogRoute"},tracer:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/tracer.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/tracer.js"},object:"LogTracer"},retry:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/retry.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/retry.js"},object:"LogRetry"},visual:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/visual.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/visual.js"},object:"LogVisual"}},__=["ab","autotrack","Stay","store","et","profile","cep","heartbeat","monitor","route","tracer"],et=function(){function r(e){this.disableAutoPageView=!1,this.bridgeReport=!1,this.staging=!1,this.pluginInstances=[],this.sended=!1,this.started=!1,this.destroy=!1,this.sdkReady=!1,this.adapters={},this.loadType="base",this.sdkStop=!1,this.name=e,this.hook=new $m,this.remotePlugin=new Map,this.Types=F,this.adapters.storage=Xt,this.loadType="full"}return r.usePlugin=function(e,t,n){if(t){for(var i=!1,o=0,a=r.plugins.length;o<a;o++)if(r.plugins[o].name===t){r.plugins[o].plugin=e,r.plugins[o].options=n||{},i=!0;break}i||r.plugins.push({name:t,plugin:e,options:n})}else r.plugins.push({plugin:e})},r.prototype.usePlugin=function(e,t,n){e&&(this.loadType==="full"&&__.includes(e)?console.info("your sdk version has "+e+" already ~"):t?typeof t=="string"?this.remotePlugin.get(e)||this.remotePlugin.set(e,{src:t,call:n}):this.remotePlugin.get(e)||this.remotePlugin.set(e,{instance:t}):this.remotePlugin.get(e)||this.remotePlugin.set(e,"sdk"))},r.prototype.init=function(e){var t,n,i=this;try{t=JSON.parse(JSON.stringify(e))}catch{t=e}if(this.logger=new ag(this.name,t.log),this.inited)this.logger.warn("[instance: "+this.name+"], every instance's api: init, can be call only one time!");else if(t&&Gr(t))if(t.app_id&&typeof(n=t.app_id)=="number"&&!isNaN(n))if(!t.app_key||function(o){return typeof o=="string"}(t.app_key)){if(t.channel_domain||(t.report_channel!=="eu_ttp_ie"&&t.channel!=="ie"||this.logger.error("ie dc will be deprecated in the future, please use other dc instead"),t.report_channel&&!Ga().has(t.report_channel)?(this.logger.warn("your report_channel: "+t.report_channel+" is not exist. report_channel must be one of "+qi().join(",")+", use default report_channel: us_east instead, please check!!!"),t.report_channel="us_east"):t.report_channel||["sg","va","in","my","ie","ie2"].indexOf(t.channel)!==-1||(this.logger.warn("your channel: "+t.channel+" is not exist. use report_channel instead and report_channel must be one of "+qi().join(",")+", use default report_channel: us_east instead, please check!!!"),t.report_channel="us_east"),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK set channel warning",level:"error",time:Date.now(),data:"your report_channel: "+t.channel+" is not exist. report_channel must be one of "+qi().join(",")+", use us_east instead, please check!!!",infoType:"sdk"})),this.spider=new cg,this.spider.checkSpider(t))return this.logger.warn("The current environment may be a spider, can not report!"),void this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK hit spider",level:"error",time:Date.now(),data:"The current environment may be a spider, can not report!",infoType:"sdk"});this.appBridge=new ug(this,t.enable_native),this.requestManager=new m_(this,t),this.bridgeReport=this.appBridge.bridgeInject(),this.configManager=new sg(this,t),this.debugger=new g_(this,t),this.initConfig=t,this.emit(F.Init),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Init",data:t,level:"info",time:Date.now(),infoType:"cus"}),t.disable_auto_pv&&(this.disableAutoPageView=!0),this.bridgeReport||(this.configManager.setAppid(t.app_id),this.eventManager=new lg,this.tokenManager=new hg,this.sessionManager=new fg,Promise.all([new Promise(function(o){i.once(F.TokenComplete,function(){o(!0)})}),new Promise(function(o){i.once(F.Start,function(){o(!0)})}),new Promise(function(o){i.once(F.LogSettingReady,function(){o(!0)})})]).then(function(){try{r.plugins.reduce(function(o,a){var s=a.plugin,u=a.options,c=Object.assign(i.initConfig,u);i.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Load "+a.name+" Plugin",level:"info",time:Date.now(),infoType:"sdk"});var d=new s;return d.apply(i,c),o.push(d),o},i.pluginInstances)}catch(o){console.warn("load plugin error, "+o.message),i.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Load Plugin Error",level:"error",time:Date.now(),data:o.message,infoType:"sdk"})}i.sdkReady=!0,i.emit(F.Ready),i.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK UserInfo Init Completed",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"}),i.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Initialization Completed",time:Date.now(),level:"info",data:i.configManager.get("user"),infoType:"sdk"}),i.logger.info("appid: "+t.app_id+", userInfo:"+JSON.stringify(i.configManager.get("user"))),i.logger.info("appid: "+t.app_id+", sdk is ready, version is "+Vr+", you can report now !!!"),t.disable_auto_pv&&(i.disableAutoPageView=!0);try{(i.loadType==="full"&&t.enable_ab_test||t.autotrack)&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")}catch(o){i.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"Something Error",level:"error",time:Date.now(),data:o.message,infoType:"sdk"})}i.pageView(),i.on(F.TokenChange,function(o){o==="webid"&&i.pageView(),i.logger.info("appid: "+t.app_id+" token change, new userInfo:"+JSON.stringify(i.configManager.get("user"))),i.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Set UserInfo",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(F.TokenReset,function(){i.logger.info("appid: "+t.app_id+" token reset, new userInfo:"+JSON.stringify(i.configManager.get("user"))),i.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Reset UserInfo",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(F.RouteChange,function(o){o.init||t.disable_route_report||i.pageView()})}),this.tokenManager.apply(this,t),this.eventManager.apply(this,t),this.sessionManager.apply(this,t)),this.inited=!0}else this.logger.warn("app_key param is error, must be string, please check!");else this.logger.warn("app_id param is error, must be number, please check!");else this.logger.warn("init params error,please check")},r.prototype.config=function(e){if(!this.inited)return console.warn("config must be use after function init"),void this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Config Error",level:"error",time:Date.now(),data:"config must be use after function init",infoType:"sdk"});if(!e||!Gr(e))return console.warn("config params is error, please check"),void this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Config Error",level:"error",time:Date.now(),data:"config params is error, please check",infoType:"sdk"});var t;try{t=JSON.parse(JSON.stringify(t))}catch{t=e}if(this.bridgeReport)this.appBridge.setConfig(t);else{t._staging_flag&&t._staging_flag===1&&(this.staging=!0),t.disable_auto_pv&&(this.disableAutoPageView=!0,delete t.disable_auto_pv);var n=me({},t);if(this.initConfig&&this.initConfig.configPersist){var i=this.configManager.getStore();i&&(n=Object.assign(i,t)),this.configManager.setStore(t)}n.web_id,n.user_unique_id,n.device_id;var o=function(a,s){var u={};for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&s.indexOf(c)<0&&(u[c]=a[c]);if(a!=null&&typeof Object.getOwnPropertySymbols=="function"){var d=0;for(c=Object.getOwnPropertySymbols(a);d<c.length;d++)s.indexOf(c[d])<0&&(u[c[d]]=a[c[d]])}return u}(n,["web_id","user_unique_id","device_id"]);n.hasOwnProperty("web_id")&&this.emit(F.ConfigWebId,n.web_id),n.hasOwnProperty("user_unique_id")&&this.emit(F.ConfigUuid,n.user_unique_id),n.hasOwnProperty("device_id")&&this.emit(F.ConfigDiD,n.device_id),this.configManager.set(o),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Config",level:"info",time:Date.now(),data:n,infoType:"cus"})}},r.prototype.setDomain=function(e){this.configManager&&this.configManager.setDomain(e),this.emit(F.ConfigDomain)},r.prototype.getConfig=function(e){return this.configManager.get(e)},r.prototype.send=function(){this.start()},r.prototype.start=function(){this.inited&&!this.sended&&(this.sended=!0,this.emit(F.Start),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Start",level:"info",time:Date.now(),infoType:"cus"}),this.bridgeReport&&(this.pageView(),this.emit(F.Ready)))},r.prototype.event=function(e,t){var n=this;try{var i=[];if(Array.isArray(e))e.forEach(function(a){var s=n.processEvent(a[0],a[1]||{});s&&i.push(s)});else{var o=this.processEvent(e,t);if(!o)return;i.push(o)}this.bridgeReport?i.forEach(function(a){var s=a.event,u=a.params;n.appBridge.onEventV3(s,JSON.stringify(u))}):i.length&&(this.emit(F.Event,i),this.emit(F.SessionResetTime)),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Event",level:"info",time:Date.now(),data:e,infoType:"cus"})}catch(a){this.logger.warn("something error, please check"),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Event Something Error",level:"error",time:Date.now(),data:a.message,infoType:"sdk"})}},r.prototype.beconEvent=function(e,t){if(Array.isArray(e))return this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK BeconEvent Error",level:"error",time:Date.now(),data:"beconEvent not support batch report, please check",infoType:"sdk"}),void this.logger.warn("beconEvent not support batch report, please check");var n=[],i=this.processEvent(e,t||{});i&&(n.push(i),n.length&&(this.emit(F.BeconEvent,n),this.emit(F.SessionResetTime)),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Beacon Event",level:"info",time:Date.now(),data:e,infoType:"sdk"}))},r.prototype.beaconEvent=function(e,t){this.beconEvent(e,t)},r.prototype.processEvent=function(e,t){t===void 0&&(t={});try{if(!e)return console.warn("eventName is null, please check"),null;var n=e;/^event\./.test(e)&&(n=e.slice(6));var i=t;typeof i!="object"&&(i={}),i.profile?delete i.profile:i.event_index=qm();var o=void 0;return i.local_ms?(o=i.local_ms,delete i.local_ms):o=+new Date,{event:n,params:i,local_time_ms:o,is_bav:this.initConfig&&this.initConfig.autotrack?1:0}}catch(a){return this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:a.message,infoType:"sdk"}),{event:e,params:t}}},r.prototype.filterEvent=function(e){this.eventFilter=e},r.prototype.on=function(e,t){this.hook.on(e,t)},r.prototype.once=function(e,t){this.hook.once(e,t)},r.prototype.off=function(e,t){this.hook.off(e,t)},r.prototype.emit=function(e,t,n){this.hook.emit(e,t,n)},r.prototype.set=function(e){this.hook.set(e)},r.prototype.stop=function(){this.sdkStop=!0},r.prototype.reStart=function(){this.sdkStop=!1},r.prototype.pageView=function(){this.disableAutoPageView||this.predefinePageView()},r.prototype.predefinePageView=function(e){if(e===void 0&&(e={}),this.inited){var t={title:document.title||location.pathname,url:location.href,url_path:location.pathname,time:Date.now(),referrer:window.document.referrer,$is_first_time:""+(this.configManager&&this.configManager.is_first_time||!1)},n=me(me({},t),e);this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Report PV",level:"info",time:Date.now(),infoType:"sdk"}),this.event("predefine_pageview",n)}else console.warn("predefinePageView should call after init")},r.prototype.clearEventCache=function(){this.emit(F.CleanEvents)},r.prototype.setWebId=function(e){this.config({web_id:""+e})},r.prototype.setNativeAppId=function(e){this.bridgeReport&&this.appBridge.setNativeAppId(e)},r.prototype.getSessionId=function(){return jr()},r.prototype.setSessionId=function(e){this.emit(F.SessionReset,e)},r.prototype.resetStayDuration=function(e,t,n){this.emit(F.ResetStay,{url_path:e,title:t,url:n},F.Stay)},r.prototype.resetStayParams=function(e,t,n){e===void 0&&(e=""),t===void 0&&(t=""),n===void 0&&(n=""),this.emit(F.SetStay,{url_path:e,title:t,url:n},F.Stay)},r.prototype.getToken=function(e,t){var n=this;if(this.inited){var i=!1,o=function(s){if(!i){i=!0;var u=n.configManager.get().user;return s&&(u.tobid=s,u["diss".split("").reverse().join("")]=s),e(me({},u))}},a=function(){n.tokenManager.getTobId().then(function(s){o(s)})};this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute GetToken",level:"info",time:Date.now(),infoType:"cus"}),this.sdkReady?a():(t&&setTimeout(function(){o()},t),this.on(F.Ready,function(){a()}))}else console.warn("predefinePageView should call after init")},r.prototype.startTrackEvent=function(e){e&&this.emit(F.TrackEventDurationStart,e,F.TrackEventDuration)},r.prototype.endTrackEvent=function(e,t){t===void 0&&(t={}),e&&this.emit(F.TrackEventDurationEnd,{eventName:e,params:t},F.TrackEventDuration)},r.prototype.pauseTrackEvent=function(e){e&&this.emit(F.TrackEventDurationPause,e,F.TrackEventDuration)},r.prototype.resumeTrackEvent=function(e){e&&this.emit(F.TrackEventDurationResume,e,F.TrackEventDuration)},r.prototype.profileSet=function(e){this.bridgeReport?this.appBridge.profileSet(JSON.stringify(e)):this.emit(F.ProfileSet,e,F.Profile),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileSet",level:"info",time:Date.now(),data:e})},r.prototype.profileSetOnce=function(e){this.bridgeReport?this.appBridge.profileSetOnce(JSON.stringify(e)):this.emit(F.ProfileSetOnce,e,F.Profile),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileSetOnce",level:"info",time:Date.now(),data:e})},r.prototype.profileIncrement=function(e){this.bridgeReport?this.appBridge.profileIncrement(JSON.stringify(e)):this.emit(F.ProfileIncrement,e,F.Profile),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileIncrement",level:"info",time:Date.now(),data:e})},r.prototype.profileUnset=function(e){this.bridgeReport?this.appBridge.profileUnset(e):this.emit(F.ProfileUnset,e,F.Profile),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileUnset",level:"info",time:Date.now(),data:e})},r.prototype.profileAppend=function(e){this.bridgeReport?this.appBridge.profileAppend(JSON.stringify(e)):this.emit(F.ProfileAppend,e,F.Profile),this.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileAppend",level:"info",time:Date.now(),data:e})},r.prototype.setExternalAbVersion=function(e){this.emit(F.AbExternalVersion,typeof e=="string"&&e?(""+e).trim():null,F.Ab)},r.prototype.getVar=function(e,t,n,i){this.emit(F.AbVar,{name:e,defaultValue:t,callback:n,uuid:i},F.Ab)},r.prototype.getABconfig=function(e,t){this.emit(F.AbConfig,{params:e,callback:t},F.Ab)},r.prototype.getABConfig=function(e,t){this.emit(F.AbConfig,{params:e,callback:t},F.Ab)},r.prototype.getAbSdkVersion=function(){return this.configManager.getAbVersion()},r.prototype.onAbSdkVersionChange=function(e){var t=this;return this.emit(F.AbVersionChangeOn,e,F.Ab),function(){t.emit(F.AbVersionChangeOff,e,F.Ab)}},r.prototype.offAbSdkVersionChange=function(e){this.emit(F.AbVersionChangeOff,e,F.Ab)},r.prototype.openOverlayer=function(){this.emit(F.AbOpenLayer,"",F.Ab)},r.prototype.closeOverlayer=function(){this.emit(F.AbCloseLayer,"",F.Ab)},r.prototype.getAllVars=function(e,t){this.emit(F.AbAllVars,{callback:e,timeout:t},F.Ab)},r.prototype.destoryInstace=function(){this.destroy||(this.destroy=!0,this.off(F.TokenComplete),this.emit(F.DestoryInstance))},r.prototype.destroyInstance=function(){this.destroy||(this.destroy=!0,this.off(F.TokenComplete),this.emit(F.DestoryInstance))},r.plugins=[],r}(),on={},Rc=[];function Ac(r,e,t,n){var i=r&&r.source||window.opener||window.parent,o=r&&r.origin||n||window.location.origin,a={type:e,payload:t};i.postMessage(JSON.stringify(a),o)}function v_(r){if(Rc.some(function(i){return r.origin.indexOf(i)>-1})){var e=r.data;if(typeof r.data=="string")try{e=JSON.parse(r.data)}catch{e=void 0}if(!e)return;var t=e.type,n=e.payload;on[t]&&on[t].forEach(function(i){typeof i=="function"&&i(r,n)})}}var sn,fo="__rangers_ab_style__";(function(r){r[r.Var=0]="Var",r[r.All=1]="All"})(sn||(sn={}));var y_=function(){function r(){this.fetchStatus="no",this.refreshFetchStatus="no",this.versions=[],this.extVersions=[],this.mulilinkVersions=[],this.enable_multilink=!1,this.enable_ab_visual=!1,this.editMode=!1,this.callbacks=[],this.data={},this.changeListener=new Map,this.readyStatus=!1,this.exposureCache=[],this.fetchQueueMap=new Map}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,this.config.enable_ab_test){var i=t.enable_multilink,o=t.ab_channel_domain,a=t.enable_ab_visual,s=t.ab_cross,u=t.ab_cookie_domain,c=t.ab_timeout,d=t.disable_auto_ab,f=Ki[t.channel||"sg"]||Ki.sg,h=o||Nr(f),g=e.adapters.storage;this.cacheStorgae=new g(!1),this.timeout=c||3e3,this.enable_multilink=i,this.enable_ab_visual=a,this.abKey="__tea_sdk_ab_version_"+t.app_id,this.ab_cross=s,this.ab_cookie_domain=u||"",this.fetchUrl=h+"/service/2/abtest_config/",this.reportUrl=this.collect.configManager.getUrl("event"),this.exposureLimit=t.exposure_limit||20,this.ab_batch_time=t.ab_batch_time||500,this.ab_user_mode=t.ab_user_mode||"user_unique_id",this.callbackMap=new Map,this.fetchQueueMap=new Map;var k=this.collect.Types;this.types=k,this.collect.on(k.TokenChange,function(z){z==="uuid"&&n.readyStatus&&(n.clearCache(),n.fetchAB())}),this.collect.on(k.AbVar,function(z){var w=z.name,b=z.defaultValue,T=z.callback;n.getVar(w,b,T)}),this.collect.on(k.AbAllVars,function(z){var w=z.callback,b=z.timeout;n.getAllVars(w,b)}),this.collect.on(k.AbConfig,function(z){var w=z.params,b=z.callback;n.getABconfig(w,b)}),this.collect.on(k.AbExternalVersion,function(z){n.setExternalAbVersion(z)}),this.collect.on(k.AbOpenLayer,function(){n.openOverlayer()}),this.collect.on(k.AbCloseLayer,function(){n.closeOverlayer()}),this.collect.on(k.AbVersionChangeOn,function(z){n.changeListener.set(z,z)}),this.collect.on(k.AbVersionChangeOff,function(z){n.changeListener.get(z)&&n.changeListener.delete(z)}),this.loadMode(),(this.enable_ab_visual||this.enable_multilink)&&this.openOverlayer(this.config.multilink_timeout_ms||500),this.checkLocal(),this.ready("ab"),this.readyStatus||(!d&&this.fetchAB(),this.readyStatus=!0),this.collect.emit(k.AbReady)}},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var n=this.collect.hook._hooksCache[e];if(!Object.keys(n).length)return;var i=function(a){n[a].length&&n[a].forEach(function(s){t.collect.hook.emit(a,s)})};for(var o in n)i(o)}},r.prototype.loadMode=function(){var e=function(){try{var o=JSON.parse(atob(window.name));return o||void 0}catch{return}}(),t="";if(e){var n=e.scenario,i=e.href;n?(this.editMode=!0,t=n):!i||i.indexOf("datatester")===-1&&i.indexOf("visual-editor")===-1||(this.editMode=!0,t="visual-editor")}this.enable_ab_visual&&t==="visual-editor"&&this.collect.destoryInstace()},r.prototype.checkLocal=function(){var e=this.getABCache(),t=e.ab_version,n=e.ab_ext_version,i=e.ab_version_multilink,o=(e.data,this.checkFromUrl());o?this.mulilinkVersions.push(o):this.mulilinkVersions=i||[],this.extVersions=n||[],this.versions=t||[];var a=this.versions.concat(this.extVersions);this.enable_multilink&&(a=a.concat(this.mulilinkVersions))},r.prototype.checkFromUrl=function(){var e=On(window.location.href);return e&&e.vid?e.vid:""},r.prototype.updateVersions=function(){var e=this.extVersions.length?this.versions.concat(this.extVersions):this.versions;this.enable_multilink&&(e=e.concat(this.mulilinkVersions)),this.configVersions(e.join(",")),this.updateABCache(),this.changeListener.size>0&&this.changeListener.forEach(function(t){typeof t=="function"&&t(e)})},r.prototype.configVersions=function(e){this.collect.configManager.setAbVersion(e)},r.prototype.getVar=function(e,t,n,i){if(!e)throw new Error("getVar key must not be empty");if(t===void 0&&console.warn("getVar defaultValue is illegal, please check!"),typeof n!="function")throw new Error("getVar callback must be a function");var o={name:e,defaultValue:t,callback:n,type:sn.Var};this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetVar",level:"info",time:Date.now(),data:e,infoType:"cus"}),this.fetchStatus==="complete"&&this.refreshFetchStatus==="complete"?this.getRealVar(o,e,i):this.callbackMap.set(e,o)},r.prototype.setAbUuid=function(e,t){this.collect.configManager.setAbUuidCache(e,t)},r.prototype.getRealVar=function(e,t,n){var i=e.name,o=e.defaultValue,a=e.callback,s=this.data;if(s){var u=s[i];if(u&&Gr(u)){var c=u.vid;return t==="$ab_url"?this.mulilinkVersions.includes(c)||this.mulilinkVersions.push(c):this.versions.includes(c)||this.versions.push(c),this.setAbUuid(c,n),this.updateVersions(),this.fechEvent(c,t||i,o,a,u.val),void this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetVar, Exposure Experiment "+i,level:"info",time:Date.now(),data:s[i],infoType:"sdk"})}this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GerVar Default Callback",level:"info",time:Date.now(),data:this.data,infoType:"sdk"}),a(o)}else a(o)},r.prototype.getAllVars=function(e,t){var n=this;if(typeof e!="function")throw new Error("getAllVars callback must be a function");var i=null,o={callback:e,type:sn.All,timer:i};this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetAllVars",level:"info",time:Date.now(),infoType:"cus"}),t&&(i=setTimeout(function(){o.timer=null,n.getRealAllVars(o),clearTimeout(i)},t),o.timer=i),this.fetchStatus==="complete"&&this.refreshFetchStatus==="complete"?(o.timer=null,this.getRealAllVars(o),i&&clearTimeout(i)):this.callbackMap.set("allVars",o)},r.prototype.getRealAllVars=function(e,t){var n=e.callback,i=e.timer;i&&(clearTimeout(i),e.timer=null);var o=(t??this.data)||{};try{n(JSON.parse(JSON.stringify(o)))}catch{n(o)}this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetAllVars Callback",level:"info",time:Date.now(),data:this.data,infoType:"sdk"})},r.prototype.fechEvent=function(e,t,n,i,o){try{if(this.config.disable_track_event||!e)return;var a=this.collect.configManager.get(),s=a.header,u=a.user,c=this.getABCache(),d=u[this.ab_user_mode]||u.user_unique_id;if(c&&c.uuid&&c.uuid!==d)return;var f={event:"abtest_exposure",ab_sdk_version:""+e,params:JSON.stringify({app_id:this.config.appId,ab_url:t==="$ab_url"?n:window.location.href,data:this.data}),local_time_ms:Date.now()};s.custom=JSON.stringify(s.custom);var h={events:[f],user:u,header:s};this.reportExposure(h,t),i&&i(o)}catch(g){this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:g.message,infoType:"sdk"})}},r.prototype.reportExposure=function(e,t){var n=this;this.exposureCache.push(e),this.reportTimeout&&clearTimeout(this.reportTimeout),this.exposureCache.length>=this.exposureLimit?this.report(t):this.reportTimeout=setTimeout(function(){n.report(t),clearTimeout(n.reportTimeout)},this.ab_batch_time)},r.prototype.report=function(e){var t=this;this.collect.requestManager.useRequest({url:this.reportUrl,data:this.exposureCache,timeout:2e4,useBeacon:e==="$ab_url",zip:!0}),this.exposureCache.forEach(function(n){t.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_EVENT,info:"SDK Report Exposure Event Success",time:Date.now(),data:[n],code:200,status:"success",infoType:"sdk"})}),this.collect.emit(this.types.AbVerify,[this.exposureCache]),this.exposureCache=[]},r.prototype.setExternalAbVersion=function(e){this.extVersions=[e],this.updateVersions()},r.prototype.getABconfig=function(e,t){var n=Object.keys(e);n&&n.length&&this.collect.configManager.set(e),this.fetchAB(t)},r.prototype.get=function(e){return this.cacheStorgae.getItem(e)},r.prototype.set=function(e,t){this.cacheStorgae.setItem(e,t),this.collect.configManager.setAbCache(t)},r.prototype.getABCache=function(e){var t={ab_version:[],ab_ext_version:[],ab_version_multilink:[],data:null,timestamp:+new Date,uuid:""};return t=this.get(this.abKey)||t,e?t[e]:t},r.prototype.updateABCache=function(){var e=this.getABCache();e.ab_version_multilink=this.mulilinkVersions,e.ab_ext_version=this.extVersions,e.ab_version=this.versions,e.timestamp=Date.now(),this.set(this.abKey,e)},r.prototype.setAbCache=function(e){var t=this.getABCache();t.data=this.data,t.uuid=e,t.timestamp=Date.now(),this.set(this.abKey,t)},r.prototype.clearCache=function(){this.refreshFetchStatus="ing",this.data={},this.extVersions=[],this.mulilinkVersions=[],this.versions=[],this.collect.configManager.clearAbCache()},r.prototype.openOverlayer=function(e){var t=this;if(function(){if(!document.getElementById(fo)){var i="body { opacity: 0 !important; }",o=document.head||document.getElementsByTagName("head")[0],a=document.createElement("style");a.id=fo,a.type="text/css",a.styleSheet?a.styleSheet.cssText=i:a.appendChild(document.createTextNode(i)),o.appendChild(a)}}(),e)var n=setTimeout(function(){t.closeOverlayer(),clearTimeout(n)},e)},r.prototype.closeOverlayer=function(){var e;(e=document.getElementById(fo))&&e.parentElement.removeChild(e)},r.prototype.fetchComplete=function(e,t){var n=this;this.changeFetchQueueStatus(t);try{if(e&&Object.prototype.toString.call(e)=="[object Object]"){var i=this.collect.configManager.get().user;if(t&&t!==i.user_unique_id)return;this.data=e,this.setAbCache(t);var o=[];Object.keys(e).forEach(function(d){var f=e[d].vid;f&&o.push(f)}),this.versions=this.versions.filter(function(d){return o.includes(d)});var a=e.$ab_url,s=e.$ab_modification;if(s&&s.val&&this.enable_ab_visual){if(this.collect.destroy)return}else if(a&&this.enable_multilink){this.mulilinkVersions=this.mulilinkVersions.filter(function(d){return o.includes(d)});var u=a.val,c=a.vid;u&&c&&this.getVar("$ab_url",u,function(){n.editMode||(u!==window.location.href?setTimeout(function(){if(!n.collect.destroy){var d=""+u;d=d.indexOf("http")===-1?"https://"+d:d,Ni(d).host!==location.host?d=d+"&vid="+c:window.history.replaceState("","",d),window.location.href=d}},100):n.closeOverlayer())})}this.updateVersions()}else this.closeOverlayer();this.callbackMap.forEach(function(d){d.type===sn.Var?n.getRealVar(d,""):n.getRealAllVars(d,e)})}catch{}},r.prototype.pushFetchToQueue=function(e){var t=e,n=this.fetchQueueMap.get(t);n?n.fetchStatus="ing":n={current_user_id:t,fetchStatus:"ing"},this.fetchQueueMap.set(t,n)},r.prototype.changeFetchQueueStatus=function(e){var t=this.fetchQueueMap.get(e);t&&(t.fetchStatus="complete",this.fetchQueueMap.set(e,t))},r.prototype.checkFetchQueueStatus=function(){if(this.fetchQueueMap.size===0)return!1;var e=!0;return this.fetchQueueMap.forEach(function(t){t.fetchStatus!=="complete"&&(e=!1)}),e},r.prototype.clearFetchQueue=function(e){this.fetchQueueMap.delete(e)},r.prototype.fetchAB=function(e){var t=this,n=this.collect.configManager.get(),i={header:me(me(me({aid:this.config.app_id},n.user||{}),n.header||{}),{ab_sdk_version:this.collect.configManager.getAbVersion(),ab_url:window.location.href})};this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch AB Request",level:"info",logType:"fetch",time:Date.now(),data:i,infoType:"sdk"});var o=n.user[this.ab_user_mode]||n.user.user_unique_id;this.pushFetchToQueue(o),this.collect.requestManager.useRequest({url:this.fetchUrl,data:i,success:function(a){t.fetchStatus="complete",t.refreshFetchStatus="complete";var s=a.data;a.message==="success"?(t.fetchComplete(s,o),e&&e(s)):(t.fetchComplete(null,o),e&&e(null)),t.collect.emit(t.types.AbComplete,s),t.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Fetch AB Request Success",level:"info",logType:"fetch",time:Date.now(),data:s,infoType:"sdk"})},fail:function(){t.fetchStatus="complete",t.refreshFetchStatus="complete",t.fetchComplete(null,o),t.collect.emit(t.types.AbTimeout),e&&e(null),t.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Fetch AB Request Network Error",level:"error",logType:"fetch",time:Date.now(),infoType:"sdk"})},timeout:this.timeout})},r.prototype.filterUrl=function(e){try{var t="";e.indexOf("&multilink=true")!==-1?t="&multilink=true[\0-ÿ]*":e.indexOf("?multilink=true")!==-1&&(t="\\?multilink=true[\0-ÿ]*");var n=new RegExp(t,"g");e=e.replace(n,"")}catch{}return e},r}(),S_=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,t.event_verify_url)if(typeof t.event_verify_url=="string"){if(this.url=t.event_verify_url+"/v1/list_test",this.url){var i=e.Types;e.on(i.SubmitVerify,function(o){n.verify(o)}),e.on(i.AbVerify,function(o){n.verify(o)})}}else console.log("please use correct et_test url")},r.prototype.verify=function(e){var t=this;e.forEach(function(n){try{var i=JSON.parse(JSON.stringify(n));t.config.filter&&((i=t.config.filter(i))||console.warn("filter must return data !!")),t.collect.eventFilter&&i&&((i=t.collect.eventFilter(i))||console.warn("filterEvent api must return data !!"));var o=i||n,a=JSON.parse(JSON.stringify(o));if(!o.length)return;var s=!0;if(o.forEach(function(u){u.events.length||(s=!1)}),!s)return;t.collect.requestManager.useBeacon({url:t.url,data:o}),t.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_EVENT,info:"SDK Report ByteIo Verify Request",time:Date.now(),data:a,code:200,status:"success",verifyType:!0})}catch(u){console.warn("something error, "+JSON.stringify(u.stack)),t.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Report ByteIo Verify Request Error",level:"error",time:Date.now(),data:u.message})}})},r}(),b_=function(){function r(e,t){this.maxDuration=432e5,this.aliveDTime=6e4,this.options={aliveName:"predefine_page_alive",params:{}},this.focusState=!0,this.collect=e,this.config=t,this.pageStartTime=Date.now(),this.sessionStartTime=this.pageStartTime,this.timerHandler=null,Gr(t.enable_stay_duration)&&(this.options=Object.assign(this.options,t.enable_stay_duration)),this.hard=this.options.mode&&this.options.mode==="hard",this.focusState=document.hasFocus()}return r.prototype.setParams=function(e,t,n){this.set_path=e,this.set_url=n,this.set_title=t},r.prototype.enable=function(e,t,n){this.url_path=e,this.url=n,this.title=t,this.disableCallback=this.enablePageAlive(),this.hard&&(this.removeMode=this.hardMode())},r.prototype.disable=function(){this.disableCallback(),this.pageStartTime=Date.now()},r.prototype.sendEvent=function(e,t){t===void 0&&(t=!1);var n=t?this.aliveDTime:Date.now()-this.sessionStartTime;n<0||n>this.aliveDTime||Date.now()-this.pageStartTime>this.maxDuration||t&&document.visibilityState==="hidden"||this.hard&&!this.focusState||(this.collect.beconEvent(this.options.aliveName,me({url_path:this.getParams("url_path"),title:this.getParams("title"),url:this.getParams("url"),duration:n,is_support_visibility_change:Pa(),startTime:this.sessionStartTime,hidden:document.visibilityState,leave:e,mode:this.hard?"hard":"normal",focusState:this.focusState},this.options.params)),this.sessionStartTime=Date.now())},r.prototype.getParams=function(e){switch(e){case"url_path":return this.set_path||this.url_path||location.pathname;case"title":return this.set_title||this.title||document.title||location.pathname;case"url":return this.set_url||this.url||location.href}},r.prototype.setUpTimer=function(){var e=this;return this.timerHandler&&clearInterval(this.timerHandler),setInterval(function(){Date.now()-e.sessionStartTime>e.aliveDTime&&e.sendEvent(!1,!0)},1e3)},r.prototype.visibilitychange=function(){document.visibilityState==="hidden"?this.timerHandler&&(clearInterval(this.timerHandler),this.sendEvent(!1)):document.visibilityState==="visible"&&(this.sessionStartTime=Date.now(),this.timerHandler=this.setUpTimer())},r.prototype.beforeunload=function(){document.hidden||this.sendEvent(!0)},r.prototype.enablePageAlive=function(){var e=this;this.timerHandler=this.setUpTimer();var t=this.visibilitychange.bind(this),n=this.beforeunload.bind(this);return document.addEventListener("visibilitychange",t),Br(n),function(){e.beforeunload(),document.removeEventListener("visibilitychange",t),window.removeEventListener("beforeunload",n),window.removeEventListener("pagehide",n)}},r.prototype.hardMode=function(){var e=this,t=function(){e.timerHandler&&(clearInterval(e.timerHandler),e.sendEvent(!1)),e.focusState=!1},n=function(){e.focusState=!0,e.sessionStartTime=Date.now(),e.timerHandler=e.setUpTimer()};return window.addEventListener("blur",t),window.addEventListener("focus",n),function(){window.removeEventListener("blur",t),window.removeEventListener("focus",n)}},r}(),E_=function(){function r(e,t){var n=this;this.maxDuration=432e5,this.aliveDTime=6e4,this.options={closeName:"predefine_page_close",params:{}},this.focusState=!0,this.visibilitychange=function(){document.visibilityState==="hidden"?n.activeEndTime=Date.now():document.visibilityState==="visible"&&(n.activeEndTime&&(n.totalTime+=n.activeEndTime-n.activeStartTime,n.activeTimes+=1),n.activeEndTime=void 0,n.activeStartTime=Date.now())},this.beforeunload=function(){if(n.totalTime+=(n.activeEndTime||Date.now())-n.activeStartTime,n.config.autotrack)try{window.sessionStorage.setItem("_tea_cache_duration",JSON.stringify({duration:n.totalTime,page_title:document.title||location.pathname}))}catch{}n.sendEventPageClose()},this.collect=e,this.config=t,this.maxDuration=t.maxDuration||864e5,this.pageStartTime=Date.now(),Gr(t.enable_stay_duration)&&(this.options=Object.assign(this.options,t.enable_stay_duration)),this.hard=this.options.mode&&this.options.mode==="hard",this.focusState=document.hasFocus(),this.resetData()}return r.prototype.setParams=function(e,t,n){this.set_path=e,this.set_url=n,this.set_title=t},r.prototype.resetParams=function(e,t,n){this.url_path=e,this.url=n,this.title=t},r.prototype.enable=function(e,t,n){this.url_path=e,this.url=n,this.title=t,this.disableCallback=this.enablePageClose(),this.hard&&(this.removeMode=this.hardMode())},r.prototype.disable=function(){this.disableCallback()},r.prototype.resetData=function(){this.activeStartTime=this.activeStartTime===void 0?this.pageStartTime:Date.now(),this.activeEndTime=void 0,this.activeTimes=1,this.totalTime=0,this.resetParams(location.pathname,document.title,location.href)},r.prototype.sendEventPageClose=function(){var e=Date.now()-this.pageStartTime;this.totalTime<0||e<0||this.totalTime>=this.maxDuration||this.hard&&!this.focusState||(this.collect.beconEvent(this.options.closeName,me({url_path:this.getParams("url_path"),title:this.getParams("title"),url:this.getParams("url"),active_times:this.activeTimes,duration:this.totalTime,total_duration:e,is_support_visibility_change:Pa(),mode:this.hard?"hard":"normal",focusState:this.focusState},this.options.params)),this.pageStartTime=Date.now(),this.resetData())},r.prototype.getParams=function(e){switch(e){case"url_path":return this.set_path||this.url_path||location.pathname;case"title":return this.set_title||this.title||document.title||location.pathname;case"url":return this.set_url||this.url||location.href}},r.prototype.enablePageClose=function(){var e=this,t=this.visibilitychange.bind(this),n=this.beforeunload.bind(this);return document.addEventListener("visibilitychange",t),Br(n),function(){e.beforeunload(),document.removeEventListener("visibilitychange",t),window.removeEventListener("beforeunload",n),window.removeEventListener("pagehide",n)}},r.prototype.hardMode=function(){var e=this,t=function(){e.focusState=!1},n=function(){e.focusState=!0};return window.addEventListener("blur",t),window.addEventListener("focus",n),function(){window.removeEventListener("blur",t),window.removeEventListener("focus",n)}},r}(),w_=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,this.config.enable_stay_duration){this.title=document.title||location.pathname,this.url=location.href,this.url_path=location.pathname,this.pageAlive=new b_(e,t),this.pageClose=new E_(e,t);var i=this.collect.Types;this.collect.on(i.ResetStay,function(o){var a=o.url_path,s=o.title,u=o.url;n.resetStayDuration(a,s,u)}),this.collect.on(i.RouteChange,function(o){o.init||t.disable_route_report||n.resetStayDuration()}),this.collect.on(i.SetStay,function(o){var a=o.url_path,s=o.title,u=o.url;n.setStayParmas(a,s,u)}),this.enable(this.url_path,this.title,this.url),this.ready(i.Stay),this.collect.emit(i.StayReady)}},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var n=this.collect.hook._hooksCache[e];if(!Object.keys(n).length)return;var i=function(a){n[a].length&&n[a].forEach(function(s){t.collect.hook.emit(a,s)})};for(var o in n)i(o)}},r.prototype.enable=function(e,t,n){this.pageAlive.enable(e,t,n),this.pageClose.enable(e,t,n)},r.prototype.disable=function(){this.pageAlive.disable(),this.pageClose.disable()},r.prototype.setStayParmas=function(e,t,n){e===void 0&&(e=""),t===void 0&&(t=""),n===void 0&&(n=""),this.pageAlive.setParams(e,t,n),this.pageClose.setParams(e,t,n),this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute resetStayParams",level:"info",time:Date.now(),data:{url_path:e,title:t,url:n}})},r.prototype.reset=function(e,t,n){this.disable(),this.enable(e,t,n)},r.prototype.resetStayDuration=function(e,t,n){this.reset(e,t,n),this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Execute resetStayDuration",level:"info",time:Date.now(),data:{url_path:e,title:t,url:n}})},r}(),C_=function(){function r(){var e=this;this.setInterval=function(){e.clearIntervalFunc=function(t,n){t===void 0&&(t=function(){}),n===void 0&&(n=1e3);var i,o=Date.now()+n;return i=window.setTimeout(function a(){var s=Date.now()-o;t(),o+=n,i=window.setTimeout(a,Math.max(0,n-s))},n),function(){window.clearTimeout(i)}}(function(){e.isSessionhasEvent&&e.endCurrentSession()},e.sessionInterval)},this.clearInterval=function(){e.clearIntervalFunc&&e.clearIntervalFunc()}}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,!t.disable_heartbeat){this.sessionInterval=6e4,this.startTime=0,this.lastTime=0,this.setInterval();var i=this.collect.Types;this.collect.on(i.SessionReset,function(){n.process()})}},r.prototype.endCurrentSession=function(){this.collect.event("_be_active",{start_time:this.startTime,end_time:this.lastTime,url:window.location.href,referrer:window.document.referrer,title:document.title||location.pathname}),this.isSessionhasEvent=!1,this.startTime=0},r.prototype.process=function(){this.isSessionhasEvent||(this.isSessionhasEvent=!0,this.startTime=+new Date);var e=this.lastTime||+new Date;this.lastTime=+new Date,this.lastTime-e>this.sessionInterval&&(this.clearInterval(),this.endCurrentSession(),this.setInterval())},r}(),k_=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,!this.config.channel_domain&&!t.disable_track_event&&!t.disable_sdk_monitor){this.url=e.configManager.getUrl("event");var i=this.collect.Types;this.collect.on(i.Ready,function(){n.sdkOnload()}),this.collect.on(i.SubmitError,function(o){var a=o.type,s=o.eventData,u=o.errorCode,c=o.response;a==="f_data"&&n.sdkError(s,u,c)}),this.collect.on(e.Types.SDKInnerError,function(o){var a=o.type,s=o.eventData,u=o.errorCode,c=o.msg;n.sdkInnerError(a,s,u,c)})}},r.prototype.sdkOnload=function(){var e=this;try{var t=this.collect.configManager.get(),n=t.header,i=t.user,o=n.app_id,a=n.app_name,s=n.sdk_version,u=(i.web_id,{events:[{event:"onload",params:JSON.stringify({app_id:o,app_name:a||"",sdk_version:s,sdk_type:"npm",sdk_config:this.config,sdk_desc:"TOC_OVERSEA",url:location.href,is_setting:this.config.enable_logsetting||!1,enable_logsetting_params:this.config.enable_logsetting_params||!1,enable_logsetting_header_custom:this.config.enable_logsetting_header_custom||!1}),local_time_ms:Date.now()}],user:{user_unique_id:i.user_unique_id},header:{app_id:6656}});setTimeout(function(){e.collect.requestManager.useRequest({url:e.url,data:[u],timeout:3e4,forceXhr:!0})},16)}catch{}},r.prototype.sdkError=function(e,t,n){var i=this;try{var o=e[0],a=o.user,s=o.header,u=[];e.forEach(function(d){d.events.forEach(function(f){u.push(f)})});var c={events:u.map(function(d){return{event:"on_error",params:JSON.stringify({type:"sdk_event_error",error_code:t,app_id:s.app_id,app_name:s.app_name||"",error_event:d.event,sdk_version:s.sdk_version,local_time_ms:d.local_time_ms,tea_event_index:Date.now(),params:d.params,header:s,user:a,err_msg:n.m||""}),local_time_ms:Date.now()}}),user:{user_unique_id:a.user_unique_id},header:{app_id:6656}};setTimeout(function(){i.collect.requestManager.useRequest({url:i.url,data:[c],timeout:3e4,forceXhr:!0})},16)}catch{}},r.prototype.sdkInnerError=function(e,t,n,i){var o=this;try{var a=t[0],s=a.user,u=a.header,c=[];t.forEach(function(f){f.events.forEach(function(h){c.push(h)})});var d={events:c.map(function(f){return{event:"on_error",params:JSON.stringify({type:e,error_code:n,app_id:u.app_id,app_name:u.app_name||"",error_event:f.event,sdk_version:u.sdk_version,local_time_ms:f.local_time_ms,tea_event_index:Date.now(),params:f.params,header:u,user:s,ua:window.navigator.userAgent,err_msg:i}),local_time_ms:Date.now()}}),user:s,header:{}};setTimeout(function(){o.collect.requestManager.useRequest({url:o.url,data:[d],timeout:3e4,app_key:"566f58151b0ed37e",forceXhr:!0})},16)}catch{}},r}();function po(r,e){if(e===void 0&&(e="list"),!r)return!1;if(e&&e==="list"){if(["LI","TR","DL"].includes(r.nodeName)||r.dataset&&r.dataset.hasOwnProperty("teaIdx")||r.hasAttribute&&r.hasAttribute("data-tea-idx"))return!0}else if(["A","BUTTON"].includes(r.nodeName)||r.dataset&&r.dataset.hasOwnProperty("teaContainer")||r.hasAttribute&&r.hasAttribute("data-tea-container"))return!0;return!1}function mo(r){for(var e=r;e&&!po(e,"container");){if(e.nodeName==="HTML"||e.nodeName==="BODY")return r;e=e.parentElement}return e||r}function Dc(r){var e="";return r.nodeType===3?e=r.textContent.trim():r.dataset&&r.dataset.hasOwnProperty("teaTitle")||r.hasAttribute("ata-tea-title")?e=r.getAttribute("data-tea-title"):r.hasAttribute("title")?e=r.getAttribute("title"):r.nodeName==="INPUT"&&["button","submit"].includes(r.getAttribute("type"))?e=r.getAttribute("value"):r.nodeName==="IMG"&&r.getAttribute("alt")&&(e=r.getAttribute("alt")),e.slice(0,200)}function Ic(r){for(var e=r;e&&e.parentNode;){if(e.hasAttribute("data-tea-ignore"))return!0;if(e.nodeName==="HTML"||e.nodeName==="body")return!1;e=e.parentNode}return!1}var jn=function(r,e){return r.hasAttribute?r.hasAttribute(e):r.attributes?!(!r.attributes[e]||!r.attributes[e].specified):void 0},T_=function(r,e){if(typeof e=="string")return jn(r,e);if(Gi(e)){for(var t=!1,n=0;n<e.length;n++)if(jn(r,e[n])){t=!0;break}return t}},z_=function(){function r(e,t,n){var i=this;this.statistics=!1,this.pageView=!1,this.clickEvent=function(o){(function(a,s){if(a.nodeType!==1||!s.svg&&function(c){if(c.tagName.toLowerCase()==="svg")return!0;for(var d=c.parentElement,f=!1;d;)d.tagName.toLowerCase()==="svg"?(d=null,f=!0):d=d.parentElement;return f}(a)||["HTML","BODY"].includes(a.tagName.toUpperCase()))return!1;var u=a;return u.style.display!=="none"&&(!!po(u,"container")||!(!function(c){if(c.children.length){var d=c.children;return![].slice.call(d).some(function(f){return f.children.length>0})}return!0}(u)&&!s.svg))})(o.target,i.options)&&i.eventHandel({eventType:"dom",eventName:"click"},o)},this.changeEvent=function(o){i.eventHandel({eventType:"dom",eventName:"change"},o)},this.submitEvent=function(o){i.eventHandel({eventType:"dom",eventName:"submit"},o)},this.getPageViewEvent=function(o,a){a&&a==="pushState"&&i.eventHandel({eventType:"dom",eventName:"beat"},me({beat_type:0},o)),i.eventHandel({eventType:"dom",eventName:"page_view"},o)},this.getPageLoadEvent=function(o){i.eventHandel({eventType:"dom",eventName:"page_statistics"},{lcp:o})},this.config=n.getConfig().eventConfig,this.collect=t,this.options=e,this.beatTime=e.beat}return r.prototype.init=function(e){this.eventHandel=e;var t=this.config.mode;this.addListener(t)},r.prototype.addListener=function(e){var t=this;if(e==="proxy-capturing"){if(this.config.click&&window.document.addEventListener("click",this.clickEvent,!0),this.config.change&&window.document.addEventListener("change",this.changeEvent,!0),this.config.submit&&window.document.addEventListener("submit",this.submitEvent,!0),this.config.pv){this.collect.on("route-change",function(u){var c=u.config,d=u.name;t.getPageViewEvent(c,d),t.pageView=!0});var n=setTimeout(function(){t.pageView||(t.getPageViewEvent(t.getDefaultConfig()),t.pageView=!0,clearTimeout(n))},2e3)}if(this.config.beat){try{document.readyState==="complete"?this.beatEvent(this.beatTime):window.addEventListener("load",function(){t.beatEvent(t.beatTime)});var i=0,o=null;window.addEventListener("scroll",function(){clearTimeout(o),o=setTimeout(a,500),i=document.documentElement.scrollTop||document.body.scrollTop});var a=function(){(document.documentElement.scrollTop||document.body.scrollTop)==i&&t.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:1})}}catch{}try{var s=window.performance&&window.performance.getEntriesByType("paint");s&&s.length?(new PerformanceObserver(function(u){var c=u.getEntries(),d=c[c.length-1],f=d.renderTime||d.loadTime;t.statistics||(t.getPageLoadEvent(f),t.statistics=!0)}).observe({entryTypes:["largest-contentful-paint"]}),setTimeout(function(){t.statistics||(t.getPageLoadEvent(s[0].startTime||0),t.statistics=!0)},2e3)):this.getPageLoadEvent(0)}catch{this.getPageLoadEvent(0)}}}},r.prototype.removeListener=function(){window.document.removeEventListener("click",this.clickEvent,!0),window.document.removeEventListener("change",this.changeEvent,!0),window.document.removeEventListener("submit",this.submitEvent,!0)},r.prototype.beatEvent=function(e){var t=this;try{var n;this.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:3}),this.beatTime&&(n=setInterval(function(){t.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:2})},e)),Br(function(){t.eventHandel({eventType:"dom",eventName:"beat",eventSend:"becon"},{beat_type:0}),t.beatTime&&clearInterval(n)})}catch{}},r.prototype.getDefaultConfig=function(){return{is_html:1,url:location.href,referrer:document.referrer,page_key:location.href,refer_page_key:document.referrer,page_title:document.title||location.pathname,page_manual_key:"",refer_page_manual_key:"",refer_page_title:"",page_path:location.pathname,page_host:location.host}},r}(),R_={eventConfig:{mode:"proxy-capturing",submit:!1,click:!0,change:!1,pv:!0,beat:!0,hashTag:!1,impr:!1},scoutConfig:{mode:"xpath"}},A_=function(){function r(e,t){this.config=e,this.config.eventConfig=Object.assign(this.config.eventConfig,t)}return r.prototype.getConfig=function(){return this.config},r.prototype.setConfig=function(e){return this.config=e},r}();function D_(r){for(var e=[];r.parentElement!==null;)e.push(r),r=r.parentElement;var t=[],n=[];return e.forEach(function(i){var o=function(u){if(u===null)return{str:"",index:0};var c=0,d=u.parentElement;if(d)for(var f=d.children,h=0;h<f.length&&f[h]!==u;h++)f[h].nodeName===u.nodeName&&c++;return{str:[u.nodeName.toLowerCase(),po(u,"list")?"[]":""].join(""),index:c}}(i),a=o.str,s=o.index;t.unshift(a),n.unshift(s)}),{element_path:"/"+t.join("/"),positions:n}}function I_(r,e,t,n){var i={},o=function(I){if(I){var U=I.getBoundingClientRect(),L=U.width,j=U.height;return{left:U.left,top:U.top,element_width:L,element_height:j}}}(e),a=function(I,U){I===void 0&&(I={}),U===void 0&&(U={});var L=I.clientX,j=I.clientY,$=U.left,K=U.top,Z=L-$>=0?L-$:0,W=j-K>=0?j-K:0;return{touch_x:Math.floor(Z),touch_y:Math.floor(W)}}(r,o),s=o.element_width,u=o.element_height,c=a.touch_x,d=a.touch_y,f=D_(e),h=f.element_path,g=f.positions,k=function(I){var U=mo(I),L=[];return function j($){var K=Dc($);if(K&&L.indexOf(K)===-1&&L.push(K),$.childNodes.length>0)for(var Z=$.childNodes,W=0;W<Z.length;W++)Z[W].nodeType!==8&&j(Z[W])}(U),L}(e),z=window.performance.timing.navigationStart,w=Date.now()-z,b=g.map(function(I){return""+I}),T=null;if(window.TEAVisualEditor&&window.TEAVisualEditor.getOriginXpath&&(T=window.TEAVisualEditor.getOriginXpath({xpath:h,positions:b})),i.element_path=T&&T.xpath||h,i.positions=T&&T.positions||b,n&&!n.text&&(i.texts=k,i.element_title=function(I){var U=mo(I),L="";return function j($){var K=Dc($);if(K&&(L+=K),$.childNodes.length>0)for(var Z=$.childNodes,W=0;W<Z.length;W++)Z[W].nodeType===3&&j(Z[W])}(U),L}(e)),i.element_id=e.getAttribute("id")||"",i.element_class_name=e.getAttribute("class")||"",i.element_type=e.nodeType,i.element_width=Math.floor(s),i.element_height=Math.floor(u),i.touch_x=c,i.touch_y=d,i.page_manual_key="",i.elememt_manual_key="",i.since_page_start_ms=w,i.page_start_ms=z,i.page_path=location.pathname,i.page_host=location.host,t.track_attr&&function(I,U){return!!T_(I,U)}(e,t.track_attr)){var E=function(I,U){var L={};if(typeof U=="string")jn(I,U)&&(L.attrs=I.getAttribute(U));else if(Gi(U))for(var j=0;j<U.length;j++)jn(I,U[j])&&(L[U[j]]=I.getAttribute(U[j]));return L}(e,t.track_attr);for(var O in E)i[O]=E[O]}var G=mo(e);return G.tagName==="A"&&(i.href=G.getAttribute("href")),e.tagName==="IMG"&&(i.src=e.getAttribute("src")),i}var an=function(r,e,t,n,i){return me(me({event:r},I_(e,t,n,i)),{is_html:1,page_key:window.location.href,page_title:document.title})},x_=function(){function r(e,t){this.ignore={text:!0},this.initConfig=e,this.options=t,this.eventName=t&&t.custom==="tea"?{click:"__bav_click",page:"__bav_page",beat:"__bav_beat",static:"__bav_page_statistics",exposure:"__bav_page_exposure"}:{click:"bav2b_click",page:"bav2b_page",beat:"bav2b_beat",static:"bav2b_page_statistics",exposure:"bav2b_exposure"},t&&t.text===!0&&(this.ignore.text=!1),t&&t.exposure&&t.exposure.eventName&&(this.eventName.exposure=t.exposure.eventName)}return r.prototype.handleEvent=function(e,t){try{if(Ic(e.target))return null;var n="bav2b_click";switch(t){case"click":return n=e.target.getAttribute("data-applog-click-event")||this.eventName.click,an(n,e,e.target,this.options,this.ignore);case"change":return me(me({},an(n="bav2b_change",e,e.target,this.options)),function(i,o){try{if(i==="bav2b_change")return o.hasAttribute("data-tea-track")?{value:o.value}:{}}catch{return{}}}(n,e.target));case"submit":return an(n="bav2b_submit",e,e.target,this.options)}}catch(i){return console.error(i),null}},r.prototype.handleViewEvent=function(e){e.event=this.eventName.page,e.page_title=document.title,e.page_total_width=window.innerWidth,e.page_total_height=window.innerHeight;try{var t=window.sessionStorage.getItem("_tea_cache_duration");if(t){var n=JSON.parse(t);e.refer_page_duration_ms=n?n.duration:""}e.scroll_width=document.documentElement.scrollLeft?document.documentElement.scrollLeft+window.innerWidth:window.innerWidth,e.scroll_height=document.documentElement.scrollTop?document.documentElement.scrollTop+window.innerHeight:window.innerHeight,e.page_start_ms=window.performance.timing.navigationStart}catch(i){console.log("page event error "+JSON.stringify(i))}return e},r.prototype.handleStatisticsEvent=function(e){var t={};t.event=this.eventName.static,t.is_html=1,t.page_key=location.href,t.refer_page_key=document.referrer||"",t.page_title=document.title,t.page_manual_key=this.initConfig.autotrack.page_manual_key||"",t.refer_page_manual_key="";try{var n=e.lcp,i=window.performance.timing,o=i.loadEventEnd-i.navigationStart;t.page_init_cost_ms=parseInt(n||(o>0?o:0)),t.page_start_ms=i.navigationStart}catch(a){console.log("page_statistics event error "+JSON.stringify(a))}return t},r.prototype.handleBeadtEvent=function(e){e.event=this.eventName.beat,e.page_key=window.location.href,e.is_html=1,e.page_title=document.title,e.page_manual_key=this.initConfig.autotrack.page_manual_key||"";try{e.page_viewport_width=window.innerWidth,e.page_viewport_height=window.innerHeight,e.page_total_width=document.documentElement.scrollWidth,e.page_total_height=document.documentElement.scrollHeight,e.scroll_width=document.documentElement.scrollLeft+window.innerWidth,e.scroll_height=document.documentElement.scrollTop+window.innerHeight,e.since_page_start_ms=Date.now()-window.performance.timing.navigationStart,e.page_start_ms=window.performance.timing.navigationStart}catch(t){console.log("beat event error "+JSON.stringify(t))}return e},r.prototype.handleExposureEvent=function(e,t){if(Ic(t.target))return null;var n=an(e.event||this.eventName.exposure,t,t.target||t,this.options,this.ignore);if(n.$exposure_type=e.exposureType,this.options.exposure.callback){var i=this.options.exposure.callback(n);return i||Object.keys(i).length?i:(console.warn("exposure callback must return data!"),n)}return n},r.prototype.handleScrollEvent=function(e,t){var n=an(e.event||this.eventName.scroll,t,t.target||t,this.options,this.ignore);if(n=Object.assign(n,e.params),!this.options.scroll.callback||(n=this.options.scroll.callback(n))||Object.keys(n).length)return n;console.warn("scroll callback must return data!")},r}(),M_=function(){function r(e){this.collect=e,this.eventNameList=["report_click_event","report_change_event","report_submit_event","report_exposure_event","report_page_view_event","report_page_statistics_event","report_beat_event"]}return r.prototype.send=function(e,t){var n=e.eventSend,i=t.event;delete t.event,n&&n==="becon"?this.collect.beconEvent(i,t):this.collect.event(i,t)},r.prototype.get=function(e,t){var n=Object.assign({headers:{"content-type":"application/json"},method:"GET"},t);fetch(e,n)},r.prototype.post=function(e,t){var n=Object.assign({headers:{"content-type":"application/json"},method:"POST"},t);fetch(e,n)},r}(),go=!1;function O_(r){var e,t,n,i,o=r.event,a=r.editorUrl,s=r.autoTrackInstance;go||(go=!0,e=a,t=function(){Ac(o,"editorScriptloadSuccess"),s.destroy()},n=function(){o&&Ac(o,"editorScriptloadError"),go=!1},(i=document.createElement("script")).src=e,i.onerror=function(){n(e)},i.onload=function(){t()},document.getElementsByTagName("head")[0].appendChild(i))}function P_(r,e){window.TEAVisualEditor=window.TEAVisualEditor||{},window.TEAVisualEditor.appId=e.app_id;var t,n,i,o=e.channel_domain,a="";if((t=ng).length&&t.forEach(function(h){Rc.push(h)}),o){var s=void 0,u="";try{var c=window.performance.getEntriesByType("resource");if(c&&c.length&&(c.forEach(function(h){h.initiatorType==="script"&&h.name&&h.name.indexOf("collect")!==-1&&(u=h.name)}),u&&(s=u.split("/"))&&s.length)){a="https:/";for(var d=2;d<s.length&&d!==s.length-1;d++)a=a+"/"+s[d];if(a&&a.indexOf("/5.0")){var f=a.split("/5.0");a=f[0]||a}}}catch{}}window.addEventListener("message",v_,!1);try{i=function(h){var g=h.data.app_id;g&&g!==e.app_id||O_({event:h,editorUrl:"https://sf16-website-login.neutral.ttwstatic.com/obj/tiktok_web_login_static/log-sdk/collect/heatmap-core.js?query="+Date.now(),autoTrackInstance:r})},on[n="tea:openHeatMapCore"]=on[n]||[],on[n].push(i)}catch{console.log("openHeatMapCore error")}}var gt,L_=function(){function r(e,t){this._instance=null,this._intersection=e,this.config=t,this._intersection&&this.init()}return r.prototype.init=function(){var e=this;if(window.MutationObserver)try{if(this._instance=new MutationObserver(function(n){n.forEach(function(i){i.type==="attributes"&&e.attributeChangeObserve(i),i.type==="childList"&&e.modifyNodeObserve(i)})}),!document||!document.body)return void console.warn("please use sdk api init after body element");var t=this.config.autotrack.exposure.attributes!==!1;this._instance.observe(document.body,{childList:!0,attributes:t,subtree:!0,attributeOldValue:!1})}catch{console.log("your browser cannot support MutationObserver,so cannot report exposure event, please update")}else console.log("your browser cannot support MutationObserver,so cannot report exposure event, please update")},r.prototype.attributeChangeObserve=function(e){e.target.hasAttribute("data-exposure")?this.exposureAdd(e,"mutation"):this.exposureRemove(e)},r.prototype.modifyNodeObserve=function(e){var t=this;Array.prototype.forEach.call(e.addedNodes,function(n){n.nodeType===1&&n.hasAttribute("data-exposure")&&t.exposureAdd(n,"intersect"),t.mapChild(n,t.exposureAdd.bind(t))}),Array.prototype.forEach.call(e.removedNodes,function(n){n.nodeType===1&&n.hasAttribute("data-exposure")&&t.exposureRemove(n),t.mapChild(n,t.exposureRemove.bind(t))})},r.prototype.mapChild=function(e,t){var n=this;e.nodeType===1&&e.children.length&&Array.prototype.forEach.call(e.children,function(i){i.nodeType===1&&i.hasAttribute("data-exposure")&&t(i),n.mapChild(i,t)})},r.prototype.exposureAdd=function(e,t){try{this._intersection&&this._intersection.exposureAdd(e,t)}catch(n){console.log("intersection error",JSON.stringify(n.message))}},r.prototype.exposureRemove=function(e){try{this._intersection&&this._intersection.exposureRemove(e)}catch(t){console.log("intersection error",JSON.stringify(t.message))}},r._exposure_observer=null,r}();(function(r){r[r.EXPOSURE_ONCE=0]="EXPOSURE_ONCE",r[r.LIFECYCLE_SHOW_NEW=3]="LIFECYCLE_SHOW_NEW",r[r.RESUME_FORM_PAGE=6]="RESUME_FORM_PAGE",r[r.RESUME_FORM_BACK=7]="RESUME_FORM_BACK",r[r.NOT_EXPOSURE=-1]="NOT_EXPOSURE"})(gt||(gt={}));var rr,U_=function(){function r(e,t,n){var i=this;this.backStatus=!1,this.instance=this.buildObserver(),this.collect=e,this.observeMap=r._observer_map,t.autotrack.exposure.ratio?this.ratio=t.autotrack.exposure.ratio:t.autotrack.exposure.ratio===0?this.ratio=0:this.ratio=.5,this.timeLimit=t.autotrack.exposure.stay||0,this.exposureType=gt.NOT_EXPOSURE,this.eventHandle=n,this.hashMap=new Map,this.backStatus=!1,this.lastState=null,this.collect.on("re-start-sdk",function(){i.visibilitychange()}),this.addListen()}return r.prototype.buildObserver=function(){var e=this;if(r._observer_instance)return console.log("your browser cannot support IntersectionObserver, so cannot report exposure event, please update"),null;if(window.IntersectionObserver){for(var t=[],n=0;n<=1;n+=.01)t.push(n);t.push(1);try{r._observer_instance=new IntersectionObserver(function(i){i.forEach(function(o){var a=o.target.observeId,s=e.observeMap.get(a),u=(o.target,o.isIntersecting,o.intersectionRatio);if(s.intersectionRatio=u,u<=.1&&(o.target.backStatus=!1),e.observeMap.set(a,s),u<e.ratio)return s.isIntersecting=!1,s.added=!1,s.exposured=!1,s.startTime=Date.now(),void e.observeMap.set(a,s);if(!s.added){if(s.startTime=Date.now(),s.added=!0,s.isIntersecting=!0,e.timeLimit){var c=setTimeout(function(){try{if(s.isIntersecting&&!s.exposured&&e.observeMap.get(a)){var d=e.observeMap.get(a).intersectionRatio;e.exposureEvent(o,d,a,s)}}catch(f){console.log("IntersectionObserver setTimeout error,msg: "+JSON.stringify(f))}},e.timeLimit);s.wait=c}e.observeMap.set(a,s)}Date.now()-s.startTime>=e.timeLimit&&!s.exposured&&e.exposureEvent(o,u,a,s)})},{threshold:t})}catch(i){console.log("IntersectionObserver error,msg: "+JSON.stringify(i))}return r._observer_instance}return console.log("your browser cannot support IntersectionObserver, so cannot report exposure event, please update"),null},r.prototype.exposureAdd=function(e,t){var n=t==="mutation"?e.target:e,i=n.observeId,o=Ln();if(i||this.observeMap.has(i)){var a=this.observeMap.get(i);if(a&&n!==a.instance)this.unobserve(n),this.observeMap.delete(i),n.observeId=o,n.visible=!1,this.observeMap.set(o,{instance:n.cloneNode(!0),isIntersecting:!1}),this.observe(n);else{if(n.visible===!0)return;this.handleBoundingExposure(n)}}else n.observeId=o,n.visible=!1,this.observeMap.set(o,{instance:n.cloneNode(!0),isIntersecting:!1}),this.observe(n)},r.prototype.exposureRemove=function(e){this.observeMap.has(e.observeId)&&(this.observeMap.delete(e.observeId),this.unobserve(e),e.observeId="",e.visible=!1)},r.prototype.exposureEvent=function(e,t,n,i){if(t>=this.ratio){if(e.target.style.opacity==="0"||e.target.style.visibility==="hidden"||i.exposured===!0)return;i.startWait&&clearTimeout(i.startWait);var o=e.target.getAttribute("data-applog-exposure-event");this.eventHandle({eventType:"dom",eventName:"exposure",event:o,exposureType:this.getExposureType(e.target)},e),e.target.visible=!0,e.target.hasExposure=!0,i.startTime=Date.now(),i.exposured=!0}else i.startTime=Date.now(),i.exposured=!1;this.observeMap.set(n,i)},r.prototype.observe=function(e){this.instance&&this.instance.observe(e)},r.prototype.unobserve=function(e){this.instance&&this.instance.unobserve(e)},r.prototype.getExposureDomToExposure=function(){var e=this;Array.prototype.forEach.call(document.querySelectorAll("[data-exposure]"),function(t){e.handleBoundingExposure(t)})},r.prototype.visibilitychange=function(){var e=this,t=null;document.visibilityState==="visible"?this.timeLimit?t=setTimeout(function(){e.getExposureDomToExposure()},this.timeLimit):this.getExposureDomToExposure():(clearTimeout(t),this.customType=void 0)},r.prototype.handleBoundingExposure=function(e){if(this.getBoundingRatio(e)>=this.ratio){e.visible=!0;var t=e.getAttribute&&e.getAttribute("data-exposure-event");this.eventHandle({eventType:"dom",eventName:"exposure",event:t,exposureType:this.customType||gt.RESUME_FORM_BACK},e)}},r.prototype.getBoundingRatio=function(e){var t=e.getBoundingClientRect(),n=t.top,i=t.left,o=t.width,a=t.height,s=window.innerWidth||document.documentElement.clientWidth,u=window.innerHeight||document.documentElement.clientHeight;return n>=0&&i>=0&&n<=u&&i<=s?(o>s?s:o)*(u-n)/(o*a):0},r.prototype.getExposureType=function(e){return e.visible?e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=gt.RESUME_FORM_PAGE:this.exposureType=gt.LIFECYCLE_SHOW_NEW:(e.hasExposure,e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=gt.RESUME_FORM_PAGE:this.exposureType=gt.EXPOSURE_ONCE),this.exposureType},r.prototype.addListen=function(){var e=this;this.collect.on("set-exposure-type",function(s){e.customType=s});var t,n,i,o,a=this.visibilitychange.bind(this);return t=document,n="visibilitychange",i=a,o=!1,t.addEventListener?t.addEventListener(n,i,o):t.attachEven?t.attachEven("on"+n,i):t["on"+n]=i,window.addEventListener("hashchange",function(s){var u=e.hashMap.get(s.oldURL);u&&location.href===u.prev?(e.backStatus=!0,e.exposureType=gt.RESUME_FORM_PAGE):(e.backStatus=!1,e.hashMap.set(location.href,{current:s.newURL,prev:s.oldURL}))}),this.collect.on("STATE_CHANGE",function(s){e.lastState=s}),window.addEventListener("popstate",function(s){var u=s.state;u&&u.current&&e.lastState&&e.lastState.back&&u.current===e.lastState.back?(e.backStatus=!0,e.exposureType=gt.RESUME_FORM_PAGE):e.backStatus=!1}),function(){(function(s,u,c,d){s.addEventListener?s.removeEventListener(u,c,d):s.attachEven&&s.detachEven("on"+u,c)})(document,"visibilitychange",a,!1)}},r._observer_instance=null,r._observer_map=new Map,r}(),G_=function(){function r(e,t,n){t.autotrack&&t.autotrack.exposure&&(this._intersection=new U_(e,t,n),this._observer=new L_(this._intersection,t),this._intersection&&this._observer?this.initObserver():console.log("your browser version cannot support exposure event, please update~"))}return r.prototype.initObserver=function(){var e=this;Array.prototype.forEach.call(document.querySelectorAll("[data-exposure]"),function(t){e._intersection.exposureAdd(t,"intersect")})},r}();(function(r){r[r.SCROLL_UP=1]="SCROLL_UP",r[r.SCROLL_DOWN=2]="SCROLL_DOWN",r[r.SCROLL_LEFT=3]="SCROLL_LEFT",r[r.SCROLL_RIGHT=4]="SCROLL_RIGHT",r[r.NOT_SCROLL=-1]="NOT_SCROLL"})(rr||(rr={}));var xc,N_=function(){function r(e,t){this.distance=30,e.autotrack&&e.autotrack.scroll&&(e.autotrack.scroll.distance&&(this.distance=e.autotrack.scroll.distance),this.eventHandle=t,this.addLinstenr(),this.mutation())}return r.prototype.addLinstenr=function(){var e=this;Array.prototype.forEach.call(document.querySelectorAll("[data-scroll]"),function(t){e.scrollHandle(t)})},r.prototype.mutation=function(){var e=this;if(window.MutationObserver)try{var t=new MutationObserver(function(n){n.forEach(function(i){i.type==="childList"&&e.modifyNodeObserve(i)})});if(!document||!document.body)return void console.warn("please use sdk api init after body element");t.observe(document.body,{childList:!0,attributes:!0,subtree:!0,attributeOldValue:!1})}catch{console.log("your browser cannot support MutationObserver")}else console.log("your browser cannot support MutationObserver")},r.prototype.modifyNodeObserve=function(e){var t=this;Array.prototype.forEach.call(e.addedNodes,function(n){n.nodeType===1&&n.hasAttribute("data-scroll")&&t.scrollHandle(n),t.mapChild(n,t.scrollHandle.bind(t))}),Array.prototype.forEach.call(e.removedNodes,function(n){n.nodeType===1&&n.hasAttribute("data-scroll")&&t.scrollHandle(n,"remove"),t.mapChild(n,t.scrollHandle.bind(t))})},r.prototype.mapChild=function(e,t){var n=this;e.nodeType===1&&e.children.length&&Array.prototype.forEach.call(e.children,function(i){i.nodeType===1&&i.hasAttribute("data-scroll")&&t(i),n.mapChild(i,t)})},r.prototype.scrollHandle=function(e,t){var n=this;try{var i=e.scrollTop,o=e.scrollLeft,a=null,s=0,u=0,c=function(d){clearTimeout(a),a=setTimeout(function(){var k=e.scrollTop,z=e.scrollLeft,w=d.target&&d.target.getAttribute("data-scroll-event")||"";g===1||g===2?k===f&&(u=f-i,Math.abs(u)>=n.distance&&n.distance&&n.eventHandle({eventType:"dom",eventName:"scroll",event:w,params:{$direction:g,$offsetY:u,$offsetX:s}},d)):g!==3&&g!==4||z===h&&(s=h-o,Math.abs(s)>=n.distance&&n.distance&&n.eventHandle({eventType:"dom",eventName:"scroll",event:w,params:{$direction:g,$offsetY:u,$offsetX:s}},d)),i=f,o=h},100);var f=e.scrollTop,h=e.scrollLeft,g=rr.NOT_SCROLL;f>i?g=rr.SCROLL_DOWN:f<i?g=rr.SCROLL_UP:h>o?g=rr.SCROLL_LEFT:h<o&&(g=rr.SCROLL_RIGHT)};return t==="remove"?e.removeEventListener("scroll",c,!1):e.addEventListener("scroll",c,!1),function(){e.removeEventListener("scroll",c,!1)}}catch(d){console.warn("scroll event error",JSON.stringify(d))}},r}(),B_={hashTag:!1,impr:!1},F_=function(){function r(){}return r.prototype.apply=function(e,t){if(this.autoTrackStart=!1,this.collect=e,this.config=t,t.autotrack){var n=e.Types;this.ready(n.Autotrack),this.collect.emit(n.AutotrackReady)}},r.prototype.ready=function(e){this.collect.set(e);var t=this.config.autotrack;t=typeof t=="object"?t:{},t=Object.assign(B_,t),this.destroyed=!1,this.options=t,this.Config=new A_(R_,this.options),this.Exposure=new G_(this.collect,this.config,this.handle.bind(this)),this.Scroll=new N_(this.config,this.handle.bind(this)),this.Listener=new z_(t,this.collect,this.Config),this.EventHandle=new x_(this.config,t),this.Request=new M_(this.collect),this.autoTrackStart=!0,this.init(),P_(this,this.config)},r.prototype.init=function(){this.Listener.init(this.handle.bind(this)),this.collect.loadType==="base"&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")},r.prototype.handle=function(e,t){try{if(this.config.autotrack.collect_url&&!this.config.autotrack.collect_url())return}catch{}e.eventType==="dom"&&this.handleDom(e,t)},r.prototype.handleDom=function(e,t){try{var n=e.eventName;if(n==="click"||n==="change"||n==="submit")(s=this.EventHandle.handleEvent(t,n))&&this.Request.send({eventType:"custom"},s);else if(n==="page_view"||n==="page_statistics"){var i=void 0;(i=n==="page_view"?this.EventHandle.handleViewEvent(t):this.EventHandle.handleStatisticsEvent(t))&&this.Request.send({eventType:"custom"},i)}else if(n==="beat"){var o=this.EventHandle.handleBeadtEvent(t),a=e.eventSend;o&&this.Request.send({eventType:"custom",eventSend:a},o)}else if(n==="exposure")(s=this.EventHandle.handleExposureEvent(e,t))&&this.Request.send({eventType:"custom"},s);else if(n==="scroll"){var s;(s=this.EventHandle.handleScrollEvent(e,t))&&this.Request.send({eventType:"custom"},s)}}catch(u){console.log("handel dom event error "+JSON.stringify(u))}},r.prototype.destroy=function(){if(!this.autoTrackStart)return console.warn("engine is undefined, make sure you have called autoTrack.start()");this.autoTrackStart=!1,this.Listener.removeListener()},r}();(function(r){r.Net="net",r.FailNet="f_net",r.FailData="f_data"})(xc||(xc={}));var Mc={pv:["predefine_pageview"],sdk:["_be_active","predefine_page_alive","predefine_page_close","__profile_set","__profile_set_once","__profile_increment","__profile_unset","__profile_append"],autotrack:["bav2b_click","bav2b_page","bav2b_beat","bav2b_page_statistics","__bav_click","__bav_page","__bav_beat","__bav_page_statistics"]},V_=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.ready=t.app_id&&t.enable_tracer&&!t.disable_track_event,this.ready){this.limit={pv:1,sdk:3,autotrack:3,log:3},this.errorCode={f_net:0,f_data:0},this.tracerCache=new Map,this.collect=e,this.appid=t.app_id,this.reportUrl=e.configManager.getUrl("event");var i=this.collect.Types;e.adapters.fetch,this.collect.on(i.Event,function(o){Gi(o)?o.forEach(function(a){n.addCount("log")}):n.addCount("log")}),this.collect.on(i.SubmitError,function(o){var a=o.type,s=o.eventDate,u=o.errorCode,c=o.response;n.addErrorCount(s,a,u,c)}),this.listener(),this.collect.emit(i.TracerReady)}},r.prototype.addCount=function(e,t,n){t===void 0&&(t="net"),n===void 0&&(n=1);try{this.tracerCache||(this.tracerCache=new Map);var i=void 0;if(this.tracerCache.has(e))(o=this.tracerCache.get(e)).has(t)?(i=o.get(t).params.count,i++,o.set(t,this.processTracer(i,e,t))):(i=n,o.set(t,this.processTracer(n,e,t)));else{var o=new Map;i=n,o.set(t,this.processTracer(n,e,t)),this.tracerCache.set(e,o)}t==="net"&&i>=this.limit[e]&&this.report(!1)}catch(a){console.log(a)}},r.prototype.addErrorCount=function(e,t,n,i){var o=this;try{if(e&&e.length){var a=e[0].events;a&&a.length&&(t==="f_data"?(i&&i.hasOwnProperty("sc")?this.addCount("log",t,a.length-i.sc):this.addCount("log",t,a.length),this.errorCode[t]=n):a.forEach(function(s){var u="log";for(var c in Mc)if(Mc[c].indexOf(s.event)!==-1){u=c;break}o.addCount(u,t,1),o.errorCode[t]=n}))}}catch{}},r.prototype.report=function(e){if(this.tracerCache){var t=[];this.tracerCache.forEach(function(n){console.log(n),n.forEach(function(i){t.push(i)})}),t&&t.length&&this.sendTracer(t,e)}},r.prototype.sendTracer=function(e,t){try{var n=this.collect.eventManager.merge(e);this.collect.requestManager.useRequest({url:this.reportUrl,data:n,useBeacon:t}),this.tracerCache=null}catch{}},r.prototype.processTracer=function(e,t,n){try{var i={count:e,state:n,key:t,params_for_special:"applog_trace",aid:this.appid,platform:"web",_staging_flag:1,sdk_version:Vr};n!=="f_net"&&n!=="f_data"||(i.errorCode=this.errorCode[n]);var o=this.collect.processEvent("applog_trace",i);if(o&&o.event)return delete o.is_bav,o}catch{console.warn("something error")}},r.prototype.listener=function(){var e=this;document.addEventListener("visibilitychange",function(){document.visibilityState==="hidden"&&e.leavePage()}),Br(function(){e.leavePage()})},r.prototype.leavePage=function(){this.report(!0)},r}(),j_=function(){function r(){this.retryWaitTime=3e3,this.retryStatus=!1,this.retryCacheStatus=!1}return r.prototype.apply=function(e,t){var n=this;if(t.enable_storage&&!t.disable_storage&&(this.collect=e,this.config=t,!this.collect.destroy)){var i=e.Types,o=e.adapters.storage;this.storage=new o(!1),this.eventUrl=this.collect.configManager.getUrl("event"),this.eventKey="__tea_cache_events_"+t.app_id,this.storageNum=t.storage_num||50,this.retryNum=t.retry_num||3,this.retryInterval=1e3,e.on(i.SubmitError,function(a){a.type!=="f_data"&&n.storeData(a)}),e.on(i.Ready,function(){n.checkStorage()})}},r.prototype.retryRightNow=function(e){var t=this;if(this.retryStatus)this.errorCache.push(e);else{var n=0;this.retryStatus=!0;var i=setInterval(function(){if(n===3)return t.storeData(t.errorCache),t.retryStatus=!1,void clearInterval(i);var o=e.eventData;t.fetchData(o,function(){t.retryStatus=!1,clearInterval(i),t.retryCacheStatus&&t.errorCache.splice(0,1),t.errorCache.length&&(t.retryCacheStatus=!0,t.retryRightNow(t.errorCache[0]))},function(){n++})},this.retryInterval)}},r.prototype.storeData=function(e){var t=this.storage.getItem(this.eventKey),n=e.eventData;Object.keys(t).length!==this.storageNum&&(t[Date.now()]=n,this.storage.setItem(this.eventKey,t))},r.prototype.checkStorage=function(){var e=this;try{if(!window.navigator.onLine)return;var t=this.storage.getItem(this.eventKey);if(!t||!Object.keys(t).length)return;var n={events:[{event:"ontest",params:{app_id:this.config.app_id},local_time_ms:Date.now()}],user:{user_unique_id:this.collect.configManager.get("web_id")},header:{}};this.fetchData([n],function(){var i=JSON.parse(JSON.stringify(t)),o=function(s){e.fetchData(t[s],function(){delete i[s],e.storage.setItem(e.eventKey,i)},function(){},!1)};for(var a in t)o(a)},function(){},!0)}catch{console.warn("error check storage")}},r.prototype.fetchData=function(e,t,n,i){this.collect.requestManager.useRequest({url:this.eventUrl,data:e,timeout:3e4,success:t,fail:n,app_key:i?"566f58151b0ed37e":""})},r}(),_o=typeof window<"u"?(window.LogPluginObject||(window.LogPluginObject={}),window.LogPluginObject):null,H_=function(){function r(){}return r.prototype.apply=function(e,t){this._plugin={},this.config=t,this.collect=e,this.channel="va",this.loadExtend()},r.prototype.loadExtend=function(){var e=this;try{this.collect.remotePlugin.forEach(function(t,n){if(t==="sdk")if(ho.hasOwnProperty(n)){var i=ho[n].object,o=""+ho[n].src[e.channel];e.exist(n,i,o)}else console.warn("your "+n+" is not exist,please check plugin name");else typeof t=="object"&&(t.src?e.exist(n,t.call,t.src):e.process(n,t.instance,"INSTANCE"))})}catch(t){this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"LoadExtend Fail",level:"error",time:Date.now(),data:t.message}),console.log("load extend error")}},r.prototype.exist=function(e,t,n){var i=this;_o[t]?(this.process(e,_o[t]),console.log("already has "+e+" plugin~")):this.loadPlugin(e,n,function(){i.process(e,_o[t]),console.log(" %c %s %s %s","color: yellow; background-color: black;","–","load plugin:"+e+" success","-")},function(){console.log(" %c %s %s %s","color: red; background-color: yellow;","–","load plugin:"+e+" error","-")})},r.prototype.process=function(e,t,n){try{if(n){var i=new t;i.apply&&i.apply(this.collect,this.config),console.log("excude "+e+" success")}else t&&t(this.collect,this.config)}catch(o){this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"Extend Process Fail",level:"error",time:Date.now(),data:o.message}),console.log("excude "+e+" error, message:"+o.message)}},r.prototype.loadPlugin=function(e,t,n,i){var o=this;try{var a=document.createElement("script");a.src=t,this._plugin[e]||(this._plugin[e]=[]),this._plugin[e].push(n),a.onerror=function(){i(t)},a.onload=function(){o._plugin[e].forEach(function(s){s()})},document.getElementsByTagName("head")[0].appendChild(a)}catch(s){this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"Extend LoadPlugin Fail",level:"error",time:Date.now(),data:s.message})}},r}(),$_=function(){function r(){this.autotrack=!1,this.spa=!1,this.cache={},this.allowHash=!1}return r.prototype.apply=function(e,t){if(t.spa||t.autotrack){var n=e.Types;this.collect=e,this.config=t,this.appid=t.app_id,this.allowHash=t.allow_hash,this.fncArray=new Map,this.setKey(),this.setLocation(),this.hack(),this.init(),this.listener(),e.emit(n.RouteReady)}},r.prototype.setKey=function(){var e=this.collect.adapters.storage;this.storage=new e(!1),this.cache_key="__tea_cache_refer_"+this.appid,this.cache={refer_key:"",refer_title:document.title||location.pathname,refer_manual_key:"",routeChange:!1},this.config.autotrack&&typeof this.config.autotrack=="object"&&this.config.autotrack.page_manual_key&&(this.cache.refer_manual_key=this.config.autotrack.page_manual_key),this.storage.setItem(this.cache_key,this.cache)},r.prototype.hack=function(){var e=this,t=window.history.pushState;history.pushState=function(i){for(var o=[],a=1;a<arguments.length;a++)o[a-1]=arguments[a];typeof history.onpushstate=="function"&&history.onpushstate({state:i});var s=t.call.apply(t,Ur([history,i],o));if(e.collect.sdkStop||e.collect.destroy)return s;if(!(e.lastLocation===location.href||e.config.disable_spa_query&&e.pathEquel())){e.setReferCache(e.lastLocation);var u=e.getPopStateChangeEventData();return e.lastLocation=location.href,e.sendPv(u,"pushState"),s}};var n=history.replaceState;history.replaceState=function(i){for(var o=[],a=1;a<arguments.length;a++)o[a-1]=arguments[a];typeof history.onreplacestate=="function"&&history.onreplacestate({state:i});var s=n.call.apply(n,Ur([history,i],o));if(e.collect.sdkStop||e.collect.destroy)return s;if(!(e.lastLocation===location.href||e.config.disable_spa_query&&e.pathEquel())){e.setReferCache(e.lastLocation);var u=e.getPopStateChangeEventData();return e.lastLocation=location.href,e.sendPv(u),s}}},r.prototype.setLocation=function(){typeof window<"u"&&(this.lastLocation=window.location.href)},r.prototype.getLocation=function(){return this.lastLocation},r.prototype.pathEquel=function(){try{return new URL(this.lastLocation).origin+new URL(this.lastLocation).pathname===new URL(location.href).origin+new URL(location.href).pathname}catch{return!1}},r.prototype.init=function(){var e=this.getPopStateChangeEventData();this.collect.emit("route-change",{config:e,init:!0})},r.prototype.listener=function(){var e=this;window.addEventListener("hashchange",function(t){if(!e.collect.sdkStop&&!e.collect.destroy&&e.lastLocation!==window.location.href&&(!e.config.disable_spa_query||!e.pathEquel())&&e.allowHash){e.setReferCache(e.lastLocation),e.lastLocation=window.location.href;var n=e.getPopStateChangeEventData();e.sendPv(n)}}),window.addEventListener("popstate",function(t){if(!e.collect.sdkStop&&!e.collect.destroy&&!(e.lastLocation===window.location.href||e.config.disable_spa_query&&e.pathEquel())){e.setReferCache(e.lastLocation),e.lastLocation=window.location.href;var n=e.getPopStateChangeEventData();e.sendPv(n)}})},r.prototype.getPopStateChangeEventData=function(){var e=this.pageConfig();return e.is_back=0,e},r.prototype.pageConfig=function(){try{var e=this.storage.getItem(this.cache_key)||{},t=!1,n=this.storage.getItem("__tea_cache_first_"+this.appid);return t=!n||n!=1,{is_html:1,url:location.href,referrer:this.handleRefer(),page_key:location.href,refer_page_key:this.handleRefer(),page_title:document.title||location.pathname,page_manual_key:this.config.autotrack&&this.config.autotrack.page_manual_key||"",refer_page_manual_key:e&&e.refer_manual_key||"",refer_page_title:e&&e.refer_title||"",page_path:location.pathname,page_host:location.host,is_first_time:""+t}}catch(i){return this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"something error",level:"error",time:Date.now(),data:i.message}),{}}},r.prototype.sendPv=function(e,t){this.collect.emit("route-change",{config:e,init:!1})},r.prototype.handleRefer=function(){var e="";try{var t=this.storage.getItem(this.cache_key)||{};e=t.routeChange?t.refer_key:this.collect.configManager.get("referrer")}catch{e=document.referrer}return e},r.prototype.removeQuery=function(e){try{var t=new URL(e);return t.search="",t.href}catch{return e.split(/[?#]/)[0]}},r.prototype.setReferCache=function(e){var t=this.storage.getItem(this.cache_key)||{},n=this.removeQuery(e);t.refer_key=n,t.routeChange=!0,this.storage.setItem(this.cache_key,t)},r}(),q_=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;this.collect=e,this.config=t;var i=e.Types;e.on(i.TrackDurationStart,function(o){n.trackEventStart(o)}),e.on(i.TrackDurationEnd,function(o){n.trackEventEnd(o)}),e.on(i.TrackDurationPause,function(o){n.trackEventPause(o)}),e.on(i.TrackDurationResume,function(o){n.trackEventResume(o)}),this.Types=i,this.TrackEventMap=new Map,this.ready(i.TrackDuration)},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var n=this.collect.hook._hooksCache[e];if(!Object.keys(n).length)return;var i=function(a){n[a].length&&n[a].forEach(function(s){t.collect.hook.emit(a,s)})};for(var o in n)i(o)}},r.prototype.trackEventStart=function(e){this.TrackEventMap.set(e,{startTime:Date.now(),isPause:!1,pauseTime:0,resumeTime:0})},r.prototype.trackEventEnd=function(e){var t=e.eventName,n=e.params;if(this.TrackEventMap.has(t)){var i=this.TrackEventMap.get(t),o=0;o=i.isPause?i.pauseTime-i.startTime:i.resumeTime?i.pauseTime-i.startTime+(Date.now()-i.resumeTime):Date.now()-i.startTime;var a=Object.assign(n,{event_duration:o});this.collect.event(t,a),this.cleanEventTrack(t)}},r.prototype.trackEventPause=function(e){if(this.TrackEventMap.has(e)){var t=this.TrackEventMap.get(e);t.isPause||(t.isPause=!0,t.pauseTime=Date.now(),this.TrackEventMap.set(e,t))}},r.prototype.trackEventResume=function(e){if(this.TrackEventMap.has(e)){var t=this.TrackEventMap.get(e);t.isPause&&(t.isPause=!1,t.resumeTime=Date.now(),this.TrackEventMap.set(e,t))}},r.prototype.cleanEventTrack=function(e){this.TrackEventMap.delete(e)},r}();et.usePlugin(H_,"extend"),et.usePlugin(S_,"et"),et.usePlugin(j_,"retry"),et.usePlugin(y_,"ab"),et.usePlugin(w_,"stay"),et.usePlugin(F_,"autotrack"),et.usePlugin(q_,"trackeventduration"),et.usePlugin(C_,"heartbeat"),et.usePlugin(k_,"monitor"),et.usePlugin($_,"route"),et.usePlugin(V_,"tracer");var cn=new et("default");const vo="VEPUSHER_DEVICE_ID",yo="VEPUSHER_USER_ID",Oc=r=>Math.floor((Math.random()*9+1)*Math.pow(10,r-1)).toString();function K_(r){const e={};if(!(r instanceof Object))throw new Error("params type error");for(const[t,n]of Object.entries(r))if(["string","number","boolean"].includes(typeof n))e[t]=n;else try{e[t]=JSON.stringify(n)}catch(i){console.error("serialize error",i)}return e}function W_(r){if(r)return localStorage.setItem(yo,r),r;const e=localStorage.getItem(yo);if(e)return e;const t=Oc(12);return localStorage.setItem(yo,t),r}function J_(r){if(r)return localStorage.setItem(vo,r),r;const e=localStorage.getItem(vo);if(e)return e;const t=Oc(11);return localStorage.setItem(vo,t),t}const J={PUSHER_INIT:"pusher_init",SET_PROPERTY_CALL:"set_property_call",SET_VIDEO_QUALITY:"set_video_quality",SET_AUDIO_QUALITY:"set_audio_quality",PAGE_VISIBLE_CHANGE:"page_visible_change",PUSHER_DESTROY:"pusher_destroy",...{GET_DEVICES_RESULT:"get_devices_result",CAMERA_CAPTURE_RESULT:"camera_capture_result",MICROPHONE_CAPTURE_RESULT:"microphone_capture_result",SCREEN_CAPTURE_RESULT:"screen_capture_result",VIDEO_FILE_CAPTURE_RESULT:"video_file_capture_result",AUDIO_FILE_CAPTURE_RESULT:"audio_file_capture_result",IMAGE_FILE_CAPTURE_RESULT:"image_file_capture_result",VOLUME_DETECTOR_START_RESULT:"volume_detector_start_result",STOP_CAPTURE:"stop_capture"},...{SWITCH_ENABLE_MIXING:"switch_enable_mixing",SET_MIXING_CONFIG:"set_mixing_config",ADD_VIDEO_STREAM:"add_video_stream",UPDATE_VIDEO_STREAM:"update_video_stream",DELETE_VIDEO_STREAM:"delete_video_stream",CHANGE_VIDEO_STREAM_MUTE:"change_video_stream_mute",ADD_AUDIO_STREAM:"add_audio_stream",UPDATE_AUDIO_STREAM:"update_audio_stream",DELETE_AUDIO_STREAM:"delete_audio_stream",CHANGE_AUDIO_STREAM_MUTE:"change_audio_stream_mute"},...{START_PUSH:"start_push",STOP_PUSH_STREAM:"stop_push_stream",STOP_PUSH_STREAM_API_CALL:"stop_push_stream_api_call",START_PUSH_STATUS:"start_push_status",PUSH_RECONNECT_START:"push_reconnect_start",PUSH_RECONNECT_STATUS:"push_reconnect_status",PUSH_STATS:"push_stats",PUSH_AUDIO_CONTEXT_START_FAILED:"push_audio_context_start_failed",PUSH_RTC_STATE_CHANGE:"push_rtc_state_change",PUSH_SDP_INFO:"push_sdp_info"}};class X_{constructor({showLogInConsole:e=!1}){this._showLogInConsole=!1,this.markCollectTeaEventReady=()=>{this.isReady=!0,cn.start(),this.queueTeaEvent.forEach(t=>this.sendTeaEvent(...t)),this.queueTeaEvent=[]},this.configTea=(t,n)=>{const i={...t,evtParams:{page_url_fe:encodeURIComponent(window.location.href)||"",page_path_fe:window.location.pathname||"unknown",page_host_fe:window.location.hostname||"unknown",sdk_version:"2.0.3",build_version:"1.0.0.131",...n}};cn.config(i),this.markCollectTeaEventReady()},this.isReady=!1,this.queueTeaEvent=[],cn.init({app_id:778494,channel:"sg"}),this._showLogInConsole=e}sendTeaEvent(e,t,n=!1){if(e)if(this.isReady)try{const i={...K_(t||{})};cn.event(e,i),this._showLogInConsole&&!n&&console.log("[VePusher logger]:",e,i)}catch(i){console.error(i)}else this._showLogInConsole&&!n&&console.log("[VePusher logger]:",e,t),this.queueTeaEvent.push([e,t])}getIsReady(){return this.isReady}getRawTea(){return cn}}let un;function Z_({showLogInConsole:r}){un=new X_({showLogInConsole:r})}function X(r,e,t=!1){un&&un.sendTeaEvent(r,e,t)}function Y_(r,e){un&&un.configTea(r,e)}const Pc=()=>{X(J.PAGE_VISIBLE_CHANGE,{page_visible:!document.hidden})},Q_=()=>{document.addEventListener("visibilitychange",Pc)},ev=()=>{document.removeEventListener("visibilitychange",Pc)};function vr(r){var e;return{error:r,error_code:r.code,error_message:r.message,original_error_message:(e=r.error)==null?void 0:e.message}}class tv extends Mt{constructor(e){super(),this._videoConstraints={width:1080,height:720,frameRate:30},this._cameraStreams={},this._screenStreams={},this._videoFileStreams={},this._microphoneStreams={},this._audioFileStreams={},this._imageStreams={},this._customVideoStreams={},this._customAudioStreams={};const{width:t,height:n,frameRate:i}=pr(vs,"video"),{sampleRate:o}=pr(ys,"audio");this._videoConstraints={width:t,height:n,frameRate:i},this._audioConstraints={sampleRate:o,enableAutoGainControl:!0,enableNoiseSuppression:!0,enableEchoCancellation:!0},this._livePusher=e}_notifyCaptured(e){this.emit(dt.DeviceCaptured,e)}_notifyStopCapture(e){this.emit(dt.DeviceStopCapture,e)}_bindStreamEvent(e){e.bindTrackEnd(()=>{this.emit(dt.Interrupted,e),this.stopCapture({streamId:e.id,type:e.type})})}_handleError(e,t){const n=new fr(t,e.message);this.emit(dt.Error,n)}setVideoResolution(e){this._videoConstraints={...this._videoConstraints,...e}}setVideoFps(e){this._videoConstraints={...this._videoConstraints,frameRate:e}}setAudioSampleRate(e){this._audioConstraints={...this._audioConstraints,sampleRate:e}}async getDevicesList(e){try{const t=await El(e?[e]:["audioinput","videoinput"]);return X(J.GET_DEVICES_RESULT,{type:e,is_success:!0,devices:t}),t}catch(t){return X(J.GET_DEVICES_RESULT,{type:e,is_success:!1,error:t,origin_error:t.error,error_code:t.code,error_message:t.message}),[]}}async getMicrophones(){return this.getDevicesList("audioinput")}async getCameras(){return this.getDevicesList("videoinput")}stopCapture({streamId:e,type:t}){let n;switch(t){case ae.Camera:n="_cameraStreams";break;case ae.Screen:n="_screenStreams";break;case ae.VideoFile:n="_videoFileStreams";break;case ae.Microphone:n="_microphoneStreams";break;case ae.AudioFile:n="_audioFileStreams";break;case ae.Image:n="_imageStreams";break;case ae.CustomVideo:n="_customVideoStreams";break;case ae.CustomAudio:n="_customAudioStreams";break}if(n){let i=[];if(e){const o=this[n][e];i.push(o)}else i=kt(this[n]);X(J.STOP_CAPTURE,{stream_id:e,type:t,number:i.length}),i.forEach(o=>{this._notifyStopCapture(o),o.destroy(),delete this[n][o.id]})}}async startCameraCapture(e){let t={};Bm.includes(e)?t={facingMode:e}:e&&(t={deviceId:{exact:e}});const n={...t,...this._videoConstraints};try{const i=await wl(n,!this._livePusher.isEnableMixing),o=new Jl(i,{frameRate:this._videoConstraints.frameRate});return this._cameraStreams[o.id]=o,this._notifyCaptured(o),this._bindStreamEvent(o),X(J.CAMERA_CAPTURE_RESULT,{is_success:!0,stream_id:o.id,device_id:e,capture_params:n}),o.id}catch(i){throw X(J.CAMERA_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:n,...vr(i)}),this._handleError(i,qe.OPEN_CAMERA_FAILED),i}}async startMicrophoneCapture(e){let t={};e&&(t={deviceId:{exact:e}});const n={...this._audioConstraints,...t};try{const i=await kl(n),o=new Mm(i);return this._microphoneStreams[o.id]=o,this._notifyCaptured(o),this._bindStreamEvent(o),X(J.MICROPHONE_CAPTURE_RESULT,{is_success:!0,stream_id:o.id,device_id:e,capture_params:n}),o.id}catch(i){throw X(J.MICROPHONE_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:n,...vr(i)}),this._handleError(i,qe.OPEN_MICROPHONE_FAILED),i}}async startScreenCapture(e){const t={audio:e,video:this._videoConstraints};try{const n=await Tl(t,void 0,!this._livePusher.isEnableMixing),i=new Pm(n,{frameRate:this._videoConstraints.frameRate});return this._screenStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),X(J.SCREEN_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,capture_params:t}),i.id}catch(n){throw X(J.SCREEN_CAPTURE_RESULT,{is_success:!1,capture_params:t,...vr(n)}),this._handleError(n,qe.OPEN_SCREEN_FAILED),n}}async startVideoFileCapture(e){try{const t=await Gs({url:e,video:!0,audio:!0,loop:!0}),n=new Om(t);return this._videoFileStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),X(J.VIDEO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,file_url:e}),n.id}catch(t){throw this._handleError(t,qe.VIDEO_FILE_CAPTURE_FAILED),X(J.VIDEO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...vr(t)}),t}}async startAudioFileCapture(e){try{const t=await Gs({url:e,video:!1,audio:!0,loop:!0}),n=new Lm(t);return this._audioFileStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),X(J.AUDIO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,file_url:e}),n.id}catch(t){throw X(J.AUDIO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...vr(t)}),this._handleError(t,qe.AUDIO_FILE_CAPTURE_FAILED),t}}async startImageCapture(e){try{const t=await Cl({url:e,width:0,height:0,frameRate:30}),n=new Um(t);return this._imageStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),X(J.IMAGE_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,file_url:e}),n.id}catch(t){throw X(J.IMAGE_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...vr(t)}),this._handleError(t,qe.IMAGE_FILE_CAPTURE_FAILED),t}}startCustomVideoCapture(e){const t=Rl(e);if(t){const n=new Gm(t);return this._customVideoStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),n.id}}startCustomAudioCapture(e){const t=Al(e);if(t){const n=new Nm(t);return this._customAudioStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),n.id}}async startVolumeDetect(e){const t=this.getStreamById(e);if(t)try{await t.startVolumeDetect(),X(J.VOLUME_DETECTOR_START_RESULT,{is_success:!0,stream_id:t.id})}catch(n){X(J.VOLUME_DETECTOR_START_RESULT,{is_success:!1,stream_id:t.id,error_message:n.message}),this._handleError(n,qe.VOLUME_DETECT_FAILED)}}stopVolumeDetect(e){const t=this.getStreamById(e);t&&t.stopVolumeDetect()}getDefaultVideoStream(){return kt(this._cameraStreams)[0]||kt(this._screenStreams)[0]||kt(this._videoFileStreams)[0]||kt(this._imageStreams)[0]||kt(this._customVideoStreams)[0]}getDefaultAudioStream(){return kt(this._microphoneStreams)[0]||kt(this._audioFileStreams)[0]||kt(this._customAudioStreams)[0]}getVideoStream(e){return this._cameraStreams[e]||this._screenStreams[e]||this._videoFileStreams[e]||this._imageStreams[e]||this._customVideoStreams[e]}getAudioStream(e){return this._microphoneStreams[e]||this._audioFileStreams[e]||this._customAudioStreams[e]}getStreamById(e){return this.getAudioStream(e)||this.getVideoStream(e)}getVolume(e){const t=this.getStreamById(e);return(t==null?void 0:t.volume)||0}destroy(){Object.values(ae).forEach(e=>{this.stopCapture({type:e})})}}let Bt=class{constructor(e){this._enabled=!1,this.group=(...t)=>{this._enabled&&console.group(`[${this._prefix}]: `,...t)},this.groupCollapsed=(...t)=>{this._enabled&&console.groupCollapsed(`[${this._prefix}]: `,...t)},this.groupEnd=()=>{this._enabled&&console.groupEnd()},this.log=(...t)=>{this._enabled&&console.log(`[${this._prefix}]: `,...t)},this.warn=(...t)=>{this._enabled&&console.warn(`[${this._prefix}]: `,...t)},this.error=(...t)=>{this._enabled&&console.error(`[${this._prefix}]: `,...t)},this.table=(...t)=>{this._enabled&&console.table(...t)},this._prefix=e;try{this._enabled=location.href.indexOf("rtmdebug")!==-1}catch{}}};class So{constructor({streamManagerController:e,composedStream:t,streamComposeController:n}){this._streamManagerController=e,this._composedStream=t,this._streamComposeController=n,this._active=!1,this.bindStreamManagerControllerEvent()}bindStreamManagerControllerEvent(){this._streamManagerController.on(dt.DeviceCaptured,e=>{this._active&&this.onStreamCapture(e)}),this._streamManagerController.on(dt.DeviceStopCapture,e=>{this._active&&this.onStreamStopCapture(e)})}getComposedStream(){return this._composedStream}enable(){this._active=!0}disable(){this._active=!1}}const Lc=new Bt("SingleComposer");class rv extends So{onStreamCapture(e){e.isVideoStream?this._handleVideoStreamCapture(e):this._handleAudioStreamCapture(e)}onStreamStopCapture(e){e&&(e.isVideoStream?this._handleVideoStreamStopCapture(e):this._handleAudioStreamStopCapture(e))}enable(){if(super.enable(),this._composedStream.videoStream){const e=this._streamManagerController.getDefaultVideoStream();e&&this._handleVideoStreamCapture(e)}}async setVideoQuality({width:e,height:t,frameRate:n}){var i,o;if(this._active)try{await((o=(i=this._composedStream.videoStream)==null?void 0:i.videoTrack)==null?void 0:o.applyConstraints({width:{min:e,ideal:e},height:{min:t,ideal:t},frameRate:{min:n,ideal:n}}))}catch(a){Lc.error("setVideoQuality error",a)}}_handleVideoStreamCapture(e){const t=this._composedStream.videoStream;t!=null&&t.id&&this._streamComposeController.getMixerComposer().haveMixedStream(t.id)&&this._streamComposeController.removeAudioStream(t.id),e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100}),this._composedStream.setVideoStream(e)}_handleAudioStreamCapture(e){const t=this._streamComposeController.getMixerComposer().getMixedStreamByType(e.type);t.length>0&&t.forEach(n=>{this._streamComposeController.removeAudioStream(n.id)}),this._streamComposeController.addAudioStream({streamId:e.id,volume:100})}_handleVideoStreamStopCapture(e){const t=this._composedStream.videoStream;if((t==null?void 0:t.id)===e.id){const n=this._streamManagerController.getDefaultVideoStream();n?this._handleVideoStreamCapture(n):Lc.error("all video stream stop capture")}}muteVideoStream(){var e;(e=this._composedStream.videoStream)!=null&&e.videoTrack&&(this._composedStream.videoStream.videoTrack.enabled=!1)}unmuteVideoStream(){var e;(e=this._composedStream.videoStream)!=null&&e.videoTrack&&(this._composedStream.videoStream.videoTrack.enabled=!0)}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class nv extends Mt{constructor(e,{width:t,height:n,x:i,y:o,zOrder:a,keepRatio:s,mirrorType:u}){super(),this._rect={x:0,y:0,width:0,height:0,zOrder:0},this._isHidden=!1,this._paintSize={width:0,height:0},this._rect.width=t??e.width,this._rect.height=n??e.height,this._rect.x=i??0,this._rect.y=o??0,this._rect.zOrder=a??0,this._rect.sourceHeight=e.height,this._rect.sourceWidth=e.width,this._rect.keepRatio=s??!1,this._rect.mirrorType=u,this._stream=e,this._bindVideoTrackSizeChange()}_getPaintSize({elementWidth:e,elementHeight:t}){const n=this._rect.width,i=this._rect.height;if(n===0&&i===0)return{width:0,height:0};if(n===0)return{height:i,width:e*(i/t)};if(i===0)return{width:n,height:t*(n/e)};const o=e/t,a=n/i;let s=n,u=i;return o>a?(s=n,u=2*Math.round(n/o/2)):o<a&&(s=2*Math.round(i*o/2),u=i),{width:s,height:u}}_bindVideoTrackSizeChange(){this._stream.on(_s.SizeChange,({width:e,height:t})=>{this.setBaseProps("sourceWidth",e),this.setBaseProps("sourceHeight",t)})}getViewNode(){var i;if(!this._stream)return;let e={width:this._rect.width,height:this._rect.height};this._rect.keepRatio&&(e=this._getPaintSize({elementWidth:this._stream.width,elementHeight:this._stream.height})),this._paintSize=e;const t=(i=this._stream.viewNode)==null?void 0:i.size(e.width,e.height);let n;return this._rect.mirrorType!==void 0&&this._rect.mirrorType!==hs.None?n=t==null?void 0:t.mirror(this._rect.mirrorType):n=t,n=n==null?void 0:n.position(this._rect.x,this._rect.y),n}get x(){return this._rect.x}set x(e){this.setBaseProps("x",e)}get y(){return this._rect.y}set y(e){this.setBaseProps("y",e)}get width(){return this._rect.width}set width(e){this.setBaseProps("width",e)}get height(){return this._rect.height}set height(e){this.setBaseProps("height",e)}get zOrder(){return this._rect.zOrder}set zOrder(e){this.setBaseProps("zOrder",e)}get keepRatio(){return this._rect.keepRatio??!1}set keepRatio(e){this.setBaseProps("keepRatio",e)}set mirrorType(e){this.setBaseProps("mirrorType",e)}get paintSize(){return this._paintSize}setBaseProps(e,t){const n=this._rect[e]!==t;switch(e){case"width":this._rect.width=t;break;case"height":this._rect.height=t;break;case"x":this._rect.x=t;break;case"y":this._rect.y=t;break;case"zOrder":this._rect.zOrder=t;break;case"keepRatio":this._rect.keepRatio=t;break;case"mirrorType":this._rect.mirrorType=t;break}n&&this.emit("propsChange",{[e]:t})}show(){this._isHidden=!1}hide(){this._isHidden=!0}get stream(){return this._stream}get isHidden(){return this._isHidden}destroy(){}}class Uc extends ur{constructor(e,t){super({type:ae.MixVideo,stream:e}),this._trackMap.video=e,this._frameRate=(t==null?void 0:t.frameRate)??1}get source(){return this._source}replaceVideoTrack(e){this._trackMap.video=e,this._source=e}get viewNode(){return null}get mixerNode(){return null}bindTrackEnd(e){this.source.onended=e}destroy(){this.source.stop(),delete this._trackMap.video}}var iv=Object.defineProperty,ov=Object.getOwnPropertyDescriptor,dn=(r,e,t,n)=>{for(var i=ov(e,t),o=r.length-1,a;o>=0;o--)(a=r[o])&&(i=a(e,t,i)||i);return i&&iv(e,t,i),i};const Gc=new Bt("composition-composer");function ln(r,e,t){const n=t.value;return t.value=function(...i){return this._active||Gc.error("composer is not active"),n.apply(this,i)},t}class yr extends So{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new Hl}onStreamCapture(e){}onStreamStopCapture(e){e&&e.isVideoStream&&this.removeVideoStream(e.id)}enable(){var n;if(this._active)return;super.enable();const e=this._videoMixer.track(),t=this._mixedVideoStream;this._mixedVideoStream=new Uc(e,{frameRate:this._compositionViewConfig.frameRate}),this._composedStream.setVideoStream(this._mixedVideoStream),t&&((n=t.videoTrack)==null?void 0:n.id)!==e.id&&t.destroy()}disable(){super.disable(),this._videoMixer.stop()}_updateSpriteToMixer(){const e=xa(this._sprites.map(t=>t.isHidden?null:t.getViewNode()));this._videoMixer.draw(e)}_removeSprite(e){this._sprites=this._sprites.filter(t=>t!==e),e.destroy(),this._updateSpriteToMixer()}_addSprite(e){this._sprites.push(e),this._sprites=this._sprites.sort((t,n)=>t.zOrder-n.zOrder),e.on("propsChange",t=>{xm(t.zOrder)||(this._sprites=this._sprites.sort((n,i)=>n.zOrder-i.zOrder)),this._updateSpriteToMixer()}),this._updateSpriteToMixer()}setMixingConfig(e){const t=e.frameRate&&e.frameRate!==this._compositionViewConfig.frameRate;if(this._compositionViewConfig={...this._compositionViewConfig,...e},this._compositionViewConfig.frameRate<1&&(this._compositionViewConfig.frameRate=1),this._videoMixer.updateConfig(this._compositionViewConfig),t&&this._mixedVideoStream){const n=this._mixedVideoStream,i=this._videoMixer.updateFps();this._mixedVideoStream=new Uc(i,{frameRate:this._compositionViewConfig.frameRate}),this._composedStream.setVideoStream(this._mixedVideoStream),n.destroy()}}getMixingConfig(){return this._compositionViewConfig}addVideoStream(e,t){if(!e.viewNode){Gc.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const n=new nv(e,t);this._addSprite(n)}_updateSingleVideoStream(e){const t=e.streamId;if(!t)return;const n=this._sprites.find(i=>i.stream.id===t);n&&(n.height=e.height,n.width=e.width,n.x=e.x,n.y=e.y,n.zOrder=e.zOrder,n.keepRatio=e.keepRatio??!1,n.mirrorType=e.mirrorType)}updateVideoStream(e){e.forEach(t=>{this._updateSingleVideoStream(t)}),this._updateSpriteToMixer()}removeVideoStream(e){if(!e)return;const t=this._sprites.find(n=>n.stream.id===e);t&&this._removeSprite(t)}muteVideoStream(e){if(e){const t=this._sprites.find(n=>n.stream.id===e);t&&t.hide()}else this._sprites.forEach(t=>{t.hide()});this._updateSpriteToMixer()}unmuteVideoStream(e){if(e){const t=this._sprites.find(n=>n.stream.id===e);t&&t.show()}else this._sprites.forEach(t=>{t.show()});this._updateSpriteToMixer()}setMixerWorkerScript(e){this._videoMixer.setWorkerTimerScriptUrl(e)}getVideoStreamRenderConfig(e){const t=this._sprites.find(n=>n.stream.id===e);if(t)return{width:t.width,height:t.height,paintWidth:t.paintSize.width,paintHeight:t.paintSize.height,x:t.x,y:t.y,zOrder:t.zOrder}}getDrawCountPerSecond(){return this._videoMixer.getDrawCountPerSecond()}}dn([ln],yr.prototype,"addVideoStream"),dn([ln],yr.prototype,"updateVideoStream"),dn([ln],yr.prototype,"removeVideoStream"),dn([ln],yr.prototype,"muteVideoStream"),dn([ln],yr.prototype,"unmuteVideoStream");class sv extends Mt{constructor(e,{volume:t}){super(),this._volume=100,this._isMute=!1,this._volume=t??100,this._stream=e}get volume(){return this._volume}set volume(e){const t=this._volume!==e;this._volume=e,t&&this.emit("propsChange",{volume:e})}getMixerNode(){var e;return(e=this._stream.mixerNode)==null?void 0:e.gain(this._volume/100)}mute(){this._isMute=!0}unmute(){this._isMute=!1}get isMute(){return this._isMute}get stream(){return this._stream}}class av extends kn{constructor(e){super({type:ae.MixAudio,stream:e}),this._trackMap.audio=e}get source(){return this._source}hasVideoTrack(){return!1}get mixerNode(){return null}bindTrackEnd(e){this.source.onended=e}destroy(){var e;(e=this._trackMap.audio)==null||e.stop(),delete this._trackMap.audio}}class cv extends So{constructor(e){super(e),this._spriteList=[],this._audioMixer=new Il({keepAlive:!0})}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=xa(this._spriteList.map(t=>t.isMute?null:t.getMixerNode()));this._audioMixer.mix(e)}_updateSingleAudioStream(e){const{streamId:t,volume:n}=e,i=this._spriteList.find(o=>o.stream.id===t);i?n!==void 0&&(i.volume=n):console.error("can not find stream"+t)}enable(){super.enable();const e=this._audioMixer.track(),t=new av(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}resumeMixer(){this._audioMixer.resume()}addAudioStream(e,t){const n=new sv(e,t);this._spriteList.push(n),this._updateSpriteToMixer()}tryResume(){return this._audioMixer.resume()}removeAudioStream(e){const t=this._spriteList.find(n=>n.stream.id===e);t&&(this._spriteList=this._spriteList.filter(n=>n!==t),this._updateSpriteToMixer())}updateAudioStream(e){e.forEach(t=>{this._updateSingleAudioStream(t)}),this._updateSpriteToMixer()}muteAudioStream(e){if(e){const t=this._spriteList.find(n=>n.stream.id===e);t&&t.mute()}else this._spriteList.forEach(t=>{t.mute()});this._updateSpriteToMixer()}unmuteAudioStream(e){if(e){const t=this._spriteList.find(n=>n.stream.id===e);t&&t.unmute()}else this._spriteList.forEach(t=>{t.unmute()});this._updateSpriteToMixer()}haveMixedStream(e){return this._spriteList.some(t=>t.stream.id===e)}getMixedStreamByType(e){return this._spriteList.filter(t=>t.stream.type===e).map(t=>t.stream)}}class uv extends Mt{constructor({videoStream:e,audioStream:t}={}){super(),this._videoStream=e,this._audioStream=t}setVideoStream(e){var t;((t=this._videoStream)==null?void 0:t.id)!==(e==null?void 0:e.id)&&(this._videoStream=e,this.emit(qt.VideoStreamChange,e))}setAudioStream(e){var t;((t=this._audioStream)==null?void 0:t.id)!==e.id&&(this._audioStream=e,this.emit(qt.AudioStreamChange,e))}get audioStream(){return this._audioStream}get videoStream(){return this._videoStream}get videoTrack(){var e;return(e=this._videoStream)==null?void 0:e.videoTrack}get audioTrack(){var e;return(e=this._audioStream)==null?void 0:e.audioTrack}}const dv=new Bt("streamComposeController");class lv{constructor(e){this._streamManagerController=e,this._composedStream=new uv,this.singleComposer=new rv({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new yr({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new cv({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.singleComposer.enable(),this.mixerComposer.enable()}enableMixing(e){e?(this.compositionComposer.enable(),this.singleComposer.disable()):(this.compositionComposer.disable(),this.singleComposer.enable())}setVideoQuality({width:e,height:t,frameRate:n}){this.singleComposer.setVideoQuality({width:e,height:t,frameRate:n}),this.compositionComposer.setMixingConfig({width:e,height:t,frameRate:n})}setMixingConfig(e){this.compositionComposer.setMixingConfig(e)}getMixingConfig(){return this.compositionComposer.getMixingConfig()}addAudioStream(e){const t=this._streamManagerController.getStreamById(e.streamId);this.mixerComposer.addAudioStream(t,{volume:e.volume??100})}removeAudioStream(e){return this.mixerComposer.removeAudioStream(e)}updateAudioStream(e){this.mixerComposer.updateAudioStream(e)}addVideoStream(e){const t=this._streamManagerController.getVideoStream(e.streamId);if(!t){dv.error("can not find video stream"+e.streamId);return}this.compositionComposer.addVideoStream(t,e)}updateVideoStream(e){this.compositionComposer.updateVideoStream(e);const t=e.map(n=>({streamId:n.streamId,volume:n.volume}));this.mixerComposer.updateAudioStream(t)}removeVideoStream(e){this.compositionComposer.removeVideoStream(e),this.mixerComposer.removeAudioStream(e)}getComposer(){return this.isEnableMixing?this.compositionComposer:this.singleComposer}getComposedStream(){return this._composedStream}muteVideoStream(e){this.isEnableMixing?this.compositionComposer.muteVideoStream(e):this.singleComposer.muteVideoStream()}unmuteVideoStream(e){this.isEnableMixing?this.compositionComposer.unmuteVideoStream(e):this.singleComposer.unmuteVideoStream()}muteAudioStream(e){this.mixerComposer.muteAudioStream(e)}unmuteAudioStream(e){this.mixerComposer.unmuteAudioStream(e)}get isEnableMixing(){return this.compositionComposer._active}getMixerComposer(){return this.mixerComposer}setMixerWorkerScript(e){this.compositionComposer.setMixerWorkerScript(e)}getVideoStreamRenderConfig(e){if(this.compositionComposer._active)return this.compositionComposer.getVideoStreamRenderConfig(e)}resumeMixer(){return this.mixerComposer.tryResume()}getCompositionDrawCountPerSecond(){return this.compositionComposer.getDrawCountPerSecond()}}class Nc{constructor(e){this._hasBindComposedStreamEvent=!1,this._composedStream=e}bindComposedStreamEvent(){this._hasBindComposedStreamEvent||(this._composedStream.on(qt.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.on(qt.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!0)}unbindComposedStreamEvent(){this._hasBindComposedStreamEvent&&(this._composedStream.off(qt.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.off(qt.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!1)}}const Sr=new Bt("PreviewConsumer");class hv extends Nc{constructor(e,{streamConsumeController:t}){super(e),this._isPreviewing=!1,this._previewElement=null,this.handleAudioStreamChange=n=>{this.startPreview()},this.handleVideoStreamChange=n=>{this.startPreview()},this._streamConsumeController=t}start(){this.bindComposedStreamEvent()}stop(){this.unbindComposedStreamEvent()}setRenderView(e){if(!e)return;const t=document.getElementById(e);if(!t)throw new Error(`can not found element with id ${e}`);if(t===this._previewElement)return;if(this._previewElement){if(t.contains(this._previewElement))return;t.appendChild(this._previewElement);return}const n=document.createElement("video");n.style.width="100%",n.style.height="100%",n.autoplay=!0,n.playsInline=!0,n.setAttribute("webkit-playsinline",""),n.setAttribute("x5-playsinline",""),this._previewElement=n;const i={video:null,audio:null};n.addEventListener("loadeddata",()=>{const o=n.srcObject.getVideoTracks()[0],a=n.srcObject.getAudioTracks()[0];o&&o!==i.video&&(this._streamConsumeController.emit(Ee.CaptureFirstVideoFrame),i.video=o),a&&a!==i.audio&&(this._streamConsumeController.emit(Ee.CaptureFirstAudioFrame),i.audio=a)}),t.appendChild(n)}startPreview(){if(Sr.log("startPreview"),!this._previewElement){Sr.warn("preview element not found");return}this._isPreviewing||this.start();const e=this._composedStream.audioTrack,t=this._composedStream.videoTrack;e&&(this._appendTrack(this._previewElement,e),this._removeTrack(this._previewElement,null)),t&&(this._appendTrack(this._previewElement,t),this._removeTrack(this._previewElement,null)),this._previewElement.play().catch(n=>{this._streamConsumeController.emit(Ee.NotAllowedAutoPlay)}),this._isPreviewing=!0}stopPreview(){this._isPreviewing=!1;const e=this._composedStream.audioTrack,t=this._composedStream.videoTrack;e&&this._removeTrack(this._previewElement,e),t&&this._removeTrack(this._previewElement,t),this.stop()}destroy(){this.stopPreview(),this._previewElement=null,this.unbindComposedStreamEvent()}_appendTrack(e,t){if(!e||!t)return;const n=e.srcObject||new MediaStream;n.getTracks().find(i=>i.id===t.id)||(t.kind==="audio"&&n.getTracks().forEach(i=>{i.kind==="audio"&&(Sr.log(`remove preview track, ${i.label}, readyState=${i.readyState}`),n.removeTrack(i))}),t.kind==="video"&&n.getTracks().forEach(i=>{i.kind==="video"&&(n.removeTrack(i),Sr.log(`remove preview track, ${i.label}, readyState=${i.readyState}`))}),n.addTrack(t),e.srcObject?e.load():e.srcObject=n)}_removeTrack(e,t){if(!e)return;const n=e.srcObject;n&&(n.getTracks().forEach(i=>{(i.id===(t==null?void 0:t.id)||i.readyState==="ended")&&(Sr.log(`remove preview track ${i.label}`),n.removeTrack(i))}),n.getTracks().length===0&&(e.srcObject=null,Sr.log("set srcObject null")))}getPreviewElement(){if(this.isPreviewing)return this._previewElement}get isPreviewing(){return this._isPreviewing}}var ot={},bo={},Eo={exports:{}},Bc;function wo(){if(Bc)return Eo.exports;Bc=1;var r=Eo.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(r).forEach(function(e){var t=r[e];t.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),Eo.exports}var Fc;function fv(){return Fc||(Fc=1,function(r){var e=function(s){return String(Number(s))===s?Number(s):s},t=function(s,u,c,d){if(d&&!c)u[d]=e(s[1]);else for(var f=0;f<c.length;f+=1)s[f+1]!=null&&(u[c[f]]=e(s[f+1]))},n=function(s,u,c){var d=s.name&&s.names;s.push&&!u[s.push]?u[s.push]=[]:d&&!u[s.name]&&(u[s.name]={});var f=s.push?{}:d?u[s.name]:u;t(c.match(s.reg),f,s.names,s.name),s.push&&u[s.push].push(f)},i=wo(),o=RegExp.prototype.test.bind(/^([a-z])=(.*)/);r.parse=function(s){var u={},c=[],d=u;return s.split(/(\r\n|\r|\n)/).filter(o).forEach(function(f){var h=f[0],g=f.slice(2);h==="m"&&(c.push({rtp:[],fmtp:[]}),d=c[c.length-1]);for(var k=0;k<(i[h]||[]).length;k+=1){var z=i[h][k];if(z.reg.test(g))return n(z,d,g)}}),u.media=c,u};var a=function(s,u){var c=u.split(/=(.+)/,2);return c.length===2?s[c[0]]=e(c[1]):c.length===1&&u.length>1&&(s[c[0]]=void 0),s};r.parseParams=function(s){return s.split(/;\s?/).reduce(a,{})},r.parseFmtpConfig=r.parseParams,r.parsePayloads=function(s){return s.toString().split(" ").map(Number)},r.parseRemoteCandidates=function(s){for(var u=[],c=s.split(" ").map(e),d=0;d<c.length;d+=3)u.push({component:c[d],ip:c[d+1],port:c[d+2]});return u},r.parseImageAttributes=function(s){return s.split(" ").map(function(u){return u.substring(1,u.length-1).split(",").reduce(a,{})})},r.parseSimulcastStreamList=function(s){return s.split(";").map(function(u){return u.split(",").map(function(c){var d,f=!1;return c[0]!=="~"?d=e(c):(d=e(c.substring(1,c.length)),f=!0),{scid:d,paused:f}})})}}(bo)),bo}var Co,Vc;function pv(){if(Vc)return Co;Vc=1;var r=wo(),e=/%[sdv%]/g,t=function(a){var s=1,u=arguments,c=u.length;return a.replace(e,function(d){if(s>=c)return d;var f=u[s];switch(s+=1,d){case"%%":return"%";case"%s":return String(f);case"%d":return Number(f);case"%v":return""}})},n=function(a,s,u){var c=s.format instanceof Function?s.format(s.push?u:u[s.name]):s.format,d=[a+"="+c];if(s.names)for(var f=0;f<s.names.length;f+=1){var h=s.names[f];s.name?d.push(u[s.name][h]):d.push(u[s.names[f]])}else d.push(u[s.name]);return t.apply(null,d)},i=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];return Co=function(a,s){s=s||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(f){f.payloads==null&&(f.payloads="")});var u=s.outerOrder||i,c=s.innerOrder||o,d=[];return u.forEach(function(f){r[f].forEach(function(h){h.name in a&&a[h.name]!=null?d.push(n(f,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(g){d.push(n(f,h,g))})})}),a.media.forEach(function(f){d.push(n("m",r.m[0],f)),c.forEach(function(h){r[h].forEach(function(g){g.name in f&&f[g.name]!=null?d.push(n(h,g,f)):g.push in f&&f[g.push]!=null&&f[g.push].forEach(function(k){d.push(n(h,g,k))})})})}),d.join(`\r
67
67
  `)+`\r
68
68
  `},Co}var jc;function mv(){if(jc)return ot;jc=1;var r=fv(),e=pv(),t=wo();return ot.grammar=t,ot.write=e,ot.parse=r.parse,ot.parseParams=r.parseParams,ot.parseFmtpConfig=r.parseFmtpConfig,ot.parsePayloads=r.parsePayloads,ot.parseRemoteCandidates=r.parseRemoteCandidates,ot.parseImageAttributes=r.parseImageAttributes,ot.parseSimulcastStreamList=r.parseSimulcastStreamList,ot}var gv=mv();const Hn=Oe(gv);function hn(r){return new Promise(e=>{setTimeout(e,r)})}async function _v(r,e={},t=0,n=!1){const i=new AbortController;let o=!1;e=Object.assign({},e,{signal:i.signal});const a=[fetch(r,e)];t&&a.push(new Promise((s,u)=>{setTimeout(()=>{o||(u({httpCode:0,message:"Timeout"}),i.abort())},t)}));try{const s=await Promise.race(a);if(o=!0,!s.ok||s.status<200||s.status>=300)throw{httpCode:s.status,message:s.statusText};const u=await s.text();if(n||(s.headers.get("Content-Type")||"").includes("application/sdp"))return u;try{return JSON.parse(u)}catch{return u}}catch(s){throw o=!0,s}}async function ko(r,e={},t={}){const{timeout:n=0,retryDelay:i=0,expectText:o=!1}=t;let{retryCount:a=0}=t;try{return await _v(r,e,n,o)}catch(s){if(a--,t.retryCount=a,a<0)throw s;return await hn(i),await ko(r,e,t)}}const To=-1;function Ae(r,e){let t;return e.forEach(n=>{n.type===r&&(t=n)}),t}async function zo(r,e){const t={},n=await(r==null?void 0:r.getStats()),i=await(e==null?void 0:e.getStats());return n&&(t.audio={mediaSource:Ae("media-source",n),codec:Ae("codec",n),candidatePair:Ae("candidate-pair",n),remoteCandidate:Ae("remote-candidate",n),localCandidate:Ae("local-candidate",n),track:Ae("track",n),outboundRtp:Ae("outbound-rtp",n),remoteInboundRtp:Ae("remote-inbound-rtp",n),transport:Ae("transport",n)}),i&&(t.video={mediaSource:Ae("media-source",i),codec:Ae("codec",i),candidatePair:Ae("candidate-pair",i),remoteCandidate:Ae("remote-candidate",i),localCandidate:Ae("local-candidate",i),track:Ae("track",i),outboundRtp:Ae("outbound-rtp",i),remoteInboundRtp:Ae("remote-inbound-rtp",i),transport:Ae("transport",i)}),t}async function vv(r,e,t){var d,f,h,g,k,z,w,b,T,E,O,G,I,U,L,j,$,K,Z,W,se,oe,Y,le,fe,ue,be,ye,re,ke,de,_e,De,Ht,Ue,$t,Dt,Xe,Te;const n=await zo(e,t);await hn(r);const i=await zo(e,t),{audio:o,video:a}=n,{audio:s,video:u}=i,c={};if(o!=null&&o.codec&&(s!=null&&s.codec)){const Ie=((d=s.outboundRtp)==null?void 0:d.timestamp)-((f=o.outboundRtp)==null?void 0:f.timestamp),Ge=((h=s.outboundRtp)==null?void 0:h.bytesSent)-((g=o.outboundRtp)==null?void 0:g.bytesSent),Ne=((k=s.remoteInboundRtp)==null?void 0:k.packetsLost)-((z=o.remoteInboundRtp)==null?void 0:z.packetsLost),Be=((w=s.outboundRtp)==null?void 0:w.packetsSent)-((b=o.outboundRtp)==null?void 0:b.packetsSent),nt=(((T=s.mediaSource)==null?void 0:T.totalAudioEnergy)??0)-(((E=o.mediaSource)==null?void 0:E.totalAudioEnergy)??0);c.audio={codec:s.codec.mimeType,channels:s.codec.channels,sendBitrate:Ge/Ie*8e3,packetsSent:(O=s.outboundRtp)==null?void 0:O.packetsSent,nackCount:(G=s.outboundRtp)==null?void 0:G.nackCount,packetsLost:(I=s.remoteInboundRtp)==null?void 0:I.packetsLost,packetsLostPercent:Ne/Be,deltaAudioEnergy:nt}}if(a!=null&&a.codec&&(u!=null&&u.codec)){const Ie=((U=u.outboundRtp)==null?void 0:U.timestamp)-((L=a.outboundRtp)==null?void 0:L.timestamp),Ge=((j=u.outboundRtp)==null?void 0:j.bytesSent)-(($=a.outboundRtp)==null?void 0:$.bytesSent),Ne=((K=u.outboundRtp)==null?void 0:K.framesEncoded)-((Z=a.outboundRtp)==null?void 0:Z.framesEncoded),Be=((W=u.outboundRtp)==null?void 0:W.totalEncodeTime)-((se=a.outboundRtp)==null?void 0:se.totalEncodeTime),nt=((oe=u.outboundRtp)==null?void 0:oe.framesSent)-((Y=a.outboundRtp)==null?void 0:Y.framesSent),It=((le=u.outboundRtp)==null?void 0:le.packetsSent)-((fe=a.outboundRtp)==null?void 0:fe.packetsSent),ct=((ue=u.outboundRtp)==null?void 0:ue.totalPacketSendDelay)-((be=a.outboundRtp)==null?void 0:be.totalPacketSendDelay),ut=((ye=u.remoteInboundRtp)==null?void 0:ye.packetsLost)-((re=a.remoteInboundRtp)==null?void 0:re.packetsLost);c.video={codec:u.codec.mimeType,sendBitrate:Ge/Ie*8e3,frameWidth:(ke=u.outboundRtp)==null?void 0:ke.frameWidth,frameHeight:(de=u.outboundRtp)==null?void 0:de.frameHeight,framesPerSecond:Math.floor(nt/Ie*1e3||0),framesEncoded:(_e=u.outboundRtp)==null?void 0:_e.framesEncoded,framesEncodedPerSecond:Ne*1e3/Ie,keyFramesEncoded:(De=u.outboundRtp)==null?void 0:De.keyFramesEncoded,framesSent:(Ht=u.outboundRtp)==null?void 0:Ht.frameHeight,frameEncodeAvgTime:Be*1e3/Ne,packetsSent:(Ue=u.outboundRtp)==null?void 0:Ue.packetsSent,packetSendDelay:ct*1e3/It,nackCount:($t=u.outboundRtp)==null?void 0:$t.nackCount,firCount:(Dt=u.outboundRtp)==null?void 0:Dt.firCount,pliCount:(Xe=u.outboundRtp)==null?void 0:Xe.pliCount,packetsLost:(Te=u.remoteInboundRtp)==null?void 0:Te.packetsLost,packetsLostPercent:ut/It,deltaTime:Ie}}return{stats:c,originStats:{audio:s,video:u}}}function Ce(r,e=To){return r??e}function yv(r){var e,t,n,i,o,a,s,u,c,d,f,h,g,k,z,w,b,T,E,O,G,I,U,L,j,$,K,Z,W,se,oe,Y,le,fe,ue,be,ye,re,ke,de,_e;return{audio_bytes:(e=r.outboundRtp)==null?void 0:e.bytesSent,audio_packets_sent:(t=r.outboundRtp)==null?void 0:t.packetsSent,audio_nack_count:(n=r.outboundRtp)==null?void 0:n.nackCount,audio_ssrc:(i=r.outboundRtp)==null?void 0:i.ssrc,audio_retransmitted_bytes_sent:(o=r.outboundRtp)==null?void 0:o.retransmittedBytesSent,audio_retransmitted_packets_sent:(a=r.outboundRtp)==null?void 0:a.retransmittedPacketsSent,audio_record_sample_rate:(s=r.codec)==null?void 0:s.clockRate,audio_num_channels:(u=r.codec)==null?void 0:u.channels,audio_level:(c=r.mediaSource)!=null&&c.audioLevel?-10*Math.log10(Math.pow((d=r.mediaSource)==null?void 0:d.audioLevel,2)):(f=r.mediaSource)==null?void 0:f.audioLevel,audio_volume:(h=r.mediaSource)!=null&&h.audioLevel?((g=r.mediaSource)==null?void 0:g.audioLevel)*255:(k=r.mediaSource)==null?void 0:k.audioLevel,audio_total_audio_energy:(z=r.mediaSource)==null?void 0:z.totalAudioEnergy,audio_total_input_duration:(w=r.mediaSource)==null?void 0:w.totalSamplesDuration,audio_send_level:(b=r.mediaSource)==null?void 0:b.audioLevel,audio_ice_available_outgoing_bitrate:(T=r.candidatePair)==null?void 0:T.availableOutgoingBitrate,audio_ice_bytes_received:(E=r.candidatePair)==null?void 0:E.bytesReceived,audio_ice_bytes_sent:(O=r.candidatePair)==null?void 0:O.bytesSent,audio_ice_nominated:(G=r.candidatePair)==null?void 0:G.nominated,audio_ice_pair_id:(I=r.candidatePair)==null?void 0:I.id,audio_ice_pair_rtt:(U=r.candidatePair)==null?void 0:U.currentRoundTripTime,audio_ice_pair_state:(L=r.candidatePair)==null?void 0:L.state,audio_ice_pair_writable:(j=r.candidatePair)==null?void 0:j.writable,audio_recv_ping_requests:($=r.candidatePair)==null?void 0:$.requestsReceived,audio_recv_ping_responses:(K=r.candidatePair)==null?void 0:K.responsesReceived,audio_sent_ping_requests_before_first_response:(Z=r.candidatePair)==null?void 0:Z.requestsSent,audio_sent_ping_requests_total:(((W=r.candidatePair)==null?void 0:W.requestsSent)??0)+(((se=r.candidatePair)==null?void 0:se.consentRequestsSent)??0),audio_sent_ping_responses:(oe=r.candidatePair)==null?void 0:oe.responsesSent,audio_local_candidate_type:(Y=r.localCandidate)==null?void 0:Y.candidateType,audio_local_ip:((le=r.localCandidate)==null?void 0:le.ip)||((fe=r.localCandidate)==null?void 0:fe.address),audio_local_network_type:(ue=r.localCandidate)==null?void 0:ue.networkType,audio_local_port:(be=r.localCandidate)==null?void 0:be.port,audio_local_protocol:(ye=r.localCandidate)==null?void 0:ye.protocol,audio_remote_candidate_type:(re=r.remoteCandidate)==null?void 0:re.candidateType,audio_remote_ip:((ke=r.remoteCandidate)==null?void 0:ke.ip)||((de=r.remoteCandidate)==null?void 0:de.address),audio_remote_port:(_e=r.remoteCandidate)==null?void 0:_e.port}}function Sv(r){var e,t,n,i,o,a,s,u,c,d,f,h,g,k,z,w,b,T,E,O,G,I,U,L,j,$,K,Z,W,se,oe,Y,le,fe,ue,be,ye;return{video_qp_sum:(e=r.outboundRtp)==null?void 0:e.qpSum,video_pli_count:(t=r.outboundRtp)==null?void 0:t.pliCount,video_ssrc:(n=r.outboundRtp)==null?void 0:n.ssrc,video_quality_limitation_reason:(i=r.outboundRtp)==null?void 0:i.qualityLimitationReason,video_quality_limitation_durations:(o=r.outboundRtp)==null?void 0:o.qualityLimitationDurations,video_target_bitrate:(a=r.outboundRtp)==null?void 0:a.targetBitrate,video_rtt:(((s=r.remoteInboundRtp)==null?void 0:s.roundTripTime)||0)*1e3,video_jitter:(((u=r.remoteInboundRtp)==null?void 0:u.jitter)||0)*1e3,video_packets_lost:(c=r.remoteInboundRtp)==null?void 0:c.packetsLost,video_fraction_lost:(d=r.remoteInboundRtp)==null?void 0:d.fractionLost,video_ice_available_outgoing_bitrate:(f=r.candidatePair)==null?void 0:f.availableOutgoingBitrate,video_ice_bytes_received:(h=r.candidatePair)==null?void 0:h.bytesReceived,video_ice_bytes_sent:(g=r.candidatePair)==null?void 0:g.bytesSent,video_ice_nominated:(k=r.candidatePair)==null?void 0:k.nominated,video_ice_pair_id:(z=r.candidatePair)==null?void 0:z.id,video_ice_pair_rtt:(w=r.candidatePair)==null?void 0:w.currentRoundTripTime,video_ice_pair_state:(b=r.candidatePair)==null?void 0:b.state,video_ice_pair_writable:(T=r.candidatePair)==null?void 0:T.writable,video_recv_ping_requests:(E=r.candidatePair)==null?void 0:E.requestsReceived,video_recv_ping_responses:(O=r.candidatePair)==null?void 0:O.responsesReceived,video_sent_ping_requests_before_first_response:(G=r.candidatePair)==null?void 0:G.requestsSent,video_sent_ping_requests_total:(((I=r.candidatePair)==null?void 0:I.requestsSent)??0)+(((U=r.candidatePair)==null?void 0:U.consentRequestsSent)??0),video_sent_ping_responses:(L=r.candidatePair)==null?void 0:L.responsesSent,video_local_candidate_type:(j=r.localCandidate)==null?void 0:j.candidateType,video_local_ip:(($=r.localCandidate)==null?void 0:$.ip)||((K=r.localCandidate)==null?void 0:K.address),video_local_network_type:(Z=r.localCandidate)==null?void 0:Z.networkType,video_local_port:(W=r.localCandidate)==null?void 0:W.port,video_local_protocol:(se=r.localCandidate)==null?void 0:se.protocol,video_remote_candidate_type:(oe=r.remoteCandidate)==null?void 0:oe.candidateType,video_remote_ip:((Y=r.remoteCandidate)==null?void 0:Y.ip)||((le=r.remoteCandidate)==null?void 0:le.address),video_remote_port:(fe=r.remoteCandidate)==null?void 0:fe.port,video_input_frame_rate:(ue=r.mediaSource)==null?void 0:ue.framesPerSecond,video_input_frame_width:(be=r.mediaSource)==null?void 0:be.width,video_input_frame_height:(ye=r.mediaSource)==null?void 0:ye.height}}function bv(r,e,t){var c,d,f,h,g,k,z,w,b,T,E,O,G,I,U,L,j,$,K,Z,W,se,oe,Y,le,fe,ue;const n=Sv(e.video??{}),{video_input_frame_width:i,video_input_frame_height:o}=n,a=Ce((c=r.video)==null?void 0:c.frameWidth),s=Ce((d=r.video)==null?void 0:d.frameHeight),u=a<Number(i)||s<Number(o);return{...n,video_send_k_bitrate:Ce((f=r.video)==null?void 0:f.sendBitrate)/1e3,video_send_frame_rate:Ce((h=r.video)==null?void 0:h.framesPerSecond),video_encode_avg_time:Ce((g=r.video)==null?void 0:g.frameEncodeAvgTime),video_encoder_output_frame_rate:Ce((k=r.video)==null?void 0:k.framesEncodedPerSecond),video_encoded_frame_width:Ce((z=r.video)==null?void 0:z.frameWidth),video_encoded_frame_height:Ce((w=r.video)==null?void 0:w.frameHeight),video_encoded_key_frames:Ce((b=r.video)==null?void 0:b.keyFramesEncoded),video_delta_time:Ce((T=r.video)==null?void 0:T.deltaTime,2e3),video_packets_sent:Ce((E=r.video)==null?void 0:E.packetsSent),video_nack_count:Ce((O=r.video)==null?void 0:O.nackCount),video_fir_count:Ce((G=r.video)==null?void 0:G.firCount),video_pli_count:Ce((I=r.video)==null?void 0:I.pliCount),video_packets_lost:Ce((U=r.video)==null?void 0:U.packetsLost),video_packets_lost_percent:(L=r.video)==null?void 0:L.packetsLostPercent,video_codec:(j=r.video)==null?void 0:j.codec,video_duration:($=r.video)==null?void 0:$.deltaTime,video_frame_rate_compliance:t!=null&&t.idealFrameRate?Math.min(Ce((K=r.video)==null?void 0:K.framesPerSecond)/t.idealFrameRate,1)*100:To,video_bitrate_compliance:t!=null&&t.idealBitrate?Math.min(Ce((Z=r.video)==null?void 0:Z.sendBitrate)/t.idealBitrate,1)*100:To,video_resolution_downgrade:u,...yv(e.audio??{}),audio_send_k_bitrate:Ce((W=r.audio)==null?void 0:W.sendBitrate)/1e3,audio_send_channels:Ce((se=r.audio)==null?void 0:se.channels),audio_packets_sent:Ce((oe=r.audio)==null?void 0:oe.packetsSent),audio_packets_lost:Ce((Y=r.audio)==null?void 0:Y.packetsLost),audio_packets_lost_percent:(le=r.audio)==null?void 0:le.packetsLostPercent,audio_codec:(fe=r.audio)==null?void 0:fe.codec,audio_delta_energy:(ue=r.audio)==null?void 0:ue.deltaAudioEnergy}}function Ev(r){return{video_send_k_bitrate:r.video.sendBitrate/1e3,video_send_frame_rate:r.video.framesPerSecond,video_encoded_frame_width:r.video.frameWidth,video_encoded_frame_height:r.video.frameHeight,video_encoded_key_frames:r.video.keyFramesEncoded,video_send_speed:r.video.sendSpeed/1e3,video_gop_size:r.video.gopSize,video_codec:r.video.codec,video_duration:0,audio_send_k_bitrate:r.audio.sendBitrate/1e3,audio_codec:r.audio.codec,audio_send_channels:r.audio.channels,audio_send_sample_rate:r.audio.sampleRate}}const wv="42001f",Cv="42e01f",kv=r=>{var t;if(!Ts)return;const e=(t=r.rtp.filter(n=>n.codec==="opus")[0])==null?void 0:t.payload;e&&r.fmtp.forEach(n=>{n.payload===e&&(n.config="minptime=10;useinbandfec=1")})},Tv=r=>{r.ext&&(Od||yn)&&(r.ext=r.ext.filter(e=>{var t;return!((t=e.uri)!=null&&t.includes("video-orientation"))}))};function zv(r,e){r==null||r.rtp.forEach(({codec:t,payload:n})=>{if(["vp8","h264"].includes(t.toLocaleLowerCase())){const i=r.fmtp.find(o=>o.payload===n);if(i){if(i.config.includes("x-google-max-bitrate")||i.config.includes("x-google-start-bitrate")||i.config.includes("x-google-min-bitrate"))return;i.config=[...i.config.split(";"),`x-google-min-bitrate=${e*.4}`,`x-google-start-bitrate=${e}`].join(";")}else r.fmtp.push({payload:n,config:`x-google-min-bitrate=${e*.4};x-google-start-bitrate=${e}`})}})}function Hc(r,e){if(!Array.isArray(r.fmtp)||!Array.isArray(r.rtp))return;const t=r.fmtp.find(a=>a.config&&a.config.includes(wv)),n=r.fmtp.find(a=>a.config&&a.config.includes(Cv));if(!t||!n)return;const i=r.rtp.findIndex(a=>a.payload===t.payload),o=r.rtp.findIndex(a=>a.payload===n.payload);if(i!==-1&&o!==-1){if(e==="hardware"){if(o<i){const a=r.rtp[o];r.rtp[o]=r.rtp[i],r.rtp[i]=a}}else if(i<o){const a=r.rtp[i];r.rtp[i]=r.rtp[o],r.rtp[o]=a}}r.payloads=r.rtp.map(a=>a.payload).join(" ")}function Rv(r,e){if(!Array.isArray(r.rtp))return;const t=r.rtp.find(o=>o.codec===e),n=r.fmtp.find(o=>o.config.includes(String(t==null?void 0:t.payload))),i=[t==null?void 0:t.payload,n==null?void 0:n.payload];r.rtp=r.rtp.filter(o=>!i.includes(o.payload)),r.fmtp=r.fmtp.filter(o=>!i.includes(o.payload)),r.rtcpFb&&(r.rtcpFb=r.rtcpFb.filter(o=>!i.includes(o.payload))),r.payloads=r.rtp.map(o=>o.payload).join(" ")}const Av=()=>typeof window>"u",_t={},$n=async r=>{const e=new RTCPeerConnection({sdpSemantics:"unified-plan"});e.addTransceiver("video",{direction:r});const t=await e.createOffer();return e.close(),t.sdp.toLowerCase()};function $c(r){const e=r.split(`
69
69
  `);let t=!1;for(const n of e)if(n.includes("level-asymmetry-allowed=1")&&n.includes("packetization-mode=1")&&n.includes("profile-level-id=42e0")){t=!0;break}if(t){const n=navigator.userAgent.toLowerCase();let i=!1;const o=[/miuibrowser/,/70.*HeyTapBrowser/i];for(const a of o)a.test(n)&&(i=!0);return!i}return!1}const Dv=async()=>{let r=await $n("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await $n("sendonly")),_t.h264encode=$c(r),_t.vp8encode=r.indexOf("vp8")>-1,_t},Iv=async()=>{let r=await $n("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await $n("recvonly")),_t.h264decode=$c(r),_t.vp8decode=r.indexOf("vp8")>-1,_t},xv=async()=>{if(typeof _t.h264encode>"u")try{await Dv()}catch{return!1}return _t.h264encode||!1},Mv=async()=>{if(typeof _t.h264decode>"u")try{await Iv()}catch{return!1}return _t.h264decode||!1},je=new Bt("PCConnect"),us=class us{constructor(e,t,n){this._pc=null,this._ms=new MediaStream,this._signalUrl="",this._videoTransceiver=null,this._audioTransceiver=null,this._opts=void 0,this._sessionId=Date.now(),this._signalUrl=e,this._opts=t,this._onConnectStateChange=n}get isPushing(){var e,t,n,i;return!!((t=(e=this._videoTransceiver)==null?void 0:e.sender)!=null&&t.track||(i=(n=this._audioTransceiver)==null?void 0:n.sender)!=null&&i.track)}get videoSenderTrackStats(){var e,t,n,i;return{track_enabled:(t=(e=this._videoTransceiver)==null?void 0:e.sender.track)==null?void 0:t.enabled,track_muted:(i=(n=this._videoTransceiver)==null?void 0:n.sender.track)==null?void 0:i.muted}}get pushUrl(){return this._signalUrl}get sessionId(){return this._sessionId}async getSdpWithWHIP({url:e,bearerToken:t,offer:n,isReconnect:i}){var a;return{code:200,message:"success",remoteSdp:{sdp:await ko(e,{method:"POST",headers:{"Content-Type":"application/sdp",Authorization:`Bearer ${t}`},body:n.sdp},{...this._opts,timeout:i?10*Pi:(a=this._opts)==null?void 0:a.timeout}),type:"answer"}}}async getSdpWithSdp({url:e,offer:t,isReconnect:n}){var o;return await ko(e,{method:"POST",mode:"cors",body:JSON.stringify({sessionId:""+this._sessionId,version:"1.0-html",localSdp:t,metadata:{platform:"Web"}})},{...this._opts,timeout:n?10*Pi:(o=this._opts)==null?void 0:o.timeout})}async getCustomRTMAnswerSdp(e){var t,n;try{const i=await((n=(t=ht.instance).getCustomRTMAnswerSdp)==null?void 0:n.call(t,e));return i?{code:200,message:"success",remoteSdp:i}:{code:400,message:"getCustomRTMAnswerSdp return empty sdp",remoteSdp:null}}catch{return{code:500,message:"getCustomRTMAnswerSdp error",remoteSdp:null}}}async publish(e,t,n){var d,f;const i=new RTCPeerConnection;this._pc=i,this._bindRTCEvent();const o=e.filter(h=>(h==null?void 0:h.kind)==="audio")[0],a=e.filter(h=>(h==null?void 0:h.kind)==="video")[0];o&&this._ms.addTrack(o),a&&this._ms.addTrack(a),this._audioTransceiver=i.addTransceiver(o||"audio",{direction:"sendonly",sendEncodings:[{maxBitrate:t[0]}],streams:[this._ms]}),je.log("add track to pc,",o),this._videoTransceiver=i.addTransceiver(a||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),je.log("add track to pc,",a);const s=await i.createOffer();je.groupCollapsed("local offer"),je.log(s.sdp),await i.setLocalDescription(s);let u;if(ht.instance.getCustomRTMAnswerSdp?u=await this.getCustomRTMAnswerSdp(s):(d=n==null?void 0:n.whipConfig)!=null&&d.useWHIP?u=await this.getSdpWithWHIP({url:this._signalUrl,bearerToken:(f=n==null?void 0:n.whipConfig)==null?void 0:f.bearerToken,offer:s,isReconnect:n==null?void 0:n.isReconnect}):u=await this.getSdpWithSdp({url:this._signalUrl,offer:s,isReconnect:n==null?void 0:n.isReconnect}),(u==null?void 0:u.code)!==200)throw{code:u.code,message:u.message};je.log("remote answer:"),je.log(u.remoteSdp.sdp);const c=Hn.parse(u.remoteSdp.sdp);if(c.media.forEach(h=>{var g;(g=h.fingerprint)!=null&&g.hash&&(h.fingerprint.hash=h.fingerprint.hash.toUpperCase()),h.type==="audio"?kv(h):h.type==="video"&&(Tv(h),Hc(h,"software"),Rv(h,"AV1"),zv(h,t[1]))}),u.remoteSdp.sdp=Hn.write(c),je.log("remote answer modified"),je.log(u.remoteSdp.sdp),je.groupEnd(),i.connectionState==="closed"){je.log("PeerConnection is closed, skipping setRemoteDescription");return}X(J.PUSH_SDP_INFO,{offer_sdp:s.sdp,answer_sdp:u.remoteSdp.sdp}),await i.setRemoteDescription(u.remoteSdp)}updateVideoEncodeType(e){var o,a;const t=this._pc,n=(o=t==null?void 0:t.localDescription)==null?void 0:o.sdp,i=(a=t==null?void 0:t.remoteDescription)==null?void 0:a.sdp;if(n&&i){const s=Hn.parse(i);s.media.forEach(u=>{u.type==="video"&&Hc(u,e)}),t.setLocalDescription(t.localDescription),t.setRemoteDescription({type:"answer",sdp:Hn.write(s)})}}async updatePublish(e,t){var o,a;let n;t==="video"?n=this._videoTransceiver:n=this._audioTransceiver;const i=(o=n==null?void 0:n.sender)==null?void 0:o.track;(i==null?void 0:i.id)!==(e==null?void 0:e.id)&&(await((a=n==null?void 0:n.sender)==null?void 0:a.replaceTrack(e)),je.log(`replace ${t} track done! ${i==null?void 0:i.label} -> ${e==null?void 0:e.label}`))}applyBitrate(e,t,n){var a,s,u;const i=t==="video"?(a=this._videoTransceiver)==null?void 0:a.sender:(s=this._audioTransceiver)==null?void 0:s.sender;if(!i)return;const o=i.getParameters();o.encodings=(u=o.encodings)!=null&&u.length?o.encodings:[{}],n?o.encodings[0].minBitrate=e:o.encodings[0].maxBitrate=e,i.setParameters(o),je.log(`set bitrate for ${t}, ${e} bps, min:${n}`)}unpublish(){var e,t;(e=this._pc)==null||e.getSenders().forEach(n=>{var i;(i=this._pc)==null||i.removeTrack(n)}),(t=this._pc)==null||t.close(),this._audioTransceiver=null,this._videoTransceiver=null,this._pc=null,je.log("close pc!")}getStats(){var e,t;return zo((e=this._audioTransceiver)==null?void 0:e.sender,(t=this._videoTransceiver)==null?void 0:t.sender)}getStatsSnapshoot(e){var t,n;return vv(e||100,(t=this._audioTransceiver)==null?void 0:t.sender,(n=this._videoTransceiver)==null?void 0:n.sender)}_bindRTCEvent(){const e=this._pc;e==null||e.addEventListener("connectionstatechange",()=>{je.log("onconnectionstatechange:",e.connectionState),this._onConnectStateChange(e.connectionState)})}};us.isSupported=async()=>{try{return Av()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await Mv()&&await xv()}catch{return!1}};let qn=us;var Ft=(r=>(r.OnError="onerror",r.OnConnectClosed="onconnectclosed",r.OnFirstFramePushed="onfirstframepushed",r))(Ft||{}),Vt=(r=>(r.Video="video",r.Audio="audio",r))(Vt||{}),tt=(r=>(r.Init="init",r.AvExist="avexist",r.VideoFrame="videoframe",r.MockVideoEncode="mockvideoencode",r.AudioFrame="audioframe",r.AdjustBitrate="adjustbitrate",r.Publish="publish",r.UnPublish="unpublish",r.Download="download",r.GetStats="getstats",r.EncodeConfig="encodeconfig",r))(tt||{}),nr=(r=>(r.Ready="ready",r.Error="error",r.FirstFramePushed="firstframepushed",r.Flvfile="flvfile",r.STATS="stats",r.Close="close",r))(nr||{}),Ro={exports:{}},qc;function Ov(){return qc||(qc=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(t=!1));function i(u,c,d){this.fn=u,this.context=c,this.once=d||!1}function o(u,c,d,f,h){if(typeof d!="function")throw new TypeError("The listener must be a function");var g=new i(d,f||u,h),k=t?t+c:c;return u._events[k]?u._events[k].fn?u._events[k]=[u._events[k],g]:u._events[k].push(g):(u._events[k]=g,u._eventsCount++),u}function a(u,c){--u._eventsCount===0?u._events=new n:delete u._events[c]}function s(){this._events=new n,this._eventsCount=0}s.prototype.eventNames=function(){var c=[],d,f;if(this._eventsCount===0)return c;for(f in d=this._events)e.call(d,f)&&c.push(t?f.slice(1):f);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(d)):c},s.prototype.listeners=function(c){var d=t?t+c:c,f=this._events[d];if(!f)return[];if(f.fn)return[f.fn];for(var h=0,g=f.length,k=new Array(g);h<g;h++)k[h]=f[h].fn;return k},s.prototype.listenerCount=function(c){var d=t?t+c:c,f=this._events[d];return f?f.fn?1:f.length:0},s.prototype.emit=function(c,d,f,h,g,k){var z=t?t+c:c;if(!this._events[z])return!1;var w=this._events[z],b=arguments.length,T,E;if(w.fn){switch(w.once&&this.removeListener(c,w.fn,void 0,!0),b){case 1:return w.fn.call(w.context),!0;case 2:return w.fn.call(w.context,d),!0;case 3:return w.fn.call(w.context,d,f),!0;case 4:return w.fn.call(w.context,d,f,h),!0;case 5:return w.fn.call(w.context,d,f,h,g),!0;case 6:return w.fn.call(w.context,d,f,h,g,k),!0}for(E=1,T=new Array(b-1);E<b;E++)T[E-1]=arguments[E];w.fn.apply(w.context,T)}else{var O=w.length,G;for(E=0;E<O;E++)switch(w[E].once&&this.removeListener(c,w[E].fn,void 0,!0),b){case 1:w[E].fn.call(w[E].context);break;case 2:w[E].fn.call(w[E].context,d);break;case 3:w[E].fn.call(w[E].context,d,f);break;case 4:w[E].fn.call(w[E].context,d,f,h);break;default:if(!T)for(G=1,T=new Array(b-1);G<b;G++)T[G-1]=arguments[G];w[E].fn.apply(w[E].context,T)}}return!0},s.prototype.on=function(c,d,f){return o(this,c,d,f,!1)},s.prototype.once=function(c,d,f){return o(this,c,d,f,!0)},s.prototype.removeListener=function(c,d,f,h){var g=t?t+c:c;if(!this._events[g])return this;if(!d)return a(this,g),this;var k=this._events[g];if(k.fn)k.fn===d&&(!h||k.once)&&(!f||k.context===f)&&a(this,g);else{for(var z=0,w=[],b=k.length;z<b;z++)(k[z].fn!==d||h&&!k[z].once||f&&k[z].context!==f)&&w.push(k[z]);w.length?this._events[g]=w.length===1?w[0]:w:a(this,g)}return this},s.prototype.removeAllListeners=function(c){var d;return c?(d=t?t+c:c,this._events[d]&&a(this,d)):(this._events=new n,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prefixed=t,s.EventEmitter=s,r.exports=s}(Ro)),Ro.exports}var Pv=Ov();const Lv=Oe(Pv);var Kn=(r=>(r[r.RTMP_INIT_FAIL=3e3]="RTMP_INIT_FAIL",r[r.AUDIO_ENCODER_INIT_FAIL=3001]="AUDIO_ENCODER_INIT_FAIL",r[r.AUDIO_RRNOISE_INIT_FAIL=3002]="AUDIO_RRNOISE_INIT_FAIL",r[r.AUDIO_ENCODE_FAIL=3003]="AUDIO_ENCODE_FAIL",r[r.VIDEO_ENCODE_CONFIGURE_FAIL=3004]="VIDEO_ENCODE_CONFIGURE_FAIL",r[r.VIDEO_ENCODE_FAIL=3005]="VIDEO_ENCODE_FAIL",r[r.WTP_OPEN_FAIL=3006]="WTP_OPEN_FAIL",r[r.WTP_CONNECT_FAIL=3007]="WTP_CONNECT_FAIL",r[r.WORKER_ERROR=3008]="WORKER_ERROR",r))(Kn||{});class Kc extends Error{constructor(e,t,n){super(),this.code=e,this.message=t,n&&(this.ext=n),this.toJson=()=>({code:this.code,message:this.message,ext:this.ext})}}function Wc(r,e,t){return new Kc(r,e,t)}let br=(At=class{constructor(e){this.group=(...t)=>{this._enabled&&console.group(`[${this._prefix}]: `,...t)},this.groupCollapsed=(...t)=>{this._enabled&&console.groupCollapsed(`[${this._prefix}]: `,...t)},this.groupEnd=()=>{this._enabled&&console.groupEnd()},this.log=(...t)=>{this._enabled&&console.log(`[${this._prefix}]: `,...t)},this.warn=(...t)=>{this._enabled&&console.warn(`[${this._prefix}]: `,...t)},this.error=(...t)=>{this._enabled&&console.error(`[${this._prefix}]: `,...t)},this.table=(...t)=>{this._enabled&&console.table(...t)},this._prefix=e}get _enabled(){return At.enable}get _enableLong(){return At.enableLong}get long(){return this._enableLong}},At.enable=!1,At.enableLong=!1,At);const rt=new br("RTMP_Capture");class Uv{constructor(e){this._videoFirstframeCaptured=!1,this._audioFirstframeCaptured=!1,this._videoProcessorReader=null,this._audioProcessorReader=null,this._bridge=e}get audioTrack(){return this._bridge.audioMsTrack}get videoTrack(){return this._bridge.videoMsTrack}start(){this._startVideoCapture(),this._startAudioCapture()}restartCapture(e){if(rt.log(`replace ${e} track`),e===Vt.Video){if(this._videoProcessorReader){this._videoProcessorReader.cancel().finally(()=>{this._startVideoCapture()});return}this._startVideoCapture();return}if(this._audioProcessorReader){this._audioProcessorReader.cancel().finally(()=>{this._startAudioCapture()});return}this._startAudioCapture()}async _startVideoCapture(){var i;if(!this.videoTrack){rt.log("no video track to capture");return}if(this.videoTrack.readyState!=="live"){rt.warn("video track not live");return}const e=new MediaStreamTrackProcessor(this.videoTrack);e.track=this.videoTrack;const t=e.readable.getReader();this._videoProcessorReader=t,rt.log("start capture video frame",this.videoTrack);let n;for(;;){n&&clearInterval(n),n=setTimeout(()=>{rt.warn("long time no capture output"),this._bridge._postMockVideoEncodeFlag()},1500);const o=await t.read();if(clearInterval(n),this._videoFirstframeCaptured||(this._videoFirstframeCaptured=!0,rt.log("video first frame captured")),o.done||!o.value){(i=o.value)==null||i.close();break}this._bridge._postVideoFrame(o.value,this.videoTrack.getSettings())}clearInterval(n),this._videoFirstframeCaptured=!1,this._videoProcessorReader=null,rt.log("video track read done!",e.track)}async _startAudioCapture(){if(!this.audioTrack){rt.log("no audio track to capture");return}if(this.audioTrack.readyState!=="live"){rt.warn("audio track not live");return}const e=new MediaStreamTrackProcessor(this.audioTrack);e.track=this.audioTrack;const t=e.readable.getReader();for(this._audioProcessorReader=t,rt.log("start capture audio frame");;){const n=await t.read();if(this._audioFirstframeCaptured||(this._audioFirstframeCaptured=!0,rt.log("audio first frame captured")),n.done||!n.value)break;this._bridge._postAudioFrame(n.value,this.audioTrack.getSettings())}this._audioFirstframeCaptured=!1,this._audioProcessorReader=null,rt.log("audio track read done!",e.track)}destroy(){var e,t;(e=this._audioProcessorReader)==null||e.cancel().catch(()=>{}),(t=this._videoProcessorReader)==null||t.cancel().catch(()=>{})}}const Jc='(function(){"use strict";var l=(i=>(i.OnVideoCaptured="onvideocaptured",i.OnAudioCaptured="onaudiocaptured",i.OnVideoCaptureNoOutput="onvideocapturenooutput",i.OnVideoEncoded="onvideoencoded",i.OnAudioEncoded="onaudioencoded",i.OnEncodedFrame="onencodedframe",i.OnPacketed="onpacketed",i.OnUpstreamFeedback="onupstreamfeedback",i.OnBitrateChanged="onbitratechanged",i))(l||{}),O=(i=>(i.OnError="onerror",i.OnConnectClosed="onconnectclosed",i.OnFirstFramePushed="onfirstframepushed",i))(O||{}),I=(i=>(i.Video="video",i.Audio="audio",i))(I||{}),v=(i=>(i.Init="init",i.AvExist="avexist",i.VideoFrame="videoframe",i.MockVideoEncode="mockvideoencode",i.AudioFrame="audioframe",i.AdjustBitrate="adjustbitrate",i.Publish="publish",i.UnPublish="unpublish",i.Download="download",i.GetStats="getstats",i.EncodeConfig="encodeconfig",i))(v||{}),w=(i=>(i.Ready="ready",i.Error="error",i.FirstFramePushed="firstframepushed",i.Flvfile="flvfile",i.STATS="stats",i.Close="close",i))(w||{});function $(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var k={exports:{}},U;function q(){return U||(U=1,function(i){var t=Object.prototype.hasOwnProperty,e="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(e=!1));function r(u,a,n){this.fn=u,this.context=a,this.once=n||!1}function o(u,a,n,h,m){if(typeof n!="function")throw new TypeError("The listener must be a function");var g=new r(n,h||u,m),f=e?e+a:a;return u._events[f]?u._events[f].fn?u._events[f]=[u._events[f],g]:u._events[f].push(g):(u._events[f]=g,u._eventsCount++),u}function _(u,a){--u._eventsCount===0?u._events=new s:delete u._events[a]}function c(){this._events=new s,this._eventsCount=0}c.prototype.eventNames=function(){var a=[],n,h;if(this._eventsCount===0)return a;for(h in n=this._events)t.call(n,h)&&a.push(e?h.slice(1):h);return Object.getOwnPropertySymbols?a.concat(Object.getOwnPropertySymbols(n)):a},c.prototype.listeners=function(a){var n=e?e+a:a,h=this._events[n];if(!h)return[];if(h.fn)return[h.fn];for(var m=0,g=h.length,f=new Array(g);m<g;m++)f[m]=h[m].fn;return f},c.prototype.listenerCount=function(a){var n=e?e+a:a,h=this._events[n];return h?h.fn?1:h.length:0},c.prototype.emit=function(a,n,h,m,g,f){var F=e?e+a:a;if(!this._events[F])return!1;var d=this._events[F],C=arguments.length,B,p;if(d.fn){switch(d.once&&this.removeListener(a,d.fn,void 0,!0),C){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,n),!0;case 3:return d.fn.call(d.context,n,h),!0;case 4:return d.fn.call(d.context,n,h,m),!0;case 5:return d.fn.call(d.context,n,h,m,g),!0;case 6:return d.fn.call(d.context,n,h,m,g,f),!0}for(p=1,B=new Array(C-1);p<C;p++)B[p-1]=arguments[p];d.fn.apply(d.context,B)}else{var fe=d.length,R;for(p=0;p<fe;p++)switch(d[p].once&&this.removeListener(a,d[p].fn,void 0,!0),C){case 1:d[p].fn.call(d[p].context);break;case 2:d[p].fn.call(d[p].context,n);break;case 3:d[p].fn.call(d[p].context,n,h);break;case 4:d[p].fn.call(d[p].context,n,h,m);break;default:if(!B)for(R=1,B=new Array(C-1);R<C;R++)B[R-1]=arguments[R];d[p].fn.apply(d[p].context,B)}}return!0},c.prototype.on=function(a,n,h){return o(this,a,n,h,!1)},c.prototype.once=function(a,n,h){return o(this,a,n,h,!0)},c.prototype.removeListener=function(a,n,h,m){var g=e?e+a:a;if(!this._events[g])return this;if(!n)return _(this,g),this;var f=this._events[g];if(f.fn)f.fn===n&&(!m||f.once)&&(!h||f.context===h)&&_(this,g);else{for(var F=0,d=[],C=f.length;F<C;F++)(f[F].fn!==n||m&&!f[F].once||h&&f[F].context!==h)&&d.push(f[F]);d.length?this._events[g]=d.length===1?d[0]:d:_(this,g)}return this},c.prototype.removeAllListeners=function(a){var n;return a?(n=e?e+a:a,this._events[n]&&_(this,n)):(this._events=new s,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=e,c.EventEmitter=c,i.exports=c}(k)),k.exports}var z=q(),H=$(z);const N=class N{constructor(t){this.group=(...e)=>{this._enabled&&console.group(`[${this._prefix}]: `,...e)},this.groupCollapsed=(...e)=>{this._enabled&&console.groupCollapsed(`[${this._prefix}]: `,...e)},this.groupEnd=()=>{this._enabled&&console.groupEnd()},this.log=(...e)=>{this._enabled&&console.log(`[${this._prefix}]: `,...e)},this.warn=(...e)=>{this._enabled&&console.warn(`[${this._prefix}]: `,...e)},this.error=(...e)=>{this._enabled&&console.error(`[${this._prefix}]: `,...e)},this.table=(...e)=>{this._enabled&&console.table(...e)},this._prefix=t}get _enabled(){return N.enable}get _enableLong(){return N.enableLong}get long(){return this._enableLong}};N.enable=!1,N.enableLong=!1;let E=N;function S(i){i=i.filter(Boolean);const t=new Uint8Array(i.reduce((s,r)=>s+r.byteLength,0));let e=0;return i.forEach(s=>{t.set(s,e),e+=s.byteLength}),t}const A={codec:"avc1.4DE033",MaxCachedFrameSize:100,RealSpeedPercent:.8,UplinkBitrateCheckInterval:60*1e3,VideoBitrateDefault:1e6,AudioBitrateDefault:68e3,gopSize:90,sampleRate:48e3,channel:2,audioEncoderPath:"https://lf-unpkg.volccdn.com/obj/vcloudfe/sdk/Web_push/1.0.1/1735619140327/pcm2aac.js",audioEncoderWasmPath:"https://lf-unpkg.volccdn.com/obj/vcloudfe/sdk/Web_push/1.0.2/1735619208418/pcm2aac.wasm",ignoreRelPublish:!1},T=new E("RTMP_AudioEncoder");class j{constructor(t){this._encodedFrameCount=0,this._ready=!1,this._lastFrame=null,this._aacOutput=(e,s)=>{const r=this._module.HEAPU8.subarray(e,e+s);if(!this._lastFrame)return;this._encodedFrameCount++;const{props:o}=this._lastFrame,_={buffer:new Uint8Array(r),props:{timestamp:parseInt(o.timestamp/1e3),originTs:parseInt(o.timestamp/1e3)}};this._core.emit(l.OnAudioEncoded,_)},this._core=t}async init(){const t=await fetch(A.audioEncoderPath).then(_=>_.text());new Function(`self.exports={};${t}`)();const e=self.exports.m;let s,r;const o=new Promise((_,c)=>{r=_,s=c});return e({instantiateWasm:function(_,c){fetch(A.audioEncoderWasmPath).then(u=>u.arrayBuffer()).then(u=>WebAssembly.instantiate(u,_)).then(function(u){return c(u.instance)}).then(()=>{r(),T.log("aac module inited")}).catch(u=>{s(u)})}}).then(_=>{const c=_.addFunction(this._aacOutput,"vii");_._init_callback(c),this._module=_}).catch(s),o}rnnoise(t){var s;const e=t.length;for(let r=0;r<e;r++)t[r]=t[r]*32768;(s=this._rnnoiseModule)==null||s.processFrame(t);for(let r=0;r<e;r++)t[r]=t[r]/32768}updateConfigure(){this._module._flush(),this._module._free_encoder(),this._ready=!1}encode(t){if(!this._ready){const o=this._start_encoder();if(o<0)throw new Error(`init aac encoder error, code:${o}`)}this._lastFrame=t;const e=t.buffer.buffer,s=this._module._malloc(e.byteLength);this._module.HEAPU8.subarray(s,s+e.byteLength).set(new Uint8Array(e));const r=this._module._encode_one_frame(s);if(r<0)throw new Error(`encode aac frame error, code:${r}`)}_start_encoder(){const t=this._core.getSetting(),e=this._module._init_encoder(t.sampleRate,t.channel,t.audioBitrate);if(e<0)return e;this._ready=!0,T.log(`init encoder: sampleRate=${t.sampleRate}, channel:${t.channel}, bitrate:${t.audioBitrate}`)}destroy(){var t;(t=this._module)==null||t._free_encoder()}}const P=1024;class M{constructor(){this._queue=[],this._sampleCount=0}compose(t){if(this._queue.push(t),this._sampleCount+=t.data.audioData.numberOfFrames,this._sampleCount>=P)return this._doCompose()}_doCompose(){const t=new Float32Array(P);let e=0,s=P;const r=this._queue[0];for(;;){const o=this._queue[0];if(!o)break;const _=Math.min(s,o.data.audioData.numberOfFrames-o.offset,480),c=o.data.buffer.slice(o.offset,o.offset+_);if(o.offset+=_,o.offset>=o.data.audioData.numberOfFrames&&this._queue.shift(),s-=_,this._sampleCount-=_,t.set(c,e),e+=_,s<=0)break}return{buffer:t,props:{timestamp:r.data.audioData.timestamp,sampleRate:r.data.audioData.sampleRate,numberOfChannels:r.data.audioData.numberOfChannels}}}}var y=(i=>(i[i.RTMP_INIT_FAIL=3e3]="RTMP_INIT_FAIL",i[i.AUDIO_ENCODER_INIT_FAIL=3001]="AUDIO_ENCODER_INIT_FAIL",i[i.AUDIO_RRNOISE_INIT_FAIL=3002]="AUDIO_RRNOISE_INIT_FAIL",i[i.AUDIO_ENCODE_FAIL=3003]="AUDIO_ENCODE_FAIL",i[i.VIDEO_ENCODE_CONFIGURE_FAIL=3004]="VIDEO_ENCODE_CONFIGURE_FAIL",i[i.VIDEO_ENCODE_FAIL=3005]="VIDEO_ENCODE_FAIL",i[i.WTP_OPEN_FAIL=3006]="WTP_OPEN_FAIL",i[i.WTP_CONNECT_FAIL=3007]="WTP_CONNECT_FAIL",i[i.WORKER_ERROR=3008]="WORKER_ERROR",i))(y||{});class W extends Error{constructor(t,e,s){super(),this.code=t,this.message=e,s&&(this.ext=s),this.toJson=()=>({code:this.code,message:this.message,ext:this.ext})}}function b(i,t,e){return new W(i,t,e)}class G{constructor(t){this._audioFrameQueue=new M,this.encode=e=>{const s=new Float32Array(e.numberOfFrames);e.copyTo(s,{planeIndex:0,frameOffset:0,frameCount:e.numberOfFrames});const r=this._audioFrameQueue.compose({offset:0,data:{audioData:e,buffer:s}});if(r)try{this._encoder.encode(r)}catch(o){this._core.emit(O.OnError,b(y.AUDIO_ENCODE_FAIL,o.message))}},this._core=t,this._encoder=new j(t)}async init(){try{await this._encoder.init()}catch(t){throw b(y.AUDIO_ENCODER_INIT_FAIL,t.message)}}setConfiguration(t){const e=Object.assign({},this._core.getSetting(),{audioBitrate:t});this._core.updateSetting(e),this._encoder.updateConfigure()}destroy(){this._encoder.destroy()}}const x=new E("RTMP_VEncoder");class J{constructor(t){this._encoder=null,this._queue=[],this._encodeTimer=0,this._loopEncodeTimer=0,this._frameIndex=0,this._gopSize=0,this._encodedFrameCount=0,this._lastFrame=null,this._startTimer=()=>{this._clearEncodeTimer(),this._encodeTimer=setInterval(()=>{const e=this._queue.shift();if(!(!e||!this._encoder||this._encoder.state==="closed"))try{this._encoder.encode(e,{keyFrame:this._frameIndex%this._gopSize===0}),this._frameIndex++,this._lastFrame&&this._lastFrame.close(),this._lastFrame=e}catch(s){x.log("encode frame error",s)}},5)},this._core=t}configurate(t){return this._gopSize=t.gopSize,this._encoder?this.flush().then(()=>this._configure(t)):this._configure(t)}_configure(t){return this._clearEncodeTimer(),x.log("start config encoder",t),VideoEncoder.isConfigSupported(t).then(e=>{if(!e.supported)throw new Error(`VideoEncoder not support config, ${JSON.stringify(t)}`);this._encoder=new VideoEncoder({output:(s,r)=>{const o=new Uint8Array(s.byteLength);s.copyTo(o),this._emitFrame(o,s,r)},error:s=>{this._clearEncodeTimer(),this._core.emit(O.OnError,b(y.VIDEO_ENCODE_FAIL,s.message))}}),this._encoder.configure(t),x.log("encoder configured")}).then(this._startTimer).catch(e=>{throw b(y.VIDEO_ENCODE_CONFIGURE_FAIL,e.message)})}_emitFrame(t,e,s){this._encodedFrameCount++,this._core.emit(l.OnVideoEncoded,{buffer:t,props:{byteLength:e.byteLength,duration:e.duration,timestamp:parseInt(e.timestamp/1e3),originTs:parseInt(e.timestamp/1e3),type:e.type},cfg:s.decoderConfig})}_clearEncodeTimer(){clearInterval(this._encodeTimer)}_clearLoopEncodeTimer(){this._loopEncodeTimer&&clearInterval(this._loopEncodeTimer)}flush(){return this._encoder?this._encoder.flush().then(()=>{var t;this._clearEncodeTimer(),(t=this._encoder)==null||t.close(),this._frameIndex=0,this._encoder=null,x.log("encoder flush & closed")}).catch(t=>{console.log("encoder flush & close error:",t)}):Promise.resolve()}encode(t){this._clearLoopEncodeTimer(),this._queue.push(t)}startLoop(t){if(!this._lastFrame)return;const e=Math.floor(1e3/t*1e3);x.log("start encode last frame looped, ",t,"increment:",e),this._loopEncodeTimer=setInterval(()=>{if(!this._lastFrame)return;const s=new VideoFrame(this._lastFrame,{duration:e,timestamp:(this._lastFrame.timestamp||0)+e});this._queue.push(s)},Math.floor(1e3/t))}destroy(){this._queue.forEach(t=>t.close()),this._lastFrame&&this._lastFrame.close(),this._clearEncodeTimer(),this._clearLoopEncodeTimer(),this.flush()}}const Q=new E("RTMP_VideoEncode");class K{constructor(t){this._core=t,this._encoder=new J(t)}async setConfiguration(t={}){const e=Object.assign({},this._core.getSetting(),t),s={width:e.width,height:e.height,displayWidth:e.width,displayHeight:e.height,bitrate:e.videoBitrate,framerate:Math.floor(e.frameRate),codec:e.codec,gopSize:e.gopSize,hardwareAcceleration:e.hardwareAcceleration};this._core.updateSetting(e),Q.log("set Configuration:",s,t);try{await this._encoder.configurate(s)}catch(r){this._core.emit(O.OnError,r)}}encode(t){this._encoder.encode(t)}startLoopEncodeLastFrame(){this._encoder.startLoop(this._core.getSetting().frameRate)}flushEncoder(){this._encoder.flush()}destroy(){this._encoder.destroy()}}const V=new E("RTMP_AVSync");class Z{constructor(t){this._videoFrameGot=!1,this._videoBaseDts=0,this._audioBaseDts=0,this._videoNextDts=0,this._videoLastDts=0,this._audioNextDts=0,this._lastVideoReceived=0,this._core=t}get avExist(){return this._core.getSetting().hasVideo&&this._core.getSetting().hasAudio}get videoRefDuration(){return parseInt(1e3/this._core.getSetting().frameRate)}get audioRefDuration(){return parseInt(1024/this._core.getSetting().sampleRate*1e3)}addVideoFrame(t){this._videoFrameGot||(this._videoFrameGot=!0);const e=t.props;if(Math.abs(this._videoNextDts-e.timestamp-this._videoBaseDts)>1e3){const r=Date.now()-this._lastVideoReceived;this._videoNextDts=this._videoNextDts===this._audioNextDts?this._videoNextDts+this.videoRefDuration:this._audioNextDts||this._videoNextDts+r,this._videoBaseDts=this._videoNextDts-e.timestamp,V.warn(`video stream timestamp breaked! dts:${this._videoNextDts} -> ${e.timestamp}, videoBaseDts=${this._videoBaseDts}, deltaToLastFrame=${r}`)}e.timestamp=e.timestamp+this._videoBaseDts;const s=e.timestamp-this._videoLastDts;return s>100&&V.warn("video frame large gap",s),this._videoLastDts=this._videoNextDts=e.timestamp,V.long&&V.log(`V frame, dts: ${e.timestamp}, originDts:${e.originTs}, videoBaseDts=${this._videoBaseDts}, type=${e.type}, duration=${s}`),this._lastVideoReceived=Date.now(),this._core.emit(l.OnEncodedFrame,I.Video,t),{size:t.buffer.length,duration:s,key:t.props.type==="key"}}addAudioFrame(t){if(this.avExist&&!this._videoFrameGot)return;const e=t.props;return this._audioBaseDts||(this._audioBaseDts=e.timestamp-this._videoNextDts),Math.abs(e.timestamp-this._audioBaseDts-this._audioNextDts)>1e3&&(this._audioBaseDts=this._audioNextDts+this.audioRefDuration-e.timestamp,V.warn(`audio stream timestamp breaked! dts:${this._audioNextDts} -> ${e.timestamp}, audioBaseDts=${this._audioBaseDts}`)),this._audioNextDts=e.timestamp=e.timestamp-this._audioBaseDts,V.long&&V.log(`A frame, dts: ${e.timestamp}, originDts:${e.originTs}`),this._core.emit(l.OnEncodedFrame,I.Audio,t),{size:t.buffer.length,duration:this.audioRefDuration}}}class X{constructor(){this._videoSize=0,this._videoDuration=0,this._videoBitrate=0,this._frameCount=0,this._fps=0,this._videoEncodedCount=0,this._keyCount=0,this._audioSize=0,this._audioDuration=0,this._audioBitrate=0,this._audioEncodedCount=0}get videoStats(){return{sendBitrate:this._videoBitrate,framesPerSecond:this._fps,framesEncoded:this._videoEncodedCount,keyFramesEncoded:this._keyCount}}get audioStats(){return{sendBitrate:this._audioBitrate,framesEncoded:this._audioEncodedCount}}addVideoSample({size:t,duration:e,key:s}){this._videoEncodedCount++,this._videoSize+=t,this._videoDuration+=e,this._frameCount++,s&&this._keyCount++,this._videoDuration>=1e3&&(this._videoBitrate=Math.floor(this._videoSize/this._videoDuration*8e3),this._fps=this._frameCount,this._frameCount=0,this._videoSize=0,this._videoDuration=0)}addAudioSample({size:t,duration:e}){this._audioEncodedCount++,this._audioSize+=t,this._audioDuration+=e,this._audioDuration>=1e3&&(this._audioBitrate=Math.floor(this._audioSize/this._audioDuration*1e3),this._audioSize=0,this._audioDuration=0)}}const Y=new E("RTMP_EncodeController");class ee{constructor(t){this._analyse=new X,this._gotFrame=!1,this._OnVideoCaptured=(e,s)=>{this._gotFrame=!0,this._videoSettingChanged(s)&&(Y.log("video track setting changed!",s),this._core.updateSetting({width:s.width,height:s.height,frameRate:s.frameRate,vDeviceId:s.deviceId}),this._videoEncode.setConfiguration()),this._videoEncode.encode(e)},this._OnVideoCaptureNoOutput=()=>{this._videoEncode.startLoopEncodeLastFrame()},this._OnAudioCaptured=e=>{this._gotFrame=!0,this._audioEncode.encode(e)},this._OnVideoEncoded=e=>{const s=this._avSync.addVideoFrame(e);this._analyse.addVideoSample(s)},this._OnAudioEncoded=e=>{if(!e.buffer.length)return;const s=this._avSync.addAudioFrame(e);s&&this._analyse.addAudioSample(s)},this._OnUpstreamFeedback=e=>{this._videoEncode.setConfiguration(e)},this._OnBitrateChanged=(e,s)=>{this._gotFrame&&(e===I.Video&&this._videoEncode.setConfiguration({videoBitrate:s}),e===I.Audio&&this._audioEncode.setConfiguration(s))},this._core=t,this._audioEncode=new G(t),this._videoEncode=new K(t),this._avSync=new Z(t),this._bindEvents()}getStats(){return{video:this._analyse.videoStats,audio:this._analyse.audioStats}}init(){return this._audioEncode.init()}_bindEvents(){this._core.on(l.OnVideoCaptured,this._OnVideoCaptured),this._core.on(l.OnAudioCaptured,this._OnAudioCaptured),this._core.on(l.OnVideoCaptureNoOutput,this._OnVideoCaptureNoOutput),this._core.on(l.OnVideoEncoded,this._OnVideoEncoded),this._core.on(l.OnAudioEncoded,this._OnAudioEncoded),this._core.on(l.OnUpstreamFeedback,this._OnUpstreamFeedback),this._core.on(l.OnBitrateChanged,this._OnBitrateChanged)}_videoSettingChanged(t){const e=this._core.getSetting();return t.width!==e.width||t.height!==e.height||Math.floor(t.frameRate)!==Math.floor(e.frameRate)||t.deviceId!==e.vDeviceId}destroy(){this._videoEncode.destroy(),this._audioEncode.destroy()}}var L=(i=>(i[i.AUDIO=8]="AUDIO",i[i.VIDEO=9]="VIDEO",i[i.SCRIPT_DATA=18]="SCRIPT_DATA",i))(L||{});const te=10,ie=1,se=7,oe={96e3:0,48e3:3,44100:4,22050:7,16e3:8,8e3:11};function re(i){const t=(i[4]&3)+1;let e;const s=[],r=[];let o=6;const _=i[5]&31;let c;for(let n=0;n<_;n++){if(c=i[o]<<8|i[o+1],o+=2,!c)continue;const h=i.subarray(o,o+c);o+=c,s.push(h)}const u=i[o];o++;let a;for(let n=0;n<u;n++)a=i[o]<<8|i[o+1],o+=2,a&&(r.push(i.subarray(o,o+a)),o+=a);return{sps:e,spsArr:s,ppsArr:r,nalUnitSize:t}}class ne{constructor(){this._cfg={hasVideo:!1,hasAudio:!1,sampleRate:48e3,channelCount:1},this._hasAudioSeqHeader=!1,this._hasVideoSeqHeader=!1}setConfig(t){this._cfg=Object.assign(this._cfg,t)}genHeader(){const t=[70,76,86,1,(this._cfg.hasAudio?1:0)<<2|(this._cfg.hasVideo?1:0),0,0,0,9,0,0,0,0];return new Uint8Array(t)}genSeqTag(t,e){let s;t===8?(s=this._genAudioTagPaylod(0,e),this._hasAudioSeqHeader=!0):(s=this._genVideoTagPayload(0,e),this._hasVideoSeqHeader=!0);const r=this._genTagHeader(t,s.length,e.props.timestamp),o=r.length+s.length;return S([r,s,new Uint8Array([o>>>24,o>>>16,o>>>8,o])])}genFrameTag(t,e){let s;t===8?s=this._genAudioTagPaylod(1,e):s=this._genVideoTagPayload(1,e);const r=this._genTagHeader(t,s.length,e.props.timestamp),o=r.length+s.length;return S([r,s,new Uint8Array([o>>>24,o>>>16,o>>>8,o])])}_genTagHeader(t,e,s){return new Uint8Array([t,e>>>16,e>>>8,e,s>>>16,s>>>8,s,s>>>24,0,0,0])}_genAudioTagPaylod(t,e){return S(t===0?[this._genAudioTagHeader(),this._genAudioSequenceHeader()]:[this._genAudioTagHeader(),this._genAudioData(e)])}_genAudioTagHeader(){return new Uint8Array([te<<4|12|ie<<1|this._cfg.channelCount-1])}_genAudioSequenceHeader(){const t=4096|oe[this._cfg.sampleRate]<<7|this._cfg.channelCount<<3;return new Uint8Array([0,t>>8,t])}_genAudioData(t){const e=new Uint8Array(1+t.buffer.length);return e.set([1],0),e.set(t.buffer,1),e}_genVideoTagPayload(t,e){return S(t===0?[this._genVideoTagHeader(e),this._genVideoSequenceHeader(e)]:[this._genVideoTagHeader(e),this._genVideoData(e)])}_genVideoTagHeader(t){return new Uint8Array([(t.props.type==="key"?1:2)<<4|se,this._hasVideoSeqHeader?1:0,0,0,0])}_genVideoSequenceHeader(t){return new Uint8Array(t.cfg.description)}_genVideoData(t){if(t.props.type==="delta")return t.buffer;const e=re(new Uint8Array(t.cfg.description)),s=e.spsArr[0].length,r=e.ppsArr[0].length;return S([new Uint8Array([0,0,s>>8,s%256]),e.spsArr[0],new Uint8Array([0,0,r>>8,r%256]),e.ppsArr[0],t.buffer])}}const ae=new E("RTMP_Packet");class de{constructor(t){this._firstFrame=!0,this._flv=new ne,this._OnEncodedFrame=(e,s)=>{if(this._firstFrame){const o=this._core.getSetting();this._flv.setConfig({hasVideo:o.hasVideo,hasAudio:o.hasAudio,sampleRate:o.sampleRate,channelCount:o.channel});const _=this._flv.genHeader();if(this._core.emit(l.OnPacketed,_),o.hasVideo){const c=this._flv.genSeqTag(L.VIDEO,s);this._core.emit(l.OnPacketed,c)}if(o.hasAudio){const c=this._flv.genSeqTag(L.AUDIO,s);this._core.emit(l.OnPacketed,c)}this._firstFrame=!1,ae.log("first frame encoded & packed")}const r=this._flv.genFrameTag(e==="video"?L.VIDEO:L.AUDIO,s);this._core.emit(l.OnPacketed,r,s.props.type==="key")},this._core=t,this._bindEvents()}_bindEvents(){this._core.on(l.OnEncodedFrame,this._OnEncodedFrame)}destroy(){}}class he{constructor(){this._lastDot=0,this._totalSize=0,this._speed=[]}addSample(t){this._lastDot||(this._lastDot=Date.now()),this._totalSize+=t;const e=Date.now()-this._lastDot;e>=500&&(this._addSpeedSample(this._totalSize/e*8e3),this._totalSize=0,this._lastDot=Date.now())}_addSpeedSample(t){this._speed.push(t),this._speed=this._speed.slice(-6)}reset(){this._speed=[]}getUpSpeed(){return this._speed.length?parseInt(this._speed.reduce((t,e)=>t+=e,0)/this._speed.length):0}}const D=new E("RTMP_Wtp");class ce{constructor(t){this._queue=[],this._url="",this._connectClosed=!1,this._upSpeed=new he,this._transport=null,this._writer=null,this._inWriting=!1,this._inAdjustEncode=!1,this._increaseTimer=0,this._firstFramePushed=!1,this._core=t,this._bindEvents()}get sendSpeed(){return this._upSpeed.getUpSpeed()}getStats(){var t;return(t=this._transport)==null?void 0:t.getStats()}_bindEvents(){this._core.on(l.OnPacketed,(t,e=!1)=>{this._checkDecreaseBitrate(),this._checkDeleteCache(e),this._queue.push(t),this._inWriting||this._write()})}_checkDecreaseBitrate(){if(this._inAdjustEncode)return;const t=this._upSpeed.getUpSpeed();if(!t||this._queue.length<A.MaxCachedFrameSize)return;D.log(`up speed: ${t} low, ajust encode setting`);const e=this._core.getSetting();this._core.emit(l.OnUpstreamFeedback,{videoBitrate:t*A.RealSpeedPercent,width:e.width,height:e.height,frameRate:e.frameRate}),this._inAdjustEncode=!0,this._checkIncreaseBitrate()}_checkIncreaseBitrate(){D.log("add timer to check uplink speed increased"),clearInterval(this._increaseTimer),this._increaseTimer=setTimeout(()=>{const t=this._core.getSetting();D.log(`set encode bitrate to specified ${t.originVideoBitrate}`),this._core.emit(l.OnUpstreamFeedback,{videoBitrate:t.originVideoBitrate,width:t.width,height:t.height,frameRate:t.frameRate}),this._inAdjustEncode=!0},A.UplinkBitrateCheckInterval)}_checkDeleteCache(t){this._inAdjustEncode&&t&&(D.log(`ajust encode setting finish, delete cached ${this._queue.length} frame`),this._queue=[],this._upSpeed.reset(),this._inAdjustEncode=!1)}async start(t){this._url=t;try{await this._connect()}catch(e){throw b(y.WTP_OPEN_FAIL,e.message)}}async _connect(){const t=new WebTransport(this._url);let e;t.closed.then(()=>{D.log("webtransport closed")}).catch(r=>{e=r.message,D.log("webtransport closed due to",r)}).finally(()=>{this._connectClosed=!0,this._core.emit(O.OnConnectClosed,e),this._core.emit(O.OnError,b(y.WTP_CONNECT_FAIL,e))}),await t.ready,this._transport=t;const s=await t.createBidirectionalStream();this._writer=s.writable.getWriter(),this._write(),D.log("transport opend")}async _write(){var e;if(!this._writer)return;this._inWriting=!0;const t=this._queue.shift();if(!t){this._inWriting=!1;return}await((e=this._writer)==null?void 0:e.write(t)),this._firstFramePushed||(this._firstFramePushed=!0,this._core.emit(O.OnFirstFramePushed),D.log("first frame pushed")),this._upSpeed.addSample(t.length);try{await this._write()}catch(s){D.log("writer error:",s)}}getFile(){return S(this._queue)}destroy(){var t,e;clearTimeout(this._increaseTimer),this._connectClosed||(t=this._writer)==null||t.close(),this._writer=null,(e=this._transport)==null||e.close(),this._transport=null}}const ue=new E("LiveRTMP");class _e extends H{constructor(){super(),this._ts=0,this._setting={codec:A.codec,hardwareAcceleration:"prefer-hardware",width:-1,height:-1,frameRate:-1,sampleRate:A.sampleRate,channel:A.channel,gopSize:A.gopSize,videoBitrate:A.VideoBitrateDefault,originVideoBitrate:A.VideoBitrateDefault,audioBitrate:A.AudioBitrateDefault,hasAudio:!1,hasVideo:!1,vDeviceId:"",aDeviceId:""},this._encode=new ee(this),this._packet=new de(this),this._transport=new ce(this)}async checkVideoHardwareAcceleration(){const t=["prefer-hardware","prefer-software","no-preference"],e=this.getSetting(),s={codec:e.codec,width:1280,height:720,framerate:15,bitrate:e.videoBitrate};for(const r of t)try{if((await VideoEncoder.isConfigSupported({...s,hardwareAcceleration:r})).supported)return this.updateSetting({hardwareAcceleration:r,originVideoBitrate:e.originVideoBitrate}),Promise.resolve()}catch{throw b(y.VIDEO_ENCODE_CONFIGURE_FAIL,`VideoEncoder not support hardwareAcceleration, ${JSON.stringify({...s,hardwareAcceleration:r})}`)}throw b(y.VIDEO_ENCODE_CONFIGURE_FAIL,"VideoEncoder not support hardwareAcceleration")}async ready(){await Promise.all([this.checkVideoHardwareAcceleration(),this._encode.init()])}getSetting(){return this._setting}updateSetting(t){this._setting=Object.assign({},this._setting,t)}videoFrameCaptured(t,e){this.emit(l.OnVideoCaptured,t,e)}audioFrameCaptured(t,e){this.emit(l.OnAudioCaptured,t,e)}startMockVideoEncode(){this.emit(l.OnVideoCaptureNoOutput)}adjustBitrate(t,e){t===I.Video&&this.updateSetting({videoBitrate:e,originVideoBitrate:e}),t===I.Audio&&this.updateSetting({audioBitrate:e}),this.emit(l.OnBitrateChanged,t,e)}avExist(t,e){this._setting.hasVideo=t,this._setting.hasAudio=e}publish(t){return this._transport.start(t)}setEncodeCapacity(t){this._setting=Object.assign({},this._setting,t)}getStats(){return{video:{...this._encode.getStats().video,sendSpeed:this._transport.sendSpeed,codec:this._setting.codec,frameWidth:this._setting.width,frameHeight:this._setting.height,gopSize:this._setting.gopSize},audio:{...this._encode.getStats().audio,codec:"aac",channels:this._setting.channel,sampleRate:this._setting.sampleRate}}}destroy(){ue.log("destroy"),this._encode.destroy(),this._packet.destroy(),this._transport.destroy()}down(){return this._transport.getFile()}}self.constructor.name!=="Window"&&le();function le(){let i={};self.addEventListener("message",async t=>{switch(t.data.type){case v.Init:{const{options:e}=t.data;e.logEnable&&(E.enable=!0),e.logEnableLong&&(E.enableLong=!0),i=new _e,i.on(O.OnError,s=>{self.postMessage({type:w.Error,data:s.toJson()})}),i.on(O.OnConnectClosed,()=>{self.postMessage({type:w.Close})}),i.on(O.OnFirstFramePushed,()=>{self.postMessage({type:w.FirstFramePushed})});try{await i.ready(),self.postMessage({type:w.Ready})}catch(s){self.postMessage({type:w.Error,data:s.toJson()})}}break;case v.AvExist:{const{hasAudio:e,hasVideo:s}=t.data;i.avExist(s,e)}break;case v.VideoFrame:{const{frame:e,setting:s}=t.data;i.videoFrameCaptured(e,s)}break;case v.MockVideoEncode:i.startMockVideoEncode();break;case v.AudioFrame:{const{frame:e,setting:s}=t.data;i.audioFrameCaptured(e,s)}break;case v.AdjustBitrate:{const{kind:e,bitrate:s}=t.data;i.adjustBitrate(e,s)}break;case v.Publish:{const{url:e}=t.data;try{await i.publish(e)}catch(s){self.postMessage({type:w.Error,data:s.toJson()})}}break;case v.GetStats:self.postMessage({type:w.STATS,data:i.getStats()});break;case v.EncodeConfig:{i.setEncodeCapacity(t.data.cfg);break}case v.Download:{const e=i.down();self.postMessage({type:w.Flvfile,buffer:e},[e.buffer])}break;case v.UnPublish:{i.destroy();break}}})}})();\n',Xc=typeof self<"u"&&self.Blob&&new Blob([Jc],{type:"text/javascript;charset=utf-8"});function Gv(r){let e;try{if(e=Xc&&(self.URL||self.webkitURL).createObjectURL(Xc),!e)throw"";const t=new Worker(e,{name:r==null?void 0:r.name});return t.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),t}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(Jc),{name:r==null?void 0:r.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}try{br.enable=location.href.indexOf("rtmpdebug")!==-1,br.enableLong=location.href.indexOf("rtmpdebug=long")!==-1}catch{}const Wn=new br("Bridge");class Zc extends Lv{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new Uv(this)}static isSupported(){return typeof WebTransport<"u"&&typeof MediaStreamTrackProcessor<"u"&&typeof MediaStreamTrackGenerator<"u"&&typeof VideoEncoder<"u"}get audioMsTrack(){return this._audioMsTrack}get videoMsTrack(){return this._videoMsTrack}async ready(){var o,a;let e,t;const n=new Promise((s,u)=>{e=s,t=u}),i=s=>{var u;switch((u=this._worker)==null||u.removeEventListener("message",i),s.data.type){case nr.Error:t(s.data.data);break;default:this._bindWorkerEvent(),Wn.log("rtmp ready!"),e(!0)}};try{this._worker=new Gv}catch(s){t(Wc(Kn.RTMP_INIT_FAIL,s.message))}return(o=this._worker)==null||o.postMessage({type:tt.Init,options:{logEnable:br.enable,logEnableLong:br.enableLong}}),(a=this._worker)==null||a.addEventListener("message",i),n}_bindWorkerEvent(){var e,t;(e=this._worker)==null||e.addEventListener("message",n=>{switch(n.data.type){case nr.Error:Wn.table(n.data.data),this.emit(Ft.OnError,n.data.data);break;case nr.Flvfile:Nv(n.data.buffer);break;case nr.FirstFramePushed:this.emit(Ft.OnFirstFramePushed);break;case nr.Close:this.emit(Ft.OnConnectClosed),this.destroy();break}}),(t=this._worker)==null||t.addEventListener("error",n=>{this.emit(Ft.OnError,Wc(Kn.WORKER_ERROR,n.message))})}addTrack(e){e.kind===Vt.Video&&(this._videoMsTrack=e),e.kind===Vt.Audio&&(this._audioMsTrack=e),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack)}replaceTrack(e,t){e===Vt.Video&&(this._videoMsTrack=t),e===Vt.Audio&&(this._audioMsTrack=t),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack),this._capture.restartCapture(e)}async getStats(){var o,a;let e,t;const n=new Promise((s,u)=>{e=s,t=u});this._worker||setTimeout(()=>{t()},0);const i=s=>{var u;switch(s.data.type){case nr.STATS:e(s.data.data),(u=this._worker)==null||u.removeEventListener("message",i);break}};return(o=this._worker)==null||o.addEventListener("message",i),(a=this._worker)==null||a.postMessage({type:tt.GetStats}),n}_postVideoFrame(e,t){var n;(n=this._worker)==null||n.postMessage({type:tt.VideoFrame,frame:e,setting:t},[e])}_postMockVideoEncodeFlag(){var e;(e=this._worker)==null||e.postMessage({type:tt.MockVideoEncode})}_setAVExist(e,t){var n;(n=this._worker)==null||n.postMessage({type:tt.AvExist,hasVideo:e,hasAudio:t})}_postAudioFrame(e,t){var n;(n=this._worker)==null||n.postMessage({type:tt.AudioFrame,frame:e,setting:t},[e])}setEncodeCapacity(e){var t;(t=this._worker)==null||t.postMessage({type:tt.EncodeConfig,cfg:e})}adjustBitrate(e,t){var n;(n=this._worker)==null||n.postMessage({type:tt.AdjustBitrate,kind:e,bitrate:t})}publish(e){var t;Wn.log("start capture & connect"),this._capture.start(),(t=this._worker)==null||t.postMessage({type:tt.Publish,url:e})}unpublish(){var e;this._capture.destroy(),(e=this._worker)==null||e.postMessage({type:tt.UnPublish})}destroy(){var e;Wn.log("destroy capture & rtmp worker"),this._capture.destroy(),(e=this._worker)==null||e.terminate(),this._worker=null}download(){var e;(e=this._worker)==null||e.postMessage({type:tt.Download})}}function Nv(r){const e=document.createElement("a");e.href=URL.createObjectURL(new Blob([r])),e.download=Date.now()+".flv",e.click()}const Yc=new Bt("RTMPConnect");class Bv{constructor(e,t,n,i){this._opts=void 0,this._isPushing=!1,this._url=e,this._opts=t,this._onError=n,this._OnSuccess=i,this._rtmp=new Zc,this._bindEvents()}get isPushing(){return this._isPushing}get pushUrl(){return this._url}get sessionId(){return 0}_bindEvents(){this._rtmp.on(Ft.OnError,e=>{this._isPushing=!1,this._onError(e)}),this._rtmp.on(Ft.OnConnectClosed,()=>{this._isPushing=!1,this._onError(new Kc(Kn.WTP_CONNECT_FAIL,"connect lost"))}),this._rtmp.on(Ft.OnFirstFramePushed,()=>{this._isPushing=!0,this._OnSuccess()})}async publish(e,t,n){await this._rtmp.ready(),n!=null&&n.cfg&&this._rtmp.setEncodeCapacity(n.cfg),e.filter(Boolean).forEach(i=>this._rtmp.addTrack(i)),t[0]&&this._rtmp.adjustBitrate(Vt.Audio,t[0]),t[1]&&this._rtmp.adjustBitrate(Vt.Video,t[1]),this._rtmp.publish(this._url)}updatePublish(e,t){Yc.log(`replace track to ${e==null?void 0:e.label}`),this._rtmp.replaceTrack(t,e)}applyBitrate(e,t){this._rtmp.adjustBitrate(t,e)}async getStats(){return this._rtmp.getStats()}async getStatsSnapshoot(e){return e&&await hn(e),{stats:await this._rtmp.getStats(),originStats:void 0}}unpublish(){Yc.warn("unpublish"),this._rtmp.unpublish(),this._isPushing=!1}}var st=(r=>(r[r.Start=0]="Start",r[r.Stop=1]="Stop",r[r.GameControl=2]="GameControl",r[r.InitPushReader=3]="InitPushReader",r[r.Online=4]="Online",r[r.Reconnect=5]="Reconnect",r[r.UpdateTrack=6]="UpdateTrack",r[r.SetBitrate=7]="SetBitrate",r[r.PassEngineEvent=8]="PassEngineEvent",r[r.StopSuccess=9]="StopSuccess",r[r.VideoLog=10]="VideoLog",r[r.SetJitterBuffer=11]="SetJitterBuffer",r[r.ResetEngine=12]="ResetEngine",r[r.GetStats=13]="GetStats",r[r.Test=14]="Test",r[r.Plugin=15]="Plugin",r[r.EnableLogger=16]="EnableLogger",r[r.SendLogToMain=17]="SendLogToMain",r))(st||{});const Fv=1e3;function Vv(){return!1}class Qc{constructor(){this.maxSize=Fv,this.supported=Vv(),this.supported&&(this.buffer=new SharedArrayBuffer(this.maxSize),this.arr=new Uint8Array(this.buffer))}share(e){return this.supported?(this.arr.set(e),this.buffer):e.buffer}}class jv{constructor(e){this.encoder=new TextEncoder,this.decoder=new TextDecoder,this.buffer=new Qc,this.client=e}send(e){this.client.postMessage(e)}sendTransportable(e,t){Object.assign(e,t);const n=Object.values(t);this.client.postMessage(e,n)}onMessage(e){this.client.addEventListener("message",t=>{e(t.data)})}destroy(){var e,t;(t=(e=this.client).terminate)==null||t.call(e)}}class Hv{constructor(){this.usePrevEmit=!0,this._map={},this._prevData={}}hasEvent(e){return!!this._map[e]}on(e,t){if(typeof e=="object"){const n=[];for(const i in e)n.push(this.on(i,e[i]));return()=>{n.forEach(i=>i())}}else{if(!t)throw new Error("fn is required");const n=this._formatTarget(t);return this._checkPrev(e,n)&&n.once?()=>{}:(this._getList(e).push(n),()=>{this.off(e,n)})}}_formatTarget(e,t){return typeof e=="function"?{listener:e,once:t??!1,prev:this.usePrevEmit}:(typeof t=="boolean"&&(e.once=t),e)}emit(e,...t){this._prevData[e]=t;const n=this._map[e];if(!n)return!1;for(let i=0;i<n.length;i++){const o=n[i];o.listener(...t),o.once&&(n.splice(i,1),i--)}return!0}off(e,t){const n=this._map[e];if(!n)return!1;const i=n.findIndex(o=>o===t||o.listener===t);return i===-1?!1:(n.splice(i,1),!0)}clear(e){return this._map[e]?(delete this._map[e],delete this._prevData[e],!0):!1}async onWait(e,t){return new Promise(n=>{var a;let i=(...s)=>n(s);t&&(i={listener:i,...t});const o=this.once(e,i);(a=t==null?void 0:t.onclear)==null||a.call(t,o)})}destroy(){this._map={},this._prevData={}}_checkPrev(e,t){if(!t.prev)return!1;const n=this._prevData[e];return typeof n<"u"?(t.listener(...n),!0):!1}once(e,t){return this.on(e,this._formatTarget(t,!0))}head(e,t){const n=this._formatTarget(t);return this._checkPrev(e,n)&&n.once?()=>{}:(this._getList(e).unshift(t),()=>{this.off(e,t)})}headOnce(e,t){return this.head(e,this._formatTarget(t,!0))}_getList(e){let t=this._map[e];return t||(this._map[e]=t=[]),t}passEvents(e,t){t.forEach(n=>{e.on(n,i=>{this.emit(n,i)})})}}class $v extends Hv{constructor(e){super();const t=new e;this.messenger=new jv(t),this.buffer=new Qc,this.onMessage(n=>{this.receiveWorkerMessage(n)})}onMessage(e){this.messenger.onMessage(e)}sendMessage(e){var t;e.type===st.GameControl&&((t=window.__vecg_debug_helper)==null||t.log("debugtouch sendMessage",e.data.byteLength)),this.messenger.send(e)}sendTransportable(e,t){this.messenger.sendTransportable(e,t)}}const eu='(function(){"use strict";var g=(s=>(s[s.Start=0]="Start",s[s.Stop=1]="Stop",s[s.GameControl=2]="GameControl",s[s.InitPushReader=3]="InitPushReader",s[s.Online=4]="Online",s[s.Reconnect=5]="Reconnect",s[s.UpdateTrack=6]="UpdateTrack",s[s.SetBitrate=7]="SetBitrate",s[s.PassEngineEvent=8]="PassEngineEvent",s[s.StopSuccess=9]="StopSuccess",s[s.VideoLog=10]="VideoLog",s[s.SetJitterBuffer=11]="SetJitterBuffer",s[s.ResetEngine=12]="ResetEngine",s[s.GetStats=13]="GetStats",s[s.Test=14]="Test",s[s.Plugin=15]="Plugin",s[s.EnableLogger=16]="EnableLogger",s[s.SendLogToMain=17]="SendLogToMain",s))(g||{});const j=1e3;function $(){return!1}class G{constructor(){this.maxSize=j,this.supported=$(),this.supported&&(this.buffer=new SharedArrayBuffer(this.maxSize),this.arr=new Uint8Array(this.buffer))}share(e){return this.supported?(this.arr.set(e),this.buffer):e.buffer}}class q{constructor(e){this.encoder=new TextEncoder,this.decoder=new TextDecoder,this.buffer=new G,this.client=e}send(e){this.client.postMessage(e)}sendTransportable(e,t){Object.assign(e,t);const i=Object.values(t);this.client.postMessage(e,i)}onMessage(e){this.client.addEventListener("message",t=>{e(t.data)})}destroy(){var e,t;(t=(e=this.client).terminate)==null||t.call(e)}}class p{constructor(){this.usePrevEmit=!0,this._map={},this._prevData={}}hasEvent(e){return!!this._map[e]}on(e,t){if(typeof e=="object"){const i=[];for(const n in e)i.push(this.on(n,e[n]));return()=>{i.forEach(n=>n())}}else{if(!t)throw new Error("fn is required");const i=this._formatTarget(t);return this._checkPrev(e,i)&&i.once?()=>{}:(this._getList(e).push(i),()=>{this.off(e,i)})}}_formatTarget(e,t){return typeof e=="function"?{listener:e,once:t??!1,prev:this.usePrevEmit}:(typeof t=="boolean"&&(e.once=t),e)}emit(e,...t){this._prevData[e]=t;const i=this._map[e];if(!i)return!1;for(let n=0;n<i.length;n++){const r=i[n];r.listener(...t),r.once&&(i.splice(n,1),n--)}return!0}off(e,t){const i=this._map[e];if(!i)return!1;const n=i.findIndex(r=>r===t||r.listener===t);return n===-1?!1:(i.splice(n,1),!0)}clear(e){return this._map[e]?(delete this._map[e],delete this._prevData[e],!0):!1}async onWait(e,t){return new Promise(i=>{var a;let n=(...o)=>i(o);t&&(n={listener:n,...t});const r=this.once(e,n);(a=t==null?void 0:t.onclear)==null||a.call(t,r)})}destroy(){this._map={},this._prevData={}}_checkPrev(e,t){if(!t.prev)return!1;const i=this._prevData[e];return typeof i<"u"?(t.listener(...i),!0):!1}once(e,t){return this.on(e,this._formatTarget(t,!0))}head(e,t){const i=this._formatTarget(t);return this._checkPrev(e,i)&&i.once?()=>{}:(this._getList(e).unshift(t),()=>{this.off(e,t)})}headOnce(e,t){return this.head(e,this._formatTarget(t,!0))}_getList(e){let t=this._map[e];return t||(this._map[e]=t=[]),t}passEvents(e,t){t.forEach(i=>{e.on(i,n=>{this.emit(i,n)})})}}class M extends p{constructor(){super(),this.messenger=new q(globalThis),this.messenger.onMessage(this.receiveMainMessage.bind(this))}onMessage(e){this.messenger.onMessage(e)}send(e,t){this.messenger.send({type:e,data:t})}}var l=(s=>(s[s.Connecting=0]="Connecting",s[s.Open=1]="Open",s[s.Closing=2]="Closing",s[s.Closed=3]="Closed",s))(l||{}),S=(s=>(s.Init="init",s.Online="online",s.Error="error",s.ApiCall="api_call",s))(S||{});function E(){let s,e;return{ready:new Promise((i,n)=>{s=i,e=n}),resolve:s,reject:e}}function J(s=500,e){const{ready:t,resolve:i}=E(),n=setTimeout(i,s);return e==null||e(n),t}function V(s){let e=!0,t="";for(const i of s)if(!(i in window)){e=!1,t=`${i} not Supported`;break}return{supported:e,info:t}}function x({task:s,timeout:e,time:t=200}){const{ready:i,resolve:n}=E(),r=setTimeout(async()=>{let a;typeof e<"u"&&(typeof e=="function"?(a=e(),a instanceof Promise&&(a=await a)):a=e),n(a)},t);return s().then(a=>{clearTimeout(r),n(a)}),i}const K=24*60*60*1e3;function F(s,e="1d"){const t=`_me_expire_${s}`;let i=0;if(typeof e=="string"){if(!/^[0-9]+d$/.test(e))throw new Error("expire format error");i=K*parseInt(e)}else i=e;return{get(){const n=localStorage.getItem(t);if(!n)return null;let r=null;try{r=JSON.parse(n)}catch{return null}const{value:a,expire:o}=r;return o<Date.now()?(localStorage.removeItem(t),null):a},set(n){localStorage.setItem(t,JSON.stringify({value:n,expire:Date.now()+i}))},remove(){localStorage.removeItem(t)}}}function C(s){let e=s.length,t=0;for(let r=e-1;r>=0;r--)s[r]?t+=s[r].byteLength:(e--,s.splice(r,1));const i=new Uint8Array(t);let n=0;for(let r=0;r<e;r++)i.set(s[r],n),n+=s[r].byteLength;return i}function _(s){for(const e in s)typeof s[e]>"u"&&delete s[e];return s}function X(s,e){let t=Number.MAX_SAFE_INTEGER,i=0;for(const n of e){const r=Math.abs(s-n);if(r===0)return n;r<t&&(t=r,i=n)}return i}var f=(s=>(s[s.AAC=0]="AAC",s[s.OPUS=1]="OPUS",s[s.H264=2]="H264",s[s.H265=3]="H265",s[s.AV1=4]="AV1",s))(f||{});f.AAC+"",f.OPUS+"",f.H264+"",f.H265+"",f.AV1+"";const U={[f.AAC]:"mp4a.40.2",[f.OPUS]:"opus",[f.H264]:"avc1.4DE033",[f.H265]:"hev1.1.6.L93.B0"};function O({readable:s,onFrame:e,onFinish:t,onError:i}){if(!s)return()=>{};const n=s.getReader();console.log("getReader");let r=!0;return Z({reader:n,flag:()=>r,onFrame:e,onFinish:t,onError:i}),()=>{r=!1}}async function Z({reader:s,flag:e,onFrame:t,onFinish:i,onError:n}){for(;e();)try{const{done:r,value:a}=await s.read();if(r){console.warn("Stream complete"),i==null||i();return}t(a),a.close()}catch(r){console.error("read error,",r),n==null||n(r)}}function W(s){const{video:e,audio:t}=Y(s);return{video:e?R(e):void 0,audio:t?R(t):void 0}}function R(s){const e=new MediaStreamTrackProcessor(s),{readable:t}=e,i=s.getSettings();return{readable:t,settings:i}}function Y(s){return{video:s.getVideoTracks()[0],audio:s.getAudioTracks()[0]}}function ee(s){const e=new Uint8Array(s.byteLength);return s.copyTo(e),e}const u={log(){},send(){},$custom:{},$enableLog(s=!0){u.log=s?(...e)=>{console.log(L(),...e),u.enableLogSend&&z(e)}:()=>{}},$enableSend(){u.send=(...s)=>{z(s)}}};function te(){var n;typeof window=="object"&&!window.__me_debug_helper&&(window.__me_debug_helper=u);let s=location.search.substring(1);const e="_medh_",t=((n=u.$isInnerEnv)==null?void 0:n.call(u))||!0;if(!s){const{hash:r}=location,a=r.indexOf("?");if(!r||a===-1||(s=r.substring(a+1),!s))return}const i=s.split("&");for(const r of i){const[a,o]=r.split("=");if(a.startsWith(e)){let c=a.replace(e,"");if(c.startsWith("inner_")){if(!t)continue;c=c.replace("inner_","")}c==="log"?u.$enableLog():c==="send"?u.$enableSend():u[c]=o||!0}}location.hostname==="localhost"&&u.$enableLog()}function z(s){if(u.$logger)try{u.$logger(s)}catch(e){console.error(L(),"debug send fail:",e)}}function L(){const s=new Date;return`[${s.toLocaleTimeString()} ${s.getMilliseconds().toString().padStart(3,"0")} media-engine]`}te();let ie=class{constructor(){this._lastDot=0,this._totalSize=0,this._speed=[]}addSample(e){this._lastDot||(this._lastDot=Date.now()),this._totalSize+=e;const t=Date.now()-this._lastDot;t>=500&&(this._addSpeedSample(this._totalSize/t*8e3),this._totalSize=0,this._lastDot=Date.now())}_addSpeedSample(e){this._speed.push(e),this._speed=this._speed.slice(-6)}reset(){this._speed=[]}getUpSpeed(){return this._speed.length?parseInt(this._speed.reduce((e,t)=>e+=t,0)/this._speed.length):0}};class se{constructor(){this._bandwidth=0,this._dbrDataSize=0,this.MAX_ESTIMATE_DURATION_MS=2e3,this.MIN_ESTIMATE_DURATION_MS=1e3,this.packets=[]}addDbrPacket(e){this.packets.push(e),this._dbrDataSize+=e.size;const t=this.packets[0],i=e.sendEndTime-t.sendBeginTime;for(;this.packets.length>0;){const n=this.packets[0];if(e.sendEndTime-n.sendBeginTime>this.MAX_ESTIMATE_DURATION_MS)this._dbrDataSize-=n.size,this.packets.shift();else break}this._bandwidth=i>=this.MIN_ESTIMATE_DURATION_MS?this._dbrDataSize*1e3/i*8:0}getEstimateBandwidth(){return this._bandwidth}reset(){this._bandwidth=0,this._dbrDataSize=0,this.packets=[]}}class ne extends p{constructor(e,t,i){super(),this.streamWriter=null,this.datagramWriter=null,this.failQueue=[],this.bandwidth=0,this.smoothTime=0,this.failCount=0,this.timeoutCount=0,this.streamWriter=e.writable.getWriter(),this.datagramWriter=t.writable.getWriter(),this.upspeed=new ie,this.bandwidthEstimate=new se,i&&(this.strategy=i,i.upstream=this)}async resetStream(e){var t;(t=this.streamWriter)==null||t.releaseLock(),this.streamWriter=e.writable.getWriter(),this.failQueue.forEach(({data:i,config:n})=>{this.sendStream(i,n)}),this.failQueue=[]}async sendStream(e,{extra:t,force:i}={extra:{},force:!1}){var d;if(!i&&((d=this.strategy)==null?void 0:d.onSendStream(e,t))===!1)return;const n={sendBeginTime:performance.now(),size:e.byteLength,sendEndTime:0};this.upspeed.addSample(e.byteLength);const r=performance.now(),a=await this._writeData(e);if(a){(a==="error"||a==="timeout")&&(this.failQueue.push({data:e,config:{extra:t,force:i}}),this.emit("write-error",a));return}n.sendEndTime=performance.now(),this.bandwidthEstimate.addDbrPacket(n);const o=performance.now()-r||.001;this.smoothTime=this.smoothTime===0?o:this.smoothTime*.7+o*.3;const h=e.byteLength/1024*8/(this.smoothTime/1e3);this.bandwidth=Math.min(this.bandwidth===0?h:this.bandwidth*.7+h*.3,1e4)}async _writeData(e){return await x({task:()=>{if(!this.streamWriter)return Promise.resolve("no_stream");const{ready:i,resolve:n}=E();return this.streamWriter.write(e).then(()=>{n("")}).catch(()=>{this.failCount++,n("error")}),i},timeout:()=>(this.timeoutCount++,"timeout"),time:1e3})}async sendDgm(e,{extra:t,force:i}={extra:{},force:!0}){var n,r;!i&&((n=this.strategy)==null?void 0:n.onSendDgm(e,t))===!1||(this.upspeed.addSample(e.byteLength),await((r=this.datagramWriter)==null?void 0:r.write(e).catch(a=>{console.log("send dgm fail",a)})))}async destroy(){var e,t,i;try{await((e=this.streamWriter)==null?void 0:e.close()),await((t=this.datagramWriter)==null?void 0:t.close())}catch(n){console.warn("upstream destroy:",n)}this.upspeed.reset(),(i=this.strategy)==null||i.destroy()}getSpeed(){return this.upspeed.getUpSpeed()}getBandwidth(){return this.bandwidth}getEstimateBandwidth(){return this.bandwidthEstimate.getEstimateBandwidth()}clearEstimateBandwidth(){this.bandwidthEstimate.reset()}}class re extends p{constructor(e,t){super(),this.destroyed=!1,this.read(e.readable,i=>{this.emit("stream",i)},!0),this.read(t.readable,i=>{this.emit("datagram",i)})}async read(e,t=()=>{},i=!1){const n=e.getReader();for(i&&(this.streamReader=n);!this.destroyed;){const{value:r,done:a}=await n.read().catch(()=>({done:!0,value:null}));if(a)break;t(r)}}resetStream(e){this.streamReader.releaseLock(),this.read(e.readable,t=>{this.emit("stream",t)})}destroy(){this.destroyed=!0,super.destroy()}}const P={clearConnection:()=>Promise.resolve(),sendStream:async()=>{},sendDgm:async()=>{},getUpSpeed:()=>0,getUpBandwidth:()=>0,getId:()=>0};class ae extends p{constructor(e){super(),this.destroyed=!1,this._resetLock=!1,this.options=e,this.ready=this.connect(),this.ready.then(t=>{var i;t&&(this.initStream(),(i=this.transport)==null||i.closed.then(n=>{this.emit("closed",n)}).catch(n=>{this.emit("closed",{closeCode:-1,reason:`catch ${n.toString()}`})}))})}get id(){return this.options.id}async destroy(){var e,t,i,n;if(super.destroy(),!this.destroyed){this.destroyed=!0,await((e=this.upstream)==null?void 0:e.destroy()),(t=this.downstream)==null||t.destroy();try{(i=this.transport)==null||i.close(),await((n=this.transport)==null?void 0:n.closed)}catch(r){console.warn("close fail",r)}this.transport=null,u.log("close transport"),this.emit("destroyed")}}async connect(){try{const e=new WebTransport(this.options.url);if(!e)this.onFail("Init error");else{this.transport=e;const t=await x({task:async()=>{var i;try{return await((i=this.transport)==null?void 0:i.ready),u.log("transport ready"),""}catch(n){return`Ready Catch: ${(n==null?void 0:n.toString())||"Fail"}`}},timeout:"Init timeout",time:2e3});if(t)this.onFail(t);else return this.emit("success"),!0}}catch(e){this.onFail(`Init Catch: ${(e==null?void 0:e.toString())||"Fail"}`)}return!1}onFail(e){this.emit("fail",e),this.transport=null,this.destroy()}async initStream(){const{transport:e}=this;if(!e)return;const t=await this.createBidStream();if(!t)return;this._prevStream=t;const i=e.datagrams;this.upstream=new ne(t,i,this.options.strategy),this.downstream=new re(t,i),this.downstream.on({stream:n=>this.emit("stream",n),datagram:n=>{this.emit("datagram",n)}}),this.upstream.on("write-error",()=>{this.resetStream()}),this.emit("upstream-ready")}async resetStream(){var t,i,n,r;if(this._resetLock)return;this._resetLock=!0;const e=await this.createBidStream();if(!e){this._resetLock=!1;return}(t=this.upstream)==null||t.resetStream(e),(i=this._prevStream)==null||i.writable.close(),(n=this.downstream)==null||n.resetStream(e),(r=this._prevStream)==null||r.readable.cancel(),this._prevStream=e,this._resetLock=!1}async createBidStream(){var e;return(e=this.transport)==null?void 0:e.createBidirectionalStream()}}class oe{constructor(e){this.index=0,this.gaps=[5,5,5,5,10,10,10,20,20,30,30,40,50,70,100],this.count=0,this.n=this.gaps.length,this.max=this.gaps[this.n-1]*100,this.maxCount=e}reset(){this.index=0,this.count=0}get gap(){return typeof this.maxCount=="number"&&this.count>=this.maxCount?0:(this.count++,this.index>=this.n-1?this.max:this.gaps[this.index++]*100)}}class ce extends p{constructor(){super(...arguments),this.readyState=l.Connecting,this.connectId=0,this.connectionUtil=P,this.destroyed=!1}setState(e){this.readyState=e}get isConnecting(){return this.readyState===l.Connecting}async init(e){this.options=Object.assign({autoReconnect:!0,useDownstream:!0},e),this.reconnectGap=new oe(e.maxCount),await this.connect({connectReason:S.Init})}async connect({first:e=!0,connectReason:t,url:i}){if(this.destroyed)return this.setState(l.Closed),Promise.resolve("Reconnector destroyed");const n=t===S.Init;e&&(this.reconnectGap.reset(),n||this.emit("reconnecting",t)),this.setState(l.Connecting);const{success:r,reason:a}=await this.singleConnect(i);if(this.destroyed)return this.setState(l.Closed),Promise.resolve("Reconnector destroyed stage2");if(!r){const{gap:o}=this.reconnectGap,c=e&&n?"connect-fail":"reconnect-fail";return this.emit(c,a),o===0||!this.options.autoReconnect?(this.emit("end"),this.setState(l.Closed),a):(await J(o,h=>this.delayTimer=h),this.connect({first:!1,url:i,connectReason:S.Error}))}return this.setState(l.Open),this.emit("connect-open",n),this.onConnected(),n||this.onMonitorConnectionNormal(),""}async onConnected(){var t;(t=this.clearWaitClosed)==null||t.call(this);const[e]=await this.onWait("connection-closed",{onclear:i=>this.clearWaitClosed=i});if(e.closeCode!==-1){if(console.log("reason",e.reason),this.emit("connect-close",e.reason||""),this.isConnecting){console.warn("isConnecting",e.reason);return}console.log("close: webts closed gracefully.",e.reason),e.closeCode===0&&(this.emit("end"),this.setState(l.Closed))}else{const i=e.reason;console.error("close: webts closed due to ",e),this.emit("connect-close",i),this.emit("disconnected",i),this.options.autoReconnect?this.connect({connectReason:S.Error}):(this.emit("connect-fail",i),this.emit("end"))}}onMonitorConnectionNormal(){this.options.useDownstream&&(this.waitTimer=setTimeout(()=>{this.emit("reconnect-fail","no packet"),this.emit("connect-close","no packet received"),this.emit("end"),this.setState(l.Closed)},3e3))}onReceivePacket(e){this.waitTimer!==null&&(e<10||(clearTimeout(this.waitTimer),this.waitTimer=null,console.warn("DEBUG 重连恢复收包"),this.emit("reconnected")))}async singleConnect(e){const{resolve:t,ready:i}=E();await this.clearReconnect();const n=new ae({id:this.connectId++,url:e||this.options.url,strategy:this.options.strategy});n.on({success:()=>{t({success:!0,reason:""})},fail:a=>{t({success:!1,reason:a})},destroyed:()=>{t({success:!1,reason:"Connection destroyed"})},datagram:a=>{this.onReceivePacket(a.byteLength),this.emit("datagram",a)},closed:a=>{this.emit("connection-closed",a)}}),this.passEvents(n,["upstream-ready","stream"]);const r=n.onWait("upstream-ready");return this.connectionUtil={clearConnection:()=>n.destroy(),sendStream:async(a,o)=>{var c;if(!n.destroyed)return await r,(c=n.upstream)==null?void 0:c.sendStream(a,o)},sendDgm:async(a,o)=>{var c;if(!n.destroyed)return await r,(c=n.upstream)==null?void 0:c.sendDgm(a,o)},getUpSpeed:()=>{var a;return((a=n.upstream)==null?void 0:a.getSpeed())||0},getUpBandwidth:()=>{var a;return((a=n.upstream)==null?void 0:a.getBandwidth())||0},getId:()=>n.id},i}async destroy(){this.destroyed||(this.destroyed=!0,await this.clearReconnect(),this.emit("connect-close","api call"),this.emit("disconnected","api call"),super.destroy())}async clearReconnect(){var e;await((e=this.connectionUtil)==null?void 0:e.clearConnection()),clearTimeout(this.delayTimer),clearTimeout(this.waitTimer),this.waitTimer=this.delayTimer=null}onlineReconnect(){this.options.autoReconnect&&(this.clearReconnect(),this.connect({first:!0,connectReason:S.Online}))}}class he extends p{get readyState(){var e;return((e=this.reconnector)==null?void 0:e.readyState)||l.Closed}get closed(){return this.readyState===l.Closed}get connection(){var e;return((e=this.reconnector)==null?void 0:e.connectionUtil)||P}async init(e){this.reconnector=new ce,this.initEvents(),this.ready=this.reconnector.init({...Object.assign({useDownstream:!0},e)}),await this.ready}async close(){await this.reconnector.destroy()}online(){this.reconnector.onlineReconnect()}reconnect(e){this.reconnector.connect({connectReason:S.ApiCall,url:e})}async sendStream(e,t){var i;return await this.ready,(i=this.connection)==null?void 0:i.sendStream(e,t)}async sendDgm(e,t){var i;return await this.ready,(i=this.connection)==null?void 0:i.sendDgm(e,t)}initEvents(){this.passEvents(this.reconnector,["reconnected","reconnect-fail","connect-close","disconnected","reconnecting","connect-fail","connect-open","upstream-ready","stream","datagram"])}getUpSpeed(){return this.connection.getUpSpeed()}getUpBandwidth(){return this.connection.getUpBandwidth()}async destroy(){await this.close(),super.destroy()}}class de extends p{sendStream(e,t){return this.upstream.sendStream(e,{force:!0,extra:t})}sendDgm(e,t){return this.upstream.sendDgm(e,{force:!0,extra:t})}}class ue{constructor(){this.totalFrames=0,this.periodFrames=0,this.periodSize=0,this.periodDuration=0,this.keyFrames=0,this.bitrate=0,this.framerate=0,this.lastTs=0}addFrame(e){const t=e.byteLength;let i=0;const n=Math.round(e.timestamp/1e3);this.lastTs!==0&&(i=n-this.lastTs),this.lastTs=n,this.totalFrames++,this.periodFrames++,this.periodSize+=t,this.periodDuration+=i,e.type==="key"&&this.keyFrames++,this.periodDuration>=1e3&&(this.bitrate=Math.floor(this.periodSize/this.periodDuration*8e3),this.framerate=this.periodFrames,this.periodFrames=0,this.periodDuration=0,this.periodSize=0)}getStats(){return{bitrate:this.bitrate,framerate:this.framerate,encodedFrames:this.totalFrames,encodedKeyFrames:this.keyFrames,codec:""}}reset(){this.totalFrames=0,this.periodFrames=0,this.periodSize=0,this.periodDuration=0,this.keyFrames=0,this.bitrate=0,this.framerate=0,this.lastTs=0}}class H extends p{constructor(){super(...arguments),this.configInitialized=!1,this.firstFrame=!1,this.stats=new ue,this._config={},this._finalConfig={},this._decoderConfig={},this._destroyed=!1}extraEncodeConfig(){return{}}getStats(){return this.stats.getStats()}get mediaType(){return this._config.mediaType}async updateConfig(e){if(e=_(e),Object.keys(e).length===0)return;Object.assign(this._config,e),this.encoder&&(await this.encoder.flush(),this.encoder.close(),this.init());const t=await this.checkConfigSupported(this.formatConfig());this._config={...this._config,...t},this._finalConfig=this.formatConfig(),this.configInitialized=!1}getConfig(){return this._config}getDecoderConfig(){return this._decoderConfig}init(e){e&&this.updateConfig(e),u.log("init encoder"),this.encoder=new this.Encoder({output:(t,i)=>{t.syncTimestamp=t.timestamp,this.stats.addFrame(t);const n=i==null?void 0:i.decoderConfig;let r;n&&(r=n,Object.assign(this._decoderConfig,n),this.emit("decoder-config-change",this._decoderConfig)),this.emit("frame-encoded",t,r),this.firstFrame||(this.emit("first-frame-encoded",t,r),this.firstFrame=!0)},error:t=>{this.emit("encode-error",t)}})}encode(e){var t;if(!this._destroyed){if(!this.configInitialized){const i=this._finalConfig;(t=this.encoder)==null||t.configure(i),this.configInitialized=!0,console.warn("configure final done",i)}this.encoder.encode(e,this.extraEncodeConfig())}}async destroy(){var e,t;this.stats.reset(),this._destroyed=!0;try{await((e=this.encoder)==null?void 0:e.flush()),(t=this.encoder)==null||t.close()}catch{}super.destroy()}async checkConfigSupported(e,t=!1){if(this.Encoder.isConfigSupported)try{const{config:i,supported:n}=await this.Encoder.isConfigSupported(e);if(n)return e;if(!t&&this.retryConfig)return this.checkConfigSupported(this.retryConfig(e),!0);this.emit("config-error",{message:"config not supported",config:i})}catch(i){if(!t&&this.retryConfig)return this.checkConfigSupported(this.retryConfig(e));this.emit("config-error",{message:"config uncaught error",err:i,config:e})}}}F("audio_encoder_support","3d");function le(){return V(["EncodedAudioChunk","AudioEncoder","AudioData"])}const m={mediaType:f.H264,format:"annexb",bitrate:2e5,framerate:15,bitrateMode:"variable",keyInterval:3e3,keyGopSize:90,hardwareAcceleration:"prefer-hardware",latencyMode:"quality"},w={mediaType:f.AAC,bitrate:96e3,sampleRate:48e3,numberOfChannels:2,bitrateMode:"constant"},T=class T extends H{constructor(){super(...arguments),this.Encoder=AudioEncoder,this.isAudio=!0}updateConfig(e){if(typeof e.bitrate=="number"){const t=[96e3,128e3,16e4,192e3],i=X(e.bitrate,t);i!==e.bitrate&&(console.warn(`audio bitrate ${e.bitrate} not supported, use ${i} instead`),e.bitrate=i)}return super.updateConfig(e)}getStats(){const{codec:e="",numberOfChannels:t=0,sampleRate:i=0}=this._finalConfig;return{...super.getStats(),codec:e,numberOfChannels:t,sampleRate:i}}formatConfig(e){const{bitrate:t=w.bitrate,bitrateMode:i=w.bitrateMode,codec:n=w.codec||U[this._config.mediaType??w.mediaType],numberOfChannels:r=w.numberOfChannels,format:a=w.format||(e==null?void 0:e.format),sampleRate:o=w.sampleRate}=this._config,c=_({codec:n,sampleRate:o,numberOfChannels:r,bitrate:t,bitrateMode:i,format:a});return this.emit("config-change",c),c}};T.isSupported=le;let v=T;F("video_encoder_support","3d");function fe(){return V(["EncodedVideoChunk","VideoEncoder","VideoFrame"])}function me(s=m.keyInterval){let e=!0,t;return{is(){return e?(e=!1,t=setTimeout(()=>{e=!0},s),!0):!1},reset(){e=!0,clearTimeout(t)}}}function pe(s=m.keyGopSize){let e=s;return{is(){return e++,e>=s?(e=0,!0):!1},reset(){e=s}}}const B=class B extends H{constructor(){super(...arguments),this.Encoder=VideoEncoder,this.isAudio=!1,this.retryConfig=e=>(e.hardwareAcceleration==="prefer-hardware"&&(e.hardwareAcceleration="prefer-software",this._config.hardwareAcceleration="prefer-software",console.warn("retry config with software hardwareAcceleration")),e)}getStats(){const e=super.getStats();let{keyGopSize:t}=this._finalConfig;const{keyInterval:i=m.keyInterval}=this._config,{width:n=0,height:r=0,codec:a="",framerate:o=0}=this._finalConfig;return typeof t>"u"&&(t=Math.round(i/1e3*o)),{...e,width:n,height:r,codec:a,keyGopSize:t}}formatConfig(e){const{codec:t=m.codec||U[this._config.mediaType??m.mediaType],bitrate:i=m.bitrate,framerate:n=m.framerate,keyInterval:r=m.keyInterval,hardwareAcceleration:a=m.hardwareAcceleration,latencyMode:o=m.latencyMode,keyGopSize:c,width:h=m.width||(e==null?void 0:e.codedWidth),height:d=m.height||(e==null?void 0:e.codedHeight)}=this._config;this.keyframe=c?pe(c):me(r);const b=_({latencyMode:o,codec:t,hardwareAcceleration:a,bitrate:i,width:h,height:d,framerate:n});return console.log("config video",JSON.stringify(b,null,2)),this.emit("config-change",b),b}extraEncodeConfig(){return{keyFrame:this.keyframe.is()}}resetKeyFrame(){var e;(e=this.keyframe)==null||e.reset()}async destroy(){try{this.resetKeyFrame()}catch{}await super.destroy()}};B.isSupported=fe;let k=B;const N=16;function Q(){let s=-1,e=-1,t=-1;return{getLatest(){return s},setBase(i){t===-1&&(t=i)},check(i){return s===-1?s=t:s+=i-e,e=i,s},reset(){s=e=t=-1}}}class ge extends p{constructor(){super(...arguments),this.video=Q(),this.audio=Q(),this.base=N,this._sendQueue=[],this._processedVideo=!1,this._processedAudio=!1,this._maximumVideoSyncTimestamp=0,this._maximumAudioSyncTimestamp=0,this.cacheAudioChunk=[],this.cacheVideoChunk=[],this.hasGetFirstVideoFrame=!1,this.SYNC_THRESHOLD=40}insertPacket(e,t,i){let n=0;for(;n<this._sendQueue.length&&!(this._sendQueue[n].frame.syncTimestamp===e.syncTimestamp&&t==="video"||this._sendQueue[n].frame.syncTimestamp>e.syncTimestamp);n++);this._sendQueue.splice(n,0,{frame:e,type:t,cfg:i})}processPacket(e,t,i){switch(this._processedAudio&&this._processedVideo||(t==="video"?this._processedVideo=!0:this._processedAudio=!0),this.insertPacket(e,t,i),t){case"video":this._maximumVideoSyncTimestamp<e.syncTimestamp&&(this._maximumVideoSyncTimestamp=e.syncTimestamp);break;case"audio":this._maximumAudioSyncTimestamp<e.syncTimestamp&&(this._maximumAudioSyncTimestamp=e.syncTimestamp);break}if(this._processedAudio&&this._processedVideo)for(;this._sendQueue.length>0;){const r=this._sendQueue[0];if(!this.checkOpposingTimestamp(r.frame,r.type))return!1;this.emit("processed-frame",r.frame,r.type,r.cfg),this._sendQueue.shift()}}checkOpposingTimestamp(e,t){switch(t){case"audio":return this._maximumVideoSyncTimestamp>e.syncTimestamp;case"video":return this._maximumAudioSyncTimestamp>e.syncTimestamp;default:return!1}}formatFrame(e,t,i,n){this[t].setBase(this.base);const a=Math.round(e.timestamp/1e3),o=this[t].check(a);return e.syncTimestamp=o,this.processPacket(e,t,n),[e]}syncAVFrame(e,t){if(t==="audio")this.cacheAudioChunk.push(e),this.cacheAudioChunk.sort((i,n)=>i.syncTimestamp-n.syncTimestamp);else if(this.cacheVideoChunk.push(e),this.cacheVideoChunk.sort((i,n)=>i.syncTimestamp-n.syncTimestamp),!this.hasGetFirstVideoFrame)return this.hasGetFirstVideoFrame=!0,null;return this.flushSynchronizedFrames()}flushSynchronizedFrames(){const e=[];for(;this.canSendFrame();){const t=this.getNextFrameToSend();if(t)e.push(t);else break}return e}canSendFrame(){if(this.cacheAudioChunk.length===0&&this.cacheVideoChunk.length===0)return!1;if(this.cacheAudioChunk.length===0)return this.cacheVideoChunk.length>0;if(this.cacheVideoChunk.length===0)return!1;const e=this.cacheAudioChunk[0],t=this.cacheVideoChunk[0];return Math.abs(e.syncTimestamp-t.syncTimestamp)<=this.SYNC_THRESHOLD}getNextFrameToSend(){if(this.cacheAudioChunk.length===0&&this.cacheVideoChunk.length>0)return this.cacheVideoChunk.shift()||null;if(this.cacheVideoChunk.length===0&&this.cacheAudioChunk.length>0||this.cacheAudioChunk.length===0&&this.cacheVideoChunk.length===0)return null;const e=this.cacheAudioChunk[0],t=this.cacheVideoChunk[0];return e.syncTimestamp<=t.syncTimestamp?this.cacheAudioChunk.shift()||null:this.cacheVideoChunk.shift()||null}reset(){this.audio.reset(),this.video.reset(),this.base=N,this._processedAudio=!1,this._processedVideo=!1,this._maximumAudioSyncTimestamp=0,this._maximumVideoSyncTimestamp=0,this.cacheAudioChunk=[],this.cacheVideoChunk=[],this.hasGetFirstVideoFrame=!1}}var y=(s=>(s[s.AUDIO=8]="AUDIO",s[s.VIDEO=9]="VIDEO",s[s.SCRIPT_DATA=18]="SCRIPT_DATA",s))(y||{}),A=(s=>(s[s.SEQUENCE_HEADER=0]="SEQUENCE_HEADER",s[s.AAC=1]="AAC",s))(A||{}),D=(s=>(s[s.SEQUENCE_HEADER=0]="SEQUENCE_HEADER",s[s.NALU=1]="NALU",s))(D||{}),I=(s=>(s[s.KEY=1]="KEY",s[s.INNER=2]="INNER",s))(I||{});const _e=10,ye=1,Se=7,we={96e3:0,48e3:3,44100:4,22050:7,16e3:8,8e3:11};function be(s){const e=(s[4]&3)+1;let t;const i=[],n=[];let r=6;const a=s[5]&31;let o;for(let d=0;d<a;d++){if(o=s[r]<<8|s[r+1],r+=2,!o)continue;const b=s.subarray(r,r+o);r+=o,i.push(b)}const c=s[r];r++;let h;for(let d=0;d<c;d++)h=s[r]<<8|s[r+1],r+=2,h&&(n.push(s.subarray(r,r+h)),r+=h);return{sps:t,spsArr:i,ppsArr:n,nalUnitSize:e}}class Ce{constructor(){this._cfg={hasVideo:!1,hasAudio:!1,sampleRate:48e3,numberOfChannels:1},this._hasVideoSeqHeader=!1}get hasVideo(){return!!this._cfg.hasVideo}get hasAudio(){return!!this._cfg.hasAudio}setConfig(e){this._cfg=Object.assign(this._cfg,e),console.log("---flv setConfig",this._cfg)}genHeader(){const e=[70,76,86,1,(this.hasAudio?1:0)<<2|(this.hasVideo?1:0),0,0,0,9,0,0,0,0];return new Uint8Array(e)}geneSEQ(e,t){let i;return e===y.AUDIO?i=this._genAudioSEQPayload():(i=this._genVideoSEQPayload(t.frame.type,t.description),this._hasVideoSeqHeader=!0),this._concatPayload(e,t.frame.syncTimestamp,i)}genPayload(e){const t=e.type===y.AUDIO,i=ee(e.frame),n=C([t?this._genAudioTagHeader():this._genVideoTagHeader(e.frame.type),t?this._genAudioData(i):this._genVideoData(e,i)]);return this._concatPayload(e.type,e.frame.syncTimestamp,n)}_concatPayload(e,t,i){const n=this._genTagHeader(e,i.length,t),r=n.length+i.length;return C([n,i,new Uint8Array([r>>>24,r>>>16,r>>>8,r])])}_genTagHeader(e,t,i){return new Uint8Array([e,t>>>16,t>>>8,t,i>>>16,i>>>8,i,i>>>24,0,0,0])}_genAudioSEQPayload(){return C([this._genAudioTagHeader(),this._genAudioSequenceHeader()])}_genVideoSEQPayload(e,t){return C([this._genVideoTagHeader(e),this._genVideoSequenceHeader(t)])}_genAudioTagHeader(){return new Uint8Array([_e<<4|12|ye<<1|this._cfg.numberOfChannels-1])}_genVideoTagHeader(e){return new Uint8Array([(e==="key"?I.KEY:I.INNER)<<4|Se,this._hasVideoSeqHeader?D.NALU:D.SEQUENCE_HEADER,0,0,0])}_genAudioSequenceHeader(){const e=4096|we[this._cfg.sampleRate]<<7|this._cfg.numberOfChannels<<3;return new Uint8Array([A.SEQUENCE_HEADER,e>>8,e])}_genAudioData(e){const t=new Uint8Array(1+e.length);return t.set([A.AAC],0),t.set(e,1),t}_genVideoSequenceHeader(e){return new Uint8Array(e||[])}_genVideoData(e,t){if(e.frame.type==="delta")return t;const i=be(new Uint8Array(e.description)),n=i.spsArr[0].length,r=i.ppsArr[0].length;return C([new Uint8Array([0,0,n>>8,n%256]),i.spsArr[0],new Uint8Array([0,0,r>>8,r%256]),i.ppsArr[0],t])}reset(){this._hasVideoSeqHeader=!1}}class Ee{constructor(){this._firstFrame=!0,this._flv=new Ce}updateConfig(e){e&&this._flv.setConfig(e)}receiveMediaFrame(e,t){const i=e.type===y.AUDIO;this._firstFrame&&i||(this._firstFrame&&(t({buffer:this._flv.genHeader(),type:"header"}),this._flv.hasAudio&&t({buffer:this._flv.geneSEQ(y.AUDIO,e),type:"seq"}),this._flv.hasVideo&&t({buffer:this._flv.geneSEQ(y.VIDEO,e),type:"seq"}),this._firstFrame=!1),t({buffer:this._flv.genPayload(e),type:"payload"}))}reset(){this._firstFrame=!0,this._flv.reset()}destroy(){this.reset()}}class ve{constructor(e=1e3){this._packets=[],this._latestDts=0,this._videoDuration=0,this._batchSize=e}addPacket(e,t){this._packets.push({data:e,isSeparator:!1,...t}),t.mediaType==="video"&&(this._latestDts=t.dts||0)}getVideoDuration(){const e=this._packets.find(t=>t.mediaType==="video");return!e||!e.dts?0:this._latestDts-e.dts}shift(){if(this._packets.length===0)return;let e=0;for(const r of this._packets)e+=r.data.byteLength;if(e<this._batchSize)return;const t=new Uint8Array(this._batchSize);let i=0,n=this._batchSize;for(;n>0&&this._packets.length>0;){const r=this._packets[0],a=r.data.byteLength;if(a<=n)t.set(r.data,i),i+=a,n-=a,this._packets.shift();else{const o=r.data.slice(0,n);t.set(o,i),this._packets[0]={...r,data:r.data.slice(n),isSeparator:!0},n=0}}return t}shiftSinglePacket(){if(this._packets.length===0)return;const e=this._packets.shift();return e==null?void 0:e.data}forceShift(){if(this._packets.length===0)return;let e=0;for(const a of this._packets)e+=a.data.byteLength;const t=Math.min(e,this._batchSize),i=new Uint8Array(t);let n=0,r=t;for(;r>0&&this._packets.length>0;){const a=this._packets[0],o=a.data.byteLength;if(o<=r)i.set(a.data,n),n+=o,r-=o,this._packets.shift();else{const c=a.data.slice(0,r);i.set(c,n),this._packets[0]={...a,data:a.data.slice(r),isSeparator:!0},r=0}}return i}dropPackets(e){const t=Math.min(e,this._packets.length);this._packets.splice(0,t)}dropVideoPackets(){this._packets=this._packets.filter(e=>e.mediaType!=="video")}get size(){return this._packets.length}get totalBytes(){return this._packets.reduce((e,t)=>e+t.data.byteLength,0)}get hasEnoughData(){return this.totalBytes>=this._batchSize}reset(){this._packets=[]}setBatchSize(e){this._batchSize=e}}class ke{constructor(){this._lastDot=0,this._totalSize=0,this._speed=[]}addSample(e){this._lastDot||(this._lastDot=Date.now()),this._totalSize+=e;const t=Date.now()-this._lastDot;t>=500&&(this._addSpeedSample(this._totalSize/t*8e3),this._totalSize=0,this._lastDot=Date.now())}_addSpeedSample(e){this._speed.push(e),this._speed=this._speed.slice(-6)}reset(){this._speed=[]}getUpSpeed(){return this._speed.length?parseInt(this._speed.reduce((e,t)=>e+=t,0)/this._speed.length):0}}class Ae extends de{constructor(e,t){super(),this.context=e,this.upSpeed=new ke,this.streamBuffer=new ve,this._inAdjustEncode=!1,this._dbrIncTimeout=0,this._dbrPrevBitrate=0,this._increaseTimer=0,this.isSending=!1,this.config={maxCacheSize:50,realSpeedPercent:.8,setting:{},uplinkBitrateCheckInterval:4*1e3,dbrIncreaseStep:.1},this.getCurrentBitrate=()=>this.context.videoEncoderConfig.bitrate??0,t&&this.updateConfig(t)}reset(){this.upSpeed.reset(),this.streamBuffer.reset(),this.isSending=!1,clearInterval(this._increaseTimer),this._increaseTimer=0,this._inAdjustEncode=!1}updateConfig(e){Object.assign(this.config,e)}_isHavingCongestion(){return this.streamBuffer.size>this.config.maxCacheSize}_setEncoderBitrate(e){const{width:t,height:i,framerate:n}=this.context.videoEncoderConfig;console.log(`set encode bitrate to specified ${e}`),this.context.emit("video-encoder-config",{bitrate:e,width:t,height:i,framerate:n}),this._inAdjustEncode=!0}_increaseBitrate(){this._dbrIncTimeout=0,this._dbrPrevBitrate=this.getCurrentBitrate();const e=this.context.videoEncoderConfig.originBitrate;if(!e)return;let t=this.getCurrentBitrate()+e*this.config.dbrIncreaseStep;t>=e?t=e:this._dbrIncTimeout=Date.now()+this.config.uplinkBitrateCheckInterval,this._setEncoderBitrate(t)}_decreaseBitrate(){const e=this._dbrPrevBitrate;let t=0,i;if(this.upstream.getEstimateBandwidth()&&this.upstream.getEstimateBandwidth()<this.getCurrentBitrate()&&(t=Math.floor(this.upstream.getEstimateBandwidth()*90/100/1e5)*1e5,t<50*1e3&&(t=50*1e3),this.upstream.clearEstimateBandwidth()),t)i=t;else if(e)console.log("use prev bitrate",e),i=e;else return;this._dbrPrevBitrate=0,this._dbrIncTimeout=Date.now()+this.config.uplinkBitrateCheckInterval,this._setEncoderBitrate(i)}_checkBitrate(){this._dbrIncTimeout&&Date.now()>=this._dbrIncTimeout&&(this._isHavingCongestion()?this._dbrIncTimeout=Date.now()+this.config.uplinkBitrateCheckInterval:this._increaseBitrate()),this._isHavingCongestion()&&this.streamBuffer.getVideoDuration()>500&&this._decreaseBitrate()}onSendStream(e,t){return this._checkBitrate(),this.streamBuffer.addPacket(e,t),this.upSpeed.addSample(e.byteLength),this._sendBuffer(),!1}async _sendBuffer(){if(!this.isSending){for(this.isSending=!0;;){const e=this.streamBuffer.shiftSinglePacket();if(!e)break;await this.sendStream(e)}this.isSending=!1}}onSendDgm(){return!0}_checkDeleteCache(e=!1){this._inAdjustEncode&&e&&(console.log(`ajust encode setting finish, delete cached ${this.streamBuffer.size} frame`),this.streamBuffer.reset(),this.upSpeed.reset(),this._inAdjustEncode=!1)}}class De extends p{constructor(e){super(),this.entry=e,this.on({"video-encoder-config":t=>{this.entry.videoEncoder.updateConfig(t)},"audio-encoder-config":t=>{this.entry.audioEncoder.updateConfig(t)}})}get videoEncoderConfig(){return this.entry.videoEncoder.getConfig()}get audioEncoderConfig(){return this.entry.audioEncoder.getConfig()}}class Ie extends p{constructor({videoEncoder:e,audioEncoder:t,transport:i,flv:n,strategy:r,formatAV:a=!0}={}){super(),this.hasVideo=!0,this.stopVideoInput=()=>{},this.stopAudioInput=()=>{},this._isVideoEncoded=!1,this._destroy=!1,this.reconnecting=!1,this.context=new De(this),this.videoEncoder=e||new k,this.audioEncoder=t||new v,this.transport=i||new he,this.flv=n||new Ee,a&&(this.avFormat=new ge,this.initAvFormatEventListener()),this.strategy=r||new Ae(this.context);const{sampleRate:o,numberOfChannels:c}=this.audioEncoder.getConfig();this.flv.updateConfig(_({sampleRate:o,numberOfChannels:c}))}initAvFormatEventListener(){this.avFormat.on("processed-frame",(e,t,i)=>{const n=e;if(n instanceof EncodedAudioChunk&&this.flv.receiveMediaFrame({type:y.AUDIO,frame:n},({buffer:r,type:a})=>{this.transport.sendStream(r,{extra:{isAudio:!0,type:a,key:!0,mediaType:"audio",dts:n.syncTimestamp}})}),n instanceof EncodedVideoChunk){const r=n.type==="key";this.flv.receiveMediaFrame({type:y.VIDEO,frame:n,description:i==null?void 0:i.description},({buffer:a,type:o})=>{this.transport.sendStream(a,{extra:{isAudio:!1,type:o,key:r,mediaType:"video",dts:n.syncTimestamp}})})}})}start(e){const t=e.data,i={},n={};if(e.video){const{width:r,height:a,frameRate:o}=t.setting.video||{};Object.assign(i,_({width:r,height:a,framerate:o}))}if(e.audio){const{sampleRate:r,channelCount:a}=t.setting.audio||{};Object.assign(n,_({sampleRate:r,numberOfChannels:a}))}if(t.cfg){const{channel:r,gopSize:a,sampleRate:o}=t.cfg;e.video&&Object.assign(i,_({keyGopSize:a,bitrate:t.bitrate.video,originBitrate:t.bitrate.video})),e.audio&&Object.assign(n,_({numberOfChannels:r,sampleRate:o,bitrate:t.bitrate.audio}))}this.videoEncoder.updateConfig(i),this.audioEncoder.updateConfig(n),this.init({transport:{url:t.url,maxReconnectCount:t.maxReconnectCount,autoReconnect:t.autoReconnect},input:{audio:e.audio,video:e.video}}),console.log("On worker start",t)}async init(e){this.initPassEvents();const{url:t,maxReconnectCount:i,autoReconnect:n}=e.transport;this.options=e,await this.transport.init({url:t,maxReconnectCount:i,autoReconnect:n,strategy:this.strategy,useDownstream:!1}),this.initSyncStuff(e),this.emit("engine-ready")}initPassEvents(){this.passEvents(this.transport,["connect-open","connect-close","disconnected","reconnecting","reconnected","reconnect-fail","connect-fail"])}initWriter(e){e&&(e.stream?this.initInputWithStream(e.stream):(e.audio||e.video)&&this.initInput({video:e.video,audio:e.audio}))}initSyncStuff({encoder:e,input:t,flv:i}){this.videoEncoder.init(e==null?void 0:e.video),this.audioEncoder.init(e==null?void 0:e.audio),this.initWriter(t),this.flv.updateConfig(i),this.initEngineEvents()}async initInput({audio:e,video:t}){this.hasVideo=!!t,this.flv.updateConfig({hasAudio:!!e,hasVideo:!!t}),await this.transport.onWait("upstream-ready");const i=(r=!1)=>()=>{console.log("encode finish: ",r)},n=(r=!1)=>a=>{console.warn("encode error: ",r,a)};e&&(this.stopAudioInput=O({readable:e,onFrame:r=>{this._destroy||this.reconnecting||this.audioEncoder.encode(r)},onFinish:i(!0),onError:n(!0)})),t&&(this.stopVideoInput=O({readable:t,onFrame:r=>{this._destroy||this.reconnecting||this.videoEncoder.encode(r)},onFinish:i(),onError:n()}))}initInputWithStream(e){const{video:t,audio:i}=W(e);this.hasVideo=!!t,t&&this.videoEncoder.updateConfig(t.settings),i&&this.audioEncoder.updateConfig(i.settings),this.initInput({video:t==null?void 0:t.readable,audio:i==null?void 0:i.readable})}muxAndSend(e,t,i){this.avFormat.formatFrame(e,t,this.hasVideo,i)}initEngineEvents(){this._isVideoEncoded=!this.hasVideo,this.audioEncoder.on({"first-frame-encoded":()=>{this.emit("first-audio-frame-encoded")},"frame-encoded":e=>{this.reconnecting||this.muxAndSend(e,"audio")},"encode-error":e=>{this.triggerError("audio encode error",e)},"config-error":e=>{this.triggerError("audio config error",e)},"config-change":e=>{console.log("Encoder config audio",e)},"decoder-config-change":e=>{this.flv.updateConfig(e)}}),this.videoEncoder.on({"first-frame-encoded":()=>{this.emit("first-video-frame-encoded")},"frame-encoded":(e,t)=>{this.reconnecting||(this._isVideoEncoded||(this._isVideoEncoded=!0),this.muxAndSend(e,"video",t))},"encode-error":e=>{this.triggerError("video encode error",e)},"config-error":e=>{this.triggerError("video config error",e)},"config-change":e=>{console.log("Encoder config video",e)}})}triggerError(e,t){this.emit("error",{info:e,err:t})}async destroy(){this.stopVideoInput(),this.stopAudioInput(),console.log("transport close 1"),await this.transport.destroy(),await this.videoEncoder.destroy(),await this.audioEncoder.destroy(),this.flv.destroy(),super.destroy()}online(){this.transport.online()}setBitrate(e,t){(t==="audio"?this.audioEncoder:this.videoEncoder).updateConfig({bitrate:e,originBitrate:e})}getStats(){return{video:this.videoEncoder.getStats(),audio:this.audioEncoder.getStats(),upspeed:this.transport.getUpSpeed(),upBandwidth:this.transport.getUpBandwidth()}}async reconnect(e){this.reconnecting=!0,this.strategy.reset(),this.avFormat.reset(),this.flv.reset(),this._isVideoEncoded=!this.hasVideo,this.videoEncoder.resetKeyFrame(),this.transport.reconnect(e),await this.transport.onWait("upstream-ready",{prev:!1}),this.reconnecting=!1}}class Te extends M{receiveMainMessage(e){var t,i,n,r,a,o,c;switch(e.type){case g.Start:{this.startMsg=e,this.engine=new Ie,this.initPassEvents(),this.engine.start(e);break}case g.Stop:(t=this.engine)==null||t.destroy();break;case g.UpdateTrack:{const{engine:h}=this;if(!h)return;const d=e.data;d.isAudio?h.stopAudioInput():h.stopVideoInput(),h.initInput({[d.isAudio?"audio":"video"]:d.stream}),(i=h.avFormat)==null||i.reset(),d.setting&&(d.isAudio?h.audioEncoder:h.videoEncoder).updateConfig(d.setting)}break;case g.SetBitrate:(n=this.engine)==null||n.setBitrate(e.data.bitrate,e.data.type);break;case g.Online:(r=this.engine)==null||r.online();break;case g.Reconnect:(o=this.engine)==null||o.reconnect((a=e.data)==null?void 0:a.url);break;case g.GetStats:this.send(g.GetStats,((c=this.engine)==null?void 0:c.getStats())||{});break}}initPassEvents(){["engine-ready","first-audio-frame-encoded","first-video-frame-encoded","error","connect-fail","connect-open","disconnected","reconnected","reconnecting","reconnect-fail","connect-close"].forEach(e=>{this.engine.on(e,t=>{this.send(g.PassEngineEvent,{event:e,data:t})})})}}new Te})();\n',tu=typeof self<"u"&&self.Blob&&new Blob([eu],{type:"text/javascript;charset=utf-8"});function qv(r){let e;try{if(e=tu&&(self.URL||self.webkitURL).createObjectURL(tu),!e)throw"";const t=new Worker(e,{name:r==null?void 0:r.name});return t.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),t}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(eu),{name:r==null?void 0:r.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}var Le=function(){return(Le=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++)for(var i in e=arguments[t])Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=e[i]);return r}).apply(this,arguments)};function Ao(r,e,t,n){return new(t||(t=Promise))(function(i,o){function a(c){try{u(n.next(c))}catch(d){o(d)}}function s(c){try{u(n.throw(c))}catch(d){o(d)}}function u(c){c.done?i(c.value):new t(function(d){d(c.value)}).then(a,s)}u((n=n.apply(r,[])).next())})}function Do(r,e){var t,n,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function s(u){return function(c){return function(d){if(t)throw new TypeError("Generator is already executing.");for(;a;)try{if(t=1,n&&(i=2&d[0]?n.return:d[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,d[1])).done)return i;switch(n=0,i&&(d=[2&d[0],i.value]),d[0]){case 0:case 1:i=d;break;case 4:return a.label++,{value:d[1],done:!1};case 5:a.label++,n=d[1],d=[0];continue;case 7:d=a.ops.pop(),a.trys.pop();continue;default:if(i=a.trys,!((i=i.length>0&&i[i.length-1])||d[0]!==6&&d[0]!==2)){a=0;continue}if(d[0]===3&&(!i||d[1]>i[0]&&d[1]<i[3])){a.label=d[1];break}if(d[0]===6&&a.label<i[1]){a.label=i[1],i=d;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(d);break}i[2]&&a.ops.pop(),a.trys.pop();continue}d=e.call(r,a)}catch(f){d=[6,f],n=0}finally{t=i=0}if(5&d[0])throw d[1];return{value:d[0]?d[1]:void 0,done:!0}}([u,c])}}}function Kv(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n,i,o=t.call(r),a=[];try{for(;(e===void 0||e-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(s){i={error:s}}finally{try{n&&!n.done&&(t=o.return)&&t.call(o)}finally{if(i)throw i.error}}return a}function Io(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(Kv(arguments[e]));return r}var ru,Wv=function(){function r(){this._hooks={},this._cache=[],this._hooksCache={}}return r.prototype.on=function(e,t){e&&t&&typeof t=="function"&&(this._hooks[e]||(this._hooks[e]=[]),this._hooks[e].push(t))},r.prototype.once=function(e,t){var n=this;e&&t&&typeof t=="function"&&this.on(e,function i(o){t(o),n.off(e,i)})},r.prototype.off=function(e,t){if(e&&this._hooks[e]&&this._hooks[e].length)if(t){var n=this._hooks[e].indexOf(t);n!==-1&&this._hooks[e].splice(n,1)}else this._hooks[e]=[]},r.prototype.emit=function(e,t,n){if(n){if(!e)return;this._cache.indexOf(n)!==-1?this._emit(e,t):(this._hooksCache.hasOwnProperty(n)||(this._hooksCache[n]={}),this._hooksCache[n].hasOwnProperty(e)||(this._hooksCache[n][e]=[]),this._hooksCache[n][e].push(t))}else this._emit(e,t)},r.prototype._emit=function(e,t){e&&this._hooks[e]&&this._hooks[e].length&&Io(this._hooks[e]).forEach(function(n){try{n(t)}catch{}})},r.prototype.set=function(e){e&&this._cache.indexOf(e)===-1&&this._cache.push(e)},r}(),nu=function(r){return r!=null&&Object.prototype.toString.call(r)=="[object Object]"},Jv=(ru=+Date.now()+Number((""+Math.random()).slice(2,8)),function(){return ru+=1}),Jn=function(r){return function(e,t,n){if(typeof e=="string"&&typeof n=="number"){var i,o=[];n=n<=25?n:n%25;var a=String.fromCharCode(n+97);i=e.split(a);for(var s=0;s<i.length;s++){var u=parseInt(i[s],n);u=1*u^t;var c=String.fromCharCode(u);o.push(c)}return o.join("")}}(r,64,25)},iu=function(){return!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)},ou=function(r){var e=document.createElement("a");return e.href=r,e},xo=function(r){var e={};try{var t=ou(r).search;(t=t.slice(1)).split("&").forEach(function(n){var i,o,a=n.split("=");a.length&&(i=a[0],o=a[1]);try{e[i]=decodeURIComponent(o===void 0?"":o)}catch{e[i]=o}})}catch{}return e},Xn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Mo(){throw new Error("Dynamic requires are not currently supported by rollup-plugin-commonjs")}function su(r,e){return r(e={exports:{}},e.exports),e.exports}var fn=su(function(r,e){var t;t=function(){function n(){for(var o=0,a={};o<arguments.length;o++){var s=arguments[o];for(var u in s)a[u]=s[u]}return a}function i(o){return o.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function o(a){function s(){}function u(d,f,h){if(typeof document<"u"){typeof(h=n({path:"/"},s.defaults,h)).expires=="number"&&(h.expires=new Date(1*new Date+864e5*h.expires)),h.expires=h.expires?h.expires.toUTCString():"";try{var g=JSON.stringify(f);/^[\{\[]/.test(g)&&(f=g)}catch{}f=a.write?a.write(f,d):encodeURIComponent(String(f)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),d=encodeURIComponent(String(d)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\(\)]/g,escape);var k="";for(var z in h)h[z]&&(k+="; "+z,h[z]!==!0&&(k+="="+h[z].split(";")[0]));return document.cookie=d+"="+f+k}}function c(d,f){if(typeof document<"u"){for(var h={},g=document.cookie?document.cookie.split("; "):[],k=0;k<g.length;k++){var z=g[k].split("="),w=z.slice(1).join("=");f||w.charAt(0)!=='"'||(w=w.slice(1,-1));try{var b=i(z[0]);if(w=(a.read||a)(w,b)||i(w),f)try{w=JSON.parse(w)}catch{}if(h[b]=w,d===b)break}catch{}}return d?h[d]:h}}return s.set=u,s.get=function(d){return c(d,!1)},s.getJSON=function(d){return c(d,!0)},s.remove=function(d,f){u(d,"",n(f,{expires:-1}))},s.defaults={},s.withConverter=o,s}(function(){})},r.exports=t()}),Oo=su(function(r,e){r.exports=function t(n,i,o){function a(c,d){if(!i[c]){if(!n[c]){if(!d&&Mo)return Mo();if(s)return s(c,!0);var f=new Error("Cannot find module '"+c+"'");throw f.code="MODULE_NOT_FOUND",f}var h=i[c]={exports:{}};n[c][0].call(h.exports,function(g){var k=n[c][1][g];return a(k||g)},h,h.exports,t,n,i,o)}return i[c].exports}for(var s=Mo,u=0;u<o.length;u++)a(o[u]);return a}({1:[function(t,n,i){(function(o){var a,s,u=o.MutationObserver||o.WebKitMutationObserver;if(u){var c=0,d=new u(k),f=o.document.createTextNode("");d.observe(f,{characterData:!0}),a=function(){f.data=c=++c%2}}else if(o.setImmediate||o.MessageChannel===void 0)a="document"in o&&"onreadystatechange"in o.document.createElement("script")?function(){var z=o.document.createElement("script");z.onreadystatechange=function(){k(),z.onreadystatechange=null,z.parentNode.removeChild(z),z=null},o.document.documentElement.appendChild(z)}:function(){setTimeout(k,0)};else{var h=new o.MessageChannel;h.port1.onmessage=k,a=function(){h.port2.postMessage(0)}}var g=[];function k(){var z,w;s=!0;for(var b=g.length;b;){for(w=g,g=[],z=-1;++z<b;)w[z]();b=g.length}s=!1}n.exports=function(z){g.push(z)!==1||s||a()}}).call(this,Xn!==void 0?Xn:typeof self<"u"?self:typeof window<"u"?window:{})},{}],2:[function(t,n,i){var o=t(1);function a(){}var s={},u=["REJECTED"],c=["FULFILLED"],d=["PENDING"];function f(b){if(typeof b!="function")throw new TypeError("resolver must be a function");this.state=d,this.queue=[],this.outcome=void 0,b!==a&&z(this,b)}function h(b,T,E){this.promise=b,typeof T=="function"&&(this.onFulfilled=T,this.callFulfilled=this.otherCallFulfilled),typeof E=="function"&&(this.onRejected=E,this.callRejected=this.otherCallRejected)}function g(b,T,E){o(function(){var O;try{O=T(E)}catch(G){return s.reject(b,G)}O===b?s.reject(b,new TypeError("Cannot resolve promise with itself")):s.resolve(b,O)})}function k(b){var T=b&&b.then;if(b&&(typeof b=="object"||typeof b=="function")&&typeof T=="function")return function(){T.apply(b,arguments)}}function z(b,T){var E=!1;function O(U){E||(E=!0,s.reject(b,U))}function G(U){E||(E=!0,s.resolve(b,U))}var I=w(function(){T(G,O)});I.status==="error"&&O(I.value)}function w(b,T){var E={};try{E.value=b(T),E.status="success"}catch(O){E.status="error",E.value=O}return E}n.exports=f,f.prototype.catch=function(b){return this.then(null,b)},f.prototype.then=function(b,T){if(typeof b!="function"&&this.state===c||typeof T!="function"&&this.state===u)return this;var E=new this.constructor(a);return this.state!==d?g(E,this.state===c?b:T,this.outcome):this.queue.push(new h(E,b,T)),E},h.prototype.callFulfilled=function(b){s.resolve(this.promise,b)},h.prototype.otherCallFulfilled=function(b){g(this.promise,this.onFulfilled,b)},h.prototype.callRejected=function(b){s.reject(this.promise,b)},h.prototype.otherCallRejected=function(b){g(this.promise,this.onRejected,b)},s.resolve=function(b,T){var E=w(k,T);if(E.status==="error")return s.reject(b,E.value);var O=E.value;if(O)z(b,O);else{b.state=c,b.outcome=T;for(var G=-1,I=b.queue.length;++G<I;)b.queue[G].callFulfilled(T)}return b},s.reject=function(b,T){b.state=u,b.outcome=T;for(var E=-1,O=b.queue.length;++E<O;)b.queue[E].callRejected(T);return b},f.resolve=function(b){return b instanceof this?b:s.resolve(new this(a),b)},f.reject=function(b){var T=new this(a);return s.reject(T,b)},f.all=function(b){var T=this;if(Object.prototype.toString.call(b)!=="[object Array]")return this.reject(new TypeError("must be an array"));var E=b.length,O=!1;if(!E)return this.resolve([]);for(var G=new Array(E),I=0,U=-1,L=new this(a);++U<E;)j(b[U],U);return L;function j($,K){T.resolve($).then(function(Z){G[K]=Z,++I!==E||O||(O=!0,s.resolve(L,G))},function(Z){O||(O=!0,s.reject(L,Z))})}},f.race=function(b){var T=this;if(Object.prototype.toString.call(b)!=="[object Array]")return this.reject(new TypeError("must be an array"));var E=b.length,O=!1;if(!E)return this.resolve([]);for(var G,I=-1,U=new this(a);++I<E;)G=b[I],T.resolve(G).then(function(L){O||(O=!0,s.resolve(U,L))},function(L){O||(O=!0,s.reject(U,L))});return U}},{1:1}],3:[function(t,n,i){(function(o){typeof o.Promise!="function"&&(o.Promise=t(2))}).call(this,Xn!==void 0?Xn:typeof self<"u"?self:typeof window<"u"?window:{})},{2:2}],4:[function(t,n,i){var o=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(l){return typeof l}:function(l){return l&&typeof Symbol=="function"&&l.constructor===Symbol&&l!==Symbol.prototype?"symbol":typeof l},a=function(){try{if(typeof indexedDB<"u")return indexedDB;if(typeof webkitIndexedDB<"u")return webkitIndexedDB;if(typeof mozIndexedDB<"u")return mozIndexedDB;if(typeof OIndexedDB<"u")return OIndexedDB;if(typeof msIndexedDB<"u")return msIndexedDB}catch{return}}();function s(l,p){l=l||[],p=p||{};try{return new Blob(l,p)}catch(_){if(_.name!=="TypeError")throw _;for(var m=new(typeof BlobBuilder<"u"?BlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:WebKitBlobBuilder),v=0;v<l.length;v+=1)m.append(l[v]);return m.getBlob(p.type)}}typeof Promise>"u"&&t(3);var u=Promise;function c(l,p){p&&l.then(function(m){p(null,m)},function(m){p(m)})}function d(l,p,m){typeof p=="function"&&l.then(p),typeof m=="function"&&l.catch(m)}function f(l){return typeof l!="string"&&(console.warn(l+" used as a key, but it is not a string."),l=String(l)),l}function h(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var g=void 0,k={},z=Object.prototype.toString;function w(l){return typeof g=="boolean"?u.resolve(g):function(p){return new u(function(m){var v=p.transaction("local-forage-detect-blob-support","readwrite"),_=s([""]);v.objectStore("local-forage-detect-blob-support").put(_,"key"),v.onabort=function(S){S.preventDefault(),S.stopPropagation(),m(!1)},v.oncomplete=function(){var S=navigator.userAgent.match(/Chrome\/(\d+)/),C=navigator.userAgent.match(/Edge\//);m(C||!S||parseInt(S[1],10)>=43)}}).catch(function(){return!1})}(l).then(function(p){return g=p})}function b(l){var p=k[l.name],m={};m.promise=new u(function(v,_){m.resolve=v,m.reject=_}),p.deferredOperations.push(m),p.dbReady?p.dbReady=p.dbReady.then(function(){return m.promise}):p.dbReady=m.promise}function T(l){var p=k[l.name].deferredOperations.pop();if(p)return p.resolve(),p.promise}function E(l,p){var m=k[l.name].deferredOperations.pop();if(m)return m.reject(p),m.promise}function O(l,p){return new u(function(m,v){if(k[l.name]=k[l.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},l.db){if(!p)return m(l.db);b(l),l.db.close()}var _=[l.name];p&&_.push(l.version);var S=a.open.apply(a,_);p&&(S.onupgradeneeded=function(C){var R=S.result;try{R.createObjectStore(l.storeName),C.oldVersion<=1&&R.createObjectStore("local-forage-detect-blob-support")}catch(A){if(A.name!=="ConstraintError")throw A;console.warn('The database "'+l.name+'" has been upgraded from version '+C.oldVersion+" to version "+C.newVersion+', but the storage "'+l.storeName+'" already exists.')}}),S.onerror=function(C){C.preventDefault(),v(S.error)},S.onsuccess=function(){var C=S.result;C.onversionchange=function(R){R.target.close()},m(C),T(l)}})}function G(l){return O(l,!1)}function I(l){return O(l,!0)}function U(l,p){if(!l.db)return!0;var m=!l.db.objectStoreNames.contains(l.storeName),v=l.version<l.db.version,_=l.version>l.db.version;if(v&&(l.version!==p&&console.warn('The database "'+l.name+`" can't be downgraded from version `+l.db.version+" to version "+l.version+"."),l.version=l.db.version),_||m){if(m){var S=l.db.version+1;S>l.version&&(l.version=S)}return!0}return!1}function L(l){return s([function(p){for(var m=p.length,v=new ArrayBuffer(m),_=new Uint8Array(v),S=0;S<m;S++)_[S]=p.charCodeAt(S);return v}(atob(l.data))],{type:l.type})}function j(l){return l&&l.__local_forage_encoded_blob}function $(l){var p=this,m=p._initReady().then(function(){var v=k[p._dbInfo.name];if(v&&v.dbReady)return v.dbReady});return d(m,l,l),m}function K(l,p,m,v){v===void 0&&(v=1);try{var _=l.db.transaction(l.storeName,p);m(null,_)}catch(S){if(v>0&&(!l.db||S.name==="InvalidStateError"||S.name==="NotFoundError"))return u.resolve().then(function(){if(!l.db||S.name==="NotFoundError"&&!l.db.objectStoreNames.contains(l.storeName)&&l.version<=l.db.version)return l.db&&(l.version=l.db.version+1),I(l)}).then(function(){return function(C){b(C);for(var R=k[C.name],A=R.forages,D=0;D<A.length;D++){var M=A[D];M._dbInfo.db&&(M._dbInfo.db.close(),M._dbInfo.db=null)}return C.db=null,G(C).then(function(N){return C.db=N,U(C)?I(C):N}).then(function(N){C.db=R.db=N;for(var H=0;H<A.length;H++)A[H]._dbInfo.db=N}).catch(function(N){throw E(C,N),N})}(l).then(function(){K(l,p,m,v-1)})}).catch(m);m(S)}}var Z={_driver:"asyncStorage",_initStorage:function(l){var p=this,m={db:null};if(l)for(var v in l)m[v]=l[v];var _=k[m.name];_||(_={forages:[],db:null,dbReady:null,deferredOperations:[]},k[m.name]=_),_.forages.push(p),p._initReady||(p._initReady=p.ready,p.ready=$);var S=[];function C(){return u.resolve()}for(var R=0;R<_.forages.length;R++){var A=_.forages[R];A!==p&&S.push(A._initReady().catch(C))}var D=_.forages.slice(0);return u.all(S).then(function(){return m.db=_.db,G(m)}).then(function(M){return m.db=M,U(m,p._defaultConfig.version)?I(m):M}).then(function(M){m.db=_.db=M,p._dbInfo=m;for(var N=0;N<D.length;N++){var H=D[N];H!==p&&(H._dbInfo.db=m.db,H._dbInfo.version=m.version)}})},_support:function(){try{if(!a||!a.open)return!1;var l=typeof openDatabase<"u"&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),p=typeof fetch=="function"&&fetch.toString().indexOf("[native code")!==-1;return(!l||p)&&typeof indexedDB<"u"&&typeof IDBKeyRange<"u"}catch{return!1}}(),iterate:function(l,p){var m=this,v=new u(function(_,S){m.ready().then(function(){K(m._dbInfo,"readonly",function(C,R){if(C)return S(C);try{var A=R.objectStore(m._dbInfo.storeName).openCursor(),D=1;A.onsuccess=function(){var M=A.result;if(M){var N=M.value;j(N)&&(N=L(N));var H=l(N,M.key,D++);H!==void 0?_(H):M.continue()}else _()},A.onerror=function(){S(A.error)}}catch(M){S(M)}})}).catch(S)});return c(v,p),v},getItem:function(l,p){var m=this;l=f(l);var v=new u(function(_,S){m.ready().then(function(){K(m._dbInfo,"readonly",function(C,R){if(C)return S(C);try{var A=R.objectStore(m._dbInfo.storeName).get(l);A.onsuccess=function(){var D=A.result;D===void 0&&(D=null),j(D)&&(D=L(D)),_(D)},A.onerror=function(){S(A.error)}}catch(D){S(D)}})}).catch(S)});return c(v,p),v},setItem:function(l,p,m){var v=this;l=f(l);var _=new u(function(S,C){var R;v.ready().then(function(){return R=v._dbInfo,z.call(p)==="[object Blob]"?w(R.db).then(function(A){return A?p:(D=p,new u(function(M,N){var H=new FileReader;H.onerror=N,H.onloadend=function(q){var Q=btoa(q.target.result||"");M({__local_forage_encoded_blob:!0,data:Q,type:D.type})},H.readAsBinaryString(D)}));var D}):p}).then(function(A){K(v._dbInfo,"readwrite",function(D,M){if(D)return C(D);try{var N=M.objectStore(v._dbInfo.storeName);A===null&&(A=void 0);var H=N.put(A,l);M.oncomplete=function(){A===void 0&&(A=null),S(A)},M.onabort=M.onerror=function(){try{var q=H.error?H.error:H.transaction.error;C(q)}catch(Q){C(Q)}}}catch(q){C(q)}})}).catch(C)});return c(_,m),_},removeItem:function(l,p){var m=this;l=f(l);var v=new u(function(_,S){m.ready().then(function(){K(m._dbInfo,"readwrite",function(C,R){if(C)return S(C);try{var A=R.objectStore(m._dbInfo.storeName).delete(l);R.oncomplete=function(){_()},R.onerror=function(){S(A.error)},R.onabort=function(){try{var D=A.error?A.error:A.transaction.error;S(D)}catch(M){S(M)}}}catch(D){S(D)}})}).catch(S)});return c(v,p),v},clear:function(l){var p=this,m=new u(function(v,_){p.ready().then(function(){K(p._dbInfo,"readwrite",function(S,C){if(S)return _(S);try{var R=C.objectStore(p._dbInfo.storeName).clear();C.oncomplete=function(){v()},C.onabort=C.onerror=function(){try{var A=R.error?R.error:R.transaction.error;_(A)}catch(D){_(D)}}}catch(A){_(A)}})}).catch(_)});return c(m,l),m},length:function(l){var p=this,m=new u(function(v,_){p.ready().then(function(){K(p._dbInfo,"readonly",function(S,C){if(S)return _(S);try{var R=C.objectStore(p._dbInfo.storeName).count();R.onsuccess=function(){v(R.result)},R.onerror=function(){_(R.error)}}catch(A){_(A)}})}).catch(_)});return c(m,l),m},key:function(l,p){var m=this,v=new u(function(_,S){l<0?_(null):m.ready().then(function(){K(m._dbInfo,"readonly",function(C,R){if(C)return S(C);try{var A=R.objectStore(m._dbInfo.storeName),D=!1,M=(A.openKeyCursor||A.openCursor).call(A);M.onsuccess=function(){var N=M.result;N?l===0||D?_(N.key):(D=!0,N.advance(l)):_(null)},M.onerror=function(){S(M.error)}}catch(N){S(N)}})}).catch(S)});return c(v,p),v},keys:function(l){var p=this,m=new u(function(v,_){p.ready().then(function(){K(p._dbInfo,"readonly",function(S,C){if(S)return _(S);try{var R=C.objectStore(p._dbInfo.storeName),A=(R.openKeyCursor||R.openCursor).call(R),D=[];A.onsuccess=function(){var M=A.result;M?(D.push(M.key),M.continue()):v(D)},A.onerror=function(){_(A.error)}}catch(M){_(M)}})}).catch(_)});return c(m,l),m},dropInstance:function(l,p){p=h.apply(this,arguments);var m=this.config();(l=typeof l!="function"&&l||{}).name||(l.name=l.name||m.name,l.storeName=l.storeName||m.storeName);var v,_=this;if(l.name){var S=l.name===m.name&&_._dbInfo.db,C=S?u.resolve(_._dbInfo.db):G(l).then(function(R){var A=k[l.name],D=A.forages;A.db=R;for(var M=0;M<D.length;M++)D[M]._dbInfo.db=R;return R});v=l.storeName?C.then(function(R){if(R.objectStoreNames.contains(l.storeName)){var A=R.version+1;b(l);var D=k[l.name],M=D.forages;R.close();for(var N=0;N<M.length;N++){var H=M[N];H._dbInfo.db=null,H._dbInfo.version=A}return new u(function(q,Q){var ve=a.open(l.name,A);ve.onerror=function(Ze){ve.result.close(),Q(Ze)},ve.onupgradeneeded=function(){ve.result.deleteObjectStore(l.storeName)},ve.onsuccess=function(){var Ze=ve.result;Ze.close(),q(Ze)}}).then(function(q){D.db=q;for(var Q=0;Q<M.length;Q++){var ve=M[Q];ve._dbInfo.db=q,T(ve._dbInfo)}}).catch(function(q){throw(E(l,q)||u.resolve()).catch(function(){}),q})}}):C.then(function(R){b(l);var A=k[l.name],D=A.forages;R.close();for(var M=0;M<D.length;M++)D[M]._dbInfo.db=null;return new u(function(N,H){var q=a.deleteDatabase(l.name);q.onerror=function(){var Q=q.result;Q&&Q.close(),H(q.error)},q.onblocked=function(){console.warn('dropInstance blocked for database "'+l.name+'" until all open connections are closed')},q.onsuccess=function(){var Q=q.result;Q&&Q.close(),N(Q)}}).then(function(N){A.db=N;for(var H=0;H<D.length;H++)T(D[H]._dbInfo)}).catch(function(N){throw(E(l,N)||u.resolve()).catch(function(){}),N})})}else v=u.reject("Invalid arguments");return c(v,p),v}},W="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",se=/^~~local_forage_type~([^~]+)~/,oe=9,Y=oe+4,le=Object.prototype.toString;function fe(l){var p,m,v,_,S,C=.75*l.length,R=l.length,A=0;l[l.length-1]==="="&&(C--,l[l.length-2]==="="&&C--);var D=new ArrayBuffer(C),M=new Uint8Array(D);for(p=0;p<R;p+=4)m=W.indexOf(l[p]),v=W.indexOf(l[p+1]),_=W.indexOf(l[p+2]),S=W.indexOf(l[p+3]),M[A++]=m<<2|v>>4,M[A++]=(15&v)<<4|_>>2,M[A++]=(3&_)<<6|63&S;return D}function ue(l){var p,m=new Uint8Array(l),v="";for(p=0;p<m.length;p+=3)v+=W[m[p]>>2],v+=W[(3&m[p])<<4|m[p+1]>>4],v+=W[(15&m[p+1])<<2|m[p+2]>>6],v+=W[63&m[p+2]];return m.length%3==2?v=v.substring(0,v.length-1)+"=":m.length%3==1&&(v=v.substring(0,v.length-2)+"=="),v}var be={serialize:function(l,p){var m="";if(l&&(m=le.call(l)),l&&(m==="[object ArrayBuffer]"||l.buffer&&le.call(l.buffer)==="[object ArrayBuffer]")){var v,_="__lfsc__:";l instanceof ArrayBuffer?(v=l,_+="arbf"):(v=l.buffer,m==="[object Int8Array]"?_+="si08":m==="[object Uint8Array]"?_+="ui08":m==="[object Uint8ClampedArray]"?_+="uic8":m==="[object Int16Array]"?_+="si16":m==="[object Uint16Array]"?_+="ur16":m==="[object Int32Array]"?_+="si32":m==="[object Uint32Array]"?_+="ui32":m==="[object Float32Array]"?_+="fl32":m==="[object Float64Array]"?_+="fl64":p(new Error("Failed to get type for BinaryArray"))),p(_+ue(v))}else if(m==="[object Blob]"){var S=new FileReader;S.onload=function(){var C="~~local_forage_type~"+l.type+"~"+ue(this.result);p("__lfsc__:blob"+C)},S.readAsArrayBuffer(l)}else try{p(JSON.stringify(l))}catch(C){console.error("Couldn't convert value into a JSON string: ",l),p(null,C)}},deserialize:function(l){if(l.substring(0,oe)!=="__lfsc__:")return JSON.parse(l);var p,m=l.substring(Y),v=l.substring(oe,Y);if(v==="blob"&&se.test(m)){var _=m.match(se);p=_[1],m=m.substring(_[0].length)}var S=fe(m);switch(v){case"arbf":return S;case"blob":return s([S],{type:p});case"si08":return new Int8Array(S);case"ui08":return new Uint8Array(S);case"uic8":return new Uint8ClampedArray(S);case"si16":return new Int16Array(S);case"ur16":return new Uint16Array(S);case"si32":return new Int32Array(S);case"ui32":return new Uint32Array(S);case"fl32":return new Float32Array(S);case"fl64":return new Float64Array(S);default:throw new Error("Unkown type: "+v)}},stringToBuffer:fe,bufferToString:ue};function ye(l,p,m,v){l.executeSql("CREATE TABLE IF NOT EXISTS "+p.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],m,v)}function re(l,p,m,v,_,S){l.executeSql(m,v,_,function(C,R){R.code===R.SYNTAX_ERR?C.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[p.storeName],function(A,D){D.rows.length?S(A,R):ye(A,p,function(){A.executeSql(m,v,_,S)},S)},S):S(C,R)},S)}function ke(l,p,m,v){var _=this;l=f(l);var S=new u(function(C,R){_.ready().then(function(){p===void 0&&(p=null);var A=p,D=_._dbInfo;D.serializer.serialize(p,function(M,N){N?R(N):D.db.transaction(function(H){re(H,D,"INSERT OR REPLACE INTO "+D.storeName+" (key, value) VALUES (?, ?)",[l,M],function(){C(A)},function(q,Q){R(Q)})},function(H){if(H.code===H.QUOTA_ERR){if(v>0)return void C(ke.apply(_,[l,A,m,v-1]));R(H)}})})}).catch(R)});return c(S,m),S}function de(l){return new u(function(p,m){l.transaction(function(v){v.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",[],function(_,S){for(var C=[],R=0;R<S.rows.length;R++)C.push(S.rows.item(R).name);p({db:l,storeNames:C})},function(_,S){m(S)})},function(v){m(v)})})}var _e={_driver:"webSQLStorage",_initStorage:function(l){var p=this,m={db:null};if(l)for(var v in l)m[v]=typeof l[v]!="string"?l[v].toString():l[v];var _=new u(function(S,C){try{m.db=openDatabase(m.name,String(m.version),m.description,m.size)}catch(R){return C(R)}m.db.transaction(function(R){ye(R,m,function(){p._dbInfo=m,S()},function(A,D){C(D)})},C)});return m.serializer=be,_},_support:typeof openDatabase=="function",iterate:function(l,p){var m=this,v=new u(function(_,S){m.ready().then(function(){var C=m._dbInfo;C.db.transaction(function(R){re(R,C,"SELECT * FROM "+C.storeName,[],function(A,D){for(var M=D.rows,N=M.length,H=0;H<N;H++){var q=M.item(H),Q=q.value;if(Q&&(Q=C.serializer.deserialize(Q)),(Q=l(Q,q.key,H+1))!==void 0)return void _(Q)}_()},function(A,D){S(D)})})}).catch(S)});return c(v,p),v},getItem:function(l,p){var m=this;l=f(l);var v=new u(function(_,S){m.ready().then(function(){var C=m._dbInfo;C.db.transaction(function(R){re(R,C,"SELECT * FROM "+C.storeName+" WHERE key = ? LIMIT 1",[l],function(A,D){var M=D.rows.length?D.rows.item(0).value:null;M&&(M=C.serializer.deserialize(M)),_(M)},function(A,D){S(D)})})}).catch(S)});return c(v,p),v},setItem:function(l,p,m){return ke.apply(this,[l,p,m,1])},removeItem:function(l,p){var m=this;l=f(l);var v=new u(function(_,S){m.ready().then(function(){var C=m._dbInfo;C.db.transaction(function(R){re(R,C,"DELETE FROM "+C.storeName+" WHERE key = ?",[l],function(){_()},function(A,D){S(D)})})}).catch(S)});return c(v,p),v},clear:function(l){var p=this,m=new u(function(v,_){p.ready().then(function(){var S=p._dbInfo;S.db.transaction(function(C){re(C,S,"DELETE FROM "+S.storeName,[],function(){v()},function(R,A){_(A)})})}).catch(_)});return c(m,l),m},length:function(l){var p=this,m=new u(function(v,_){p.ready().then(function(){var S=p._dbInfo;S.db.transaction(function(C){re(C,S,"SELECT COUNT(key) as c FROM "+S.storeName,[],function(R,A){var D=A.rows.item(0).c;v(D)},function(R,A){_(A)})})}).catch(_)});return c(m,l),m},key:function(l,p){var m=this,v=new u(function(_,S){m.ready().then(function(){var C=m._dbInfo;C.db.transaction(function(R){re(R,C,"SELECT key FROM "+C.storeName+" WHERE id = ? LIMIT 1",[l+1],function(A,D){var M=D.rows.length?D.rows.item(0).key:null;_(M)},function(A,D){S(D)})})}).catch(S)});return c(v,p),v},keys:function(l){var p=this,m=new u(function(v,_){p.ready().then(function(){var S=p._dbInfo;S.db.transaction(function(C){re(C,S,"SELECT key FROM "+S.storeName,[],function(R,A){for(var D=[],M=0;M<A.rows.length;M++)D.push(A.rows.item(M).key);v(D)},function(R,A){_(A)})})}).catch(_)});return c(m,l),m},dropInstance:function(l,p){p=h.apply(this,arguments);var m=this.config();(l=typeof l!="function"&&l||{}).name||(l.name=l.name||m.name,l.storeName=l.storeName||m.storeName);var v,_=this;return c(v=l.name?new u(function(S){var C;C=l.name===m.name?_._dbInfo.db:openDatabase(l.name,"","",0),l.storeName?S({db:C,storeNames:[l.storeName]}):S(de(C))}).then(function(S){return new u(function(C,R){S.db.transaction(function(A){function D(q){return new u(function(Q,ve){A.executeSql("DROP TABLE IF EXISTS "+q,[],function(){Q()},function(Ze,ar){ve(ar)})})}for(var M=[],N=0,H=S.storeNames.length;N<H;N++)M.push(D(S.storeNames[N]));u.all(M).then(function(){C()}).catch(function(q){R(q)})},function(A){R(A)})})}):u.reject("Invalid arguments"),p),v}};function De(l,p){var m=l.name+"/";return l.storeName!==p.storeName&&(m+=l.storeName+"/"),m}function Ht(){return!function(){try{return localStorage.setItem("_localforage_support_test",!0),localStorage.removeItem("_localforage_support_test"),!1}catch{return!0}}()||localStorage.length>0}var Ue={_driver:"localStorageWrapper",_initStorage:function(l){var p={};if(l)for(var m in l)p[m]=l[m];return p.keyPrefix=De(l,this._defaultConfig),Ht()?(this._dbInfo=p,p.serializer=be,u.resolve()):u.reject()},_support:function(){try{return typeof localStorage<"u"&&"setItem"in localStorage&&!!localStorage.setItem}catch{return!1}}(),iterate:function(l,p){var m=this,v=m.ready().then(function(){for(var _=m._dbInfo,S=_.keyPrefix,C=S.length,R=localStorage.length,A=1,D=0;D<R;D++){var M=localStorage.key(D);if(M.indexOf(S)===0){var N=localStorage.getItem(M);if(N&&(N=_.serializer.deserialize(N)),(N=l(N,M.substring(C),A++))!==void 0)return N}}});return c(v,p),v},getItem:function(l,p){var m=this;l=f(l);var v=m.ready().then(function(){var _=m._dbInfo,S=localStorage.getItem(_.keyPrefix+l);return S&&(S=_.serializer.deserialize(S)),S});return c(v,p),v},setItem:function(l,p,m){var v=this;l=f(l);var _=v.ready().then(function(){p===void 0&&(p=null);var S=p;return new u(function(C,R){var A=v._dbInfo;A.serializer.serialize(p,function(D,M){if(M)R(M);else try{localStorage.setItem(A.keyPrefix+l,D),C(S)}catch(N){N.name!=="QuotaExceededError"&&N.name!=="NS_ERROR_DOM_QUOTA_REACHED"||R(N),R(N)}})})});return c(_,m),_},removeItem:function(l,p){var m=this;l=f(l);var v=m.ready().then(function(){var _=m._dbInfo;localStorage.removeItem(_.keyPrefix+l)});return c(v,p),v},clear:function(l){var p=this,m=p.ready().then(function(){for(var v=p._dbInfo.keyPrefix,_=localStorage.length-1;_>=0;_--){var S=localStorage.key(_);S.indexOf(v)===0&&localStorage.removeItem(S)}});return c(m,l),m},length:function(l){var p=this.keys().then(function(m){return m.length});return c(p,l),p},key:function(l,p){var m=this,v=m.ready().then(function(){var _,S=m._dbInfo;try{_=localStorage.key(l)}catch{_=null}return _&&(_=_.substring(S.keyPrefix.length)),_});return c(v,p),v},keys:function(l){var p=this,m=p.ready().then(function(){for(var v=p._dbInfo,_=localStorage.length,S=[],C=0;C<_;C++){var R=localStorage.key(C);R.indexOf(v.keyPrefix)===0&&S.push(R.substring(v.keyPrefix.length))}return S});return c(m,l),m},dropInstance:function(l,p){if(p=h.apply(this,arguments),!(l=typeof l!="function"&&l||{}).name){var m=this.config();l.name=l.name||m.name,l.storeName=l.storeName||m.storeName}var v,_=this;return c(v=l.name?new u(function(S){l.storeName?S(De(l,_._defaultConfig)):S(l.name+"/")}).then(function(S){for(var C=localStorage.length-1;C>=0;C--){var R=localStorage.key(C);R.indexOf(S)===0&&localStorage.removeItem(R)}}):u.reject("Invalid arguments"),p),v}},$t=function(l,p){return l===p||typeof l=="number"&&typeof p=="number"&&isNaN(l)&&isNaN(p)},Dt=function(l,p){for(var m=l.length,v=0;v<m;){if($t(l[v],p))return!0;v++}return!1},Xe=Array.isArray||function(l){return Object.prototype.toString.call(l)==="[object Array]"},Te={},Ie={},Ge={INDEXEDDB:Z,WEBSQL:_e,LOCALSTORAGE:Ue},Ne=[Ge.INDEXEDDB._driver,Ge.WEBSQL._driver,Ge.LOCALSTORAGE._driver],Be=["dropInstance"],nt=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(Be),It={description:"",driver:Ne.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function ct(l,p){l[p]=function(){var m=arguments;return l.ready().then(function(){return l[p].apply(l,m)})}}function ut(){for(var l=1;l<arguments.length;l++){var p=arguments[l];if(p)for(var m in p)p.hasOwnProperty(m)&&(Xe(p[m])?arguments[0][m]=p[m].slice():arguments[0][m]=p[m])}return arguments[0]}var y=new(function(){function l(p){for(var m in function(S,C){if(!(S instanceof C))throw new TypeError("Cannot call a class as a function")}(this,l),Ge)if(Ge.hasOwnProperty(m)){var v=Ge[m],_=v._driver;this[m]=_,Te[_]||this.defineDriver(v)}this._defaultConfig=ut({},It),this._config=ut({},this._defaultConfig,p),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch(function(){})}return l.prototype.config=function(p){if((p===void 0?"undefined":o(p))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var m in p){if(m==="storeName"&&(p[m]=p[m].replace(/\W/g,"_")),m==="version"&&typeof p[m]!="number")return new Error("Database version must be a number.");this._config[m]=p[m]}return!("driver"in p)||!p.driver||this.setDriver(this._config.driver)}return typeof p=="string"?this._config[p]:this._config},l.prototype.defineDriver=function(p,m,v){var _=new u(function(S,C){try{var R=p._driver,A=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!p._driver)return void C(A);for(var D=nt.concat("_initStorage"),M=0,N=D.length;M<N;M++){var H=D[M];if((!Dt(Be,H)||p[H])&&typeof p[H]!="function")return void C(A)}(function(){for(var Q=function(ds){return function(){var ii=new Error("Method "+ds+" is not implemented by the current driver"),wd=u.reject(ii);return c(wd,arguments[arguments.length-1]),wd}},ve=0,Ze=Be.length;ve<Ze;ve++){var ar=Be[ve];p[ar]||(p[ar]=Q(ar))}})();var q=function(Q){Te[R]&&console.info("Redefining LocalForage driver: "+R),Te[R]=p,Ie[R]=Q,S()};"_support"in p?p._support&&typeof p._support=="function"?p._support().then(q,C):q(!!p._support):q(!0)}catch(Q){C(Q)}});return d(_,m,v),_},l.prototype.driver=function(){return this._driver||null},l.prototype.getDriver=function(p,m,v){var _=Te[p]?u.resolve(Te[p]):u.reject(new Error("Driver not found."));return d(_,m,v),_},l.prototype.getSerializer=function(p){var m=u.resolve(be);return d(m,p),m},l.prototype.ready=function(p){var m=this,v=m._driverSet.then(function(){return m._ready===null&&(m._ready=m._initDriver()),m._ready});return d(v,p,p),v},l.prototype.setDriver=function(p,m,v){var _=this;Xe(p)||(p=[p]);var S=this._getSupportedDrivers(p);function C(){_._config.driver=_.driver()}function R(D){return _._extend(D),C(),_._ready=_._initStorage(_._config),_._ready}var A=this._driverSet!==null?this._driverSet.catch(function(){return u.resolve()}):u.resolve();return this._driverSet=A.then(function(){var D=S[0];return _._dbInfo=null,_._ready=null,_.getDriver(D).then(function(M){_._driver=M._driver,C(),_._wrapLibraryMethodsWithReady(),_._initDriver=function(N){return function(){var H=0;return function q(){for(;H<N.length;){var Q=N[H];return H++,_._dbInfo=null,_._ready=null,_.getDriver(Q).then(R).catch(q)}C();var ve=new Error("No available storage method found.");return _._driverSet=u.reject(ve),_._driverSet}()}}(S)})}).catch(function(){C();var D=new Error("No available storage method found.");return _._driverSet=u.reject(D),_._driverSet}),d(this._driverSet,m,v),this._driverSet},l.prototype.supports=function(p){return!!Ie[p]},l.prototype._extend=function(p){ut(this,p)},l.prototype._getSupportedDrivers=function(p){for(var m=[],v=0,_=p.length;v<_;v++){var S=p[v];this.supports(S)&&m.push(S)}return m},l.prototype._wrapLibraryMethodsWithReady=function(){for(var p=0,m=nt.length;p<m;p++)ct(this,nt[p])},l.prototype.createInstance=function(p){return new l(p)},l}());n.exports=y},{3:3}]},{},[4])(4)}),Xv=function(){function r(){this.cache={}}return r.prototype.setItem=function(e,t){this.cache[e]=t},r.prototype.getItem=function(e){return this.cache[e]},r.prototype.removeItem=function(e){this.cache[e]=void 0},r}(),Zv=function(){function r(){this.support=this.isSupportLS()}return r.prototype.isSupportLS=function(){try{return localStorage.setItem("_applogtest-test-key","hi"),localStorage.getItem("_applogtest-test-key"),localStorage.removeItem("_applogtest-test-key"),!0}catch{return!1}},r.prototype.getItem=function(e){try{var t=localStorage.getItem(e),n=t;try{t&&typeof t=="string"&&(n=JSON.parse(t))}catch{}return n||{}}catch{}return{}},r.prototype.setItem=function(e,t){try{var n=typeof t=="string"?t:JSON.stringify(t);localStorage.setItem(e,n)}catch{}},r.prototype.removeItem=function(e){try{localStorage.removeItem(e)}catch{}},r}(),Yv=function(){function r(){this.support=this.isSupportSession()}return r.prototype.isSupportSession=function(){try{return sessionStorage.setItem("_applogtest-test-key","hi"),sessionStorage.getItem("_applogtest-test-key"),sessionStorage.removeItem("_applogtest-test-key"),!0}catch{return!1}},r.prototype.getItem=function(e){try{var t=sessionStorage.getItem(e),n=t;try{t&&typeof t=="string"&&(n=JSON.parse(t))}catch{}return n||{}}catch{}return{}},r.prototype.setItem=function(e,t){try{var n=typeof t=="string"?t:JSON.stringify(t);sessionStorage.setItem(e,n)}catch{}},r.prototype.removeItem=function(e){try{sessionStorage.removeItem(e)}catch{}},r}(),Qv=function(){function r(e,t){return this.dbStorage=Oo.createInstance({driver:[Oo.INDEXEDDB,Oo.LOCALSTORAGE],name:e,storeName:t}),this.dbStorage}return r.prototype.getItem=function(e){return Ao(this,void 0,void 0,function(){var t,n;return Do(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.dbStorage.getItem(e)];case 1:t=i.sent(),n=t;try{t&&typeof t=="string"&&(n=JSON.parse(t))}catch{}return[2,n||void 0];case 2:return i.sent(),console.warn("db get storage error"),[3,3];case 3:return[2,void 0]}})})},r.prototype.setItem=function(e,t){try{this.dbStorage.setItem(e,t)}catch{console.warn("db set storage error")}},r.prototype.removeItem=function(e){try{this.dbStorage.removeItem(e)}catch{console.warn("db remove storage error")}},r}(),au=function(){function r(){this.defaultExpireTime=6048e5,this.local=new Zv,this.session=new Yv,this.cache=new Xv}return r.prototype.getLocalItem=function(e){return this.local.getItem(e)},r.prototype.setLocalItem=function(e,t){this.local.setItem(e,t)},r.prototype.removeLocalItem=function(e){this.local.removeItem(e)},r.prototype.getSessionItem=function(e){return this.session.getItem(e)},r.prototype.setSessionItem=function(e,t){this.session.setItem(e,t)},r.prototype.removeSessionItem=function(e){this.session.removeItem(e)},r.prototype.getCacheItem=function(e){return this.cache.getItem(e)},r.prototype.setCacheItem=function(e,t){this.cache.setItem(e,t)},r.prototype.removeCacheItem=function(e){this.cache.removeItem(e)},r.prototype.getCookie=function(e,t){try{return fn.get(e)}catch{return""}},r.prototype.setCookie=function(e,t,n,i){n===void 0&&(n=this.defaultExpireTime);try{var o=i||document.domain,a=+new Date+n;fn.set(e,t,{expires:new Date(a),path:"/",domain:o})}catch{}},r.prototype.removeCookie=function(e,t){try{fn.remove(e,{path:"/",domain:t||""})}catch{}},r}(),ey=function(){function r(e,t,n){this.appid=e,this.domain=t,this.userAgent=window.navigator.userAgent,this.appVersion=window.navigator.appVersion,this.cookie_expire=n}return r.prototype.init=function(){var e,t=window.navigator.userAgent,n=window.navigator.language,i=document.referrer,o=i?ou(i).hostname:"",a=xo(window.location.href),s=/Mobile|htc|mini|Android|iP(ad|od|hone)/.test(this.appVersion)?"wap":"web",u=((e=window.navigator.connection)===null||e===void 0?void 0:e.effectiveType)||"";this.utm=function(f,h,g,k){var z=new au,w=f?"_tea_utm_cache_"+f:"_tea_utm_cache",b=f?"_$utm_from_url_"+f:"_$utm_from_url",T={},E=["tr_shareuser","tr_admaster","tr_param1","tr_param2","tr_param3","tr_param4","$utm_from_url"],O={ad_id:Number(h.ad_id)||void 0,campaign_id:Number(h.campaign_id)||void 0,creative_id:Number(h.creative_id)||void 0,utm_source:h.utm_source,utm_medium:h.utm_medium,utm_campaign:h.utm_campaign,utm_term:h.utm_term,utm_content:h.utm_content,tr_shareuser:h.tr_shareuser,tr_admaster:h.tr_admaster,tr_param1:h.tr_param1,tr_param2:h.tr_param2,tr_param3:h.tr_param3,tr_param4:h.tr_param4};try{var G=!1;for(var I in O)O[I]&&(E.indexOf(I)!==-1?(T.hasOwnProperty("tracer_data")||(T.tracer_data={}),T.tracer_data[I]=O[I]):T[I]=O[I],G=!0);if(G)z.setSessionItem(b,"1"),z.setCookie(w,JSON.stringify(T),k,g);else{var U=z.getCookie(w,g);U&&(T=JSON.parse(U))}z.getSessionItem(b)==1&&(T.hasOwnProperty("tracer_data")||(T.tracer_data={}),T.tracer_data.$utm_from_url=1)}catch{return O}return T}(this.appid,a,this.domain,this.cookie_expire);var c=this.browser(),d=this.os();return{browser:c.browser,browser_version:c.browser_version,platform:s,os_name:d.os_name,os_version:d.os_version,userAgent:t,screen_width:window.screen&&window.screen.width,screen_height:window.screen&&window.screen.height,device_model:this.getDeviceModel(d.os_name),language:n,referrer:i,referrer_host:o,network_type:u,utm:this.utm,latest_data:this.last(i,o)}},r.prototype.last=function(e,t){var n="",i="",o="",a=location.hostname,s=!1;if(e&&t&&a!==t){n=e,i=t,s=!0;var u=xo(e);u.keyword&&(o=u.keyword)}return{$latest_referrer:n,$latest_referrer_host:i,$latest_search_keyword:o,isLast:s}},r.prototype.browser=function(){var e,t,n="",i=""+parseFloat(this.appVersion),o=this.userAgent;return o.indexOf("Edge")!==-1||o.indexOf("Edg")!==-1?(n="Microsoft Edge",o.indexOf("Edge")!==-1?(e=o.indexOf("Edge"),i=o.substring(e+5)):(e=o.indexOf("Edg"),i=o.substring(e+4))):(e=o.indexOf("MSIE"))!==-1?(n="Microsoft Internet Explorer",i=o.substring(e+5)):(e=o.indexOf("Lark"))!==-1?(n="Lark",i=o.substring(e+5,e+11)):o.indexOf("Chrome")!==-1?(e=o.indexOf("TTWebView"))!==-1?(n="TTWebView",i=o.substring(e+10,e+23)):((e=o.indexOf("Chrome"))!==-1||(e=o.indexOf("Chrome"))!==-1)&&(n="Chrome",i=o.substring(e+7)):o.indexOf("Safari")!==-1?(e=o.indexOf("Safari"))!==-1&&(n="Safari",i=o.substring(e+7),(e=o.indexOf("Version"))!==-1&&(i=o.substring(e+8))):(e=o.indexOf("Firefox"))!==-1&&(n="Firefox",i=o.substring(e+8)),(t=i.indexOf(";"))!==-1&&(i=i.substring(0,t)),(t=i.indexOf(" "))!==-1&&(i=i.substring(0,t)),(t=i.indexOf(")"))!==-1&&(i=i.substring(0,t)),{browser:n,browser_version:i}},r.prototype.os=function(){for(var e="",t="",n=[{s:"Windows 10",r:/(Windows 10.0|Windows NT 10.0|Windows NT 10.1)/},{s:"Windows 8.1",r:/(Windows 8.1|Windows NT 6.3)/},{s:"Windows 8",r:/(Windows 8|Windows NT 6.2)/},{s:"Windows 7",r:/(Windows 7|Windows NT 6.1)/},{s:"Android",r:/Android/},{s:"iOS",r:/(iPhone|iPad|iPod)/},{s:"Mac OS X",r:/Mac OS X/},{s:"Mac OS",r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{s:"ChromeOS",r:/CrOS/},{s:"Linux",r:/(Linux|X11)/},{s:"Sun OS",r:/SunOS/}],i=0;i<n.length;i++){var o=n[i];if(o.r.test(this.userAgent)){(e=o.s)==="Mac OS X"&&this.isNewIpad()&&(e="iOS");break}}var a=function(f,h){var g=f.exec(h);return g&&g[1]?g[1]:""},s=function(f,h){var g=RegExp("(?:^|[^A-Z0-9-_]|[^A-Z0-9-]_|sprd-)(?:"+f+")","i").exec(h);return g?g.slice(1)[0]:""};/Windows/.test(e)&&(t=a(/Windows (.*)/,e),e="windows");var u,c;switch(e){case"Mac OS X":t=s("Mac[ +]OS[ +]X(?:[ /](?:Version )?(\\d+(?:[_\\.]\\d+)+))?",this.userAgent),e="mac";break;case"Android":u=this.userAgent,(c=a(/Android ([\.\_\d]+)/,u))||(c=a(/Android\/([\.\_\d]+)/,u)),t=c,e="android";break;case"iOS":t=this.isNewIpad()?s("Mac[ +]OS[ +]X(?:[ /](?:Version )?(\\d+(?:[_\\.]\\d+)+))?",this.userAgent):(t=/OS (\d+)_(\d+)_?(\d+)?/.exec(this.appVersion))?t[1]+"."+t[2]+"."+(0|t[3]):"",e="ios";break;case"chromeOS":var d=this.userAgent.indexOf("x86_64");t=this.userAgent.substring(d+7,d+16)}return{os_name:e,os_version:t}},r.prototype.getDeviceModel=function(e){var t="";try{if(e==="android")navigator.userAgent.split(";").forEach(function(o){o.indexOf("Build/")>-1&&(t=o.slice(0,o.indexOf("Build/")))});else if(e==="ios"||e==="mac"||e==="windows")if(this.isNewIpad())t="iPad";else{var n=navigator.userAgent.replace("Mozilla/5.0 (",""),i=n.indexOf(";");t=n.slice(0,i)}}catch{return t.trim()}return t.trim()},r.prototype.isNewIpad=function(){return this.userAgent!==void 0&&navigator.platform==="MacIntel"&&typeof navigator.maxTouchPoints=="number"&&navigator.maxTouchPoints>1},r}(),Po=function(r,e){try{return fn.get(r)}catch{return""}},Lo=function(r,e,t,n){try{var i=n||document.domain,o=+new Date+(t||6048e5);fn.set(r,e,{expires:new Date(o),path:"/",domain:i})}catch{}},ty=function(){function r(){this.cache={}}return r.prototype.setItem=function(e,t){this.cache[e]=t},r.prototype.getItem=function(e){return this.cache[e]},r.prototype.removeItem=function(e){this.cache[e]=void 0},r.prototype.getCookie=function(e,t){return Po(e)},r.prototype.setCookie=function(e,t,n,i){Lo(e,t,n,i)},r}(),Uo,P,cu={getItem:function(r){try{var e=localStorage.getItem(r),t=e;try{e&&typeof e=="string"&&(t=JSON.parse(e))}catch{}return t||{}}catch{}return{}},setItem:function(r,e){try{var t=typeof e=="string"?e:JSON.stringify(e);localStorage.setItem(r,t)}catch{}},removeItem:function(r){try{localStorage.removeItem(r)}catch{}},getCookie:function(r,e){return Po(r)},setCookie:function(r,e,t,n){Lo(r,e,t,n)},isSupportLS:function(){try{return localStorage.setItem("_ranger-test-key","hi"),localStorage.getItem("_ranger-test-key"),localStorage.removeItem("_ranger-test-key"),!0}catch{return!1}}()},ry={getItem:function(r){try{var e=sessionStorage.getItem(r),t=e;try{e&&typeof e=="string"&&(t=JSON.parse(e))}catch{}return t||{}}catch{}return{}},setItem:function(r,e){try{var t=typeof e=="string"?e:JSON.stringify(e);sessionStorage.setItem(r,t)}catch{}},removeItem:function(r){try{sessionStorage.removeItem(r)}catch{}},getCookie:function(r,e){return Po(r)},setCookie:function(r,e,t,n){Lo(r,e,t,n)},isSupportSession:function(){try{return sessionStorage.setItem("_ranger-test-key","hi"),sessionStorage.getItem("_ranger-test-key"),sessionStorage.removeItem("_ranger-test-key"),!0}catch{return!1}}()},Er=function(){function r(e,t){this._storage=t&&t==="session"?ry:!e&&cu.isSupportLS?cu:new ty}return r.prototype.getItem=function(e){return this._storage.getItem(e)},r.prototype.setItem=function(e,t){this._storage.setItem(e,t)},r.prototype.getCookie=function(e,t){return this._storage.getCookie(e,t)},r.prototype.setCookie=function(e,t,n,i){this._storage.setCookie(e,t,n,i)},r.prototype.removeItem=function(e){this._storage.removeItem(e)},r}(),Go={sg_central:"1fz22z22z1nz21z4mz4bz4bz21z1ez18z1jz1gz49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",us_east:"1fz22z22z1nz21z4mz4bz4bz1kz18z1jz1gz24z18z49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",sg_central_tt:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z21z1ez4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",us_east_tt:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",us_ttp:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz24z4az23z21",us_ttp_w:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz25z4az23z21",us_ttp2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z22z22z1nz4ez4az23z21z4az22z1gz1iz22z1mz1iz4az1az1mz1k",eu_ttp_gcp:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z49z23z21z1cz18z21z22z4ez18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",eu_central:"1fz22z22z1nz21z4mz4bz4bz18z25z21z1dz20z49z1kz1az21z4az19z27z22z1cz1gz1lz22z1jz18z1nz1gz4az1az1mz1k",eu_ttp_ie2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z1gz1cz4ez4az22z1gz1iz22z1mz1iz25z4az1cz23",eu_ttp2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4dz4iz49z1lz1mz20z1kz18z1jz49z1lz1mz4dz18z4az22z1gz1iz22z1mz1iz25z4az1cz23"},uu=function(){return new Set(Object.keys(Go))},No=function(){return Object.keys(Go)},du={sg:"1fz22z22z1nz21z4mz4bz4bz21z1ez18z1jz1gz49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz18z1jz1gz24z18z49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",my:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z19z1bz49z1kz27z4az1jz18z20z1iz1mz1dz1dz1gz1az1cz4az1az1mz1k"},ny={va:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",in:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k"},iy={sg:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z21z1ez4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",in:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z49z23z21z1cz18z21z22z4ez18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",ie2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z1gz1cz4ez4az22z1gz1iz22z1mz1iz25z4az1cz23"},oy={sg:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz25z4az23z21",va:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz24z4az23z21",ie2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z1gz1cz4ez4az22z1gz1iz22z1mz1iz25z4az1cz23"};["1fz22z22z1nz21z4mz4bz4bz1bz18z22z18z4az19z27z22z1cz1bz18z1lz1az1cz4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z1cz23z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z23z21z22z21z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z21z1ez4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z49z24z18z4az19z27z22z1cz1bz18z1lz1az1cz4az1lz1cz22"].map(function(r){return Jn(r)}),function(r){r.Init="init",r.Config="config",r.Start="start",r.Ready="ready",r.TokenComplete="token-complete",r.TokenStorage="token-storage",r.TokenFetch="token-fetch",r.TokenError="token-error",r.ConfigUuid="config-uuid",r.ConfigWebId="config-webid",r.ConfigDiD="config-deviceid",r.ConfigDomain="config-domain",r.CustomWebId="custom-webid",r.TokenChange="token-change",r.TokenReset="token-reset",r.ConfigTransform="config-transform",r.EnvTransform="env-transform",r.SessionReset="session-reset",r.SessionResetTime="session-reset-time",r.SessionResetInner="session-reset-inner",r.Event="event",r.Events="events",r.EventNow="event-now",r.CleanEvents="clean-events",r.BeconEvent="becon-event",r.SubmitBefore="submit-before",r.SubmitScuess="submit-scuess",r.SubmitSuccess="submit-success",r.SubmitAfter="submit-after",r.SubmitError="submit-error",r.SubmitVerify="submit-verify",r.DestoryInstance="destory-instance",r.CustomHeader="custom-request-header",r.LogSettingReady="log-setting-ready",r.Stay="stay",r.ResetStay="reset-stay",r.StayReady="stay-ready",r.SetStay="set-stay",r.RouteChange="route-change",r.RouteReady="route-ready",r.Ab="ab",r.AbVar="ab-var",r.AbAllVars="ab-all-vars",r.AbConfig="ab-config",r.AbExternalVersion="ab-external-version",r.AbVersionChangeOn="ab-version-change-on",r.AbVersionChangeOff="ab-version-change-off",r.AbOpenLayer="ab-open-layer",r.AbCloseLayer="ab-close-layer",r.AbReady="ab-ready",r.AbComplete="ab-complete",r.AbTimeout="ab-timeout",r.AbVerify="ab-verify",r.Profile="profile",r.ProfileSet="profile-set",r.ProfileSetOnce="profile-set-once",r.ProfileUnset="profile-unset",r.ProfileIncrement="profile-increment",r.ProfileAppend="profile-append",r.ProfileClear="profile-clear",r.Autotrack="autotrack",r.AutotrackReady="autotrack-ready",r.CepReady="cep-ready",r.TracerReady="tracer-ready",r.sessionRecord="session-record",r.SessionRecordStart="session-record-start",r.SessionRecordPause="session-record-pause",r.SessionRecordEnd="session-record-end",r.SessionRecordReport="session-record-report",r.TrackEventDuration="track-event-duration",r.TrackEventDurationStart="track-event-duration-start",r.TrackEventDurationEnd="track-event-duration-end",r.TrackEventDurationPause="track-event-duration-pause",r.TrackEventDurationResume="tracl-event-duration-resume",r.VisualCollectReady="visual-collect-ready",r.VisualApiReady="visual-api-ready",r.VisualApiUpdate="visual-api-update"}(Uo||(Uo={})),function(r){r.DEBUGGER_MESSAGE="debugger-message",r.DEBUGGER_MESSAGE_SDK="debugger-message-sdk",r.DEBUGGER_MESSAGE_FETCH="debugger-message-fetch",r.DEBUGGER_MESSAGE_FETCH_RESULT="debugger-message-fetch-result",r.DEBUGGER_MESSAGE_EVENT="debugger-message-event",r.DEVTOOL_WEB_READY="devtool-web-ready"}(P||(P={}));var B=Uo,ie=void 0,lu=new Date().getTimezoneOffset(),sy=parseInt(""+-lu/60,10),ay=60*lu,cy=function(){function r(e,t){var n=this;this.is_first_time=!0,this.configPersist=!1,this.enableClientTransport=!1,this.initConfig=t,this.collect=e;var i=new ey(t.app_id,t.cookie_domain||"",t.cookie_expire||6048e5).init(),o="__tea_cache_first_"+t.app_id;this.configKey="__tea_cache_config_"+t.app_id,this.sessionStorage=new Er(!1,"session"),this.localStorage=new Er(!1,"local"),this.channelUrl=this.getChannelForUrl(),this.current_env="row",t.configPersist&&(this.configPersist=!0,this.storage=t.configPersist===1?this.sessionStorage:this.localStorage);var a=this.localStorage.getItem(o);a&&a==1?this.is_first_time=!1:(this.is_first_time=!0,this.localStorage.setItem(o,"1")),this.envInfo={user:{user_unique_id:ie,user_type:ie,user_id:ie,user_is_auth:ie,user_is_login:ie,device_id:ie,web_id:ie,ip_addr_id:ie,user_unique_id_type:ie},header:{app_id:ie,app_name:ie,app_install_id:ie,install_id:ie,app_package:ie,app_channel:ie,app_version:ie,ab_version:ie,os_name:i.os_name,os_version:i.os_version,device_model:i.device_model,ab_client:ie,traffic_type:ie,network_type:i.network_type,client_ip:ie,device_brand:ie,os_api:ie,access:ie,language:i.language,region:ie,app_language:ie,app_region:ie,creative_id:i.utm.creative_id,ad_id:i.utm.ad_id,campaign_id:i.utm.campaign_id,log_type:ie,rnd:ie,platform:i.platform,sdk_version:"5.3.14_oversea",sdk_lib:"js",province:ie,city:ie,timezone:sy,tz_offset:ay,tz_name:ie,sim_region:ie,carrier:ie,resolution:i.screen_width+"x"+i.screen_height,browser:i.browser,browser_version:i.browser_version,referrer:i.referrer,referrer_host:i.referrer_host,width:i.screen_width,height:i.screen_height,screen_width:i.screen_width,screen_height:i.screen_height,utm_term:i.utm.utm_term,utm_content:i.utm.utm_content,utm_source:i.utm.utm_source,utm_medium:i.utm.utm_medium,utm_campaign:i.utm.utm_campaign,tracer_data:JSON.stringify(i.utm.tracer_data),custom:i.network_type?{network_type:i.network_type}:{}}},this.ab_version="",this.ab_uuid_cache={},this.evtParams={},this.reportErrorCallback=function(){},this.isLast=!1,this.setCustom(i),this.initDomain(),this.initABData(),this.collect.on("route-change",function(s){n.changeReferInfo(s.config)}),this.setEnableClientTransport(!!this.initConfig.transport)}return r.prototype.initDomain=function(e){var t=this.initConfig.channel_domain;if(t)return this.domain=t,void this.setCurrentEnv(this.domain);var n=e||this.initConfig.report_channel||this.initConfig.channel,i=this.getChannelDomain(n);i||(console.warn("current channel: "+n+" is not exist, use va instead, please check!!!!"),i=du.sg),this.domain=Jn(i),this.setCurrentEnv(this.domain)},r.prototype.setDomain=function(e){this.customDomain=!0,this.domain=e,this.setCurrentEnv(this.domain)},r.prototype.getDomain=function(e){return this.customDomain||e&&this.initDomain(e),this.domain},r.prototype.getChannelDomain=function(e){var t,n,i=e||this.initConfig.report_channel||this.initConfig.channel;return uu().has(i)?Go[i]:((t=this.initConfig)===null||t===void 0?void 0:t.channel_type)==="tcpy"?iy[i]:((n=this.initConfig)===null||n===void 0?void 0:n.channel_type)==="ttp"?oy[i]:du[i]},r.prototype.getChannelForUrl=function(){return this.initConfig.channel_type?{WEBID_URL:"/v1/user/webid",TOB_URL:"",REPORT_URL:"/v1/list"}:this.initConfig.report_channel?["sg_central","us_east"].indexOf(this.initConfig.report_channel)!==-1?{WEBID_URL:"/webid",TOB_URL:"/tobid",REPORT_URL:"/list"}:{WEBID_URL:"/v1/user/webid",TOB_URL:"",REPORT_URL:"/v1/list"}:{WEBID_URL:"/webid",TOB_URL:"/tobid",REPORT_URL:"/list"}},r.prototype.setCurrentEnv=function(e){this.getDomain().includes("byteoversea")?this.current_env="row":this.current_env="other"},r.prototype.getCurrentEnv=function(){return this.current_env},r.prototype.initABData=function(){var e,t="__tea_sdk_ab_version_"+this.initConfig.app_id;e=this.localStorage.getItem(t),this.setAbCache(e)},r.prototype.setAbCache=function(e){this.ab_cache=e},r.prototype.getAbCache=function(){return this.ab_cache},r.prototype.clearAbCache=function(){this.ab_cache={},this.ab_version=""},r.prototype.setAbVersion=function(e){this.ab_version=e},r.prototype.getAbVersion=function(){return this.ab_version},r.prototype.setAbUuidCache=function(e,t){var n=t||this.envInfo.user.user_unique_id;this.ab_uuid_cache[""+n]||(this.ab_uuid_cache[""+n]=[]),this.ab_uuid_cache[""+n].indexOf(e)===-1&&this.ab_uuid_cache[""+n].push(e)},r.prototype.getAbUuidCache=function(e){return this.ab_uuid_cache[""+e]},r.prototype.getUrl=function(e){var t="";switch(e){case"event":t=this.channelUrl.REPORT_URL;break;case"webid":t=this.channelUrl.WEBID_URL;break;case"tobid":t=this.channelUrl.TOB_URL}var n="";return this.initConfig.caller&&(n="?sdk_version=5.3.14_oversea&sdk_name=web&app_id="+this.initConfig.app_id+"&caller="+this.initConfig.caller),""+this.getDomain()+t+n},r.prototype.setCustom=function(e){if(e&&e.latest_data&&e.latest_data.isLast)for(var t in delete e.latest_data.isLast,this.isLast=!0,e.latest_data)this.envInfo.header.custom[t]=e.latest_data[t]},r.prototype.setAppid=function(e){this.envInfo.header.app_id=e},r.prototype.changeReferInfo=function(e){var t=e;this.set({referrer:t.referrer});var n="";try{n=new URL(t.referrer).host}catch{}this.set({referrer_host:n||this.envInfo.header.referrer_host})},r.prototype.setEnableClientTransport=function(e){this.enableClientTransport=e},r.prototype.getEnableClientTransport=function(){return this.enableClientTransport},r.prototype.set=function(e){var t=this;Object.keys(e).forEach(function(n){if(e[n]!==void 0&&e[n]!==null||t.delete(n),n==="traffic_type"&&t.isLast&&(t.envInfo.header.custom.$latest_traffic_source_type=e[n]),n==="evtParams")t.evtParams=Le(Le({},t.evtParams||{}),e.evtParams||{});else if(n==="_staging_flag")t.evtParams=Le(Le({},t.evtParams||{}),{_staging_flag:e._staging_flag});else if(n==="reportErrorCallback"&&typeof e[n]=="function")t.reportErrorCallback=e[n];else{var i="",o="";if(n.indexOf(".")>-1){var a=n.split(".");i=a[0],o=a[1]}i?i==="user"||i==="header"?t.envInfo[i][o]=e[n]:(t.envInfo.header.custom[o]=e[n],t.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Add Custom Params",level:"info",time:Date.now(),infoType:"sdk",secType:"HEADER",common:"custom"})):Object.hasOwnProperty.call(t.envInfo.user,n)?(["user_type","ip_addr_id"].indexOf(n)>-1?t.envInfo.user[n]=e[n]?Number(e[n]):e[n]:["user_id","web_id","user_unique_id","user_unique_id_type"].indexOf(n)>-1?t.envInfo.user[n]=e[n]?String(e[n]):e[n]:["user_is_auth","user_is_login"].indexOf(n)>-1?t.envInfo.user[n]=!!e[n]:n==="device_id"&&(t.envInfo.user[n]=e[n]),t.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Set Common Params",level:"info",time:Date.now(),infoType:"sdk",secType:"USER",common:n})):Object.hasOwnProperty.call(t.envInfo.header,n)?(t.envInfo.header[n]=e[n],t.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Set Common Params",level:"info",time:Date.now(),infoType:"sdk",secType:"HEADER",common:n})):(t.envInfo.header.custom[n]=e[n],t.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Add Custom Params",level:"info",time:Date.now(),infoType:"sdk",secType:"HEADER",common:"custom"}))}})},r.prototype.get=function(e){try{return e?e==="evtParams"?this.evtParams:e==="reportErrorCallback"?this[e]:Object.hasOwnProperty.call(this.envInfo.user,e)?this.envInfo.user[e]:Object.hasOwnProperty.call(this.envInfo.header,e)?this.envInfo.header[e]:JSON.parse(JSON.stringify(this.envInfo[e])):JSON.parse(JSON.stringify(this.envInfo))}catch(t){console.log("get config stringify error "),this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:t.message,infoType:"sdk"})}},r.prototype.setStore=function(e){try{if(!this.configPersist)return;var t=this.storage.getItem(this.configKey)||{};if(t&&Object.keys(e).length){var n=Object.assign(e,t);this.storage.setItem(this.configKey,n)}}catch(i){console.log("setStore error"),this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:i.message,infoType:"sdk"})}},r.prototype.getStore=function(){try{if(!this.configPersist)return null;var e=this.storage.getItem(this.configKey)||{};return e&&Object.keys(e).length?e:null}catch(t){return this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:t.message,infoType:"sdk"}),null}},r.prototype.delete=function(e){try{if(!this.configPersist)return;var t=this.storage.getItem(this.configKey)||{};t&&Object.hasOwnProperty.call(t,e)&&(delete t[e],this.storage.setItem(this.configKey,t))}catch(n){this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:n.message,infoType:"sdk"}),console.log("delete error")}},r}(),uy=function(){function r(e){this.name=e||"default"}return r.prototype.enable=function(e){this.isLog=e!==!1},r.prototype.info=function(e){this.isLog&&console.log("%c %s","color: yellow; background-color: black;","[instance: "+this.name+"] "+e)},r.prototype.warn=function(e){this.isLog&&console.warn("%c %s","color: yellow; background-color: black;","[instance: "+this.name+"] "+e)},r.prototype.error=function(e){this.isLog&&console.error("%c %s","color: yellow; background-color: red;","[instance: "+this.name+"] "+e)},r.prototype.throw=function(e){throw this.error(this.name),new Error(e)},r}(),dy=function(){function r(){this.spiderBot=["Baiduspider","googlebot","360Spider","haosouspider","YoudaoBot","Yisouspider","Googlebot","Headless","Applebot","Bingbot","PetalBot"]}return r.prototype.checkSpider=function(e){if(!e.enable_spider)return!1;var t=window.navigator.userAgent;if(!t)return!0;var n=!1;return this.spiderBot.forEach(function(i){t.indexOf(i)!==-1&&(n=!0)}),n},r}(),ly=function(){function r(t,n){this.collect=t,this.native=n}var e=r.prototype;return e.bridgeInject=function(){try{return!!this.native&&(AppLogBridge?(console.log("AppLogBridge is injected"),!0):(console.log("AppLogBridge is not inject"),!1))}catch{return console.log("AppLogBridge is not inject"),!1}},e.bridgeReady=function(){var t=this;return new Promise(function(n,i){try{t.bridgeInject()?AppLogBridge.hasStarted(function(o){console.log("AppLogBridge is started? : "+o),o?n(!0):i(!1)}):i(!1)}catch(o){console.log("AppLogBridge, error:"+JSON.stringify(o.stack)),i(!1)}})},e.setNativeAppId=function(t){try{AppLogBridge.setNativeAppId(JSON.stringify(t)),console.log("change bridge appid, event report with appid: "+t)}catch{console.error("setNativeAppId error")}},e.setConfig=function(t){var n=this;try{Object.keys(t).forEach(function(i){i==="user_unique_id"?n.setUserUniqueId(t[i]):t[i]?n.addHeaderInfo(i,t[i]):n.removeHeaderInfo(i)})}catch{console.error("setConfig error")}},e.setUserUniqueId=function(t){try{AppLogBridge.setUserUniqueId(t)}catch{console.error("setUserUniqueId error")}},e.addHeaderInfo=function(t,n){try{AppLogBridge.addHeaderInfo(t,n)}catch{console.error("addHeaderInfo error")}},e.setHeaderInfo=function(t){try{AppLogBridge.setHeaderInfo(JSON.stringify(t))}catch{console.error("setHeaderInfo error")}},e.removeHeaderInfo=function(t){try{AppLogBridge.removeHeaderInfo(t)}catch{console.error("removeHeaderInfo error")}},e.reportPv=function(t){this.onEventV3("predefine_pageview",t)},e.onEventV3=function(t,n){try{AppLogBridge.onEventV3(t,n),this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE,{type:DebuggerMesssge.DEBUGGER_MESSAGE_EVENT,info:"bridge report success",time:Date.now(),data:[{events:[{event:t,params:n}]}],code:200,status:"success"})}catch{console.error("onEventV3 error")}},e.profileSet=function(t){try{AppLogBridge.profileSet(t)}catch{console.error("profileSet error")}},e.profileSetOnce=function(t){try{AppLogBridge.profileSetOnce(t)}catch{console.error("profileSetOnce error")}},e.profileIncrement=function(t){try{AppLogBridge.profileIncrement(t)}catch{console.error("profileIncrement error")}},e.profileUnset=function(t){try{AppLogBridge.profileUnset(t)}catch{console.error("profileUnset error")}},e.profileAppend=function(t){try{AppLogBridge.profileAppend(t)}catch{console.error("profileAppend error")}},r}(),hy=function(){function r(){this.setUrl="/service/2/web_sdk_settings/",this.expireTime=216e5}return r.prototype.apply=function(e,t){if(t.enable_logsetting){this.collect=e,this.config=t;var n=e.adapters.storage;this.setKey="applog_web_logsetting_"+t.app_id,this.uniqueKey="web_logsetting_data",this.cacheStorgae=new n(!1),this.dbStorage=new Qv(this.setKey,"LOGSETTING_DATA_STORE"),this.domain=t.logsetting_domain||this.collect.configManager.getDomain(),this.check()}else e.emit(B.LogSettingReady)},r.prototype.check=function(){return Ao(this,void 0,void 0,function(){var e;return Do(this,function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,this.getLocalData()];case 1:return(e=t.sent())&&Object.keys(e).length?(e==null?void 0:e.timestamp)<Date.now()-this.expireTime?this.fetchSetting():(this.setSettingData(e.settingConfig),this.collect.emit(B.LogSettingReady)):this.fetchSetting(),[3,3];case 2:return t.sent(),this.collect.emit(B.LogSettingReady),this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Check LogSetting Data Error",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"}),[3,3];case 3:return[2]}})})},r.prototype.fetchSetting=function(e){var t=this;if(e)this.collect.emit(B.LogSettingReady);else{var n=this.collect.configManager.get("header");n.custom=JSON.stringify(n.custom);var i=this.collect.configManager.get("user"),o={event_filter:0,header:Le(Le({aid:this.config.app_id},n),i),options:{params_block_enable:this.config.enable_logsetting_params?1:0,header_custom_allow_enable:this.config.enable_logsetting_header_custom?1:0}};this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch LogSetting Request",logType:"fetch",level:"info",time:Date.now(),data:o,infoType:"sdk"}),this.collect.requestManager.useRequest({url:""+this.domain+this.setUrl+"?device_platform=web",data:o,timeout:5e3,success:function(a){a!=null&&a.config?(t.setLocalData(a.config),t.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"LogSetting Request Success",logType:"fetch",level:"info",time:Date.now(),data:a,infoType:"sdk"})):t.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"LogSetting Request Response No Data",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"}),t.collect.emit(B.LogSettingReady)},fail:function(){t.collect.emit(B.LogSettingReady),t.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"LogSetting Request Fail",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"})}})}},r.prototype.getLocalData=function(){return Ao(this,void 0,void 0,function(){return Do(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,this.dbStorage.getItem(this.uniqueKey)];case 1:return[2,e.sent()];case 2:return e.sent(),[2,null];case 3:return[2]}})})},r.prototype.setLocalData=function(e){try{var t={timestamp:Date.now(),settingConfig:e};this.setSettingData(e),this.dbStorage.setItem(this.uniqueKey,t),this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Update LogSetting Cache",logType:"info",level:"info",time:Date.now(),infoType:"sdk",data:e})}catch{this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Set LogSetting Data Error",logType:"info",level:"error",time:Date.now(),infoType:"sdk"})}},r.prototype.getSettingData=function(e){return e?this.logSettingConfig[e]:this.logSettingConfig},r.prototype.setSettingData=function(e){this.logSettingConfig=e},r.prototype.getPredefineEventList=function(){return new Set(["predefine_pageview","onload","bav2b_click","bav2b_page","bav2b_beat","bav2b_page_statistics","bav2b_exposure","predefine_page_alive","predefine_page_close","_be_active","__bav_click","__bav_page","__bav_beat","__bav_page_statistics","__bav_page_exposure"])},r.prototype.getPredefineParamsList=function(){return new Set(["event_index"])},r}(),fy=function(){function r(){this.eventLimit=50,this.enable_ttwebid=!1,this.eventCache=[],this.beconEventCache=[]}return r.prototype.apply=function(e,t){var n=this;this.collect=e,this.config=t,this.configManager=e.configManager,this.cacheStorgae=new Er(!0),this.localStorage=new Er(!1),this.logSetting=new hy,this.maxReport=t.max_report||10,this.reportTime=t.reportTime||30,this.timeout=t.timeout||1e5,this.enable_ttwebid=t.enable_ttwebid,this.reportUrl=t.report_url||this.configManager.getUrl("event"),this.eventKey="__tea_cache_events_"+this.configManager.get("app_id"),this.beconKey="__tea_cache_events_becon_"+this.configManager.get("app_id"),this.abKey="__tea_sdk_ab_version_"+this.configManager.get("app_id"),this.refer_key="__tea_cache_refer_"+this.configManager.get("app_id"),this.logSetting.apply(e,t),this.collect.on(B.Ready,function(){n.reportAll(!1)}),this.collect.on(B.ConfigDomain,function(){n.reportUrl=n.configManager.getUrl("event")}),this.collect.on(B.Event,function(i){n.event(i)}),this.collect.on(B.BeconEvent,function(i){n.beconEvent(i)}),this.collect.on(B.CleanEvents,function(){n.reportAll(!1)}),this.linster()},r.prototype.linster=function(){var e,t=this;window.addEventListener("unload",function(){t.reportAll(!0)},!1),e=function(){t.reportAll(!0)},iu()?window.addEventListener("pagehide",e,!1):window.addEventListener("beforeunload",e,!1),document.addEventListener("visibilitychange",function(){document.visibilityState==="hidden"&&t.reportAll(!0)},!1)},r.prototype.reportAll=function(e){this.report(e),this.reportBecon()},r.prototype.event=function(e){var t=this;if(!this.collect.destroy&&!this.collect.sdkStop)try{if(this.config.enable_ios_sendbeacon&&iu())return void this.beconEvent(e);var n=Io(e,this.cacheStorgae.getItem(this.eventKey)||[]);if(this.cacheStorgae.setItem(this.eventKey,n),this.reportTimeout&&clearTimeout(this.reportTimeout),n.length>=this.maxReport)this.report(!1);else{var i=this.reportTime;this.reportTimeout=setTimeout(function(){t.report(!1),t.reportTimeout=null},i)}}catch(o){this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:o.message,infoType:"sdk"})}},r.prototype.beconEvent=function(e){if(!this.collect.destroy&&!this.collect.sdkStop){var t=Io(e,this.cacheStorgae.getItem(this.beconKey)||[]);if(this.cacheStorgae.setItem(this.beconKey,t),this.collect.tokenManager.getReady()&&this.collect.sdkReady){this.cacheStorgae.removeItem(this.beconKey);try{var n=JSON.parse(JSON.stringify(t));if(this.send(this.split(this.merge(t)),!0),this.config.event_verify_url){var i=this.split(this.merge(n,!0));this.collect.emit(B.SubmitVerify,i)}}catch{this.send(this.split(this.merge(t)),!0)}}}},r.prototype.reportBecon=function(){if(!this.collect.destroy&&!this.collect.sdkStop&&this.collect.tokenManager.getReady()&&this.collect.sdkReady){var e=this.cacheStorgae.getItem(this.beconKey)||[];if(e&&e.length){this.cacheStorgae.removeItem(this.beconKey);try{var t=JSON.parse(JSON.stringify(e));if(this.send(this.split(this.merge(e)),!0),this.config.event_verify_url){var n=this.split(this.merge(t,!0));this.collect.emit(B.SubmitVerify,n)}}catch{this.send(this.split(this.merge(e)),!0)}}}},r.prototype.report=function(e){if(!this.collect.destroy&&!this.collect.sdkStop&&this.collect.tokenManager.getReady()&&this.collect.sdkReady){var t=this.cacheStorgae.getItem(this.eventKey)||[];t.length&&(this.cacheStorgae.removeItem(this.eventKey),this.sliceEvent(t,e))}},r.prototype.sliceEvent=function(e,t){if(e.length>this.eventLimit)for(var n=0;n<e.length;n+=this.eventLimit){var i;i=e.slice(n,n+this.eventLimit);try{var o=JSON.parse(JSON.stringify(i));if(this.send(this.split(this.merge(i)),t),this.config.event_verify_url){var a=this.split(this.merge(o,!0));this.collect.emit(B.SubmitVerify,a)}}catch{this.send(this.split(this.merge(i)),t)}}else try{o=JSON.parse(JSON.stringify(e)),this.send(this.split(this.merge(e)),t),this.config.event_verify_url&&(a=this.split(this.merge(o,!0)),this.collect.emit(B.SubmitVerify,a))}catch{this.send(this.split(this.merge(e)),t)}},r.prototype.handleRefer=function(){var e="";try{if(this.config.spa||this.config.autotrack){var t=this.localStorage.getItem(this.refer_key)||{};e=t.routeChange?t.refer_key:this.configManager.get("referrer")}else e=this.configManager.get("referrer")}catch{e=document.referrer}return e},r.prototype.merge=function(e,t){var n=this;t===void 0&&(t=!1);var i=this.configManager.get(),o=i.header,a=i.user;o.custom=this.customAllow(o.custom,t);var s=this.configManager.get("evtParams"),u=this.configManager.get("user_unique_id_type"),c=[];try{var d=e.filter(function(h){try{Object.keys(s).length&&(h.params=Le(Le({},s),h.params)),u&&(h.params.$user_unique_id_type=u);var g=n.configManager.getAbCache(),k=a[n.config.ab_user_mode]||a.user_unique_id,z=n.configManager.getAbUuidCache(k);if(g&&g.uuid&&g.uuid===k){var w=n.configManager.getAbVersion();if(n.config.enable_ab_uuid){if(z&&z.length){var b=z.join(",");w&&w.includes(b)&&(h.ab_sdk_version=w)}}else w&&(h.ab_sdk_version=w)}return h.session_id=n.collect.sessionManager.getSessionId(),h.params=n.paramsAllow(h,t),h}catch(T){return console.warn("filter merge event: "+(h&&h.event)+" error, pls check",T&&T.message),n.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Merge Event Something Error",level:"error",time:Date.now(),data:T.message,infoType:"sdk"}),!1}}),f=JSON.parse(JSON.stringify({events:d,user:a,header:o}));f.local_time=Math.floor(Date.now()/1e3),f.user_unique_type=this.config.enable_ttwebid?this.config.user_unique_type:void 0,f.verbose=1,c.push(f)}catch(h){console.warn("event merge error, pls check",h&&h.message)}return c},r.prototype.split=function(e){return e=e.map(function(t){var n=[];return n.push(t),n})},r.prototype.blockEvent=function(e){try{var t=this.blockList;if(this.config.enable_logsetting){var n=this.blockList,i=this.logSetting.getSettingData("blocklist_events").block_event;t=n.concat(i.filter(function(o){return n.indexOf(o)===-1}))}return!(t&&t.length&&t.includes(e))}catch{return!0}},r.prototype.whiteEvent=function(e){var t;try{return!(!((t=this.whiteList)===null||t===void 0)&&t.length)||!!this.whiteList.includes(e)}catch{return!0}},r.prototype.customAllow=function(e,t){try{if(t||!this.config.enable_logsetting||!this.config.enable_logsetting_header_custom)return JSON.stringify(e);var n=this.logSetting.getSettingData().header_custom_allow;if(n){var i={};if(n.length&&Object.keys(e).length){var o=new Set(n);for(var a in e)o.has(a)&&(i[a]=e[a])}return JSON.stringify(i)}return JSON.stringify(e)}catch(s){return this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute customAllow Something Error",level:"error",time:Date.now(),data:s.message,infoType:"sdk"}),JSON.stringify(e)}},r.prototype.paramsAllow=function(e,t){try{if(t||!this.config.enable_logsetting||!this.config.enable_logsetting_params)return JSON.stringify(e.params);var n=this.logSetting.getSettingData().params_block,i=e.event,o=e.params;if(!n)return JSON.stringify(e.params);if(n[i]&&n[i].length){var a={},s=new Set(n[i]);for(var u in o)!this.logSetting.getPredefineParamsList().has(u)&&s.has(u)||(a[u]=o[u]);return JSON.stringify(a)}return JSON.stringify(e.params)}catch(c){return this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute paramsAllow Something Error",level:"error",time:Date.now(),data:c.message,infoType:"sdk"}),JSON.stringify(e.params)}},r.prototype.send=function(e,t){var n=this;e.length&&(this.config.disable_track_event||e.forEach(function(i){try{var o=JSON.parse(JSON.stringify(i));n.config.filter&&((o=n.config.filter(o))||console.warn("filter must return data !!")),n.collect.eventFilter&&o&&((o=n.collect.eventFilter(o))||console.warn("filterEvent api must return data !!"));var a=o||i,s=JSON.parse(JSON.stringify(a));if(!a.length)return;var u=!0;if(a.forEach(function(c){c.events.length||(u=!1)}),!u)return;n.collect.emit(B.SubmitBefore,a),n.collect.requestManager.useRequest({url:n.reportUrl,data:a,success:function(c,d,f,h){c&&c.e!==0?(n.collect.emit(B.SubmitError,{type:"f_data",eventData:d,errorCode:c.e,response:c,startTime:f,endTime:Date.now(),status:h}),n.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_EVENT,info:"Event Report Fail",time:Date.now(),data:s,code:c.e,failType:"event data error",status:"fail"})):(n.collect.emit(B.SubmitScuess,{eventData:d,res:c}),n.collect.emit(B.SubmitSuccess,{eventData:d,res:c,response:c,startTime:f,endTime:Date.now(),status:h}),n.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_EVENT,info:"Event Report Success",time:Date.now(),data:s,code:200,status:"success"}))},fail:function(c,d,f,h){n.configManager.get("reportErrorCallback")(c,d),n.collect.emit(B.SubmitError,{type:"f_net",eventData:c,errorCode:d,startTime:f,errorMessage:h,endTime:Date.now()}),n.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_EVENT,info:"Event Report Network Fail",time:Date.now(),data:s,code:d,failType:"network error",status:"fail"})},timeout:n.timeout,useBeacon:!n.config.disable_sendbeacon&&t,withCredentials:n.enable_ttwebid,zip:!0}),n.collect.emit(B.SubmitAfter,a)}catch(c){console.warn("something error, "+JSON.stringify(c.stack)),n.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Report Event Something Error",level:"error",time:Date.now(),data:c.message})}}))},r}(),Bo=function(){return function r(e){return e?(e^16*Math.random()>>e/4).toString(10):("10000000-1000-4000-8000"+-1e11).replace(/[018]/g,r)}().replace(/-/g,"").slice(0,19)},py=function(){function r(){this.cacheToken={},this.enableCookie=!1,this.enable_ttwebid=!1,this.enableCustomWebid=!1}return r.prototype.apply=function(e,t){var n=this;this.collect=e,this.config=t,this.configManager=this.collect.configManager,this.storage=new Er(!1),this.tokenKey="__tea_cache_tokens_"+t.app_id,this.enable_ttwebid=t.enable_ttwebid,this.enableCustomWebid=t.enable_custom_webid,this.collect.on(B.ConfigUuid,function(i){n.setUuid(i)}),this.collect.on(B.ConfigWebId,function(i){n.setWebId(i)}),this.collect.on(B.ConfigDiD,function(i){n.setDeviceId(i)}),this.enableCookie=t.cross_subdomain,this.expiresTime=t.cookie_expire||6048e5,this.cookieDomain=t.cookie_domain||"",this.checkStorage()},r.prototype.checkStorage=function(){var e=this;this.cacheToken=this.storage.getItem(this.tokenKey)||{},this.tokenType=this.cacheToken&&this.cacheToken._type_?this.cacheToken._type_:"default",this.tokenType!=="custom"||this.enableCustomWebid?this.enableCustomWebid?this.collect.on(B.CustomWebId,function(){e.tokenReady=!0,e.collect.emit(B.TokenComplete)}):this.checkEnv()||(this.enable_ttwebid?this.completeTtWid(this.cacheToken):this.check()):this.remoteWebid()},r.prototype.check=function(){this.cacheToken&&this.cacheToken.web_id?this.complete(this.cacheToken):this.config.disable_webid?this.complete({web_id:Bo(),user_unique_id:this.configManager.get("user_unique_id")||Bo()}):this.remoteWebid()},r.prototype.checkEnv=function(){var e=window.navigator.userAgent;if(e.indexOf("miniProgram")!==-1||e.indexOf("MiniProgram")!==-1){var t=xo(window.location.href);return!(!t||!t.Web_ID)&&(this.complete({web_id:""+t.Web_ID,user_unique_id:this.configManager.get("user_unique_id")||""+t.Web_ID}),!0)}return!1},r.prototype.remoteWebid=function(){var e=this,t=this.configManager.getUrl("webid"),n={app_key:this.config.app_key,app_id:this.config.app_id,url:location.href,user_agent:window.navigator.userAgent,referer:document.referrer,user_unique_id:""};this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch WebID Request",logType:"fetch",level:"info",time:Date.now(),data:n});var i=Bo();this.collect.requestManager.useRequest({url:t,data:n,success:function(o){var a;o&&o.e===0?(a=o.web_id,e.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"Fetch WebID Request Success",logType:"fetch",level:"info",time:Date.now(),data:o})):(a=i,e.collect.configManager.set({localWebId:i}),e.collect.emit(B.TokenError),e.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"Fetch WebID Request Data Error, Use LocalId",logType:"fetch",level:"warn",time:Date.now(),data:o}),e.collect.logger.warn("appid: "+e.config.app_id+" get webid error, use local webid~")),e.complete({web_id:e.configManager.get("web_id")||a,user_unique_id:e.configManager.get("user_unique_id")||a})},fail:function(){e.complete({web_id:e.configManager.get("web_id")||i,user_unique_id:e.configManager.get("user_unique_id")||i}),e.collect.configManager.set({localWebId:i}),e.collect.emit(B.TokenError),e.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"Fetch WebID Request Network Fail, Use LocalId",logType:"fetch",level:"error",time:Date.now(),data:null}),e.collect.logger.warn("appid: "+e.config.app_id+", get webid error, use local webid~")},timeout:3e5})},r.prototype.complete=function(e){var t=e.web_id,n=e.user_unique_id,i=e.device_id;if(e.timestamp=Date.now(),this.collect.configManager.set({web_id:t,user_unique_id:n}),this.config.enable_device_id){var o=this.configManager.get("device_id")||i||t;this.collect.configManager.set({device_id:o}),e=Le(Le({},e),{device_id:o})}else delete e.device_id;this.setStorage(e),this.tokenReady=!0,this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK UserInfo Complete",logType:"info",secType:"USER",level:"info",time:Date.now(),data:{web_id:t,user_unique_id:n},infoType:"sdk"}),this.collect.emit(B.TokenComplete)},r.prototype.completeTtWid=function(e){var t=e.user_unique_id||"",n=this.configManager.get("user_unique_id");(n||t)&&this.configManager.set({user_unique_id:n||t}),this.setStorage(e),this.tokenReady=!0,this.collect.emit(B.TokenComplete)},r.prototype.setUuid=function(e){if(e&&["null","undefined","Null","None"].indexOf(e)===-1){var t=String(e),n=this.configManager.get("user_unique_id"),i=this.cacheToken&&this.cacheToken.user_unique_id;if(t===n&&t===i)return;this.configManager.set({user_unique_id:t}),this.cacheToken||(this.cacheToken={}),this.cacheToken.user_unique_id=t,this.cacheToken.timestamp=Date.now(),this.setStorage(this.cacheToken),this.collect.emit(B.TokenChange,"uuid"),this.collect.emit(B.SessionReset)}else this.clearUuid()},r.prototype.clearUuid=function(){this.config.enable_ttwebid||this.configManager.get("web_id")&&(this.configManager.set({user_unique_id:this.configManager.get("web_id")}),this.cacheToken&&this.cacheToken.web_id&&(this.cacheToken.user_unique_id=this.cacheToken.web_id,this.cacheToken.timestamp=Date.now(),this.setStorage(this.cacheToken)),this.collect.emit(B.TokenReset))},r.prototype.setWebId=function(e){if(e&&!this.config.enable_ttwebid){this.cacheToken&&this.cacheToken.web_id?this.cacheToken.web_id!==e&&(this.cacheToken.user_unique_id=this.cacheToken.web_id===this.cacheToken.user_unique_id?e:this.cacheToken.user_unique_id,this.cacheToken.web_id=e):(this.cacheToken={},this.cacheToken.web_id=e,this.cacheToken.user_unique_id=e),this.cacheToken.timestamp=Date.now();var t=this.configManager.get("web_id"),n=this.configManager.get("user_unique_id");n&&n!==t||(this.configManager.set({user_unique_id:e}),this.collect.emit(B.TokenChange,"uuid")),t!==e&&(this.configManager.set({web_id:e}),this.collect.emit(B.TokenChange,"webid")),this.setStorage(this.cacheToken)}},r.prototype.setDeviceId=function(e){this.configManager.set({device_id:e}),this.config.enable_device_id&&this.cacheToken&&(this.cacheToken.device_id=e,this.cacheToken.timestamp=Date.now(),this.setStorage(this.cacheToken))},r.prototype.setStorage=function(e){e._type_=this.enableCustomWebid?"custom":"default",delete e["diss".split("").reverse().join("")],this.storage.setItem(this.tokenKey,e),this.cacheToken=e},r.prototype.getReady=function(){return this.tokenReady},r.prototype.getTobId=function(){var e=this;return new Promise(function(t){var n;if(e.config.channel_domain)t("");else if(((n=e.collect.configManager)===null||n===void 0?void 0:n.getCurrentEnv())==="row")if(e.config.channel_type!=="tcpy"&&e.config.channel_type!=="ttp"){var i={app_id:e.config.app_id,user_unique_id:e.configManager.get("user_unique_id"),web_id:e.configManager.get("web_id"),user_unique_id_type:e.configManager.get("user_unique_id_type")};e.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch GetToken Request",logType:"fetch",level:"info",time:Date.now(),data:i,infoType:"sdk"}),e.collect.requestManager.useRequest({url:e.configManager.getUrl("tobid"),data:i,success:function(o){o&&o.e===0?(t(o.tobid),e.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"Fetch GetToken Request Success",logType:"fetch",level:"info",time:Date.now(),data:o,infoType:"sdk"})):(t(""),e.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"Fetch GetToken Request Fail",logType:"fetch",level:"error",time:Date.now(),data:o,infoType:"sdk"}))},fail:function(){t(""),e.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"Fetch GetToken Request Network Error",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"})},timeout:3e4,withCredentials:e.enable_ttwebid})}else t("");else t("")})},r}(),pn=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){var e=16*Math.random()|0;return(r==="x"?e:3&e|8).toString(16)})},my=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;this.collect=e,this.storage=new au,this.sessionKey="__tea_session_id_"+t.app_id,this.expireTime=t.expireTime||18e5,this.disableSession=t.disable_session,this.disableSession||(this.setSessionId(),this.collect.on(B.SessionReset,function(){n.resetSessionId()}),this.collect.on(B.SessionResetTime,function(){n.updateSessionIdTime()}))},r.prototype.updateSessionIdTime=function(){var e=this.storage.getSessionItem(this.sessionKey);if(e&&e.sessionId){var t=e.timestamp;Date.now()-t>this.expireTime?(e={sessionId:pn(),timestamp:Date.now()},this.collect.emit(B.SessionResetInner)):e.timestamp=Date.now(),this.storage.setSessionItem(this.sessionKey,e),this.resetExpTime()}},r.prototype.setSessionId=function(){var e=this,t=this.storage.getSessionItem(this.sessionKey);t&&t.sessionId?t.timestamp=Date.now():t={sessionId:pn(),timestamp:Date.now()},this.storage.setSessionItem(this.sessionKey,t),this.sessionExp=setInterval(function(){e.checkEXp()},this.expireTime)},r.prototype.getSessionId=function(){var e=this.storage.getSessionItem(this.sessionKey);return this.disableSession?"":e&&e.sessionId?e.sessionId:""},r.prototype.resetExpTime=function(){var e=this;this.sessionExp&&(clearInterval(this.sessionExp),this.sessionExp=setInterval(function(){e.checkEXp()},this.expireTime))},r.prototype.resetSessionId=function(){var e={sessionId:pn(),timestamp:Date.now()};this.storage.setItem(this.sessionKey,e)},r.prototype.checkEXp=function(){var e=this.storage.getSessionItem(this.sessionKey);e&&e.sessionId&&Date.now()-e.timestamp+30>=this.expireTime&&(e={sessionId:pn(),timestamp:Date.now()},this.storage.setSessionItem(this.sessionKey,e))},r}(),at=Uint8Array,Je=Uint16Array,Fo=Int32Array,Vo=new at([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),jo=new at([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),hu=new at([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),fu=function(r,e){for(var t=new Je(31),n=0;n<31;++n)t[n]=e+=1<<r[n-1];var i=new Fo(t[30]);for(n=1;n<30;++n)for(var o=t[n];o<t[n+1];++o)i[o]=o-t[n]<<5|n;return{b:t,r:i}},pu=fu(Vo,2),gy=pu.b,Ho=pu.r;gy[28]=258,Ho[258]=28;for(var mu=fu(jo,0),kS=mu.b,gu=mu.r,$o=new Je(32768),ge=0;ge<32768;++ge){var ir=(43690&ge)>>1|(21845&ge)<<1;ir=(61680&(ir=(52428&ir)>>2|(13107&ir)<<2))>>4|(3855&ir)<<4,$o[ge]=((65280&ir)>>8|(255&ir)<<8)>>1}var or=function(r,e,t){for(var n=r.length,i=0,o=new Je(e);i<n;++i)r[i]&&++o[r[i]-1];var a,s=new Je(e);for(i=1;i<e;++i)s[i]=s[i-1]+o[i-1]<<1;if(t){a=new Je(1<<e);var u=15-e;for(i=0;i<n;++i)if(r[i])for(var c=i<<4|r[i],d=e-r[i],f=s[r[i]-1]++<<d,h=f|(1<<d)-1;f<=h;++f)a[$o[f]>>u]=c}else for(a=new Je(n),i=0;i<n;++i)r[i]&&(a[i]=$o[s[r[i]-1]++]>>15-r[i]);return a},jt=new at(288);for(ge=0;ge<144;++ge)jt[ge]=8;for(ge=144;ge<256;++ge)jt[ge]=9;for(ge=256;ge<280;++ge)jt[ge]=7;for(ge=280;ge<288;++ge)jt[ge]=8;var mn=new at(32);for(ge=0;ge<32;++ge)mn[ge]=5;var _y=or(jt,9,0);or(jt,9,1);var vy=or(mn,5,0);or(mn,5,1);var _u=function(r){return(r+7)/8|0},yy=function(r,e,t){return(t==null||t>r.length)&&(t=r.length),new at(r.subarray(e,t))},Rt=function(r,e,t){t<<=7&e;var n=e/8|0;r[n]|=t,r[n+1]|=t>>8},gn=function(r,e,t){t<<=7&e;var n=e/8|0;r[n]|=t,r[n+1]|=t>>8,r[n+2]|=t>>16},qo=function(r,e){for(var t=[],n=0;n<r.length;++n)r[n]&&t.push({s:n,f:r[n]});var i=t.length,o=t.slice();if(!i)return{t:bu,l:0};if(i==1){var a=new at(t[0].s+1);return a[t[0].s]=1,{t:a,l:1}}t.sort(function(G,I){return G.f-I.f}),t.push({s:-1,f:25001});var s=t[0],u=t[1],c=0,d=1,f=2;for(t[0]={s:-1,f:s.f+u.f,l:s,r:u};d!=i-1;)s=t[t[c].f<t[f].f?c++:f++],u=t[c!=d&&t[c].f<t[f].f?c++:f++],t[d++]={s:-1,f:s.f+u.f,l:s,r:u};var h=o[0].s;for(n=1;n<i;++n)o[n].s>h&&(h=o[n].s);var g=new Je(h+1),k=Ko(t[d-1],g,0);if(k>e){n=0;var z=0,w=k-e,b=1<<w;for(o.sort(function(G,I){return g[I.s]-g[G.s]||G.f-I.f});n<i;++n){var T=o[n].s;if(!(g[T]>e))break;z+=b-(1<<k-g[T]),g[T]=e}for(z>>=w;z>0;){var E=o[n].s;g[E]<e?z-=1<<e-g[E]++-1:++n}for(;n>=0&&z;--n){var O=o[n].s;g[O]==e&&(--g[O],++z)}k=e}return{t:new at(g),l:k}},Ko=function(r,e,t){return r.s==-1?Math.max(Ko(r.l,e,t+1),Ko(r.r,e,t+1)):e[r.s]=t},vu=function(r){for(var e=r.length;e&&!r[--e];);for(var t=new Je(++e),n=0,i=r[0],o=1,a=function(u){t[n++]=u},s=1;s<=e;++s)if(r[s]==i&&s!=e)++o;else{if(!i&&o>2){for(;o>138;o-=138)a(32754);o>2&&(a(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(a(i),--o;o>6;o-=6)a(8304);o>2&&(a(o-3<<5|8208),o=0)}for(;o--;)a(i);o=1,i=r[s]}return{c:t.subarray(0,n),n:e}},_n=function(r,e){for(var t=0,n=0;n<e.length;++n)t+=r[n]*e[n];return t},yu=function(r,e,t){var n=t.length,i=_u(e+2);r[i]=255&n,r[i+1]=n>>8,r[i+2]=255^r[i],r[i+3]=255^r[i+1];for(var o=0;o<n;++o)r[i+o+4]=t[o];return 8*(i+4+n)},Su=function(r,e,t,n,i,o,a,s,u,c,d){Rt(e,d++,t),++i[256];for(var f=qo(i,15),h=f.t,g=f.l,k=qo(o,15),z=k.t,w=k.l,b=vu(h),T=b.c,E=b.n,O=vu(z),G=O.c,I=O.n,U=new Je(19),L=0;L<T.length;++L)++U[31&T[L]];for(L=0;L<G.length;++L)++U[31&G[L]];for(var j=qo(U,7),$=j.t,K=j.l,Z=19;Z>4&&!$[hu[Z-1]];--Z);var W,se,oe,Y,le=c+5<<3,fe=_n(i,jt)+_n(o,mn)+a,ue=_n(i,h)+_n(o,z)+a+14+3*Z+_n(U,$)+2*U[16]+3*U[17]+7*U[18];if(u>=0&&le<=fe&&le<=ue)return yu(e,d,r.subarray(u,u+c));if(Rt(e,d,1+(ue<fe)),d+=2,ue<fe){W=or(h,g,0),se=h,oe=or(z,w,0),Y=z;var be=or($,K,0);for(Rt(e,d,E-257),Rt(e,d+5,I-1),Rt(e,d+10,Z-4),d+=14,L=0;L<Z;++L)Rt(e,d+3*L,$[hu[L]]);d+=3*Z;for(var ye=[T,G],re=0;re<2;++re){var ke=ye[re];for(L=0;L<ke.length;++L){var de=31&ke[L];Rt(e,d,be[de]),d+=$[de],de>15&&(Rt(e,d,ke[L]>>5&127),d+=ke[L]>>12)}}}else W=_y,se=jt,oe=vy,Y=mn;for(L=0;L<s;++L){var _e=n[L];if(_e>255){gn(e,d,W[(de=_e>>18&31)+257]),d+=se[de+257],de>7&&(Rt(e,d,_e>>23&31),d+=Vo[de]);var De=31&_e;gn(e,d,oe[De]),d+=Y[De],De>3&&(gn(e,d,_e>>5&8191),d+=jo[De])}else gn(e,d,W[_e]),d+=se[_e]}return gn(e,d,W[256]),d+se[256]},Sy=new Fo([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),bu=new at(0),by=function(){for(var r=new Int32Array(256),e=0;e<256;++e){for(var t=e,n=9;--n;)t=(1&t&&-306674912)^t>>>1;r[e]=t}return r}(),Ey=function(){var r=-1;return{p:function(e){for(var t=r,n=0;n<e.length;++n)t=by[255&t^e[n]]^t>>>8;r=t},d:function(){return~r}}},wy=function(r,e,t,n,i){if(!i&&(i={l:1},e.dictionary)){var o=e.dictionary.subarray(-32768),a=new at(o.length+r.length);a.set(o),a.set(r,o.length),r=a,i.w=o.length}return function(s,u,c,d,f,h){var g=h.z||s.length,k=new at(d+g+5*(1+Math.ceil(g/7e3))+f),z=k.subarray(d,k.length-f),w=h.l,b=7&(h.r||0);if(u){b&&(z[0]=h.r>>3);for(var T=Sy[u-1],E=T>>13,O=8191&T,G=(1<<c)-1,I=h.p||new Je(32768),U=h.h||new Je(G+1),L=Math.ceil(c/3),j=2*L,$=function(ut){return(s[ut]^s[ut+1]<<L^s[ut+2]<<j)&G},K=new Fo(25e3),Z=new Je(288),W=new Je(32),se=0,oe=0,Y=h.i||0,le=0,fe=h.w||0,ue=0;Y+2<g;++Y){var be=$(Y),ye=32767&Y,re=U[be];if(I[ye]=re,U[be]=ye,fe<=Y){var ke=g-Y;if((se>7e3||le>24576)&&(ke>423||!w)){b=Su(s,z,0,K,Z,W,oe,le,ue,Y-ue,b),le=se=oe=0,ue=Y;for(var de=0;de<286;++de)Z[de]=0;for(de=0;de<30;++de)W[de]=0}var _e=2,De=0,Ht=O,Ue=ye-re&32767;if(ke>2&&be==$(Y-Ue))for(var $t=Math.min(E,ke)-1,Dt=Math.min(32767,Y),Xe=Math.min(258,ke);Ue<=Dt&&--Ht&&ye!=re;){if(s[Y+_e]==s[Y+_e-Ue]){for(var Te=0;Te<Xe&&s[Y+Te]==s[Y+Te-Ue];++Te);if(Te>_e){if(_e=Te,De=Ue,Te>$t)break;var Ie=Math.min(Ue,Te-2),Ge=0;for(de=0;de<Ie;++de){var Ne=Y-Ue+de&32767,Be=Ne-I[Ne]&32767;Be>Ge&&(Ge=Be,re=Ne)}}}Ue+=(ye=re)-(re=I[ye])&32767}if(De){K[le++]=268435456|Ho[_e]<<18|gu[De];var nt=31&Ho[_e],It=31&gu[De];oe+=Vo[nt]+jo[It],++Z[257+nt],++W[It],fe=Y+_e,++se}else K[le++]=s[Y],++Z[s[Y]]}}for(Y=Math.max(Y,fe);Y<g;++Y)K[le++]=s[Y],++Z[s[Y]];b=Su(s,z,w,K,Z,W,oe,le,ue,Y-ue,b),w||(h.r=7&b|z[b/8|0]<<3,b-=7,h.h=U,h.p=I,h.i=Y,h.w=fe)}else{for(Y=h.w||0;Y<g+w;Y+=65535){var ct=Y+65535;ct>=g&&(z[b/8|0]=w,ct=g),b=yu(z,b+1,s.subarray(Y,ct))}h.i=g}return yy(k,0,d+_u(b)+f)}(r,e.level==null?6:e.level,e.mem==null?i.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):20:12+e.mem,t,n,i)},Wo=function(r,e,t){for(;t;++e)r[e]=t,t>>>=8},Cy=function(r,e){var t=e.filename;if(r[0]=31,r[1]=139,r[2]=8,r[8]=e.level<2?4:e.level==9?2:0,r[9]=3,e.mtime!=0&&Wo(r,4,Math.floor(new Date(e.mtime||Date.now())/1e3)),t){r[3]=8;for(var n=0;n<=t.length;++n)r[n+10]=t.charCodeAt(n)}},ky=function(r){return 10+(r.filename?r.filename.length+1:0)};function Eu(r,e){e||(e={});var t=Ey(),n=r.length;t.p(r);var i=wy(r,e,ky(e),8),o=i.length;return Cy(i,e),Wo(i,o-8,t.d()),Wo(i,o-4,n),i}var Ty=(typeof TextEncoder<"u"&&new TextEncoder,typeof TextDecoder<"u"&&new TextDecoder);try{Ty.decode(bu,{stream:!0})}catch{}var zy=function(){function r(e,t){var n=this;this.requestType="",this.collector=e,this.config=t,this.requestType=t.request_type,this.supportBeacon=!(!window.navigator||!window.navigator.sendBeacon),this.errorCode={NO_URL:4001,IMG_ON:4e3,IMG_CATCH:4002,BEACON_FALSE:4003,XHR_ERROR:5002,TIMEOUT:5005,FETCH_ERROR:5006},this.errorMessage={BEACON_FALSE:"xhr sendbeacon error",XHR_ERROR:"xhr request error",BEACON:"xhr sendbeacon error",TIMEOUT:"xhr request timeout",FETCH_ERROR:"fetch network error",FETCH_RESPONSE_ERROR:"fetch response error"},this.customHeader=t.custom_request_header||{},this.collector.on(B.CustomHeader,function(i){n.setRequestHeader(i)}),this.env=this.collector.configManager.getCurrentEnv()}return r.prototype.setRequestHeader=function(e){this.customHeader=Object.assign(this.customHeader,e)},r.prototype.useFetch=function(e){var t=this,n=e.url,i=e.data,o=e.method,a=e.success,s=e.fail,u=e.zip,c=e.timeout,d=c===void 0?5e3:c,f=e.useBeacon;if(window.fetch&&typeof Request<"u"){if(f&&!("keepalive"in Request.prototype))return void this.useBeacon(e);var h={"Content-Type":"application/json; charset=utf-8"};if(Object.keys(this.customHeader).length)for(var g in this.customHeader)h[g]=this.customHeader[g];var k=null;k=typeof AbortController<"u"?new AbortController:{signal:null,abort:function(){}};var z=setTimeout(function(){k.abort()},d),w=JSON.stringify(i);this.env==="row"&&u&&this.config.need_zip&&(w=Eu(new TextEncoder().encode(w)),h["Content-Encoding"]="gzip");var b=Date.now();try{fetch(n,{method:o||"POST",headers:h,body:w,keepalive:!0,signal:k.signal}).then(function(T){return T.ok||s&&s(i,T.status,b,T.statusText||t.errorMessage.FETCH_RESPONSE_ERROR),T.json()}).then(function(T){clearTimeout(z),a&&a(T,i,b,200)}).catch(function(T){clearTimeout(z),s&&s(i,t.errorCode.FETCH_ERROR,b,T.message||t.errorMessage.FETCH_ERROR)})}catch(T){this.useXhr(e),this.collector.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK useFetch has some errors",level:"error",time:Date.now(),data:T.message||"SDK useFetch has some errors",infoType:"sdk"})}}else f?this.useBeacon(e):(this.requestType="",this.useXhr(e)),console.log("your brwoser not support fetch, use xhr")},r.prototype.useBeacon=function(e){var t=e.url,n=e.data,i=e.success,o=e.fail,a=Date.now();window.navigator.sendBeacon(t,JSON.stringify(n))?i&&i({e:0},n,a,200):o&&o(n,this.errorCode.BEACON_FALSE,a,this.errorMessage.BEACON_FALSE)},r.prototype.useXhr=function(e){var t=this,n=e.url,i=e.data,o=e.method,a=e.success,s=e.fail,u=e.timeout,c=e.withCredentials,d=e.app_key,f=e.zip;try{var h=new XMLHttpRequest,g=o||"POST",k=Date.now();if(h.open(g,""+n,!0),h.setRequestHeader("Content-Type","application/json; charset=utf-8"),d&&h.setRequestHeader("X-MCS-AppKey",""+d),Object.keys(this.customHeader).length)for(var z in this.customHeader)h.setRequestHeader(z,this.customHeader[z]);c&&(h.withCredentials=!0),u&&(h.timeout=u,h.ontimeout=function(){s&&s(i,t.errorCode.TIMEOUT,k,t.errorMessage.TIMEOUT)}),h.onload=function(){if(a){var T=null;if(h.responseText){try{T=JSON.parse(h.responseText)}catch{T={}}a(T,i,k,h.status)}}},h.onerror=function(){h.abort(),s&&s(i,t.errorCode.XHR_ERROR,k,t.errorMessage.XHR_ERROR)};try{var w=JSON.stringify(i);if(this.config.need_zip&&f)if(this.env==="row"){var b=Eu(new TextEncoder().encode(w));h.setRequestHeader("Content-Encoding","gzip"),h.send(b)}else h.send(w),this.collector.logger.warn("your channel do not support gzip, use normal data!");else h.send(w)}catch(T){h.send(JSON.stringify(i)),this.collector.emit("sdk-inner-error",{type:"sdk_error_send",eventData:i,errorCode:1e3,msg:T.message||T.stack||"sdk_error_send"})}}catch(T){this.collector.emit("sdk-inner-error",{type:"sdk_error_request",eventData:i,errorCode:1001,msg:T.message||T.stack||"sdk_error_request"}),this.collector.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK useXhr has some error",level:"error",time:Date.now(),data:T.message,infoType:"sdk"})}},r.prototype.useRequest=function(e){var t=e.useBeacon;this.config.transport&&this.collector.configManager.getEnableClientTransport()?this.useCustomRequest(e):this.requestType&&this.requestType==="xhr"?this.useXhr(e):t&&this.supportBeacon?this.useBeacon(e):this.requestType&&this.requestType==="fetch"?this.useFetch(e):this.useXhr(e)},r.prototype.useCustomRequest=function(e){var t=this.config.transport,n=e.url,i=e.data,o=e.success,a=e.fail;if(t)try{t.post({url:n,data:JSON.stringify(i),success:function(s){o&&o(s,i)},fail:function(s){a&&a(s,i)}})}catch(s){this.collector.configManager.setEnableClientTransport(!1),this.useRequest(e),this.collector.emit("sdk-inner-error",{type:"sdk_transport_error",eventData:i,errorCode:1003,msg:s.message||s.stack||"sdk_transport_error"}),this.collector.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK useCustomRequest has some error",level:"error",time:Date.now(),data:s.message,infoType:"sdk"})}},r}(),Ry=function(){function r(e){var t=this;this.onMove=function(n){if(t.isDragging){var i=n.clientX||n.touches[0].clientX,o=n.clientY||n.touches[0].clientY;if(t.clickAllowed){var a=Math.abs(i-t.initialX),s=Math.abs(o-t.initialY);(a>t.dragThreshold||s>t.dragThreshold)&&(t.clickAllowed=!1)}t.animationFrameId&&cancelAnimationFrame(t.animationFrameId),t.animationFrameId=requestAnimationFrame(function(){var u=n.touches?n.touches[0].clientX:n.clientX,c=n.touches?n.touches[0].clientY:n.clientY,d=u-t.offsetX,f=c-t.offsetY,h=window.innerWidth-t.element.offsetWidth,g=window.innerHeight-t.element.offsetHeight;d=Math.max(0,Math.min(d,h)),f=Math.max(0,Math.min(f,g)),t.element.style.transform=`translate(
@@ -79,7 +79,7 @@ registerProcessor('vumeter', class extends AudioWorkletProcessor {
79
79
  cursor: pointer;
80
80
  z-index:100;
81
81
  background-size: 45px;
82
- }`,t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.appendChild(document.createTextNode(e)),t.appendChild(n);var i=document.createElement("div");i.innerHTML='<div id="debugger-applog-web" class="debugger-applog-web"></div>';var o=document.createElement("div");o.innerHTML='<div id="debugger-container" class="debugger-container"></div>',document.getElementsByTagName("body")[0].appendChild(i),document.getElementsByTagName("body")[0].appendChild(o);var a=document.getElementById("debugger-applog-web");new Ry(a)},r}(),Jo={autotrack:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/autotrack.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/autotrack.js"},object:"LogAutoTrack"},ab:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/ab.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/ab.js"},object:"LogAb"},stay:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/stay.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/stay.js"},object:"LogStay"},route:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/route.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/route.js"},object:"LogRoute"},tracer:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/tracer.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/tracer.js"},object:"LogTracer"},retry:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/retry.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/retry.js"},object:"LogRetry"},visual:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/visual.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/visual.js"},object:"LogVisual"}},Dy=["et","profile","heartbeat","monitor"],wr=function(){function r(e){this.disableAutoPageView=!1,this.bridgeReport=!1,this.staging=!1,this.pluginInstances=[],this.sended=!1,this.started=!1,this.destroy=!1,this.sdkReady=!1,this.adapters={},this.loadType="base",this.sdkStop=!1,this.name=e,this.hook=new Wv,this.remotePlugin=new Map,this.logger=new uy(e),this.Types=B,this.adapters.storage=Er}return r.usePlugin=function(e,t,n){if(t){for(var i=!1,o=0,a=r.plugins.length;o<a;o++)if(r.plugins[o].name===t){r.plugins[o].plugin=e,r.plugins[o].options=n||{},i=!0;break}i||r.plugins.push({name:t,plugin:e,options:n})}else r.plugins.push({plugin:e})},r.prototype.usePlugin=function(e,t,n){e&&(this.loadType==="full"&&Dy.includes(e)?console.info("your sdk version has "+e+" already ~"):t?typeof t=="string"?this.remotePlugin.get(e)||this.remotePlugin.set(e,{src:t,call:n}):this.remotePlugin.get(e)||this.remotePlugin.set(e,{instance:t}):this.remotePlugin.get(e)||this.remotePlugin.set(e,"sdk"))},r.prototype.init=function(e){var t,n=this;if(this.logger.enable(e.log),this.inited)this.logger.warn("[instance: "+this.name+"], every instance's api: init, can be call only one time!");else if(e&&nu(e))if(e.app_id&&typeof(t=e.app_id)=="number"&&!isNaN(t))if(!e.app_key||function(i){return typeof i=="string"}(e.app_key)){if(e.channel_domain||(e.report_channel!=="eu_ttp_ie"&&e.channel!=="ie"||this.logger.error("ie dc will be deprecated in the future, please use other dc instead"),e.report_channel&&!uu().has(e.report_channel)?(this.logger.warn("your report_channel: "+e.report_channel+" is not exist. report_channel must be one of "+No().join(",")+", use default report_channel: us_east instead, please check!!!"),e.report_channel="us_east"):e.report_channel||["sg","va","in","my","ie","ie2"].indexOf(e.channel)!==-1||(this.logger.warn("your channel: "+e.channel+" is not exist. use report_channel instead and report_channel must be one of "+No().join(",")+", use default report_channel: us_east instead, please check!!!"),e.report_channel="us_east"),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK set channel warning",level:"error",time:Date.now(),data:"your report_channel: "+e.channel+" is not exist. report_channel must be one of "+No().join(",")+", use us_east instead, please check!!!",infoType:"sdk"})),this.spider=new dy,this.spider.checkSpider(e))return this.logger.warn("The current environment may be a spider, can not report!"),void this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK hit spider",level:"error",time:Date.now(),data:"The current environment may be a spider, can not report!",infoType:"sdk"});this.appBridge=new ly(this,e.enable_native),this.configManager=new cy(this,e),this.requestManager=new zy(this,e),this.bridgeReport=this.appBridge.bridgeInject(),this.debugger=new Ay(this,e),this.initConfig=e,this.emit(B.Init),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Init",data:e,level:"info",time:Date.now(),infoType:"cus"}),e.disable_auto_pv&&(this.disableAutoPageView=!0),this.bridgeReport||(this.configManager.setAppid(e.app_id),this.eventManager=new fy,this.tokenManager=new py,this.sessionManager=new my,Promise.all([new Promise(function(i){n.once(B.TokenComplete,function(){i(!0)})}),new Promise(function(i){n.once(B.Start,function(){i(!0)})}),new Promise(function(i){n.once(B.LogSettingReady,function(){i(!0)})})]).then(function(){try{r.plugins.reduce(function(i,o){var a=o.plugin,s=o.options,u=Object.assign(n.initConfig,s);n.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Load "+o.name+" Plugin",level:"info",time:Date.now(),infoType:"sdk"});var c=new a;return c.apply(n,u),i.push(c),i},n.pluginInstances)}catch(i){console.warn("load plugin error, "+i.message),n.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Load Plugin Error",level:"error",time:Date.now(),data:i.message,infoType:"sdk"})}n.sdkReady=!0,n.emit(B.Ready),n.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK UserInfo Init Completed",time:Date.now(),secType:"USER",level:"info",data:n.configManager.get("user"),infoType:"sdk"}),n.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Initialization Completed",time:Date.now(),level:"info",data:n.configManager.get("user"),infoType:"sdk"}),n.logger.info("appid: "+e.app_id+", userInfo:"+JSON.stringify(n.configManager.get("user"))),n.logger.info("appid: "+e.app_id+", sdk is ready, version is 5.3.14_oversea, you can report now !!!"),e.disable_auto_pv&&(n.disableAutoPageView=!0);try{(n.loadType==="full"&&e.enable_ab_test||e.autotrack)&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")}catch(i){n.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"Something Error",level:"error",time:Date.now(),data:i.message,infoType:"sdk"})}n.pageView(),n.on(B.TokenChange,function(i){i==="webid"&&n.pageView(),n.logger.info("appid: "+e.app_id+" token change, new userInfo:"+JSON.stringify(n.configManager.get("user"))),n.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Set UserInfo",time:Date.now(),secType:"USER",level:"info",data:n.configManager.get("user"),infoType:"sdk"})}),n.on(B.TokenReset,function(){n.logger.info("appid: "+e.app_id+" token reset, new userInfo:"+JSON.stringify(n.configManager.get("user"))),n.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Reset UserInfo",time:Date.now(),secType:"USER",level:"info",data:n.configManager.get("user"),infoType:"sdk"})}),n.on(B.RouteChange,function(i){i.init||e.disable_route_report||n.pageView()})}),this.tokenManager.apply(this,e),this.eventManager.apply(this,e),this.sessionManager.apply(this,e)),this.inited=!0}else this.logger.warn("app_key param is error, must be string, please check!");else this.logger.warn("app_id param is error, must be number, please check!");else this.logger.warn("init params error,please check")},r.prototype.config=function(e){if(!this.inited)return console.warn("config must be use after function init"),void this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Config Error",level:"error",time:Date.now(),data:"config must be use after function init",infoType:"sdk"});if(!e||!nu(e))return console.warn("config params is error, please check"),void this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Config Error",level:"error",time:Date.now(),data:"config params is error, please check",infoType:"sdk"});var t;try{t=JSON.parse(JSON.stringify(t))}catch{t=e}if(this.bridgeReport)this.appBridge.setConfig(t);else{t._staging_flag&&t._staging_flag===1&&(this.staging=!0),t.disable_auto_pv&&(this.disableAutoPageView=!0,delete t.disable_auto_pv);var n=Le({},t);if(this.initConfig&&this.initConfig.configPersist){var i=this.configManager.getStore();i&&(n=Object.assign(i,t)),this.configManager.setStore(t)}n.web_id,n.user_unique_id,n.device_id;var o=function(a,s){var u={};for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&s.indexOf(c)<0&&(u[c]=a[c]);if(a!=null&&typeof Object.getOwnPropertySymbols=="function"){var d=0;for(c=Object.getOwnPropertySymbols(a);d<c.length;d++)s.indexOf(c[d])<0&&(u[c[d]]=a[c[d]])}return u}(n,["web_id","user_unique_id","device_id"]);n.hasOwnProperty("web_id")&&this.emit(B.ConfigWebId,n.web_id),n.hasOwnProperty("user_unique_id")&&this.emit(B.ConfigUuid,n.user_unique_id),n.hasOwnProperty("device_id")&&this.emit(B.ConfigDiD,n.device_id),this.configManager.set(o),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Config",level:"info",time:Date.now(),data:n,infoType:"cus"})}},r.prototype.setDomain=function(e){this.configManager&&this.configManager.setDomain(e),this.emit(B.ConfigDomain)},r.prototype.getConfig=function(e){return this.configManager.get(e)},r.prototype.send=function(){this.start()},r.prototype.start=function(){this.inited&&!this.sended&&(this.sended=!0,this.emit(B.Start),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Start",level:"info",time:Date.now(),infoType:"cus"}),this.bridgeReport&&(this.pageView(),this.emit(B.Ready)))},r.prototype.event=function(e,t){var n=this;try{var i=[];if(Array.isArray(e))e.forEach(function(a){var s=n.processEvent(a[0],a[1]||{});s&&i.push(s)});else{var o=this.processEvent(e,t);if(!o)return;i.push(o)}this.bridgeReport?i.forEach(function(a){var s=a.event,u=a.params;n.appBridge.onEventV3(s,JSON.stringify(u))}):i.length&&(this.emit(B.Event,i),this.emit(B.SessionResetTime)),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Event",level:"info",time:Date.now(),data:e,infoType:"cus"})}catch(a){this.logger.warn("something error, please check"),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Event Something Error",level:"error",time:Date.now(),data:a.message,infoType:"sdk"})}},r.prototype.beconEvent=function(e,t){if(Array.isArray(e))return this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK BeconEvent Error",level:"error",time:Date.now(),data:"beconEvent not support batch report, please check",infoType:"sdk"}),void this.logger.warn("beconEvent not support batch report, please check");var n=[],i=this.processEvent(e,t||{});i&&(n.push(i),n.length&&(this.emit(B.BeconEvent,n),this.emit(B.SessionResetTime)),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Beacon Event",level:"info",time:Date.now(),data:e,infoType:"sdk"}))},r.prototype.beaconEvent=function(e,t){this.beconEvent(e,t)},r.prototype.processEvent=function(e,t){t===void 0&&(t={});try{if(!e)return console.warn("eventName is null, please check"),null;var n=e;/^event\./.test(e)&&(n=e.slice(6));var i=t;typeof i!="object"&&(i={}),i.profile?delete i.profile:i.event_index=Jv();var o=void 0;return i.local_ms?(o=i.local_ms,delete i.local_ms):o=+new Date,{event:n,params:i,local_time_ms:o,is_bav:this.initConfig&&this.initConfig.autotrack?1:0}}catch(a){return this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:a.message,infoType:"sdk"}),{event:e,params:t}}},r.prototype.filterEvent=function(e){this.eventFilter=e},r.prototype.on=function(e,t){this.hook.on(e,t)},r.prototype.once=function(e,t){this.hook.once(e,t)},r.prototype.off=function(e,t){this.hook.off(e,t)},r.prototype.emit=function(e,t,n){this.hook.emit(e,t,n)},r.prototype.set=function(e){this.hook.set(e)},r.prototype.stop=function(){this.sdkStop=!0},r.prototype.reStart=function(){this.sdkStop=!1},r.prototype.pageView=function(){this.disableAutoPageView||this.predefinePageView()},r.prototype.predefinePageView=function(e){if(e===void 0&&(e={}),this.inited){var t={title:document.title||location.pathname,url:location.href,url_path:location.pathname,time:Date.now(),referrer:window.document.referrer,$is_first_time:""+(this.configManager&&this.configManager.is_first_time||!1)},n=Le(Le({},t),e);this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Report PV",level:"info",time:Date.now(),infoType:"sdk"}),this.event("predefine_pageview",n)}else console.warn("predefinePageView should call after init")},r.prototype.enableTransPort=function(){this.configManager.setEnableClientTransport(!0)},r.prototype.disableTransPort=function(){this.configManager.setEnableClientTransport(!1)},r.prototype.clearEventCache=function(){this.emit(B.CleanEvents)},r.prototype.setWebId=function(e){this.config({web_id:""+e})},r.prototype.setNativeAppId=function(e){this.bridgeReport&&this.appBridge.setNativeAppId(e)},r.prototype.getSessionId=function(){return pn()},r.prototype.setSessionId=function(e){this.emit(B.SessionReset,e)},r.prototype.resetStayDuration=function(e,t,n){this.emit(B.ResetStay,{url_path:e,title:t,url:n},B.Stay)},r.prototype.resetStayParams=function(e,t,n){e===void 0&&(e=""),t===void 0&&(t=""),n===void 0&&(n=""),this.emit(B.SetStay,{url_path:e,title:t,url:n},B.Stay)},r.prototype.getToken=function(e,t){var n=this;if(this.inited){var i=!1,o=function(s){if(!i){i=!0;var u=n.configManager.get().user;return s&&(u.tobid=s,u["diss".split("").reverse().join("")]=s),e(Le({},u))}},a=function(){n.tokenManager.getTobId().then(function(s){o(s)})};this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute GetToken",level:"info",time:Date.now(),infoType:"cus"}),this.sdkReady?a():(t&&setTimeout(function(){o()},t),this.on(B.Ready,function(){a()}))}else console.warn("predefinePageView should call after init")},r.prototype.startTrackEvent=function(e){e&&this.emit(B.TrackEventDurationStart,e,B.TrackEventDuration)},r.prototype.endTrackEvent=function(e,t){t===void 0&&(t={}),e&&this.emit(B.TrackEventDurationEnd,{eventName:e,params:t},B.TrackEventDuration)},r.prototype.pauseTrackEvent=function(e){e&&this.emit(B.TrackEventDurationPause,e,B.TrackEventDuration)},r.prototype.resumeTrackEvent=function(e){e&&this.emit(B.TrackEventDurationResume,e,B.TrackEventDuration)},r.prototype.profileSet=function(e){this.bridgeReport?this.appBridge.profileSet(JSON.stringify(e)):this.emit(B.ProfileSet,e,B.Profile),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileSet",level:"info",time:Date.now(),data:e})},r.prototype.profileSetOnce=function(e){this.bridgeReport?this.appBridge.profileSetOnce(JSON.stringify(e)):this.emit(B.ProfileSetOnce,e,B.Profile),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileSetOnce",level:"info",time:Date.now(),data:e})},r.prototype.profileIncrement=function(e){this.bridgeReport?this.appBridge.profileIncrement(JSON.stringify(e)):this.emit(B.ProfileIncrement,e,B.Profile),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileIncrement",level:"info",time:Date.now(),data:e})},r.prototype.profileUnset=function(e){this.bridgeReport?this.appBridge.profileUnset(e):this.emit(B.ProfileUnset,e,B.Profile),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileUnset",level:"info",time:Date.now(),data:e})},r.prototype.profileAppend=function(e){this.bridgeReport?this.appBridge.profileAppend(JSON.stringify(e)):this.emit(B.ProfileAppend,e,B.Profile),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileAppend",level:"info",time:Date.now(),data:e})},r.prototype.setExternalAbVersion=function(e){this.emit(B.AbExternalVersion,typeof e=="string"&&e?(""+e).trim():null,B.Ab)},r.prototype.getVar=function(e,t,n,i){this.emit(B.AbVar,{name:e,defaultValue:t,callback:n,uuid:i},B.Ab)},r.prototype.getABconfig=function(e,t){this.emit(B.AbConfig,{params:e,callback:t},B.Ab)},r.prototype.getABConfig=function(e,t){this.emit(B.AbConfig,{params:e,callback:t},B.Ab)},r.prototype.getAbSdkVersion=function(){return this.configManager.getAbVersion()},r.prototype.onAbSdkVersionChange=function(e){var t=this;return this.emit(B.AbVersionChangeOn,e,B.Ab),function(){t.emit(B.AbVersionChangeOff,e,B.Ab)}},r.prototype.offAbSdkVersionChange=function(e){this.emit(B.AbVersionChangeOff,e,B.Ab)},r.prototype.openOverlayer=function(){this.emit(B.AbOpenLayer,"",B.Ab)},r.prototype.closeOverlayer=function(){this.emit(B.AbCloseLayer,"",B.Ab)},r.prototype.getAllVars=function(e,t){this.emit(B.AbAllVars,{callback:e,timeout:t},B.Ab)},r.prototype.destoryInstace=function(){this.destroy||(this.destroy=!0,this.off(B.TokenComplete),this.emit(B.DestoryInstance))},r.prototype.destroyInstance=function(){this.destroy||(this.destroy=!0,this.off(B.TokenComplete),this.emit(B.DestoryInstance))},r.plugins=[],r}(),Iy=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,t.event_verify_url)if(typeof t.event_verify_url=="string"){if(this.url=t.event_verify_url+"/v1/list_test",this.url){var i=e.Types;e.on(i.SubmitVerify,function(o){n.verify(o)}),e.on(i.AbVerify,function(o){n.verify(o)})}}else console.log("please use correct et_test url")},r.prototype.verify=function(e){var t=this;e.forEach(function(n){try{var i=JSON.parse(JSON.stringify(n));t.config.filter&&((i=t.config.filter(i))||console.warn("filter must return data !!")),t.collect.eventFilter&&i&&((i=t.collect.eventFilter(i))||console.warn("filterEvent api must return data !!"));var o=i||n,a=JSON.parse(JSON.stringify(o));if(!o.length)return;var s=!0;if(o.forEach(function(u){u.events.length||(s=!1)}),!s)return;t.collect.requestManager.useBeacon({url:t.url,data:o}),t.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_EVENT,info:"SDK Report ByteIo Verify Request",time:Date.now(),data:a,code:200,status:"success",verifyType:!0})}catch(u){console.warn("something error, "+JSON.stringify(u.stack)),t.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Report ByteIo Verify Request Error",level:"error",time:Date.now(),data:u.message})}})},r}(),xy=function(){function r(){var e=this;this.setInterval=function(){e.clearIntervalFunc=function(t,n){t===void 0&&(t=function(){}),n===void 0&&(n=1e3);var i,o=Date.now()+n;return i=window.setTimeout(function a(){var s=Date.now()-o;t(),o+=n,i=window.setTimeout(a,Math.max(0,n-s))},n),function(){window.clearTimeout(i)}}(function(){e.isSessionhasEvent&&e.endCurrentSession()},e.sessionInterval)},this.clearInterval=function(){e.clearIntervalFunc&&e.clearIntervalFunc()}}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,!t.disable_heartbeat){this.sessionInterval=6e4,this.startTime=0,this.lastTime=0,this.setInterval();var i=this.collect.Types;this.collect.on(i.SessionReset,function(){n.process()})}},r.prototype.endCurrentSession=function(){this.collect.event("_be_active",{start_time:this.startTime,end_time:this.lastTime,url:window.location.href,referrer:window.document.referrer,title:document.title||location.pathname}),this.isSessionhasEvent=!1,this.startTime=0},r.prototype.process=function(){this.isSessionhasEvent||(this.isSessionhasEvent=!0,this.startTime=+new Date);var e=this.lastTime||+new Date;this.lastTime=+new Date,this.lastTime-e>this.sessionInterval&&(this.clearInterval(),this.endCurrentSession(),this.setInterval())},r}(),My=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,!this.config.channel_domain&&!t.disable_track_event&&!t.disable_sdk_monitor){this.url=e.configManager.getUrl("event");var i=this.collect.Types;this.collect.on(i.Ready,function(){n.sdkOnload()}),this.collect.on(i.SubmitError,function(o){var a=o.type,s=o.eventData,u=o.errorCode,c=o.response;a==="f_data"&&n.sdkError(s,u,c)}),this.collect.on(e.Types.SDKInnerError,function(o){var a=o.type,s=o.eventData,u=o.errorCode,c=o.msg;n.sdkInnerError(a,s,u,c)})}},r.prototype.sdkOnload=function(){var e=this;try{var t=this.collect.configManager.get(),n=t.header,i=t.user,o=n.app_id,a=n.app_name,s=n.sdk_version,u=(i.web_id,{events:[{event:"onload",params:JSON.stringify({app_id:o,app_name:a||"",sdk_version:s,sdk_type:"npm",sdk_config:this.config,sdk_desc:"TOC_OVERSEA",url:location.href,is_setting:this.config.enable_logsetting||!1,enable_logsetting_params:this.config.enable_logsetting_params||!1,enable_logsetting_header_custom:this.config.enable_logsetting_header_custom||!1}),local_time_ms:Date.now()}],user:{user_unique_id:i.user_unique_id},header:{app_id:6656}});setTimeout(function(){e.collect.requestManager.useXhr({url:e.url,data:[u],timeout:3e4})},16)}catch{}},r.prototype.sdkError=function(e,t,n){var i=this;try{var o=e[0],a=o.user,s=o.header,u=[];e.forEach(function(d){d.events.forEach(function(f){u.push(f)})});var c={events:u.map(function(d){return{event:"on_error",params:JSON.stringify({type:"sdk_event_error",error_code:t,app_id:s.app_id,app_name:s.app_name||"",error_event:d.event,sdk_version:s.sdk_version,local_time_ms:d.local_time_ms,tea_event_index:Date.now(),params:d.params,header:s,user:a,err_msg:n.m||""}),local_time_ms:Date.now()}}),user:{user_unique_id:a.user_unique_id},header:{app_id:6656}};setTimeout(function(){i.collect.requestManager.useXhr({url:i.url,data:[c],timeout:3e4})},16)}catch{}},r.prototype.sdkInnerError=function(e,t,n,i){var o=this;try{var a=t[0],s=a.user,u=a.header,c=[];t.forEach(function(f){f.events.forEach(function(h){c.push(h)})});var d={events:c.map(function(f){return{event:"on_error",params:JSON.stringify({type:e,error_code:n,app_id:u.app_id,app_name:u.app_name||"",error_event:f.event,sdk_version:u.sdk_version,local_time_ms:f.local_time_ms,tea_event_index:Date.now(),params:f.params,header:u,user:s,ua:window.navigator.userAgent,err_msg:i}),local_time_ms:Date.now()}}),user:s,header:{}};setTimeout(function(){o.collect.requestManager.useXhr({url:o.url,data:[d],timeout:3e4,app_key:"566f58151b0ed37e"})},16)}catch{}},r}(),Xo=typeof window<"u"?(window.LogPluginObject||(window.LogPluginObject={}),window.LogPluginObject):null,Oy=function(){function r(){}return r.prototype.apply=function(e,t){this._plugin={},this.config=t,this.collect=e,this.channel="va",this.loadExtend()},r.prototype.loadExtend=function(){var e=this;try{this.collect.remotePlugin.forEach(function(t,n){if(t==="sdk")if(Jo.hasOwnProperty(n)){var i=Jo[n].object,o=""+Jo[n].src[e.channel];e.exist(n,i,o)}else console.warn("your "+n+" is not exist,please check plugin name");else typeof t=="object"&&(t.src?e.exist(n,t.call,t.src):e.process(n,t.instance,"INSTANCE"))})}catch(t){this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"LoadExtend Fail",level:"error",time:Date.now(),data:t.message}),console.log("load extend error")}},r.prototype.exist=function(e,t,n){var i=this;Xo[t]?(this.process(e,Xo[t]),console.log("already has "+e+" plugin~")):this.loadPlugin(e,n,function(){i.process(e,Xo[t]),console.log(" %c %s %s %s","color: yellow; background-color: black;","–","load plugin:"+e+" success","-")},function(){console.log(" %c %s %s %s","color: red; background-color: yellow;","–","load plugin:"+e+" error","-")})},r.prototype.process=function(e,t,n){try{if(n){var i=new t;i.apply&&i.apply(this.collect,this.config),console.log("excude "+e+" success")}else t&&t(this.collect,this.config)}catch(o){this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"Extend Process Fail",level:"error",time:Date.now(),data:o.message}),console.log("excude "+e+" error, message:"+o.message)}},r.prototype.loadPlugin=function(e,t,n,i){var o=this;try{var a=document.createElement("script");a.src=t,this._plugin[e]||(this._plugin[e]=[]),this._plugin[e].push(n),a.onerror=function(){i(t)},a.onload=function(){o._plugin[e].forEach(function(s){s()})},document.getElementsByTagName("head")[0].appendChild(a)}catch(s){this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"Extend LoadPlugin Fail",level:"error",time:Date.now(),data:s.message})}},r}();wr.usePlugin(Oy,"extend"),wr.usePlugin(Iy,"et"),wr.usePlugin(xy,"heartbeat"),wr.usePlugin(My,"monitor"),new wr("default");var Py=wr;class Cr{constructor({userId:e}){this.collector=new Py("media-engine-logger"),this.collector.init({app_id:834499,channel:"cn",disable_sdk_monitor:!0}),this.collector.config({user_unique_id:e||"media-engine",evtParams:{sdk_version:"1.0.0"}}),this.collector.start()}static getInstance({userId:e}){return Cr.instance||(Cr.instance=new Cr({userId:e})),Cr.instance}event(e,t){this.collector.event(e,t||{})}}class Ly extends $v{constructor({userId:e}){super(qv),this.logger=Cr.getInstance({userId:e})}receiveWorkerMessage({type:e,data:t}){switch(e){case st.PassEngineEvent:{const n=t.event,i=t.data;this.emit(n,i)}break;case st.GetStats:this.emit("_receive_stats",t);break}}start(e){const{video:t}=e,{audio:n}=e;delete e.video,delete e.audio,this.sendTransportable({type:st.Start,data:e},{video:t,audio:n}),this.logger.event("pusher_engine_start")}stop(){this.sendMessage({type:st.Stop}),this.logger.event("pusher_engine_stop")}updateTrack(e,t,n){this.sendTransportable({type:st.UpdateTrack,data:{isAudio:t==="audio",setting:n}},{stream:e}),this.logger.event("pusher_engine_update_track",{type:t,setting:n})}setBitrate(e,t){this.sendMessage({type:st.SetBitrate,data:{bitrate:e,type:t}}),this.logger.event("pusher_engine_set_bitrate",{bitrate:e,type:t})}online(){this.sendMessage({type:st.Online})}reconnect(e){this.sendMessage({type:st.Reconnect,data:{url:e}}),this.logger.event("pusher_engine_reconnect",{url:e})}async getStats(){this.sendMessage({type:st.GetStats});const[e]=await this.onWait("_receive_stats");return e}destroy(){super.destroy(),this.stop()}}function wu(r){let e=!0,t="";for(const n of r)if(!(n in window)){e=!1,t=`${n} not Supported`;break}return{supported:e,info:t}}const Uy=24*60*60*1e3;function Cu(r,e="1d"){const t=`_me_expire_${r}`;let n=0;if(typeof e=="string"){if(!/^[0-9]+d$/.test(e))throw new Error("expire format error");n=Uy*parseInt(e)}else n=e;return{get(){const i=localStorage.getItem(t);if(!i)return null;let o=null;try{o=JSON.parse(i)}catch{return null}const{value:a,expire:s}=o;return s<Date.now()?(localStorage.removeItem(t),null):a},set(i){localStorage.setItem(t,JSON.stringify({value:i,expire:Date.now()+n}))},remove(){localStorage.removeItem(t)}}}var He=(r=>(r[r.AAC=0]="AAC",r[r.OPUS=1]="OPUS",r[r.H264=2]="H264",r[r.H265=3]="H265",r[r.AV1=4]="AV1",r))(He||{});He.AAC+"",He.OPUS+"",He.H264+"",He.H265+"",He.AV1+"";const Zn={[He.AAC]:"mp4a.40.2",[He.OPUS]:"opus",[He.H264]:"avc1.4DE033",[He.H265]:"hev1.1.6.L93.B0"};function ku(r){const e=new MediaStreamTrackProcessor(r),{readable:t}=e,n=r.getSettings();return{readable:t,settings:n}}const Zo=Cu("audio_encoder_support","3d");function Gy(){return wu(["EncodedAudioChunk","AudioEncoder","AudioData"])}function Ny(r){const e=Zo.get(),t=`${r}_support`;return e&&e[t]?e[t]:null}function By(r,e){const t=Zo.get()||{},n=`${r}_support`;t[n]=e,Zo.set(t)}async function Fy(r){if(!AudioEncoder.isConfigSupported)return{supported:!1,info:"isConfigSupported method is undefined"};try{const e={codec:r,sampleRate:48e3,numberOfChannels:2,bitrate:128e3},t=await AudioEncoder.isConfigSupported(e);return t.supported!==void 0?{supported:t.supported,info:t.supported?"isConfigSupported: true":"isConfigSupported: false"}:{supported:!1,info:"isConfigSupported returned undefined"}}catch{return{supported:!1,info:"isConfigSupported method throws error"}}}async function Tu(r){const e=Ny(r);if(e)return console.log(`Audio encoder ${r} support result from cache:`,e),e;const t=await Fy(r);return By(r,t),t}function Vy(){return Tu(Zn[He.OPUS])}function jy(){return Tu(Zn[He.AAC])}const Yo=Cu("video_encoder_support","3d");function Qo(){return wu(["EncodedVideoChunk","VideoEncoder","VideoFrame"])}function zu(r){const e=Yo.get(),t=`${r}_support`;return e&&e[t]?e[t]:null}function es(r,e){const t=Yo.get()||{},n=`${r}_support`;t[n]=e,Yo.set(t)}async function Ru(r){if(!VideoEncoder.isConfigSupported)return{supported:!1,info:"isConfigSupported method is undefined"};try{const e={codec:r,width:640,height:480,bitrate:1e6,framerate:30},t=await VideoEncoder.isConfigSupported(e);return{supported:t.supported??!1,info:t.supported?"isConfigSupported: true":"isConfigSupported: false"}}catch(e){return{supported:!1,info:`isConfigSupported error: ${e instanceof Error?e.message:String(e)}`}}}async function Hy(r,e=3e3){return new Promise(t=>{let n=!1;const i=setTimeout(()=>{n||(n=!0,t({supported:!1,info:"encoding test timeout"}))},e);try{const o=new VideoEncoder({output:h=>{n||(n=!0,clearTimeout(i),o.state!=="closed"&&o.close(),t({supported:!0,info:"encoding test success"}))},error:h=>{n||(n=!0,clearTimeout(i),o.state!=="closed"&&o.close(),t({supported:!1,info:`encoding test error: ${h.message}`}))}}),a={codec:r,width:640,height:480,bitrate:1e6,framerate:30};o.configure(a);const s=640,u=480,c=new OffscreenCanvas(s,u),d=c.getContext("2d");d&&(d.fillStyle="#FF0000",d.fillRect(0,0,s,u));const f=new VideoFrame(c,{timestamp:0});o.encode(f)}catch(o){n||(n=!0,clearTimeout(i),t({supported:!1,info:`encoding test catch: ${o.message}`}))}})}async function $y(r){if(!Qo())return{supported:!1,info:"VideoEncoder API not supported"};const e=zu(r);if(e)return console.log(`Video encoder ${r} support result from cache:`,e),e;const t=await Ru(r);return es(r,t),t}async function qy(r,e=3e3){if(!Qo())return{supported:!1,info:"VideoEncoder API not supported"};const t=zu(r);if(t)return console.log(`Video encoder ${r} support result from cache:`,t),t;const n=await Ru(r);if(!n.supported)return es(r,n),n;const i=await Hy(r,e);return es(r,i),i}function Ky(){return $y(Zn[He.H264])}function Wy(){return qy(Zn[He.H265])}function Jy(){return Gy().supported}function Xy(){return Qo().supported}async function Zy(r){if(!Jy())return{supported:!1,info:"AudioEncoder API not supported"};try{switch(r){case"aac":return await jy();case"opus":return await Vy();default:return{supported:!1,info:`Unsupported audio codec: ${r}`}}}catch(e){return{supported:!1,info:`${r} 检测失败: ${e instanceof Error?e.message:String(e)}`}}}async function Yy(r){if(!Xy())return{supported:!1,info:"VideoEncoder API not supported"};try{switch(r){case"h264":return await Ky();case"h265":return await Wy();default:return{supported:!1,info:`Unsupported video codec: ${r}`}}}catch(e){return{supported:!1,info:`${r} 检测失败: ${e instanceof Error?e.message:String(e)}`}}}async function Qy(r,e=!1){const t=["aac"],n=["h264"],i={audioCodecs:{},videoCodecs:{}};for(const f of t)i.audioCodecs[f]=await Zy(f);for(const f of n)i.videoCodecs[f]=await Yy(f);const o=[],a=[],s=[],u=[];Object.entries(i.audioCodecs).forEach(([f,h])=>{h.supported?o.push(f):a.push(f)}),Object.entries(i.videoCodecs).forEach(([f,h])=>{h.supported?s.push(f):u.push(f)});const d={supported:a.length===0&&u.length===0,supportedAudio:o,supportedVideo:s,unsupportedAudio:a,unsupportedVideo:u};return e&&(d.details=i),d}async function eS(){return(await Qy()).supported}class Au{constructor(e,t,n,i,o){this.url=e,this.config=t,this.onError=n,this.onSuccess=i,this.onReconnectError=o,this._isPushing=!1,this._clearOnline=()=>{},this.sessionId=Date.now(),this.engine=new Ly({userId:ht.instance.userId??""});const a=()=>{this.engine.online()};window.addEventListener("online",a),this._clearOnline=()=>{window.removeEventListener("online",a)}}static async isSupported(){return await eS()&&typeof WebTransport<"u"&&typeof MediaStreamTrackProcessor<"u"&&typeof MediaStreamTrackGenerator<"u"&&typeof VideoEncoder<"u"}get isPushing(){return this._isPushing}get pushUrl(){return this.url}async getStatsSnapshoot(e){e&&await hn(e);const{video:t,audio:n,upspeed:i}=await this.engine.getStats();return{stats:{video:{sendBitrate:t.bitrate,framesPerSecond:t.framerate,framesEncoded:t.encodedFrames,keyFramesEncoded:t.encodedKeyFrames,sendSpeed:i,codec:t.codec,frameWidth:t.width,frameHeight:t.height,gopSize:t.keyGopSize},audio:{sendBitrate:n.bitrate,framesEncoded:n.encodedFrames,codec:n.codec,channels:n.numberOfChannels,sampleRate:n.sampleRate}},originStats:void 0}}async publish(e,t,n){const i={url:this.url,maxReconnectCount:10,autoReconnect:!1,bitrate:{},cfg:Object.assign({gopSize:90},(n==null?void 0:n.cfg)||{}),setting:{}};e.forEach((o,a)=>{if(o.kind==="video"||o.kind==="audio"){const s=ku(o);i[o.kind]=s.readable,i.bitrate[o.kind]=t[a],i.setting[o.kind]=s.settings}}),this.engine.start(i),this._isPushing=!0,this.engine.on({"connect-open":()=>{this._isPushing=!0,this.onSuccess()},error:o=>{this.onError(new Error(JSON.stringify(o)))},"connect-close":o=>{this._isPushing=!1,o==="api call"?console.log("Connection close by api call"):this.onError(new Error(`Connect close, reason=${o}`))},"reconnect-fail":o=>{this._isPushing=!1,this.onReconnectError(new Error(`Reconnect fail, reason=${o}`))}})}unpublish(){this.engine.stop(),this._isPushing=!1}async updatePublish(e,t){e&&this.engine.updateTrack(ku(e).readable,t)}applyBitrate(e,t){this.engine.setBitrate(e,t)}reconnect(e){this.engine.reconnect(e)}destroy(){this._clearOnline(),this.engine.destroy(),this._isPushing=!1}}function Du({pushUrl:r,addPri:e=!1,disableTCC:t=!1}){const n=new URL(r),i=Date.now();return e&&n.searchParams.set("pri",i.toString()),t&&n.searchParams.set("tcc","false"),n.href}class tS{constructor(e,t=Fm){this._reconnectDelay=0,this._reconnectCount=0,this._timeoutTimerId=null,this._reconnectTimeout=null,this._totalReconnectInfo={totalReconnectCount:0,totalReconnectDuration:0},this.handleOnlineReconnect=()=>{this.execute(!0)},this.execute=(n=!1)=>{var i;this._logger.log("start reconnect strategy"),this.state==="idle"&&(this._reconnectStartTime=Date.now(),this._totalReconnectInfo.totalReconnectCount+=1,X(J.PUSH_RECONNECT_START,{start_time:this._reconnectStartTime,session_id:this._pushConsumer.pushSessionId,max_timeout:this._maxTimeout}),this.bindOnlineEvent(),this.setStrategyState("executing"),(i=this._logger)==null||i.log("start reconnecting with max timeout: ",this._maxTimeout),this.startTimeoutTimer(this._maxTimeout),this._pushConsumer.emitReconnectStateChange({state:cr.START,teaParams:{is_online:navigator.onLine,start_time:this._reconnectStartTime,max_timeout:this._maxTimeout,session_id:this._pushConsumer.pushSessionId}})),this.state==="executing"&&(this._reconnectTimeout&&clearTimeout(this._reconnectTimeout),this.executeStrategy(n))},this.attemptReconnect=async()=>{var n;if(this.state==="executing"){this.setStrategyState("reconnecting"),this._reconnectCount+=1;const i=this.getNextPushUrl();try{if(this._pushConsumer.emitReconnectStateChange({state:cr.RECONNECTING,params:{retryTime:this._reconnectCount},teaParams:{retry_push_url:i,session_id:this._pushConsumer.pushSessionId}}),await this._pushConsumer.reconnect(i),!this.isActive())return;this.setStrategyState("executing")}catch(o){const a=o.ext||{},{httpCode:s}=a;if(s!==void 0&&String(s).startsWith("4"))this.stop({isSuccess:!1,reason:si.PushUrlInvalid,failedError:o}),(n=this._onReconnectError)==null||n.call(this,"pushError",o);else{if(!this.isActive())return;this.setStrategyState("executing"),this.execute()}}}},this.executeStrategy=(n=!1)=>{const i=n?0:this._reconnectDelay;this._pushConsumer.emitReconnectStateChange({state:cr.WAITING,params:{waitingTime:i,retryTime:this._reconnectCount+1},teaParams:{is_online:navigator.onLine,session_id:this._pushConsumer.pushSessionId}}),this._logger.log("reconnect after delay: ",i,Date.now()),this._reconnectTimeout=window.setTimeout(this.attemptReconnect,i),this._reconnectDelay=this._reconnectDelay===0?2e3:Math.min(this._reconnectDelay*2,Vm)},this.state="idle",this._pushConsumer=e,this._maxTimeout=t,this._logger=new Bt("ReconnectStrategy")}getNextPushUrl(){const e=this._pushConsumer.pushUrl;return e?Du({pushUrl:e,addPri:!0}):""}set onReconnectError(e){this._onReconnectError=e}bindOnlineEvent(){window.addEventListener("online",this.handleOnlineReconnect)}unbindOnlineEvent(){window.removeEventListener("online",this.handleOnlineReconnect)}setStrategyState(e){this._logger.log("reconnect state change to: ",e),this.state=e}stop({isSuccess:e,reason:t,quiet:n=!1,failedError:i}){var a;if(this.state==="idle")return;const o=(Date.now()-this._reconnectStartTime)/1e3;n||(e?this._pushConsumer.emitReconnectStateChange({state:cr.SUCCESS,teaParams:{reconnect_duration:o,session_id:this._pushConsumer.pushSessionId}}):(this._logger.log("Reconnect strategy stopped: ",t),this._pushConsumer.emitReconnectStateChange({state:cr.FAILED,params:{failedCode:t},teaParams:{reason:t,reconnect_duration:o,error_message:i==null?void 0:i.message,http_code:(a=i==null?void 0:i.ext)==null?void 0:a.httpCode,ext:i==null?void 0:i.ext,session_id:this._pushConsumer.pushSessionId}})),this._totalReconnectInfo.totalReconnectDuration+=o),this.setStrategyState("idle"),this._timeoutTimerId&&clearTimeout(this._timeoutTimerId),this._reconnectTimeout&&clearTimeout(this._reconnectTimeout),this._reconnectDelay=0,this._reconnectCount=0,this._reconnectStartTime=void 0,this.unbindOnlineEvent()}startTimeoutTimer(e){this._timeoutTimerId=window.setTimeout(()=>{var t;this.state!=="idle"&&(this._logger.log("Reconnect strategy timed out"),this.stop({isSuccess:!1,reason:si.ReconnectTimeout}),(t=this._onReconnectError)==null||t.call(this,"timeout"))},e)}clearReconnectInfo(){this._totalReconnectInfo={totalReconnectCount:0,totalReconnectDuration:0}}getReconnectInfo(){return this._totalReconnectInfo}isActive(){return this.state!=="idle"}}const vn={ManualStop:0,ReconnectFailed:1,StartPushError:2,PushError:3},kr={PushCheck:0,PushError:1},Iu=new Bt("PushController");class rS extends Nc{constructor(e,{config:t,streamConsumeController:n,streamComposedController:i}){var o,a;if(super(e),this._connect=null,this._connectionState=$e.DISCONNECTED,this._pushSessionId=0,this._isReportStart=!1,this._pushMode="rtm",this._reconnectStrategy=null,this._needCheckAudioTrack=!1,this._pushConfig={timeout:5e3,retryCount:1,retryDelay:1e3},this._audioBitrate=pr(ys,"audio").bitrate,this._videoBitrate=pr(vs,"video").bitrate,this.handleReconnectError=(s,u)=>{var c,d;X(J.STOP_PUSH_STREAM,{reason:vn.ReconnectFailed,error_message:s,session_id:this._pushSessionId,push_mode:this._pushMode,duration:this.pushDuration,reconnect_times:(c=this._reconnectStrategy)==null?void 0:c.getReconnectInfo().totalReconnectCount,reconnect_duration:(d=this._reconnectStrategy)==null?void 0:d.getReconnectInfo().totalReconnectDuration}),this.unpublish()},this.handleAudioStreamChange=s=>{this.updatePush({audioTrack:s.audioTrack})},this.handleVideoStreamChange=s=>{this.updatePush({videoTrack:s.videoTrack})},this._OnRTMPSuccess=()=>{this.setConnectState($e.CONNECTED)},this._OnMediaReconnectFailed=()=>{this._executeReconnect()},this._OnRTMPError=s=>{const u=new fr(qe.PUBLISH_FAILED,`${s.code?`code:${s.code},`:""} message: ${s.message}`);this.pushDuration<jm||!this._reconnectStrategy||this.pushMode==="webTransport"?(this._streamConsumeController.emit(Ee.PushError,u),X(J.STOP_PUSH_STREAM,{reason:vn.PushError,duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode,error_msg:s.message,error_code:s.code}),X(J.START_PUSH_STATUS,{is_success:!1,reason:kr.PushError,error_message:s.message,session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish()):this._executeReconnect()},this._executeReconnect=()=>{var s;(s=this._reconnectStrategy)==null||s.execute(),this.setConnectState($e.RECONNECTING),this.unpublish({isReconnecting:!0})},this._OnRtcStateChange=s=>{var u;switch(X(J.PUSH_RTC_STATE_CHANGE,{state:s,push_url:this._pushUrl,session_id:this._pushSessionId,push_mode:this._pushMode}),this._streamConsumeController.emit(Ee.RTCConnectStateChanged,s),s){case"connected":this.setConnectState($e.CONNECTED);break;case"disconnected":this._reconnectStrategy&&this._executeReconnect();break;case"failed":(u=this._reconnectStrategy)!=null&&u.isActive()?this._executeReconnect():(this.connectionState===$e.CONNECTED?X(J.STOP_PUSH_STREAM,{reason:vn.PushError,error_message:"peerconnection failed",duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode}):X(J.START_PUSH_STATUS,{is_success:!1,reason:kr.PushError,error_message:"peerconnection failed",session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish(),this._streamConsumeController.emit(Ee.PushError,new fr(qe.PUSH_CONNECT_FAILED,"pc failed")));break}},this._pushMode=(t==null?void 0:t.mode)||"rtm",this._streamConsumeController=n,t&&(this._pushConfig=t,this._needCheckAudioTrack=t.checkAudio??!1),(o=t==null?void 0:t.reconnectConfig)!=null&&o.enable||!(t!=null&&t.reconnectConfig)){const s=(a=t==null?void 0:t.reconnectConfig)!=null&&a.maxTimeout?t.reconnectConfig.maxTimeout*Pi:void 0;this._reconnectStrategy=new tS(this,s),this._reconnectStrategy.onReconnectError=this.handleReconnectError}this._streamComposedController=i}get isPushing(){return this._connectionState===$e.CONNECTED||this._connectionState===$e.RECONNECTING}get pushUrl(){return this._pushUrl}get pushEncodeConfig(){return this._pushEncodeConfig}get sessionId(){var e;return((e=this._connect)==null?void 0:e.sessionId)||0}start(){this.bindComposedStreamEvent()}stop(){this.unbindComposedStreamEvent()}setPushConfig(e){e&&(this._pushConfig=e)}setConnectState(e){var t;switch(this._connectionState=e,this._streamConsumeController.emit(Ee.LiveConnectStateChange,e),e){case $e.CONNECTED:(t=this._reconnectStrategy)!=null&&t.isActive()?this._reconnectStrategy.stop({isSuccess:!0}):(this._streamConsumeController.emit(Ee.PushStart),this.setPushStatsInterval(),X(J.START_PUSH_STATUS,{is_success:!0,push_url:this._pushUrl,session_id:this._pushSessionId,push_mode:this._pushMode}));break}}async getStats(){return this._prevStats}async startPush(e,t={}){var a,s,u;if(t.isReconnect||(this._pushSessionId=Date.now(),t.whipConfig&&(this._whipConfig=t.whipConfig),X(J.START_PUSH,{push_url:e,session_id:this._pushSessionId})),!e)throw X(J.START_PUSH_STATUS,{is_success:!1,session_id:this._pushSessionId,reason:kr.PushCheck,push_url:this._pushUrl}),new Error("lack publish url");if(this._connect)return;this.start(),this._pushUrl=Du({pushUrl:e,disableTCC:!1}),this._pushEncodeConfig=t.cfg;const n=this._composedStream.videoTrack,i=this._composedStream.audioTrack;if(this._needCheckAudioTrack&&(!n||!i)){X(J.START_PUSH_STATUS,{is_success:!1,reason:kr.PushCheck,push_url:this._pushUrl,error_message:"lack videoTrack or audioTrack",video_track_id:n==null?void 0:n.id,audio_track_id:i==null?void 0:i.id,video_track_name:n==null?void 0:n.label,audio_track_name:i==null?void 0:i.label,push_mode:this._pushMode,session_id:this._pushSessionId});return}else if(!n&&!i){X(J.START_PUSH_STATUS,{is_success:!1,reason:kr.PushCheck,push_url:this._pushUrl,error_message:"lack videoTrack and audioTrack",push_mode:this._pushMode,session_id:this._pushSessionId});return}let o;if(this._pushMode==="rtm")o=new qn(this._pushUrl,this._pushConfig,this._OnRtcStateChange);else if(this._pushMode==="webTransport")o=new Bv(this._pushUrl,this._pushConfig,this._OnRTMPError,this._OnRTMPSuccess);else if(this._pushMode==="mediaEngine")o=new Au(this._pushUrl,this._pushConfig,this._OnRTMPError,this._OnRTMPSuccess,this._OnMediaReconnectFailed);else throw new Error(`not support push mode: ${this._pushMode}`);this._connect=o;try{!t.isReconnect&&((a=this._reconnectStrategy)!=null&&a.isActive())&&this._reconnectStrategy.stop({quiet:!0}),(s=this._reconnectStrategy)!=null&&s.isActive()||this.setConnectState($e.CONNECTING),await o.publish([i,n],[this._audioBitrate,this._videoBitrate],{cfg:t.cfg,isReconnect:t.isReconnect,whipConfig:this._whipConfig}),t.isReconnect||(Iu.log("startPush begin"),this._connectionStartDate=Date.now())}catch(c){const d=new fr(qe.PUBLISH_FAILED,c.message,c);if(Iu.groupEnd(),(u=this._reconnectStrategy)!=null&&u.isActive())throw this.unpublish({isReconnecting:!0}),d;this._streamConsumeController.emit(Ee.PushError,d),X(J.STOP_PUSH_STREAM,{reason:vn.PushError,error_message:d.message,enable_reconnect:!1,push_mode:this._pushMode,session_id:this._pushSessionId,duration:this.pushDuration}),X(J.START_PUSH_STATUS,{is_success:!1,push_url:this._pushUrl,reason:kr.PushError,error_message:d.message,session_id:this._pushSessionId,push_mode:this._pushMode}),this.unpublish()}}setPushStatsInterval(){if(this._isReportStart)return;this._isReportStart=!0;const e=async()=>{var t,n,i,o,a;if((t=this._connect)!=null&&t.isPushing){const s=Date.now(),{stats:u,originStats:c}=await this._connect.getStatsSnapshoot(2e3),f=Date.now()-s;!Im(u)&&((n=this._connect)!=null&&n.isPushing)&&this.connectionState===$e.CONNECTED?this._prevStats=u:this._prevStats=void 0;const h=this.pushMode==="rtm"?bv(u,c,{idealFrameRate:(i=this._composedStream._videoStream)==null?void 0:i.frameRate,idealBitrate:this._videoBitrate}):Ev(u),g=this.pushMode==="rtm"?(o=this._connect)==null?void 0:o.videoSenderTrackStats:{};X(J.PUSH_STATS,{...h,...g,video_draw_frame:this._streamComposedController.getCompositionDrawCountPerSecond(),stats:u,push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:h.video_duration||f,video_duration:h.video_duration||f,is_push:!0},!0)}else await hn(2e3),X(J.PUSH_STATS,{push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:2e3,is_push:!1,is_reconnecting:((a=this._reconnectStrategy)==null?void 0:a.isActive())??!1},!0);this.connectionState!==$e.DISCONNECTED&&(this._statsLoopTimer=window.setTimeout(e,0))};e()}async reconnect(e){if(this.pushMode==="rtm"&&this._whipConfig)return this.startPush(e,{isReconnect:!0,whipConfig:this._whipConfig});if(this.pushMode==="mediaEngine")return this._connect.reconnect(e)}async updatePush({videoTrack:e,audioTrack:t}){if(this._connect)try{const n=[];e&&n.push(()=>{var i;return(i=this._connect)==null?void 0:i.updatePublish(e,"video")}),t&&n.push(()=>{var i;return(i=this._connect)==null?void 0:i.updatePublish(t,"audio")}),await Promise.all(n.map(i=>i()))}catch(n){const i=new fr(qe.UPDATE_PUBLISH_FAILED,`${n.name}, code:${n.code}`);this._streamConsumeController.emit(Ee.PushError,i)}}unpublish(e={isReconnecting:!1,isManual:!1}){var t,n,i,o,a;e.isReconnecting&&this.pushMode==="mediaEngine"||((t=this._connect)==null||t.unpublish(),this._connect=null),this._prevStats=void 0,e.isManual&&(X(J.STOP_PUSH_STREAM,{reason:vn.ManualStop,duration:this.pushDuration,session_id:this._streamConsumeController.pushSessionId,push_mode:this._pushMode,reconnect_times:(n=this._reconnectStrategy)==null?void 0:n.getReconnectInfo().totalReconnectCount,reconnect_duration:(i=this._reconnectStrategy)==null?void 0:i.getReconnectInfo().totalReconnectDuration}),(o=this._reconnectStrategy)==null||o.clearReconnectInfo()),e.isReconnecting||(this._statsLoopTimer&&window.clearTimeout(this._statsLoopTimer),this._whipConfig=void 0,this._isReportStart=!1,this._pushEncodeConfig=void 0,this._pushUrl=void 0,this._connectionStartDate=void 0,this._pushSessionId=0,this.setConnectState($e.DISCONNECTED),(a=this._reconnectStrategy)==null||a.stop({quiet:!0}),this._streamConsumeController.emit(Ee.PushStop))}async destroy(){this._statsLoopTimer&&window.clearTimeout(this._statsLoopTimer),this._prevStats=void 0,this._isReportStart=!1,this._connect&&await this.unpublish(),this.unbindComposedStreamEvent()}setPushMode(e){this._pushMode=e}updatePushUrl(e){this._pushUrl=e}setBitrate(e,t,n){var i;t==="video"?this._videoBitrate=e:this._audioBitrate=e,(i=this._connect)==null||i.applyBitrate(e,t,n)}getReconnectDetail(){var e;return(e=this._reconnectStrategy)==null?void 0:e.getReconnectInfo()}get pushMode(){return this._pushMode}get connectionState(){return this._connectionState}get pushSessionId(){return this._pushSessionId}get pushDuration(){return this._connectionStartDate?(Date.now()-this._connectionStartDate)/1e3:0}emitReconnectStateChange({state:e,params:t,teaParams:n}){X(J.PUSH_RECONNECT_STATUS,{status:e,...t,...n}),this._streamConsumeController.emit(Ee.ReconnectStateChange,e,t)}}class nS extends Mt{constructor(e,t){super(),this._previewConsumer=new hv(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new rS(e.getComposedStream(),{streamConsumeController:this,streamComposedController:e,config:t})}startPreview(){this._previewConsumer.startPreview()}setRenderView(e){this._previewConsumer.setRenderView(e)}async startPush(e,t){return this._pushConsumer.startPush(e,t)}async stopPush(){return this._pushConsumer.unpublish({isReconnecting:!1,isManual:!0})}setPushMode(e){this._pushConsumer.setPushMode(e)}isPushing(){return this._pushConsumer.isPushing}getStats(){return this._pushConsumer.getStats()}getPreviewElement(){return this._previewConsumer.getPreviewElement()}stopPreview(){this._previewConsumer.stopPreview()}setBitrate(e,t,n){this._pushConsumer.setBitrate(e,t,n)}setPushConfig(e){this._pushConsumer.setPushConfig(e)}updatePushUrl(e){this._pushConsumer.updatePushUrl(e)}getPushDuration(){return this._pushConsumer.pushDuration}getReconnectDetail(){return this._pushConsumer.getReconnectDetail()}get pushSessionId(){return this._pushConsumer.pushSessionId}get pushMode(){return this._pushConsumer.pushMode}async destroy(){await this._pushConsumer.destroy(),this._previewConsumer.destroy()}}class iS{constructor(){this.onError=(e,t,n)=>{},this.onWarning=e=>{},this.onCaptureFirstAudioFrame=()=>{},this.onCaptureFirstVideoFrame=()=>{},this.onPushStatusUpdate=(e,t)=>{},this.onMicrophoneChanged=e=>{},this.onCameraChanged=e=>{},this.onCaptureInterrupted=e=>{},this.onPushStart=()=>{},this.onPushStop=()=>{},this.onStopCapture=e=>{},this.onLiveConnectStateChange=e=>{},this.onReconnectStateChange=(e,t)=>{}}}const oS=new iS;let xu=!0,Mu=!0;function Yn(r,e,t){const n=r.match(e);return n&&n.length>=t&&parseInt(n[t],10)}function sr(r,e,t){if(!r.RTCPeerConnection)return;const n=r.RTCPeerConnection.prototype,i=n.addEventListener;n.addEventListener=function(a,s){if(a!==e)return i.apply(this,arguments);const u=c=>{const d=t(c);d&&(s.handleEvent?s.handleEvent(d):s(d))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(s,u),i.apply(this,[a,u])};const o=n.removeEventListener;n.removeEventListener=function(a,s){if(a!==e||!this._eventMap||!this._eventMap[e])return o.apply(this,arguments);if(!this._eventMap[e].has(s))return o.apply(this,arguments);const u=this._eventMap[e].get(s);return this._eventMap[e].delete(s),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,o.apply(this,[a,u])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function sS(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(xu=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function aS(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Mu=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function Ou(){if(typeof window=="object"){if(xu)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function ts(r,e){Mu&&console.warn(r+" is deprecated, please use "+e+" instead.")}function cS(r){const e={browser:null,version:null};if(typeof r>"u"||!r.navigator||!r.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=r;if(t.userAgentData&&t.userAgentData.brands){const n=t.userAgentData.brands.find(i=>i.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=Yn(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=Yn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Yn(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=r.RTCRtpTransceiver&&"currentDirection"in r.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function Pu(r){return Object.prototype.toString.call(r)==="[object Object]"}function Lu(r){return Pu(r)?Object.keys(r).reduce(function(e,t){const n=Pu(r[t]),i=n?Lu(r[t]):r[t],o=n&&!Object.keys(i).length;return i===void 0||o?e:Object.assign(e,{[t]:i})},{}):r}function rs(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?rs(r,r.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(i=>{rs(r,r.get(i),t)})}))}function Uu(r,e,t){const n=t?"outbound-rtp":"inbound-rtp",i=new Map;if(e===null)return i;const o=[];return r.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&o.push(a)}),o.forEach(a=>{r.forEach(s=>{s.type===n&&s.trackId===a.id&&rs(r,s,i)})}),i}const Gu=Ou;function Nu(r,e){const t=r&&r.navigator;if(!t.mediaDevices)return;const n=function(s){if(typeof s!="object"||s.mandatory||s.optional)return s;const u={};return Object.keys(s).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;const d=typeof s[c]=="object"?s[c]:{ideal:s[c]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);const f=function(h,g){return h?h+g.charAt(0).toUpperCase()+g.slice(1):g==="deviceId"?"sourceId":g};if(d.ideal!==void 0){u.optional=u.optional||[];let h={};typeof d.ideal=="number"?(h[f("min",c)]=d.ideal,u.optional.push(h),h={},h[f("max",c)]=d.ideal,u.optional.push(h)):(h[f("",c)]=d.ideal,u.optional.push(h))}d.exact!==void 0&&typeof d.exact!="number"?(u.mandatory=u.mandatory||{},u.mandatory[f("",c)]=d.exact):["min","max"].forEach(h=>{d[h]!==void 0&&(u.mandatory=u.mandatory||{},u.mandatory[f(h,c)]=d[h])})}),s.advanced&&(u.optional=(u.optional||[]).concat(s.advanced)),u},i=function(s,u){if(e.version>=61)return u(s);if(s=JSON.parse(JSON.stringify(s)),s&&typeof s.audio=="object"){const c=function(d,f,h){f in d&&!(h in d)&&(d[h]=d[f],delete d[f])};s=JSON.parse(JSON.stringify(s)),c(s.audio,"autoGainControl","googAutoGainControl"),c(s.audio,"noiseSuppression","googNoiseSuppression"),s.audio=n(s.audio)}if(s&&typeof s.video=="object"){let c=s.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});const d=e.version<66;if(c&&(c.exact==="user"||c.exact==="environment"||c.ideal==="user"||c.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!d)){delete s.video.facingMode;let f;if(c.exact==="environment"||c.ideal==="environment"?f=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(f=["front"]),f)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(k=>k.kind==="videoinput");let g=h.find(k=>f.some(z=>k.label.toLowerCase().includes(z)));return!g&&h.length&&f.includes("back")&&(g=h[h.length-1]),g&&(s.video.deviceId=c.exact?{exact:g.deviceId}:{ideal:g.deviceId}),s.video=n(s.video),Gu("chrome: "+JSON.stringify(s)),u(s)})}s.video=n(s.video)}return Gu("chrome: "+JSON.stringify(s)),u(s)},o=function(s){return e.version>=64?s:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[s.name]||s.name,message:s.message,constraint:s.constraint||s.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(s,u,c){i(s,d=>{t.webkitGetUserMedia(d,u,f=>{c&&c(o(f))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const s=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(u){return i(u,c=>s(c).then(d=>{if(c.audio&&!d.getAudioTracks().length||c.video&&!d.getVideoTracks().length)throw d.getTracks().forEach(f=>{f.stop()}),new DOMException("","NotFoundError");return d},d=>Promise.reject(o(d))))}}}function Bu(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function Fu(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("ontrack"in r.RTCPeerConnection.prototype)){Object.defineProperty(r.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",i=>{let o;r.RTCPeerConnection.prototype.getReceivers?o=this.getReceivers().find(s=>s.track&&s.track.id===i.track.id):o={track:i.track};const a=new Event("track");a.track=i.track,a.receiver=o,a.transceiver={receiver:o},a.streams=[n.stream],this.dispatchEvent(a)}),n.stream.getTracks().forEach(i=>{let o;r.RTCPeerConnection.prototype.getReceivers?o=this.getReceivers().find(s=>s.track&&s.track.id===i.id):o={track:i};const a=new Event("track");a.track=i,a.receiver=o,a.transceiver={receiver:o},a.streams=[n.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else sr(r,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Vu(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("getSenders"in r.RTCPeerConnection.prototype)&&"createDTMFSender"in r.RTCPeerConnection.prototype){const e=function(i,o){return{track:o,get dtmf(){return this._dtmf===void 0&&(o.kind==="audio"?this._dtmf=i.createDTMFSender(o):this._dtmf=null),this._dtmf},_pc:i}};if(!r.RTCPeerConnection.prototype.getSenders){r.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(s,u){let c=i.apply(this,arguments);return c||(c=e(this,s),this._senders.push(c)),c};const o=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(s){o.apply(this,arguments);const u=this._senders.indexOf(s);u!==-1&&this._senders.splice(u,1)}}const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(o){this._senders=this._senders||[],t.apply(this,[o]),o.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(o){this._senders=this._senders||[],n.apply(this,[o]),o.getTracks().forEach(a=>{const s=this._senders.find(u=>u.track===a);s&&this._senders.splice(this._senders.indexOf(s),1)})}}else if(typeof r=="object"&&r.RTCPeerConnection&&"getSenders"in r.RTCPeerConnection.prototype&&"createDTMFSender"in r.RTCPeerConnection.prototype&&r.RTCRtpSender&&!("dtmf"in r.RTCRtpSender.prototype)){const e=r.RTCPeerConnection.prototype.getSenders;r.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(i=>i._pc=this),n},Object.defineProperty(r.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function ju(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender&&r.RTCRtpReceiver))return;if(!("getStats"in r.RTCRtpSender.prototype)){const t=r.RTCPeerConnection.prototype.getSenders;t&&(r.RTCPeerConnection.prototype.getSenders=function(){const o=t.apply(this,[]);return o.forEach(a=>a._pc=this),o});const n=r.RTCPeerConnection.prototype.addTrack;n&&(r.RTCPeerConnection.prototype.addTrack=function(){const o=n.apply(this,arguments);return o._pc=this,o}),r.RTCRtpSender.prototype.getStats=function(){const o=this;return this._pc.getStats().then(a=>Uu(a,o.track,!0))}}if(!("getStats"in r.RTCRtpReceiver.prototype)){const t=r.RTCPeerConnection.prototype.getReceivers;t&&(r.RTCPeerConnection.prototype.getReceivers=function(){const i=t.apply(this,[]);return i.forEach(o=>o._pc=this),i}),sr(r,"track",n=>(n.receiver._pc=n.srcElement,n)),r.RTCRtpReceiver.prototype.getStats=function(){const i=this;return this._pc.getStats().then(o=>Uu(o,i.track,!1))}}if(!("getStats"in r.RTCRtpSender.prototype&&"getStats"in r.RTCRtpReceiver.prototype))return;const e=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof r.MediaStreamTrack){const n=arguments[0];let i,o,a;return this.getSenders().forEach(s=>{s.track===n&&(i?a=!0:i=s)}),this.getReceivers().forEach(s=>(s.track===n&&(o?a=!0:o=s),s.track===n)),a||i&&o?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):i?i.getStats():o?o.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Hu(r){r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(a,s){if(!s)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const u=e.apply(this,arguments);return this._shimmedLocalStreams[s.id]?this._shimmedLocalStreams[s.id].indexOf(u)===-1&&this._shimmedLocalStreams[s.id].push(u):this._shimmedLocalStreams[s.id]=[s,u],u};const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(c=>{if(this.getSenders().find(f=>f.track===c))throw new DOMException("Track already exists.","InvalidAccessError")});const s=this.getSenders();t.apply(this,arguments);const u=this.getSenders().filter(c=>s.indexOf(c)===-1);this._shimmedLocalStreams[a.id]=[a].concat(u)};const n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],n.apply(this,arguments)};const i=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(s=>{const u=this._shimmedLocalStreams[s].indexOf(a);u!==-1&&this._shimmedLocalStreams[s].splice(u,1),this._shimmedLocalStreams[s].length===1&&delete this._shimmedLocalStreams[s]}),i.apply(this,arguments)}}function $u(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Hu(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const d=t.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(f=>this._reverseStreams[f.id])};const n=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(f=>{if(this.getSenders().find(g=>g.track===f))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){const f=new r.MediaStream(d.getTracks());this._streams[d.id]=f,this._reverseStreams[f.id]=d,d=f}n.apply(this,[d])};const i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},r.RTCPeerConnection.prototype.addTrack=function(d,f){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(z=>z===d))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(z=>z.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const k=this._streams[f.id];if(k)k.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const z=new r.MediaStream([d]);this._streams[f.id]=z,this._reverseStreams[z.id]=f,this.addStream(z)}return this.getSenders().find(z=>z.track===d)};function o(c,d){let f=d.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{const g=c._reverseStreams[h],k=c._streams[g.id];f=f.replace(new RegExp(k.id,"g"),g.id)}),new RTCSessionDescription({type:d.type,sdp:f})}function a(c,d){let f=d.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{const g=c._reverseStreams[h],k=c._streams[g.id];f=f.replace(new RegExp(g.id,"g"),k.id)}),new RTCSessionDescription({type:d.type,sdp:f})}["createOffer","createAnswer"].forEach(function(c){const d=r.RTCPeerConnection.prototype[c],f={[c](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[k=>{const z=o(this,k);h[0].apply(null,[z])},k=>{h[1]&&h[1].apply(null,k)},arguments[2]]):d.apply(this,arguments).then(k=>o(this,k))}};r.RTCPeerConnection.prototype[c]=f[c]});const s=r.RTCPeerConnection.prototype.setLocalDescription;r.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?s.apply(this,arguments):(arguments[0]=a(this,arguments[0]),s.apply(this,arguments))};const u=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){const c=u.get.apply(this);return c.type===""?c:o(this,c)}}),r.RTCPeerConnection.prototype.removeTrack=function(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(d._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(g=>{this._streams[g].getTracks().find(z=>d.track===z)&&(h=this._streams[g])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function ns(r,e){!r.RTCPeerConnection&&r.webkitRTCPeerConnection&&(r.RTCPeerConnection=r.webkitRTCPeerConnection),r.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=r.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=i[t]})}function qu(r,e){sr(r,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}const Ku=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:qu,shimAddTrackRemoveTrack:$u,shimAddTrackRemoveTrackWithNative:Hu,shimGetSendersWithDtmf:Vu,shimGetUserMedia:Nu,shimMediaStream:Bu,shimOnTrack:Fu,shimPeerConnection:ns,shimSenderReceiverGetStats:ju},Symbol.toStringTag,{value:"Module"}));function Wu(r,e){const t=r&&r.navigator,n=r&&r.MediaStreamTrack;if(t.getUserMedia=function(i,o,a){ts("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(i).then(o,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const i=function(a,s,u){s in a&&!(u in a)&&(a[u]=a[s],delete a[s])},o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),i(a.audio,"autoGainControl","mozAutoGainControl"),i(a.audio,"noiseSuppression","mozNoiseSuppression")),o(a)},n&&n.prototype.getSettings){const a=n.prototype.getSettings;n.prototype.getSettings=function(){const s=a.apply(this,arguments);return i(s,"mozAutoGainControl","autoGainControl"),i(s,"mozNoiseSuppression","noiseSuppression"),s}}if(n&&n.prototype.applyConstraints){const a=n.prototype.applyConstraints;n.prototype.applyConstraints=function(s){return this.kind==="audio"&&typeof s=="object"&&(s=JSON.parse(JSON.stringify(s)),i(s,"autoGainControl","mozAutoGainControl"),i(s,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[s])}}}}function uS(r,e){r.navigator.mediaDevices&&"getDisplayMedia"in r.navigator.mediaDevices||r.navigator.mediaDevices&&(r.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){const i=new DOMException("getDisplayMedia without video constraints is undefined");return i.name="NotFoundError",i.code=8,Promise.reject(i)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,r.navigator.mediaDevices.getUserMedia(n)})}function Ju(r){typeof r=="object"&&r.RTCTrackEvent&&"receiver"in r.RTCTrackEvent.prototype&&!("transceiver"in r.RTCTrackEvent.prototype)&&Object.defineProperty(r.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function is(r,e){if(typeof r!="object"||!(r.RTCPeerConnection||r.mozRTCPeerConnection))return;!r.RTCPeerConnection&&r.mozRTCPeerConnection&&(r.RTCPeerConnection=r.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(i){const o=r.RTCPeerConnection.prototype[i],a={[i](){return arguments[0]=new(i==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),o.apply(this,arguments)}};r.RTCPeerConnection.prototype[i]=a[i]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){const[o,a,s]=arguments;return n.apply(this,[o||null]).then(u=>{if(e.version<53&&!a)try{u.forEach(c=>{c.type=t[c.type]||c.type})}catch(c){if(c.name!=="TypeError")throw c;u.forEach((d,f)=>{u.set(f,Object.assign({},d,{type:t[d.type]||d.type}))})}return u}).then(a,s)}}function Xu(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpSender.prototype)return;const e=r.RTCPeerConnection.prototype.getSenders;e&&(r.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(o=>o._pc=this),i});const t=r.RTCPeerConnection.prototype.addTrack;t&&(r.RTCPeerConnection.prototype.addTrack=function(){const i=t.apply(this,arguments);return i._pc=this,i}),r.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Zu(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpReceiver.prototype)return;const e=r.RTCPeerConnection.prototype.getReceivers;e&&(r.RTCPeerConnection.prototype.getReceivers=function(){const n=e.apply(this,[]);return n.forEach(i=>i._pc=this),n}),sr(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Yu(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){ts("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function Qu(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function ed(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.addTransceiver;e&&(r.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const i=n.length>0;i&&n.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const o=e.apply(this,arguments);if(i){const{sender:a}=o,s=a.getParameters();(!("encodings"in s)||s.encodings.length===1&&Object.keys(s.encodings[0]).length===0)&&(s.encodings=n,a.sendEncodings=n,this.setParametersPromises.push(a.setParameters(s).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return o})}function td(r){if(!(typeof r=="object"&&r.RTCRtpSender))return;const e=r.RTCRtpSender.prototype.getParameters;e&&(r.RTCRtpSender.prototype.getParameters=function(){const n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function rd(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function nd(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.createAnswer;r.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}const id=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:ed,shimCreateAnswer:nd,shimCreateOffer:rd,shimGetDisplayMedia:uS,shimGetParameters:td,shimGetUserMedia:Wu,shimOnTrack:Ju,shimPeerConnection:is,shimRTCDataChannel:Qu,shimReceiverGetStats:Zu,shimRemoveStream:Yu,shimSenderGetStats:Xu},Symbol.toStringTag,{value:"Module"}));function od(r){if(!(typeof r!="object"||!r.RTCPeerConnection)){if("getLocalStreams"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in r.RTCPeerConnection.prototype)){const e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(i=>e.call(this,i,n)),n.getVideoTracks().forEach(i=>e.call(this,i,n))},r.RTCPeerConnection.prototype.addTrack=function(n,...i){return i&&i.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),e.apply(this,arguments)}}"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const i=t.getTracks();this.getSenders().forEach(o=>{i.includes(o.track)&&this.removeTrack(o)})})}}function sd(r){if(!(typeof r!="object"||!r.RTCPeerConnection)&&("getRemoteStreams"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in r.RTCPeerConnection.prototype))){Object.defineProperty(r.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(i=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(i))return;this._remoteStreams.push(i);const o=new Event("addstream");o.stream=i,this.dispatchEvent(o)})})}});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){const n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(i){i.streams.forEach(o=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(o)>=0)return;n._remoteStreams.push(o);const a=new Event("addstream");a.stream=o,n.dispatchEvent(a)})}),e.apply(n,arguments)}}}function ad(r){if(typeof r!="object"||!r.RTCPeerConnection)return;const e=r.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,i=e.setLocalDescription,o=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(c,d){const f=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[f]);return d?(h.then(c,d),Promise.resolve()):h},e.createAnswer=function(c,d){const f=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[f]);return d?(h.then(c,d),Promise.resolve()):h};let s=function(u,c,d){const f=i.apply(this,[u]);return d?(f.then(c,d),Promise.resolve()):f};e.setLocalDescription=s,s=function(u,c,d){const f=o.apply(this,[u]);return d?(f.then(c,d),Promise.resolve()):f},e.setRemoteDescription=s,s=function(u,c,d){const f=a.apply(this,[u]);return d?(f.then(c,d),Promise.resolve()):f},e.addIceCandidate=s}function cd(r){const e=r&&r.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=i=>n(ud(i))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,i,o){e.mediaDevices.getUserMedia(n).then(i,o)}).bind(e))}function ud(r){return r&&r.video!==void 0?Object.assign({},r,{video:Lu(r.video)}):r}function dd(r){if(!r.RTCPeerConnection)return;const e=r.RTCPeerConnection;r.RTCPeerConnection=function(n,i){if(n&&n.iceServers){const o=[];for(let a=0;a<n.iceServers.length;a++){let s=n.iceServers[a];s.urls===void 0&&s.url?(ts("RTCIceServer.url","RTCIceServer.urls"),s=JSON.parse(JSON.stringify(s)),s.urls=s.url,delete s.url,o.push(s)):o.push(n.iceServers[a])}n.iceServers=o}return new e(n,i)},r.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(r.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function ld(r){typeof r=="object"&&r.RTCTrackEvent&&"receiver"in r.RTCTrackEvent.prototype&&!("transceiver"in r.RTCTrackEvent.prototype)&&Object.defineProperty(r.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function hd(r){const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);const i=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&i?i.direction==="sendrecv"?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":i.direction==="recvonly"&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):n.offerToReceiveAudio===!0&&!i&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const o=this.getTransceivers().find(a=>a.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&o?o.direction==="sendrecv"?o.setDirection?o.setDirection("sendonly"):o.direction="sendonly":o.direction==="recvonly"&&(o.setDirection?o.setDirection("inactive"):o.direction="inactive"):n.offerToReceiveVideo===!0&&!o&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function fd(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const pd=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:fd,shimCallbacksAPI:ad,shimConstraints:ud,shimCreateOfferLegacy:hd,shimGetUserMedia:cd,shimLocalStreamsAPI:od,shimRTCIceServerUrls:dd,shimRemoteStreamsAPI:sd,shimTrackEventTransceiver:ld},Symbol.toStringTag,{value:"Module"}));var os={exports:{}},md;function dS(){return md||(md=1,function(r){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
82
+ }`,t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.appendChild(document.createTextNode(e)),t.appendChild(n);var i=document.createElement("div");i.innerHTML='<div id="debugger-applog-web" class="debugger-applog-web"></div>';var o=document.createElement("div");o.innerHTML='<div id="debugger-container" class="debugger-container"></div>',document.getElementsByTagName("body")[0].appendChild(i),document.getElementsByTagName("body")[0].appendChild(o);var a=document.getElementById("debugger-applog-web");new Ry(a)},r}(),Jo={autotrack:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/autotrack.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/autotrack.js"},object:"LogAutoTrack"},ab:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/ab.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/ab.js"},object:"LogAb"},stay:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/stay.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/stay.js"},object:"LogStay"},route:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/route.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/route.js"},object:"LogRoute"},tracer:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/tracer.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/tracer.js"},object:"LogTracer"},retry:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/retry.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/retry.js"},object:"LogRetry"},visual:{src:{sg:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-sg/log-sdk/collect/5/plugin/visual.js",va:"https://lf-global-static.iapplogcdn.com/obj/applog-sdk-static-us/log-sdk/collect/5/plugin/visual.js"},object:"LogVisual"}},Dy=["et","profile","heartbeat","monitor"],wr=function(){function r(e){this.disableAutoPageView=!1,this.bridgeReport=!1,this.staging=!1,this.pluginInstances=[],this.sended=!1,this.started=!1,this.destroy=!1,this.sdkReady=!1,this.adapters={},this.loadType="base",this.sdkStop=!1,this.name=e,this.hook=new Wv,this.remotePlugin=new Map,this.logger=new uy(e),this.Types=B,this.adapters.storage=Er}return r.usePlugin=function(e,t,n){if(t){for(var i=!1,o=0,a=r.plugins.length;o<a;o++)if(r.plugins[o].name===t){r.plugins[o].plugin=e,r.plugins[o].options=n||{},i=!0;break}i||r.plugins.push({name:t,plugin:e,options:n})}else r.plugins.push({plugin:e})},r.prototype.usePlugin=function(e,t,n){e&&(this.loadType==="full"&&Dy.includes(e)?console.info("your sdk version has "+e+" already ~"):t?typeof t=="string"?this.remotePlugin.get(e)||this.remotePlugin.set(e,{src:t,call:n}):this.remotePlugin.get(e)||this.remotePlugin.set(e,{instance:t}):this.remotePlugin.get(e)||this.remotePlugin.set(e,"sdk"))},r.prototype.init=function(e){var t,n=this;if(this.logger.enable(e.log),this.inited)this.logger.warn("[instance: "+this.name+"], every instance's api: init, can be call only one time!");else if(e&&nu(e))if(e.app_id&&typeof(t=e.app_id)=="number"&&!isNaN(t))if(!e.app_key||function(i){return typeof i=="string"}(e.app_key)){if(e.channel_domain||(e.report_channel!=="eu_ttp_ie"&&e.channel!=="ie"||this.logger.error("ie dc will be deprecated in the future, please use other dc instead"),e.report_channel&&!uu().has(e.report_channel)?(this.logger.warn("your report_channel: "+e.report_channel+" is not exist. report_channel must be one of "+No().join(",")+", use default report_channel: us_east instead, please check!!!"),e.report_channel="us_east"):e.report_channel||["sg","va","in","my","ie","ie2"].indexOf(e.channel)!==-1||(this.logger.warn("your channel: "+e.channel+" is not exist. use report_channel instead and report_channel must be one of "+No().join(",")+", use default report_channel: us_east instead, please check!!!"),e.report_channel="us_east"),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK set channel warning",level:"error",time:Date.now(),data:"your report_channel: "+e.channel+" is not exist. report_channel must be one of "+No().join(",")+", use us_east instead, please check!!!",infoType:"sdk"})),this.spider=new dy,this.spider.checkSpider(e))return this.logger.warn("The current environment may be a spider, can not report!"),void this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK hit spider",level:"error",time:Date.now(),data:"The current environment may be a spider, can not report!",infoType:"sdk"});this.appBridge=new ly(this,e.enable_native),this.configManager=new cy(this,e),this.requestManager=new zy(this,e),this.bridgeReport=this.appBridge.bridgeInject(),this.debugger=new Ay(this,e),this.initConfig=e,this.emit(B.Init),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Init",data:e,level:"info",time:Date.now(),infoType:"cus"}),e.disable_auto_pv&&(this.disableAutoPageView=!0),this.bridgeReport||(this.configManager.setAppid(e.app_id),this.eventManager=new fy,this.tokenManager=new py,this.sessionManager=new my,Promise.all([new Promise(function(i){n.once(B.TokenComplete,function(){i(!0)})}),new Promise(function(i){n.once(B.Start,function(){i(!0)})}),new Promise(function(i){n.once(B.LogSettingReady,function(){i(!0)})})]).then(function(){try{r.plugins.reduce(function(i,o){var a=o.plugin,s=o.options,u=Object.assign(n.initConfig,s);n.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Load "+o.name+" Plugin",level:"info",time:Date.now(),infoType:"sdk"});var c=new a;return c.apply(n,u),i.push(c),i},n.pluginInstances)}catch(i){console.warn("load plugin error, "+i.message),n.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Load Plugin Error",level:"error",time:Date.now(),data:i.message,infoType:"sdk"})}n.sdkReady=!0,n.emit(B.Ready),n.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK UserInfo Init Completed",time:Date.now(),secType:"USER",level:"info",data:n.configManager.get("user"),infoType:"sdk"}),n.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Initialization Completed",time:Date.now(),level:"info",data:n.configManager.get("user"),infoType:"sdk"}),n.logger.info("appid: "+e.app_id+", userInfo:"+JSON.stringify(n.configManager.get("user"))),n.logger.info("appid: "+e.app_id+", sdk is ready, version is 5.3.14_oversea, you can report now !!!"),e.disable_auto_pv&&(n.disableAutoPageView=!0);try{(n.loadType==="full"&&e.enable_ab_test||e.autotrack)&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")}catch(i){n.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"Something Error",level:"error",time:Date.now(),data:i.message,infoType:"sdk"})}n.pageView(),n.on(B.TokenChange,function(i){i==="webid"&&n.pageView(),n.logger.info("appid: "+e.app_id+" token change, new userInfo:"+JSON.stringify(n.configManager.get("user"))),n.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Set UserInfo",time:Date.now(),secType:"USER",level:"info",data:n.configManager.get("user"),infoType:"sdk"})}),n.on(B.TokenReset,function(){n.logger.info("appid: "+e.app_id+" token reset, new userInfo:"+JSON.stringify(n.configManager.get("user"))),n.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Reset UserInfo",time:Date.now(),secType:"USER",level:"info",data:n.configManager.get("user"),infoType:"sdk"})}),n.on(B.RouteChange,function(i){i.init||e.disable_route_report||n.pageView()})}),this.tokenManager.apply(this,e),this.eventManager.apply(this,e),this.sessionManager.apply(this,e)),this.inited=!0}else this.logger.warn("app_key param is error, must be string, please check!");else this.logger.warn("app_id param is error, must be number, please check!");else this.logger.warn("init params error,please check")},r.prototype.config=function(e){if(!this.inited)return console.warn("config must be use after function init"),void this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Config Error",level:"error",time:Date.now(),data:"config must be use after function init",infoType:"sdk"});if(!e||!nu(e))return console.warn("config params is error, please check"),void this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Config Error",level:"error",time:Date.now(),data:"config params is error, please check",infoType:"sdk"});var t;try{t=JSON.parse(JSON.stringify(t))}catch{t=e}if(this.bridgeReport)this.appBridge.setConfig(t);else{t._staging_flag&&t._staging_flag===1&&(this.staging=!0),t.disable_auto_pv&&(this.disableAutoPageView=!0,delete t.disable_auto_pv);var n=Le({},t);if(this.initConfig&&this.initConfig.configPersist){var i=this.configManager.getStore();i&&(n=Object.assign(i,t)),this.configManager.setStore(t)}n.web_id,n.user_unique_id,n.device_id;var o=function(a,s){var u={};for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&s.indexOf(c)<0&&(u[c]=a[c]);if(a!=null&&typeof Object.getOwnPropertySymbols=="function"){var d=0;for(c=Object.getOwnPropertySymbols(a);d<c.length;d++)s.indexOf(c[d])<0&&(u[c[d]]=a[c[d]])}return u}(n,["web_id","user_unique_id","device_id"]);n.hasOwnProperty("web_id")&&this.emit(B.ConfigWebId,n.web_id),n.hasOwnProperty("user_unique_id")&&this.emit(B.ConfigUuid,n.user_unique_id),n.hasOwnProperty("device_id")&&this.emit(B.ConfigDiD,n.device_id),this.configManager.set(o),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Config",level:"info",time:Date.now(),data:n,infoType:"cus"})}},r.prototype.setDomain=function(e){this.configManager&&this.configManager.setDomain(e),this.emit(B.ConfigDomain)},r.prototype.getConfig=function(e){return this.configManager.get(e)},r.prototype.send=function(){this.start()},r.prototype.start=function(){this.inited&&!this.sended&&(this.sended=!0,this.emit(B.Start),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Start",level:"info",time:Date.now(),infoType:"cus"}),this.bridgeReport&&(this.pageView(),this.emit(B.Ready)))},r.prototype.event=function(e,t){var n=this;try{var i=[];if(Array.isArray(e))e.forEach(function(a){var s=n.processEvent(a[0],a[1]||{});s&&i.push(s)});else{var o=this.processEvent(e,t);if(!o)return;i.push(o)}this.bridgeReport?i.forEach(function(a){var s=a.event,u=a.params;n.appBridge.onEventV3(s,JSON.stringify(u))}):i.length&&(this.emit(B.Event,i),this.emit(B.SessionResetTime)),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Event",level:"info",time:Date.now(),data:e,infoType:"cus"})}catch(a){this.logger.warn("something error, please check"),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Event Something Error",level:"error",time:Date.now(),data:a.message,infoType:"sdk"})}},r.prototype.beconEvent=function(e,t){if(Array.isArray(e))return this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK BeconEvent Error",level:"error",time:Date.now(),data:"beconEvent not support batch report, please check",infoType:"sdk"}),void this.logger.warn("beconEvent not support batch report, please check");var n=[],i=this.processEvent(e,t||{});i&&(n.push(i),n.length&&(this.emit(B.BeconEvent,n),this.emit(B.SessionResetTime)),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Beacon Event",level:"info",time:Date.now(),data:e,infoType:"sdk"}))},r.prototype.beaconEvent=function(e,t){this.beconEvent(e,t)},r.prototype.processEvent=function(e,t){t===void 0&&(t={});try{if(!e)return console.warn("eventName is null, please check"),null;var n=e;/^event\./.test(e)&&(n=e.slice(6));var i=t;typeof i!="object"&&(i={}),i.profile?delete i.profile:i.event_index=Jv();var o=void 0;return i.local_ms?(o=i.local_ms,delete i.local_ms):o=+new Date,{event:n,params:i,local_time_ms:o,is_bav:this.initConfig&&this.initConfig.autotrack?1:0}}catch(a){return this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:a.message,infoType:"sdk"}),{event:e,params:t}}},r.prototype.filterEvent=function(e){this.eventFilter=e},r.prototype.on=function(e,t){this.hook.on(e,t)},r.prototype.once=function(e,t){this.hook.once(e,t)},r.prototype.off=function(e,t){this.hook.off(e,t)},r.prototype.emit=function(e,t,n){this.hook.emit(e,t,n)},r.prototype.set=function(e){this.hook.set(e)},r.prototype.stop=function(){this.sdkStop=!0},r.prototype.reStart=function(){this.sdkStop=!1},r.prototype.pageView=function(){this.disableAutoPageView||this.predefinePageView()},r.prototype.predefinePageView=function(e){if(e===void 0&&(e={}),this.inited){var t={title:document.title||location.pathname,url:location.href,url_path:location.pathname,time:Date.now(),referrer:window.document.referrer,$is_first_time:""+(this.configManager&&this.configManager.is_first_time||!1)},n=Le(Le({},t),e);this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Report PV",level:"info",time:Date.now(),infoType:"sdk"}),this.event("predefine_pageview",n)}else console.warn("predefinePageView should call after init")},r.prototype.enableTransPort=function(){this.configManager.setEnableClientTransport(!0)},r.prototype.disableTransPort=function(){this.configManager.setEnableClientTransport(!1)},r.prototype.clearEventCache=function(){this.emit(B.CleanEvents)},r.prototype.setWebId=function(e){this.config({web_id:""+e})},r.prototype.setNativeAppId=function(e){this.bridgeReport&&this.appBridge.setNativeAppId(e)},r.prototype.getSessionId=function(){return pn()},r.prototype.setSessionId=function(e){this.emit(B.SessionReset,e)},r.prototype.resetStayDuration=function(e,t,n){this.emit(B.ResetStay,{url_path:e,title:t,url:n},B.Stay)},r.prototype.resetStayParams=function(e,t,n){e===void 0&&(e=""),t===void 0&&(t=""),n===void 0&&(n=""),this.emit(B.SetStay,{url_path:e,title:t,url:n},B.Stay)},r.prototype.getToken=function(e,t){var n=this;if(this.inited){var i=!1,o=function(s){if(!i){i=!0;var u=n.configManager.get().user;return s&&(u.tobid=s,u["diss".split("").reverse().join("")]=s),e(Le({},u))}},a=function(){n.tokenManager.getTobId().then(function(s){o(s)})};this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute GetToken",level:"info",time:Date.now(),infoType:"cus"}),this.sdkReady?a():(t&&setTimeout(function(){o()},t),this.on(B.Ready,function(){a()}))}else console.warn("predefinePageView should call after init")},r.prototype.startTrackEvent=function(e){e&&this.emit(B.TrackEventDurationStart,e,B.TrackEventDuration)},r.prototype.endTrackEvent=function(e,t){t===void 0&&(t={}),e&&this.emit(B.TrackEventDurationEnd,{eventName:e,params:t},B.TrackEventDuration)},r.prototype.pauseTrackEvent=function(e){e&&this.emit(B.TrackEventDurationPause,e,B.TrackEventDuration)},r.prototype.resumeTrackEvent=function(e){e&&this.emit(B.TrackEventDurationResume,e,B.TrackEventDuration)},r.prototype.profileSet=function(e){this.bridgeReport?this.appBridge.profileSet(JSON.stringify(e)):this.emit(B.ProfileSet,e,B.Profile),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileSet",level:"info",time:Date.now(),data:e})},r.prototype.profileSetOnce=function(e){this.bridgeReport?this.appBridge.profileSetOnce(JSON.stringify(e)):this.emit(B.ProfileSetOnce,e,B.Profile),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileSetOnce",level:"info",time:Date.now(),data:e})},r.prototype.profileIncrement=function(e){this.bridgeReport?this.appBridge.profileIncrement(JSON.stringify(e)):this.emit(B.ProfileIncrement,e,B.Profile),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileIncrement",level:"info",time:Date.now(),data:e})},r.prototype.profileUnset=function(e){this.bridgeReport?this.appBridge.profileUnset(e):this.emit(B.ProfileUnset,e,B.Profile),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileUnset",level:"info",time:Date.now(),data:e})},r.prototype.profileAppend=function(e){this.bridgeReport?this.appBridge.profileAppend(JSON.stringify(e)):this.emit(B.ProfileAppend,e,B.Profile),this.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileAppend",level:"info",time:Date.now(),data:e})},r.prototype.setExternalAbVersion=function(e){this.emit(B.AbExternalVersion,typeof e=="string"&&e?(""+e).trim():null,B.Ab)},r.prototype.getVar=function(e,t,n,i){this.emit(B.AbVar,{name:e,defaultValue:t,callback:n,uuid:i},B.Ab)},r.prototype.getABconfig=function(e,t){this.emit(B.AbConfig,{params:e,callback:t},B.Ab)},r.prototype.getABConfig=function(e,t){this.emit(B.AbConfig,{params:e,callback:t},B.Ab)},r.prototype.getAbSdkVersion=function(){return this.configManager.getAbVersion()},r.prototype.onAbSdkVersionChange=function(e){var t=this;return this.emit(B.AbVersionChangeOn,e,B.Ab),function(){t.emit(B.AbVersionChangeOff,e,B.Ab)}},r.prototype.offAbSdkVersionChange=function(e){this.emit(B.AbVersionChangeOff,e,B.Ab)},r.prototype.openOverlayer=function(){this.emit(B.AbOpenLayer,"",B.Ab)},r.prototype.closeOverlayer=function(){this.emit(B.AbCloseLayer,"",B.Ab)},r.prototype.getAllVars=function(e,t){this.emit(B.AbAllVars,{callback:e,timeout:t},B.Ab)},r.prototype.destoryInstace=function(){this.destroy||(this.destroy=!0,this.off(B.TokenComplete),this.emit(B.DestoryInstance))},r.prototype.destroyInstance=function(){this.destroy||(this.destroy=!0,this.off(B.TokenComplete),this.emit(B.DestoryInstance))},r.plugins=[],r}(),Iy=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,t.event_verify_url)if(typeof t.event_verify_url=="string"){if(this.url=t.event_verify_url+"/v1/list_test",this.url){var i=e.Types;e.on(i.SubmitVerify,function(o){n.verify(o)}),e.on(i.AbVerify,function(o){n.verify(o)})}}else console.log("please use correct et_test url")},r.prototype.verify=function(e){var t=this;e.forEach(function(n){try{var i=JSON.parse(JSON.stringify(n));t.config.filter&&((i=t.config.filter(i))||console.warn("filter must return data !!")),t.collect.eventFilter&&i&&((i=t.collect.eventFilter(i))||console.warn("filterEvent api must return data !!"));var o=i||n,a=JSON.parse(JSON.stringify(o));if(!o.length)return;var s=!0;if(o.forEach(function(u){u.events.length||(s=!1)}),!s)return;t.collect.requestManager.useBeacon({url:t.url,data:o}),t.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_EVENT,info:"SDK Report ByteIo Verify Request",time:Date.now(),data:a,code:200,status:"success",verifyType:!0})}catch(u){console.warn("something error, "+JSON.stringify(u.stack)),t.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"SDK Report ByteIo Verify Request Error",level:"error",time:Date.now(),data:u.message})}})},r}(),xy=function(){function r(){var e=this;this.setInterval=function(){e.clearIntervalFunc=function(t,n){t===void 0&&(t=function(){}),n===void 0&&(n=1e3);var i,o=Date.now()+n;return i=window.setTimeout(function a(){var s=Date.now()-o;t(),o+=n,i=window.setTimeout(a,Math.max(0,n-s))},n),function(){window.clearTimeout(i)}}(function(){e.isSessionhasEvent&&e.endCurrentSession()},e.sessionInterval)},this.clearInterval=function(){e.clearIntervalFunc&&e.clearIntervalFunc()}}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,!t.disable_heartbeat){this.sessionInterval=6e4,this.startTime=0,this.lastTime=0,this.setInterval();var i=this.collect.Types;this.collect.on(i.SessionReset,function(){n.process()})}},r.prototype.endCurrentSession=function(){this.collect.event("_be_active",{start_time:this.startTime,end_time:this.lastTime,url:window.location.href,referrer:window.document.referrer,title:document.title||location.pathname}),this.isSessionhasEvent=!1,this.startTime=0},r.prototype.process=function(){this.isSessionhasEvent||(this.isSessionhasEvent=!0,this.startTime=+new Date);var e=this.lastTime||+new Date;this.lastTime=+new Date,this.lastTime-e>this.sessionInterval&&(this.clearInterval(),this.endCurrentSession(),this.setInterval())},r}(),My=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;if(this.collect=e,this.config=t,!this.config.channel_domain&&!t.disable_track_event&&!t.disable_sdk_monitor){this.url=e.configManager.getUrl("event");var i=this.collect.Types;this.collect.on(i.Ready,function(){n.sdkOnload()}),this.collect.on(i.SubmitError,function(o){var a=o.type,s=o.eventData,u=o.errorCode,c=o.response;a==="f_data"&&n.sdkError(s,u,c)}),this.collect.on(e.Types.SDKInnerError,function(o){var a=o.type,s=o.eventData,u=o.errorCode,c=o.msg;n.sdkInnerError(a,s,u,c)})}},r.prototype.sdkOnload=function(){var e=this;try{var t=this.collect.configManager.get(),n=t.header,i=t.user,o=n.app_id,a=n.app_name,s=n.sdk_version,u=(i.web_id,{events:[{event:"onload",params:JSON.stringify({app_id:o,app_name:a||"",sdk_version:s,sdk_type:"npm",sdk_config:this.config,sdk_desc:"TOC_OVERSEA",url:location.href,is_setting:this.config.enable_logsetting||!1,enable_logsetting_params:this.config.enable_logsetting_params||!1,enable_logsetting_header_custom:this.config.enable_logsetting_header_custom||!1}),local_time_ms:Date.now()}],user:{user_unique_id:i.user_unique_id},header:{app_id:6656}});setTimeout(function(){e.collect.requestManager.useXhr({url:e.url,data:[u],timeout:3e4})},16)}catch{}},r.prototype.sdkError=function(e,t,n){var i=this;try{var o=e[0],a=o.user,s=o.header,u=[];e.forEach(function(d){d.events.forEach(function(f){u.push(f)})});var c={events:u.map(function(d){return{event:"on_error",params:JSON.stringify({type:"sdk_event_error",error_code:t,app_id:s.app_id,app_name:s.app_name||"",error_event:d.event,sdk_version:s.sdk_version,local_time_ms:d.local_time_ms,tea_event_index:Date.now(),params:d.params,header:s,user:a,err_msg:n.m||""}),local_time_ms:Date.now()}}),user:{user_unique_id:a.user_unique_id},header:{app_id:6656}};setTimeout(function(){i.collect.requestManager.useXhr({url:i.url,data:[c],timeout:3e4})},16)}catch{}},r.prototype.sdkInnerError=function(e,t,n,i){var o=this;try{var a=t[0],s=a.user,u=a.header,c=[];t.forEach(function(f){f.events.forEach(function(h){c.push(h)})});var d={events:c.map(function(f){return{event:"on_error",params:JSON.stringify({type:e,error_code:n,app_id:u.app_id,app_name:u.app_name||"",error_event:f.event,sdk_version:u.sdk_version,local_time_ms:f.local_time_ms,tea_event_index:Date.now(),params:f.params,header:u,user:s,ua:window.navigator.userAgent,err_msg:i}),local_time_ms:Date.now()}}),user:s,header:{}};setTimeout(function(){o.collect.requestManager.useXhr({url:o.url,data:[d],timeout:3e4,app_key:"566f58151b0ed37e"})},16)}catch{}},r}(),Xo=typeof window<"u"?(window.LogPluginObject||(window.LogPluginObject={}),window.LogPluginObject):null,Oy=function(){function r(){}return r.prototype.apply=function(e,t){this._plugin={},this.config=t,this.collect=e,this.channel="va",this.loadExtend()},r.prototype.loadExtend=function(){var e=this;try{this.collect.remotePlugin.forEach(function(t,n){if(t==="sdk")if(Jo.hasOwnProperty(n)){var i=Jo[n].object,o=""+Jo[n].src[e.channel];e.exist(n,i,o)}else console.warn("your "+n+" is not exist,please check plugin name");else typeof t=="object"&&(t.src?e.exist(n,t.call,t.src):e.process(n,t.instance,"INSTANCE"))})}catch(t){this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"LoadExtend Fail",level:"error",time:Date.now(),data:t.message}),console.log("load extend error")}},r.prototype.exist=function(e,t,n){var i=this;Xo[t]?(this.process(e,Xo[t]),console.log("already has "+e+" plugin~")):this.loadPlugin(e,n,function(){i.process(e,Xo[t]),console.log(" %c %s %s %s","color: yellow; background-color: black;","–","load plugin:"+e+" success","-")},function(){console.log(" %c %s %s %s","color: red; background-color: yellow;","–","load plugin:"+e+" error","-")})},r.prototype.process=function(e,t,n){try{if(n){var i=new t;i.apply&&i.apply(this.collect,this.config),console.log("excude "+e+" success")}else t&&t(this.collect,this.config)}catch(o){this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"Extend Process Fail",level:"error",time:Date.now(),data:o.message}),console.log("excude "+e+" error, message:"+o.message)}},r.prototype.loadPlugin=function(e,t,n,i){var o=this;try{var a=document.createElement("script");a.src=t,this._plugin[e]||(this._plugin[e]=[]),this._plugin[e].push(n),a.onerror=function(){i(t)},a.onload=function(){o._plugin[e].forEach(function(s){s()})},document.getElementsByTagName("head")[0].appendChild(a)}catch(s){this.collect.emit(P.DEBUGGER_MESSAGE,{type:P.DEBUGGER_MESSAGE_SDK,info:"Extend LoadPlugin Fail",level:"error",time:Date.now(),data:s.message})}},r}();wr.usePlugin(Oy,"extend"),wr.usePlugin(Iy,"et"),wr.usePlugin(xy,"heartbeat"),wr.usePlugin(My,"monitor"),new wr("default");var Py=wr;class Cr{constructor({userId:e}){this.collector=new Py("media-engine-logger"),this.collector.init({app_id:834499,channel:"cn",disable_sdk_monitor:!0}),this.collector.config({user_unique_id:e||"media-engine",evtParams:{sdk_version:"1.0.0"}}),this.collector.start()}static getInstance({userId:e}){return Cr.instance||(Cr.instance=new Cr({userId:e})),Cr.instance}event(e,t){this.collector.event(e,t||{})}}class Ly extends $v{constructor({userId:e}){super(qv),this.logger=Cr.getInstance({userId:e})}receiveWorkerMessage({type:e,data:t}){switch(e){case st.PassEngineEvent:{const n=t.event,i=t.data;this.emit(n,i)}break;case st.GetStats:this.emit("_receive_stats",t);break}}start(e){const{video:t}=e,{audio:n}=e;delete e.video,delete e.audio,this.sendTransportable({type:st.Start,data:e},{video:t,audio:n}),this.logger.event("pusher_engine_start")}stop(){this.sendMessage({type:st.Stop}),this.logger.event("pusher_engine_stop")}updateTrack(e,t,n){this.sendTransportable({type:st.UpdateTrack,data:{isAudio:t==="audio",setting:n}},{stream:e}),this.logger.event("pusher_engine_update_track",{type:t,setting:n})}setBitrate(e,t){this.sendMessage({type:st.SetBitrate,data:{bitrate:e,type:t}}),this.logger.event("pusher_engine_set_bitrate",{bitrate:e,type:t})}online(){this.sendMessage({type:st.Online})}reconnect(e){this.sendMessage({type:st.Reconnect,data:{url:e}}),this.logger.event("pusher_engine_reconnect",{url:e})}async getStats(){this.sendMessage({type:st.GetStats});const[e]=await this.onWait("_receive_stats");return e}destroy(){super.destroy(),this.stop()}}function wu(r){let e=!0,t="";for(const n of r)if(!(n in window)){e=!1,t=`${n} not Supported`;break}return{supported:e,info:t}}const Uy=24*60*60*1e3;function Cu(r,e="1d"){const t=`_me_expire_${r}`;let n=0;if(typeof e=="string"){if(!/^[0-9]+d$/.test(e))throw new Error("expire format error");n=Uy*parseInt(e)}else n=e;return{get(){const i=localStorage.getItem(t);if(!i)return null;let o=null;try{o=JSON.parse(i)}catch{return null}const{value:a,expire:s}=o;return s<Date.now()?(localStorage.removeItem(t),null):a},set(i){localStorage.setItem(t,JSON.stringify({value:i,expire:Date.now()+n}))},remove(){localStorage.removeItem(t)}}}var He=(r=>(r[r.AAC=0]="AAC",r[r.OPUS=1]="OPUS",r[r.H264=2]="H264",r[r.H265=3]="H265",r[r.AV1=4]="AV1",r))(He||{});He.AAC+"",He.OPUS+"",He.H264+"",He.H265+"",He.AV1+"";const Zn={[He.AAC]:"mp4a.40.2",[He.OPUS]:"opus",[He.H264]:"avc1.4DE033",[He.H265]:"hev1.1.6.L93.B0"};function ku(r){const e=new MediaStreamTrackProcessor(r),{readable:t}=e,n=r.getSettings();return{readable:t,settings:n}}const Zo=Cu("audio_encoder_support","3d");function Gy(){return wu(["EncodedAudioChunk","AudioEncoder","AudioData"])}function Ny(r){const e=Zo.get(),t=`${r}_support`;return e&&e[t]?e[t]:null}function By(r,e){const t=Zo.get()||{},n=`${r}_support`;t[n]=e,Zo.set(t)}async function Fy(r){if(!AudioEncoder.isConfigSupported)return{supported:!1,info:"isConfigSupported method is undefined"};try{const e={codec:r,sampleRate:48e3,numberOfChannels:2,bitrate:128e3},t=await AudioEncoder.isConfigSupported(e);return t.supported!==void 0?{supported:t.supported,info:t.supported?"isConfigSupported: true":"isConfigSupported: false"}:{supported:!1,info:"isConfigSupported returned undefined"}}catch{return{supported:!1,info:"isConfigSupported method throws error"}}}async function Tu(r){const e=Ny(r);if(e)return console.log(`Audio encoder ${r} support result from cache:`,e),e;const t=await Fy(r);return By(r,t),t}function Vy(){return Tu(Zn[He.OPUS])}function jy(){return Tu(Zn[He.AAC])}const Yo=Cu("video_encoder_support","3d");function Qo(){return wu(["EncodedVideoChunk","VideoEncoder","VideoFrame"])}function zu(r){const e=Yo.get(),t=`${r}_support`;return e&&e[t]?e[t]:null}function es(r,e){const t=Yo.get()||{},n=`${r}_support`;t[n]=e,Yo.set(t)}async function Ru(r){if(!VideoEncoder.isConfigSupported)return{supported:!1,info:"isConfigSupported method is undefined"};try{const e={codec:r,width:640,height:480,bitrate:1e6,framerate:30},t=await VideoEncoder.isConfigSupported(e);return{supported:t.supported??!1,info:t.supported?"isConfigSupported: true":"isConfigSupported: false"}}catch(e){return{supported:!1,info:`isConfigSupported error: ${e instanceof Error?e.message:String(e)}`}}}async function Hy(r,e=3e3){return new Promise(t=>{let n=!1;const i=setTimeout(()=>{n||(n=!0,t({supported:!1,info:"encoding test timeout"}))},e);try{const o=new VideoEncoder({output:h=>{n||(n=!0,clearTimeout(i),o.state!=="closed"&&o.close(),t({supported:!0,info:"encoding test success"}))},error:h=>{n||(n=!0,clearTimeout(i),o.state!=="closed"&&o.close(),t({supported:!1,info:`encoding test error: ${h.message}`}))}}),a={codec:r,width:640,height:480,bitrate:1e6,framerate:30};o.configure(a);const s=640,u=480,c=new OffscreenCanvas(s,u),d=c.getContext("2d");d&&(d.fillStyle="#FF0000",d.fillRect(0,0,s,u));const f=new VideoFrame(c,{timestamp:0});o.encode(f)}catch(o){n||(n=!0,clearTimeout(i),t({supported:!1,info:`encoding test catch: ${o.message}`}))}})}async function $y(r){if(!Qo())return{supported:!1,info:"VideoEncoder API not supported"};const e=zu(r);if(e)return console.log(`Video encoder ${r} support result from cache:`,e),e;const t=await Ru(r);return es(r,t),t}async function qy(r,e=3e3){if(!Qo())return{supported:!1,info:"VideoEncoder API not supported"};const t=zu(r);if(t)return console.log(`Video encoder ${r} support result from cache:`,t),t;const n=await Ru(r);if(!n.supported)return es(r,n),n;const i=await Hy(r,e);return es(r,i),i}function Ky(){return $y(Zn[He.H264])}function Wy(){return qy(Zn[He.H265])}function Jy(){return Gy().supported}function Xy(){return Qo().supported}async function Zy(r){if(!Jy())return{supported:!1,info:"AudioEncoder API not supported"};try{switch(r){case"aac":return await jy();case"opus":return await Vy();default:return{supported:!1,info:`Unsupported audio codec: ${r}`}}}catch(e){return{supported:!1,info:`${r} 检测失败: ${e instanceof Error?e.message:String(e)}`}}}async function Yy(r){if(!Xy())return{supported:!1,info:"VideoEncoder API not supported"};try{switch(r){case"h264":return await Ky();case"h265":return await Wy();default:return{supported:!1,info:`Unsupported video codec: ${r}`}}}catch(e){return{supported:!1,info:`${r} 检测失败: ${e instanceof Error?e.message:String(e)}`}}}async function Qy(r,e=!1){const t=["aac"],n=["h264"],i={audioCodecs:{},videoCodecs:{}};for(const f of t)i.audioCodecs[f]=await Zy(f);for(const f of n)i.videoCodecs[f]=await Yy(f);const o=[],a=[],s=[],u=[];Object.entries(i.audioCodecs).forEach(([f,h])=>{h.supported?o.push(f):a.push(f)}),Object.entries(i.videoCodecs).forEach(([f,h])=>{h.supported?s.push(f):u.push(f)});const d={supported:a.length===0&&u.length===0,supportedAudio:o,supportedVideo:s,unsupportedAudio:a,unsupportedVideo:u};return e&&(d.details=i),d}async function eS(){return(await Qy()).supported}class Au{constructor(e,t,n,i,o){this.url=e,this.config=t,this.onError=n,this.onSuccess=i,this.onReconnectError=o,this._isPushing=!1,this._clearOnline=()=>{},this.sessionId=Date.now(),this.engine=new Ly({userId:ht.instance.userId??""});const a=()=>{this.engine.online()};window.addEventListener("online",a),this._clearOnline=()=>{window.removeEventListener("online",a)}}static async isSupported(){return await eS()&&typeof WebTransport<"u"&&typeof MediaStreamTrackProcessor<"u"&&typeof MediaStreamTrackGenerator<"u"&&typeof VideoEncoder<"u"}get isPushing(){return this._isPushing}get pushUrl(){return this.url}async getStatsSnapshoot(e){e&&await hn(e);const{video:t,audio:n,upspeed:i}=await this.engine.getStats();return{stats:{video:{sendBitrate:t.bitrate,framesPerSecond:t.framerate,framesEncoded:t.encodedFrames,keyFramesEncoded:t.encodedKeyFrames,sendSpeed:i,codec:t.codec,frameWidth:t.width,frameHeight:t.height,gopSize:t.keyGopSize},audio:{sendBitrate:n.bitrate,framesEncoded:n.encodedFrames,codec:n.codec,channels:n.numberOfChannels,sampleRate:n.sampleRate}},originStats:void 0}}async publish(e,t,n){const i={url:this.url,maxReconnectCount:10,autoReconnect:!1,bitrate:{},cfg:Object.assign({gopSize:90},(n==null?void 0:n.cfg)||{}),setting:{}};e.forEach((o,a)=>{if(o.kind==="video"||o.kind==="audio"){const s=ku(o);i[o.kind]=s.readable,i.bitrate[o.kind]=t[a],i.setting[o.kind]=s.settings}}),this.engine.start(i),this._isPushing=!0,this.engine.on({"connect-open":()=>{this._isPushing=!0,this.onSuccess()},error:o=>{this.onError(new Error(JSON.stringify(o)))},"connect-close":o=>{this._isPushing=!1,o==="api call"?console.log("Connection close by api call"):this.onError(new Error(`Connect close, reason=${o}`))},"reconnect-fail":o=>{this._isPushing=!1,this.onReconnectError(new Error(`Reconnect fail, reason=${o}`))}})}unpublish(){this.engine.stop(),this._isPushing=!1}async updatePublish(e,t){e&&this.engine.updateTrack(ku(e).readable,t)}applyBitrate(e,t){this.engine.setBitrate(e,t)}reconnect(e){this.engine.reconnect(e)}destroy(){this._clearOnline(),this.engine.destroy(),this._isPushing=!1}}function Du({pushUrl:r,addPri:e=!1,disableTCC:t=!1}){const n=new URL(r),i=Date.now();return e&&n.searchParams.set("pri",i.toString()),t&&n.searchParams.set("tcc","false"),n.href}class tS{constructor(e,t=Fm){this._reconnectDelay=0,this._reconnectCount=0,this._timeoutTimerId=null,this._reconnectTimeout=null,this._totalReconnectInfo={totalReconnectCount:0,totalReconnectDuration:0},this.handleOnlineReconnect=()=>{this.execute(!0)},this.execute=(n=!1)=>{var i;this._logger.log("start reconnect strategy"),this.state==="idle"&&(this._reconnectStartTime=Date.now(),this._totalReconnectInfo.totalReconnectCount+=1,X(J.PUSH_RECONNECT_START,{start_time:this._reconnectStartTime,session_id:this._pushConsumer.pushSessionId,max_timeout:this._maxTimeout}),this.bindOnlineEvent(),this.setStrategyState("executing"),(i=this._logger)==null||i.log("start reconnecting with max timeout: ",this._maxTimeout),this.startTimeoutTimer(this._maxTimeout),this._pushConsumer.emitReconnectStateChange({state:cr.START,teaParams:{is_online:navigator.onLine,start_time:this._reconnectStartTime,max_timeout:this._maxTimeout,session_id:this._pushConsumer.pushSessionId}})),this.state==="executing"&&(this._reconnectTimeout&&clearTimeout(this._reconnectTimeout),this.executeStrategy(n))},this.attemptReconnect=async()=>{var n;if(this.state==="executing"){this.setStrategyState("reconnecting"),this._reconnectCount+=1;const i=this.getNextPushUrl();try{if(this._pushConsumer.emitReconnectStateChange({state:cr.RECONNECTING,params:{retryTime:this._reconnectCount},teaParams:{retry_push_url:i,session_id:this._pushConsumer.pushSessionId}}),await this._pushConsumer.reconnect(i),!this.isActive())return;this.setStrategyState("executing")}catch(o){const a=o.ext||{},{httpCode:s}=a;if(s!==void 0&&String(s).startsWith("4"))this.stop({isSuccess:!1,reason:si.PushUrlInvalid,failedError:o}),(n=this._onReconnectError)==null||n.call(this,"pushError",o);else{if(!this.isActive())return;this.setStrategyState("executing"),this.execute()}}}},this.executeStrategy=(n=!1)=>{const i=n?0:this._reconnectDelay;this._pushConsumer.emitReconnectStateChange({state:cr.WAITING,params:{waitingTime:i,retryTime:this._reconnectCount+1},teaParams:{is_online:navigator.onLine,session_id:this._pushConsumer.pushSessionId}}),this._logger.log("reconnect after delay: ",i,Date.now()),this._reconnectTimeout=window.setTimeout(this.attemptReconnect,i),this._reconnectDelay=this._reconnectDelay===0?2e3:Math.min(this._reconnectDelay*2,Vm)},this.state="idle",this._pushConsumer=e,this._maxTimeout=t,this._logger=new Bt("ReconnectStrategy")}getNextPushUrl(){const e=this._pushConsumer.pushUrl;return e?Du({pushUrl:e,addPri:!0}):""}set onReconnectError(e){this._onReconnectError=e}bindOnlineEvent(){window.addEventListener("online",this.handleOnlineReconnect)}unbindOnlineEvent(){window.removeEventListener("online",this.handleOnlineReconnect)}setStrategyState(e){this._logger.log("reconnect state change to: ",e),this.state=e}stop({isSuccess:e,reason:t,quiet:n=!1,failedError:i}){var a;if(this.state==="idle")return;const o=(Date.now()-this._reconnectStartTime)/1e3;n||(e?this._pushConsumer.emitReconnectStateChange({state:cr.SUCCESS,teaParams:{reconnect_duration:o,session_id:this._pushConsumer.pushSessionId}}):(this._logger.log("Reconnect strategy stopped: ",t),this._pushConsumer.emitReconnectStateChange({state:cr.FAILED,params:{failedCode:t},teaParams:{reason:t,reconnect_duration:o,error_message:i==null?void 0:i.message,http_code:(a=i==null?void 0:i.ext)==null?void 0:a.httpCode,ext:i==null?void 0:i.ext,session_id:this._pushConsumer.pushSessionId}})),this._totalReconnectInfo.totalReconnectDuration+=o),this.setStrategyState("idle"),this._timeoutTimerId&&clearTimeout(this._timeoutTimerId),this._reconnectTimeout&&clearTimeout(this._reconnectTimeout),this._reconnectDelay=0,this._reconnectCount=0,this._reconnectStartTime=void 0,this.unbindOnlineEvent()}startTimeoutTimer(e){this._timeoutTimerId=window.setTimeout(()=>{var t;this.state!=="idle"&&(this._logger.log("Reconnect strategy timed out"),this.stop({isSuccess:!1,reason:si.ReconnectTimeout}),(t=this._onReconnectError)==null||t.call(this,"timeout"))},e)}clearReconnectInfo(){this._totalReconnectInfo={totalReconnectCount:0,totalReconnectDuration:0}}getReconnectInfo(){return this._totalReconnectInfo}isActive(){return this.state!=="idle"}}const vn={ManualStop:0,ReconnectFailed:1,StartPushError:2,PushError:3},kr={PushCheck:0,PushError:1},Iu=new Bt("PushController");class rS extends Nc{constructor(e,{config:t,streamConsumeController:n,streamComposedController:i}){var o,a;if(super(e),this._connect=null,this._connectionState=$e.DISCONNECTED,this._pushSessionId=0,this._isReportStart=!1,this._pushMode="rtm",this._reconnectStrategy=null,this._needCheckAudioTrack=!1,this._pushConfig={timeout:5e3,retryCount:1,retryDelay:1e3},this._audioBitrate=pr(ys,"audio").bitrate,this._videoBitrate=pr(vs,"video").bitrate,this.handleReconnectError=(s,u)=>{var c,d;X(J.STOP_PUSH_STREAM,{reason:vn.ReconnectFailed,error_message:s,session_id:this._pushSessionId,push_mode:this._pushMode,duration:this.pushDuration,reconnect_times:(c=this._reconnectStrategy)==null?void 0:c.getReconnectInfo().totalReconnectCount,reconnect_duration:(d=this._reconnectStrategy)==null?void 0:d.getReconnectInfo().totalReconnectDuration}),this.unpublish()},this.handleAudioStreamChange=s=>{this.updatePush({audioTrack:s.audioTrack})},this.handleVideoStreamChange=s=>{this.updatePush({videoTrack:s.videoTrack})},this._OnRTMPSuccess=()=>{this.setConnectState($e.CONNECTED)},this._OnMediaReconnectFailed=()=>{this._executeReconnect()},this._OnRTMPError=s=>{const u=new fr(qe.PUBLISH_FAILED,`${s.code?`code:${s.code},`:""} message: ${s.message}`);this.pushDuration<jm||!this._reconnectStrategy||this.pushMode==="webTransport"?(this._streamConsumeController.emit(Ee.PushError,u),X(J.STOP_PUSH_STREAM,{reason:vn.PushError,duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode,error_msg:s.message,error_code:s.code}),X(J.START_PUSH_STATUS,{is_success:!1,reason:kr.PushError,error_message:s.message,session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish()):this._executeReconnect()},this._executeReconnect=()=>{var s;(s=this._reconnectStrategy)==null||s.execute(),this.setConnectState($e.RECONNECTING),this.unpublish({isReconnecting:!0})},this._OnRtcStateChange=s=>{var u;switch(X(J.PUSH_RTC_STATE_CHANGE,{state:s,push_url:this._pushUrl,session_id:this._pushSessionId,push_mode:this._pushMode}),this._streamConsumeController.emit(Ee.RTCConnectStateChanged,s),s){case"connected":this.setConnectState($e.CONNECTED);break;case"disconnected":this._reconnectStrategy&&this._executeReconnect();break;case"failed":(u=this._reconnectStrategy)!=null&&u.isActive()?this._executeReconnect():(this.connectionState===$e.CONNECTED?X(J.STOP_PUSH_STREAM,{reason:vn.PushError,error_message:"peerconnection failed",duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode}):X(J.START_PUSH_STATUS,{is_success:!1,reason:kr.PushError,error_message:"peerconnection failed",session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish(),this._streamConsumeController.emit(Ee.PushError,new fr(qe.PUSH_CONNECT_FAILED,"pc failed")));break}},this._pushMode=(t==null?void 0:t.mode)||"rtm",this._streamConsumeController=n,t&&(this._pushConfig=t,this._needCheckAudioTrack=t.checkAudio??!1),(o=t==null?void 0:t.reconnectConfig)!=null&&o.enable||!(t!=null&&t.reconnectConfig)){const s=(a=t==null?void 0:t.reconnectConfig)!=null&&a.maxTimeout?t.reconnectConfig.maxTimeout*Pi:void 0;this._reconnectStrategy=new tS(this,s),this._reconnectStrategy.onReconnectError=this.handleReconnectError}this._streamComposedController=i}get isPushing(){return this._connectionState===$e.CONNECTED||this._connectionState===$e.RECONNECTING}get pushUrl(){return this._pushUrl}get pushEncodeConfig(){return this._pushEncodeConfig}get sessionId(){var e;return((e=this._connect)==null?void 0:e.sessionId)||0}start(){this.bindComposedStreamEvent()}stop(){this.unbindComposedStreamEvent()}setPushConfig(e){e&&(this._pushConfig=e)}setConnectState(e){var t;switch(this._connectionState=e,this._streamConsumeController.emit(Ee.LiveConnectStateChange,e),e){case $e.CONNECTED:(t=this._reconnectStrategy)!=null&&t.isActive()?this._reconnectStrategy.stop({isSuccess:!0}):(this._streamConsumeController.emit(Ee.PushStart),this.setPushStatsInterval(),X(J.START_PUSH_STATUS,{is_success:!0,push_url:this._pushUrl,session_id:this._pushSessionId,push_mode:this._pushMode}));break}}async getStats(){return this._prevStats}async startPush(e,t={}){var a,s,u;if(t.isReconnect||(this._pushSessionId=Date.now(),t.whipConfig&&(this._whipConfig=t.whipConfig),X(J.START_PUSH,{push_url:e,session_id:this._pushSessionId})),!e)throw X(J.START_PUSH_STATUS,{is_success:!1,session_id:this._pushSessionId,reason:kr.PushCheck,push_url:this._pushUrl}),new Error("lack publish url");if(this._connect)return;this.start(),this._pushUrl=Du({pushUrl:e,disableTCC:!1}),this._pushEncodeConfig=t.cfg;const n=this._composedStream.videoTrack,i=this._composedStream.audioTrack;if(this._needCheckAudioTrack&&(!n||!i)){X(J.START_PUSH_STATUS,{is_success:!1,reason:kr.PushCheck,push_url:this._pushUrl,error_message:"lack videoTrack or audioTrack",video_track_id:n==null?void 0:n.id,audio_track_id:i==null?void 0:i.id,video_track_name:n==null?void 0:n.label,audio_track_name:i==null?void 0:i.label,push_mode:this._pushMode,session_id:this._pushSessionId});return}else if(!n&&!i){X(J.START_PUSH_STATUS,{is_success:!1,reason:kr.PushCheck,push_url:this._pushUrl,error_message:"lack videoTrack and audioTrack",push_mode:this._pushMode,session_id:this._pushSessionId});return}let o;if(this._pushMode==="rtm")o=new qn(this._pushUrl,this._pushConfig,this._OnRtcStateChange);else if(this._pushMode==="webTransport")o=new Bv(this._pushUrl,this._pushConfig,this._OnRTMPError,this._OnRTMPSuccess);else if(this._pushMode==="mediaEngine")o=new Au(this._pushUrl,this._pushConfig,this._OnRTMPError,this._OnRTMPSuccess,this._OnMediaReconnectFailed);else throw new Error(`not support push mode: ${this._pushMode}`);this._connect=o;try{!t.isReconnect&&((a=this._reconnectStrategy)!=null&&a.isActive())&&this._reconnectStrategy.stop({quiet:!0}),(s=this._reconnectStrategy)!=null&&s.isActive()||this.setConnectState($e.CONNECTING),await o.publish([i,n],[this._audioBitrate,this._videoBitrate],{cfg:t.cfg,isReconnect:t.isReconnect,whipConfig:this._whipConfig}),t.isReconnect||(Iu.log("startPush begin"),this._connectionStartDate=Date.now())}catch(c){const d=new fr(qe.PUBLISH_FAILED,c.message,c);if(Iu.groupEnd(),(u=this._reconnectStrategy)!=null&&u.isActive())throw this.unpublish({isReconnecting:!0}),d;this._streamConsumeController.emit(Ee.PushError,d),X(J.STOP_PUSH_STREAM,{reason:vn.PushError,error_message:d.message,enable_reconnect:!1,push_mode:this._pushMode,session_id:this._pushSessionId,duration:this.pushDuration}),X(J.START_PUSH_STATUS,{is_success:!1,push_url:this._pushUrl,reason:kr.PushError,error_message:d.message,session_id:this._pushSessionId,push_mode:this._pushMode}),this.unpublish()}}setPushStatsInterval(){if(this._isReportStart)return;this._isReportStart=!0;const e=async()=>{var t,n,i,o,a;if((t=this._connect)!=null&&t.isPushing){const s=Date.now(),{stats:u,originStats:c}=await this._connect.getStatsSnapshoot(2e3),f=Date.now()-s;!Im(u)&&((n=this._connect)!=null&&n.isPushing)&&this.connectionState===$e.CONNECTED?this._prevStats=u:this._prevStats=void 0;const h=this.pushMode==="rtm"?bv(u,c,{idealFrameRate:(i=this._composedStream._videoStream)==null?void 0:i.frameRate,idealBitrate:this._videoBitrate}):Ev(u),g=this.pushMode==="rtm"?(o=this._connect)==null?void 0:o.videoSenderTrackStats:{};X(J.PUSH_STATS,{...h,...g,video_draw_frame:this._streamComposedController.getCompositionDrawCountPerSecond(),stats:u,push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:h.video_duration||f,video_duration:h.video_duration||f,is_push:!0},!0)}else await hn(2e3),X(J.PUSH_STATS,{push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:2e3,is_push:!1,is_reconnecting:((a=this._reconnectStrategy)==null?void 0:a.isActive())??!1},!0);this.connectionState!==$e.DISCONNECTED&&(this._statsLoopTimer=window.setTimeout(e,0))};e()}async reconnect(e){if(this.pushMode==="rtm")return this.startPush(e,{isReconnect:!0,whipConfig:this._whipConfig});if(this.pushMode==="mediaEngine")return this._connect.reconnect(e)}async updatePush({videoTrack:e,audioTrack:t}){if(this._connect)try{const n=[];e&&n.push(()=>{var i;return(i=this._connect)==null?void 0:i.updatePublish(e,"video")}),t&&n.push(()=>{var i;return(i=this._connect)==null?void 0:i.updatePublish(t,"audio")}),await Promise.all(n.map(i=>i()))}catch(n){const i=new fr(qe.UPDATE_PUBLISH_FAILED,`${n.name}, code:${n.code}`);this._streamConsumeController.emit(Ee.PushError,i)}}unpublish(e={isReconnecting:!1,isManual:!1}){var t,n,i,o,a;e.isReconnecting&&this.pushMode==="mediaEngine"||((t=this._connect)==null||t.unpublish(),this._connect=null),this._prevStats=void 0,e.isManual&&(X(J.STOP_PUSH_STREAM,{reason:vn.ManualStop,duration:this.pushDuration,session_id:this._streamConsumeController.pushSessionId,push_mode:this._pushMode,reconnect_times:(n=this._reconnectStrategy)==null?void 0:n.getReconnectInfo().totalReconnectCount,reconnect_duration:(i=this._reconnectStrategy)==null?void 0:i.getReconnectInfo().totalReconnectDuration}),(o=this._reconnectStrategy)==null||o.clearReconnectInfo()),e.isReconnecting||(this._statsLoopTimer&&window.clearTimeout(this._statsLoopTimer),this._whipConfig=void 0,this._isReportStart=!1,this._pushEncodeConfig=void 0,this._pushUrl=void 0,this._connectionStartDate=void 0,this._pushSessionId=0,this.setConnectState($e.DISCONNECTED),(a=this._reconnectStrategy)==null||a.stop({quiet:!0}),this._streamConsumeController.emit(Ee.PushStop))}async destroy(){this._statsLoopTimer&&window.clearTimeout(this._statsLoopTimer),this._prevStats=void 0,this._isReportStart=!1,this._connect&&await this.unpublish(),this.unbindComposedStreamEvent()}setPushMode(e){this._pushMode=e}updatePushUrl(e){this._pushUrl=e}setBitrate(e,t,n){var i;t==="video"?this._videoBitrate=e:this._audioBitrate=e,(i=this._connect)==null||i.applyBitrate(e,t,n)}getReconnectDetail(){var e;return(e=this._reconnectStrategy)==null?void 0:e.getReconnectInfo()}get pushMode(){return this._pushMode}get connectionState(){return this._connectionState}get pushSessionId(){return this._pushSessionId}get pushDuration(){return this._connectionStartDate?(Date.now()-this._connectionStartDate)/1e3:0}emitReconnectStateChange({state:e,params:t,teaParams:n}){X(J.PUSH_RECONNECT_STATUS,{status:e,...t,...n}),this._streamConsumeController.emit(Ee.ReconnectStateChange,e,t)}}class nS extends Mt{constructor(e,t){super(),this._previewConsumer=new hv(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new rS(e.getComposedStream(),{streamConsumeController:this,streamComposedController:e,config:t})}startPreview(){this._previewConsumer.startPreview()}setRenderView(e){this._previewConsumer.setRenderView(e)}async startPush(e,t){return this._pushConsumer.startPush(e,t)}async stopPush(){return this._pushConsumer.unpublish({isReconnecting:!1,isManual:!0})}setPushMode(e){this._pushConsumer.setPushMode(e)}isPushing(){return this._pushConsumer.isPushing}getStats(){return this._pushConsumer.getStats()}getPreviewElement(){return this._previewConsumer.getPreviewElement()}stopPreview(){this._previewConsumer.stopPreview()}setBitrate(e,t,n){this._pushConsumer.setBitrate(e,t,n)}setPushConfig(e){this._pushConsumer.setPushConfig(e)}updatePushUrl(e){this._pushConsumer.updatePushUrl(e)}getPushDuration(){return this._pushConsumer.pushDuration}getReconnectDetail(){return this._pushConsumer.getReconnectDetail()}get pushSessionId(){return this._pushConsumer.pushSessionId}get pushMode(){return this._pushConsumer.pushMode}async destroy(){await this._pushConsumer.destroy(),this._previewConsumer.destroy()}}class iS{constructor(){this.onError=(e,t,n)=>{},this.onWarning=e=>{},this.onCaptureFirstAudioFrame=()=>{},this.onCaptureFirstVideoFrame=()=>{},this.onPushStatusUpdate=(e,t)=>{},this.onMicrophoneChanged=e=>{},this.onCameraChanged=e=>{},this.onCaptureInterrupted=e=>{},this.onPushStart=()=>{},this.onPushStop=()=>{},this.onStopCapture=e=>{},this.onLiveConnectStateChange=e=>{},this.onReconnectStateChange=(e,t)=>{}}}const oS=new iS;let xu=!0,Mu=!0;function Yn(r,e,t){const n=r.match(e);return n&&n.length>=t&&parseInt(n[t],10)}function sr(r,e,t){if(!r.RTCPeerConnection)return;const n=r.RTCPeerConnection.prototype,i=n.addEventListener;n.addEventListener=function(a,s){if(a!==e)return i.apply(this,arguments);const u=c=>{const d=t(c);d&&(s.handleEvent?s.handleEvent(d):s(d))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(s,u),i.apply(this,[a,u])};const o=n.removeEventListener;n.removeEventListener=function(a,s){if(a!==e||!this._eventMap||!this._eventMap[e])return o.apply(this,arguments);if(!this._eventMap[e].has(s))return o.apply(this,arguments);const u=this._eventMap[e].get(s);return this._eventMap[e].delete(s),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,o.apply(this,[a,u])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function sS(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(xu=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function aS(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Mu=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function Ou(){if(typeof window=="object"){if(xu)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function ts(r,e){Mu&&console.warn(r+" is deprecated, please use "+e+" instead.")}function cS(r){const e={browser:null,version:null};if(typeof r>"u"||!r.navigator||!r.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=r;if(t.userAgentData&&t.userAgentData.brands){const n=t.userAgentData.brands.find(i=>i.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=Yn(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=Yn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Yn(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=r.RTCRtpTransceiver&&"currentDirection"in r.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function Pu(r){return Object.prototype.toString.call(r)==="[object Object]"}function Lu(r){return Pu(r)?Object.keys(r).reduce(function(e,t){const n=Pu(r[t]),i=n?Lu(r[t]):r[t],o=n&&!Object.keys(i).length;return i===void 0||o?e:Object.assign(e,{[t]:i})},{}):r}function rs(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?rs(r,r.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(i=>{rs(r,r.get(i),t)})}))}function Uu(r,e,t){const n=t?"outbound-rtp":"inbound-rtp",i=new Map;if(e===null)return i;const o=[];return r.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&o.push(a)}),o.forEach(a=>{r.forEach(s=>{s.type===n&&s.trackId===a.id&&rs(r,s,i)})}),i}const Gu=Ou;function Nu(r,e){const t=r&&r.navigator;if(!t.mediaDevices)return;const n=function(s){if(typeof s!="object"||s.mandatory||s.optional)return s;const u={};return Object.keys(s).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;const d=typeof s[c]=="object"?s[c]:{ideal:s[c]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);const f=function(h,g){return h?h+g.charAt(0).toUpperCase()+g.slice(1):g==="deviceId"?"sourceId":g};if(d.ideal!==void 0){u.optional=u.optional||[];let h={};typeof d.ideal=="number"?(h[f("min",c)]=d.ideal,u.optional.push(h),h={},h[f("max",c)]=d.ideal,u.optional.push(h)):(h[f("",c)]=d.ideal,u.optional.push(h))}d.exact!==void 0&&typeof d.exact!="number"?(u.mandatory=u.mandatory||{},u.mandatory[f("",c)]=d.exact):["min","max"].forEach(h=>{d[h]!==void 0&&(u.mandatory=u.mandatory||{},u.mandatory[f(h,c)]=d[h])})}),s.advanced&&(u.optional=(u.optional||[]).concat(s.advanced)),u},i=function(s,u){if(e.version>=61)return u(s);if(s=JSON.parse(JSON.stringify(s)),s&&typeof s.audio=="object"){const c=function(d,f,h){f in d&&!(h in d)&&(d[h]=d[f],delete d[f])};s=JSON.parse(JSON.stringify(s)),c(s.audio,"autoGainControl","googAutoGainControl"),c(s.audio,"noiseSuppression","googNoiseSuppression"),s.audio=n(s.audio)}if(s&&typeof s.video=="object"){let c=s.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});const d=e.version<66;if(c&&(c.exact==="user"||c.exact==="environment"||c.ideal==="user"||c.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!d)){delete s.video.facingMode;let f;if(c.exact==="environment"||c.ideal==="environment"?f=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(f=["front"]),f)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(k=>k.kind==="videoinput");let g=h.find(k=>f.some(z=>k.label.toLowerCase().includes(z)));return!g&&h.length&&f.includes("back")&&(g=h[h.length-1]),g&&(s.video.deviceId=c.exact?{exact:g.deviceId}:{ideal:g.deviceId}),s.video=n(s.video),Gu("chrome: "+JSON.stringify(s)),u(s)})}s.video=n(s.video)}return Gu("chrome: "+JSON.stringify(s)),u(s)},o=function(s){return e.version>=64?s:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[s.name]||s.name,message:s.message,constraint:s.constraint||s.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(s,u,c){i(s,d=>{t.webkitGetUserMedia(d,u,f=>{c&&c(o(f))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const s=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(u){return i(u,c=>s(c).then(d=>{if(c.audio&&!d.getAudioTracks().length||c.video&&!d.getVideoTracks().length)throw d.getTracks().forEach(f=>{f.stop()}),new DOMException("","NotFoundError");return d},d=>Promise.reject(o(d))))}}}function Bu(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function Fu(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("ontrack"in r.RTCPeerConnection.prototype)){Object.defineProperty(r.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",i=>{let o;r.RTCPeerConnection.prototype.getReceivers?o=this.getReceivers().find(s=>s.track&&s.track.id===i.track.id):o={track:i.track};const a=new Event("track");a.track=i.track,a.receiver=o,a.transceiver={receiver:o},a.streams=[n.stream],this.dispatchEvent(a)}),n.stream.getTracks().forEach(i=>{let o;r.RTCPeerConnection.prototype.getReceivers?o=this.getReceivers().find(s=>s.track&&s.track.id===i.id):o={track:i};const a=new Event("track");a.track=i,a.receiver=o,a.transceiver={receiver:o},a.streams=[n.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else sr(r,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Vu(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("getSenders"in r.RTCPeerConnection.prototype)&&"createDTMFSender"in r.RTCPeerConnection.prototype){const e=function(i,o){return{track:o,get dtmf(){return this._dtmf===void 0&&(o.kind==="audio"?this._dtmf=i.createDTMFSender(o):this._dtmf=null),this._dtmf},_pc:i}};if(!r.RTCPeerConnection.prototype.getSenders){r.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(s,u){let c=i.apply(this,arguments);return c||(c=e(this,s),this._senders.push(c)),c};const o=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(s){o.apply(this,arguments);const u=this._senders.indexOf(s);u!==-1&&this._senders.splice(u,1)}}const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(o){this._senders=this._senders||[],t.apply(this,[o]),o.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(o){this._senders=this._senders||[],n.apply(this,[o]),o.getTracks().forEach(a=>{const s=this._senders.find(u=>u.track===a);s&&this._senders.splice(this._senders.indexOf(s),1)})}}else if(typeof r=="object"&&r.RTCPeerConnection&&"getSenders"in r.RTCPeerConnection.prototype&&"createDTMFSender"in r.RTCPeerConnection.prototype&&r.RTCRtpSender&&!("dtmf"in r.RTCRtpSender.prototype)){const e=r.RTCPeerConnection.prototype.getSenders;r.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(i=>i._pc=this),n},Object.defineProperty(r.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function ju(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender&&r.RTCRtpReceiver))return;if(!("getStats"in r.RTCRtpSender.prototype)){const t=r.RTCPeerConnection.prototype.getSenders;t&&(r.RTCPeerConnection.prototype.getSenders=function(){const o=t.apply(this,[]);return o.forEach(a=>a._pc=this),o});const n=r.RTCPeerConnection.prototype.addTrack;n&&(r.RTCPeerConnection.prototype.addTrack=function(){const o=n.apply(this,arguments);return o._pc=this,o}),r.RTCRtpSender.prototype.getStats=function(){const o=this;return this._pc.getStats().then(a=>Uu(a,o.track,!0))}}if(!("getStats"in r.RTCRtpReceiver.prototype)){const t=r.RTCPeerConnection.prototype.getReceivers;t&&(r.RTCPeerConnection.prototype.getReceivers=function(){const i=t.apply(this,[]);return i.forEach(o=>o._pc=this),i}),sr(r,"track",n=>(n.receiver._pc=n.srcElement,n)),r.RTCRtpReceiver.prototype.getStats=function(){const i=this;return this._pc.getStats().then(o=>Uu(o,i.track,!1))}}if(!("getStats"in r.RTCRtpSender.prototype&&"getStats"in r.RTCRtpReceiver.prototype))return;const e=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof r.MediaStreamTrack){const n=arguments[0];let i,o,a;return this.getSenders().forEach(s=>{s.track===n&&(i?a=!0:i=s)}),this.getReceivers().forEach(s=>(s.track===n&&(o?a=!0:o=s),s.track===n)),a||i&&o?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):i?i.getStats():o?o.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Hu(r){r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(a,s){if(!s)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const u=e.apply(this,arguments);return this._shimmedLocalStreams[s.id]?this._shimmedLocalStreams[s.id].indexOf(u)===-1&&this._shimmedLocalStreams[s.id].push(u):this._shimmedLocalStreams[s.id]=[s,u],u};const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(c=>{if(this.getSenders().find(f=>f.track===c))throw new DOMException("Track already exists.","InvalidAccessError")});const s=this.getSenders();t.apply(this,arguments);const u=this.getSenders().filter(c=>s.indexOf(c)===-1);this._shimmedLocalStreams[a.id]=[a].concat(u)};const n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],n.apply(this,arguments)};const i=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(s=>{const u=this._shimmedLocalStreams[s].indexOf(a);u!==-1&&this._shimmedLocalStreams[s].splice(u,1),this._shimmedLocalStreams[s].length===1&&delete this._shimmedLocalStreams[s]}),i.apply(this,arguments)}}function $u(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Hu(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const d=t.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(f=>this._reverseStreams[f.id])};const n=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(f=>{if(this.getSenders().find(g=>g.track===f))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){const f=new r.MediaStream(d.getTracks());this._streams[d.id]=f,this._reverseStreams[f.id]=d,d=f}n.apply(this,[d])};const i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},r.RTCPeerConnection.prototype.addTrack=function(d,f){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(z=>z===d))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(z=>z.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const k=this._streams[f.id];if(k)k.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const z=new r.MediaStream([d]);this._streams[f.id]=z,this._reverseStreams[z.id]=f,this.addStream(z)}return this.getSenders().find(z=>z.track===d)};function o(c,d){let f=d.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{const g=c._reverseStreams[h],k=c._streams[g.id];f=f.replace(new RegExp(k.id,"g"),g.id)}),new RTCSessionDescription({type:d.type,sdp:f})}function a(c,d){let f=d.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{const g=c._reverseStreams[h],k=c._streams[g.id];f=f.replace(new RegExp(g.id,"g"),k.id)}),new RTCSessionDescription({type:d.type,sdp:f})}["createOffer","createAnswer"].forEach(function(c){const d=r.RTCPeerConnection.prototype[c],f={[c](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[k=>{const z=o(this,k);h[0].apply(null,[z])},k=>{h[1]&&h[1].apply(null,k)},arguments[2]]):d.apply(this,arguments).then(k=>o(this,k))}};r.RTCPeerConnection.prototype[c]=f[c]});const s=r.RTCPeerConnection.prototype.setLocalDescription;r.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?s.apply(this,arguments):(arguments[0]=a(this,arguments[0]),s.apply(this,arguments))};const u=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){const c=u.get.apply(this);return c.type===""?c:o(this,c)}}),r.RTCPeerConnection.prototype.removeTrack=function(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(d._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(g=>{this._streams[g].getTracks().find(z=>d.track===z)&&(h=this._streams[g])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function ns(r,e){!r.RTCPeerConnection&&r.webkitRTCPeerConnection&&(r.RTCPeerConnection=r.webkitRTCPeerConnection),r.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=r.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=i[t]})}function qu(r,e){sr(r,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}const Ku=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:qu,shimAddTrackRemoveTrack:$u,shimAddTrackRemoveTrackWithNative:Hu,shimGetSendersWithDtmf:Vu,shimGetUserMedia:Nu,shimMediaStream:Bu,shimOnTrack:Fu,shimPeerConnection:ns,shimSenderReceiverGetStats:ju},Symbol.toStringTag,{value:"Module"}));function Wu(r,e){const t=r&&r.navigator,n=r&&r.MediaStreamTrack;if(t.getUserMedia=function(i,o,a){ts("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(i).then(o,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const i=function(a,s,u){s in a&&!(u in a)&&(a[u]=a[s],delete a[s])},o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),i(a.audio,"autoGainControl","mozAutoGainControl"),i(a.audio,"noiseSuppression","mozNoiseSuppression")),o(a)},n&&n.prototype.getSettings){const a=n.prototype.getSettings;n.prototype.getSettings=function(){const s=a.apply(this,arguments);return i(s,"mozAutoGainControl","autoGainControl"),i(s,"mozNoiseSuppression","noiseSuppression"),s}}if(n&&n.prototype.applyConstraints){const a=n.prototype.applyConstraints;n.prototype.applyConstraints=function(s){return this.kind==="audio"&&typeof s=="object"&&(s=JSON.parse(JSON.stringify(s)),i(s,"autoGainControl","mozAutoGainControl"),i(s,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[s])}}}}function uS(r,e){r.navigator.mediaDevices&&"getDisplayMedia"in r.navigator.mediaDevices||r.navigator.mediaDevices&&(r.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){const i=new DOMException("getDisplayMedia without video constraints is undefined");return i.name="NotFoundError",i.code=8,Promise.reject(i)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,r.navigator.mediaDevices.getUserMedia(n)})}function Ju(r){typeof r=="object"&&r.RTCTrackEvent&&"receiver"in r.RTCTrackEvent.prototype&&!("transceiver"in r.RTCTrackEvent.prototype)&&Object.defineProperty(r.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function is(r,e){if(typeof r!="object"||!(r.RTCPeerConnection||r.mozRTCPeerConnection))return;!r.RTCPeerConnection&&r.mozRTCPeerConnection&&(r.RTCPeerConnection=r.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(i){const o=r.RTCPeerConnection.prototype[i],a={[i](){return arguments[0]=new(i==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),o.apply(this,arguments)}};r.RTCPeerConnection.prototype[i]=a[i]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){const[o,a,s]=arguments;return n.apply(this,[o||null]).then(u=>{if(e.version<53&&!a)try{u.forEach(c=>{c.type=t[c.type]||c.type})}catch(c){if(c.name!=="TypeError")throw c;u.forEach((d,f)=>{u.set(f,Object.assign({},d,{type:t[d.type]||d.type}))})}return u}).then(a,s)}}function Xu(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpSender.prototype)return;const e=r.RTCPeerConnection.prototype.getSenders;e&&(r.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(o=>o._pc=this),i});const t=r.RTCPeerConnection.prototype.addTrack;t&&(r.RTCPeerConnection.prototype.addTrack=function(){const i=t.apply(this,arguments);return i._pc=this,i}),r.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Zu(r){if(!(typeof r=="object"&&r.RTCPeerConnection&&r.RTCRtpSender)||r.RTCRtpSender&&"getStats"in r.RTCRtpReceiver.prototype)return;const e=r.RTCPeerConnection.prototype.getReceivers;e&&(r.RTCPeerConnection.prototype.getReceivers=function(){const n=e.apply(this,[]);return n.forEach(i=>i._pc=this),n}),sr(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Yu(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){ts("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function Qu(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function ed(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.addTransceiver;e&&(r.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const i=n.length>0;i&&n.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const o=e.apply(this,arguments);if(i){const{sender:a}=o,s=a.getParameters();(!("encodings"in s)||s.encodings.length===1&&Object.keys(s.encodings[0]).length===0)&&(s.encodings=n,a.sendEncodings=n,this.setParametersPromises.push(a.setParameters(s).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return o})}function td(r){if(!(typeof r=="object"&&r.RTCRtpSender))return;const e=r.RTCRtpSender.prototype.getParameters;e&&(r.RTCRtpSender.prototype.getParameters=function(){const n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function rd(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function nd(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.createAnswer;r.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}const id=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:ed,shimCreateAnswer:nd,shimCreateOffer:rd,shimGetDisplayMedia:uS,shimGetParameters:td,shimGetUserMedia:Wu,shimOnTrack:Ju,shimPeerConnection:is,shimRTCDataChannel:Qu,shimReceiverGetStats:Zu,shimRemoveStream:Yu,shimSenderGetStats:Xu},Symbol.toStringTag,{value:"Module"}));function od(r){if(!(typeof r!="object"||!r.RTCPeerConnection)){if("getLocalStreams"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in r.RTCPeerConnection.prototype)){const e=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(i=>e.call(this,i,n)),n.getVideoTracks().forEach(i=>e.call(this,i,n))},r.RTCPeerConnection.prototype.addTrack=function(n,...i){return i&&i.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),e.apply(this,arguments)}}"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const i=t.getTracks();this.getSenders().forEach(o=>{i.includes(o.track)&&this.removeTrack(o)})})}}function sd(r){if(!(typeof r!="object"||!r.RTCPeerConnection)&&("getRemoteStreams"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in r.RTCPeerConnection.prototype))){Object.defineProperty(r.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(i=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(i))return;this._remoteStreams.push(i);const o=new Event("addstream");o.stream=i,this.dispatchEvent(o)})})}});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){const n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(i){i.streams.forEach(o=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(o)>=0)return;n._remoteStreams.push(o);const a=new Event("addstream");a.stream=o,n.dispatchEvent(a)})}),e.apply(n,arguments)}}}function ad(r){if(typeof r!="object"||!r.RTCPeerConnection)return;const e=r.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,i=e.setLocalDescription,o=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(c,d){const f=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[f]);return d?(h.then(c,d),Promise.resolve()):h},e.createAnswer=function(c,d){const f=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[f]);return d?(h.then(c,d),Promise.resolve()):h};let s=function(u,c,d){const f=i.apply(this,[u]);return d?(f.then(c,d),Promise.resolve()):f};e.setLocalDescription=s,s=function(u,c,d){const f=o.apply(this,[u]);return d?(f.then(c,d),Promise.resolve()):f},e.setRemoteDescription=s,s=function(u,c,d){const f=a.apply(this,[u]);return d?(f.then(c,d),Promise.resolve()):f},e.addIceCandidate=s}function cd(r){const e=r&&r.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=i=>n(ud(i))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,i,o){e.mediaDevices.getUserMedia(n).then(i,o)}).bind(e))}function ud(r){return r&&r.video!==void 0?Object.assign({},r,{video:Lu(r.video)}):r}function dd(r){if(!r.RTCPeerConnection)return;const e=r.RTCPeerConnection;r.RTCPeerConnection=function(n,i){if(n&&n.iceServers){const o=[];for(let a=0;a<n.iceServers.length;a++){let s=n.iceServers[a];s.urls===void 0&&s.url?(ts("RTCIceServer.url","RTCIceServer.urls"),s=JSON.parse(JSON.stringify(s)),s.urls=s.url,delete s.url,o.push(s)):o.push(n.iceServers[a])}n.iceServers=o}return new e(n,i)},r.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(r.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function ld(r){typeof r=="object"&&r.RTCTrackEvent&&"receiver"in r.RTCTrackEvent.prototype&&!("transceiver"in r.RTCTrackEvent.prototype)&&Object.defineProperty(r.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function hd(r){const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);const i=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&i?i.direction==="sendrecv"?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":i.direction==="recvonly"&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):n.offerToReceiveAudio===!0&&!i&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const o=this.getTransceivers().find(a=>a.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&o?o.direction==="sendrecv"?o.setDirection?o.setDirection("sendonly"):o.direction="sendonly":o.direction==="recvonly"&&(o.setDirection?o.setDirection("inactive"):o.direction="inactive"):n.offerToReceiveVideo===!0&&!o&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function fd(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const pd=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:fd,shimCallbacksAPI:ad,shimConstraints:ud,shimCreateOfferLegacy:hd,shimGetUserMedia:cd,shimLocalStreamsAPI:od,shimRTCIceServerUrls:dd,shimRemoteStreamsAPI:sd,shimTrackEventTransceiver:ld},Symbol.toStringTag,{value:"Module"}));var os={exports:{}},md;function dS(){return md||(md=1,function(r){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
83
83
  `).map(n=>n.trim())},e.splitSections=function(t){return t.split(`
84
84
  m=`).map((i,o)=>(o>0?"m="+i:i).trim()+`\r
85
85
  `)},e.getDescription=function(t){const n=e.splitSections(t);return n&&n[0]},e.getMediaSections=function(t){const n=e.splitSections(t);return n.shift(),n},e.matchPrefix=function(t,n){return e.splitLines(t).filter(i=>i.indexOf(n)===0)},e.parseCandidate=function(t){let n;t.indexOf("a=candidate:")===0?n=t.substring(12).split(" "):n=t.substring(10).split(" ");const i={foundation:n[0],component:{1:"rtp",2:"rtcp"}[n[1]]||n[1],protocol:n[2].toLowerCase(),priority:parseInt(n[3],10),ip:n[4],address:n[4],port:parseInt(n[5],10),type:n[7]};for(let o=8;o<n.length;o+=2)switch(n[o]){case"raddr":i.relatedAddress=n[o+1];break;case"rport":i.relatedPort=parseInt(n[o+1],10);break;case"tcptype":i.tcpType=n[o+1];break;case"ufrag":i.ufrag=n[o+1],i.usernameFragment=n[o+1];break;default:i[n[o]]===void 0&&(i[n[o]]=n[o+1]);break}return i},e.writeCandidate=function(t){const n=[];n.push(t.foundation);const i=t.component;i==="rtp"?n.push(1):i==="rtcp"?n.push(2):n.push(i),n.push(t.protocol.toUpperCase()),n.push(t.priority),n.push(t.address||t.ip),n.push(t.port);const o=t.type;return n.push("typ"),n.push(o),o!=="host"&&t.relatedAddress&&t.relatedPort&&(n.push("raddr"),n.push(t.relatedAddress),n.push("rport"),n.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(n.push("tcptype"),n.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(n.push("ufrag"),n.push(t.usernameFragment||t.ufrag)),"candidate:"+n.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let n=t.substring(9).split(" ");const i={payloadType:parseInt(n.shift(),10)};return n=n[0].split("/"),i.name=n[0],i.clockRate=parseInt(n[1],10),i.channels=n.length===3?parseInt(n[2],10):1,i.numChannels=i.channels,i},e.writeRtpMap=function(t){let n=t.payloadType;t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType);const i=t.channels||t.numChannels||1;return"a=rtpmap:"+n+" "+t.name+"/"+t.clockRate+(i!==1?"/"+i:"")+`\r