@byteplus/vepusher 2.0.4-rc.7 → 2.0.4-rc.9
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.es.d.ts +2 -2
- package/dist/index.es.js +8939 -4874
- package/dist/index.umd.js +35 -22
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(Ne,_e){typeof exports=="object"&&typeof module<"u"?module.exports=_e():typeof define=="function"&&define.amd?define(_e):(Ne=typeof globalThis<"u"?globalThis:Ne||self,Ne.vePusher=_e())})(this,function(){"use strict";var Tg=Object.defineProperty;var kg=(Ne,_e,it)=>_e in Ne?Tg(Ne,_e,{enumerable:!0,configurable:!0,writable:!0,value:it}):Ne[_e]=it;var P=(Ne,_e,it)=>kg(Ne,typeof _e!="symbol"?_e+"":_e,it);var Gc,Bc,Fc,Vc,jc,Hc;function Ne(r,e){for(var t=0;t<e.length;t++){const n=e[t];if(typeof n!="string"&&!Array.isArray(n)){for(const i in n)if(i!=="default"&&!(i in r)){const s=Object.getOwnPropertyDescriptor(n,i);s&&Object.defineProperty(r,i,s.get?s:{enumerable:!0,get:()=>n[i]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}function _e(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var it={exports:{}},as;function $c(){return as||(as=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(d,c,u){this.fn=d,this.context=c,this.once=u||!1}function s(d,c,u,h,l){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new i(u,h||d,l),y=t?t+c:c;return d._events[y]?d._events[y].fn?d._events[y]=[d._events[y],f]:d._events[y].push(f):(d._events[y]=f,d._eventsCount++),d}function a(d,c){--d._eventsCount===0?d._events=new n:delete d._events[c]}function o(){this._events=new n,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,h;if(this._eventsCount===0)return c;for(h in u=this._events)e.call(u,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var l=0,f=h.length,y=new Array(f);l<f;l++)y[l]=h[l].fn;return y},o.prototype.listenerCount=function(c){var u=t?t+c:c,h=this._events[u];return h?h.fn?1:h.length:0},o.prototype.emit=function(c,u,h,l,f,y){var C=t?t+c:c;if(!this._events[C])return!1;var v=this._events[C],E=arguments.length,k,g;if(v.fn){switch(v.once&&this.removeListener(c,v.fn,void 0,!0),E){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,u),!0;case 3:return v.fn.call(v.context,u,h),!0;case 4:return v.fn.call(v.context,u,h,l),!0;case 5:return v.fn.call(v.context,u,h,l,f),!0;case 6:return v.fn.call(v.context,u,h,l,f,y),!0}for(g=1,k=new Array(E-1);g<E;g++)k[g-1]=arguments[g];v.fn.apply(v.context,k)}else{var D=v.length,L;for(g=0;g<D;g++)switch(v[g].once&&this.removeListener(c,v[g].fn,void 0,!0),E){case 1:v[g].fn.call(v[g].context);break;case 2:v[g].fn.call(v[g].context,u);break;case 3:v[g].fn.call(v[g].context,u,h);break;case 4:v[g].fn.call(v[g].context,u,h,l);break;default:if(!k)for(L=1,k=new Array(E-1);L<E;L++)k[L-1]=arguments[L];v[g].fn.apply(v[g].context,k)}}return!0},o.prototype.on=function(c,u,h){return s(this,c,u,h,!1)},o.prototype.once=function(c,u,h){return s(this,c,u,h,!0)},o.prototype.removeListener=function(c,u,h,l){var f=t?t+c:c;if(!this._events[f])return this;if(!u)return a(this,f),this;var y=this._events[f];if(y.fn)y.fn===u&&(!l||y.once)&&(!h||y.context===h)&&a(this,f);else{for(var C=0,v=[],E=y.length;C<E;C++)(y[C].fn!==u||l&&!y[C].once||h&&y[C].context!==h)&&v.push(y[C]);v.length?this._events[f]=v.length===1?v[0]:v:a(this,f)}return this},o.prototype.removeAllListeners=function(c){var u;return c?(u=t?t+c:c,this._events[u]&&a(this,u)):(this._events=new n,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,r.exports=o}(it)),it.exports}var Kc=$c();const st=_e(Kc);var cs=(r=>(r.LeftToRight="LeftToRight",r.UpToDown="UpToDown",r.All="All",r.None="None",r))(cs||{}),Q=(r=>(r.Camera="camera",r.Screen="screen",r.VideoFile="videoFile",r.Microphone="microphone",r.AudioFile="audioFile",r.Image="image",r.MixAudio="mixAudio",r.MixVideo="mixVideo",r.CustomVideo="customVideo",r.CustomAudio="customAudio",r))(Q||{}),Be=(r=>(r.DeviceCaptured="deviceCaptured",r.DeviceStopCapture="deviceStopCapture",r.Error="error",r.Interrupted="interrupted",r))(Be||{}),se=(r=>(r.PushStart="pushStart",r.PushStop="pushStop",r.PushError="pushError",r.RTCConnectStateChanged="rtcConnectStateChanged",r.CaptureFirstVideoFrame="capturefirstvideoframe",r.CaptureFirstAudioFrame="capturefirstaudioframe",r.NotAllowedAutoPlay="notallowedautoplay",r.ReconnectStateChange="reconnectStateChange",r.LiveConnectStateChange="liveConnectStateChange",r))(se||{}),us=(r=>(r["120p"]="160x120x15x200",r["180p"]="320x180x15x350",r["240p"]="320x240x15x400",r["360p"]="640x360x15x800",r["480p"]="640x480x15x900",r["720p-1"]="1280x720x15x1500",r["720p-2"]="1280x720x25x1500",r["720p-3"]="1280x720x30x1500",r["1080p-1"]="1920x1080x15x2080",r["1080p-2"]="1920x1080x25x3000",r["1080p-3"]="1920x1080x30x3150",r))(us||{}),ds=(r=>(r["120p"]="120x160x15x200",r["180p"]="180x320x15x350",r["240p"]="240x320x15x400",r["360p"]="360x640x15x800",r["480p"]="480x640x15x900",r["720p-1"]="720x1280x15x1500",r["720p-2"]="720x1280x25x1500",r["720p-3"]="720x1280x30x1500",r["1080p-1"]="1080x1920x15x2080",r["1080p-2"]="1080x1920x25x3000",r["1080p-3"]="1080x1920x30x3150",r))(ds||{}),ls=(r=>(r.STANDARD="48000x40",r.HIGH="48000x128",r))(ls||{}),vt=(r=>(r.VideoStreamChange="videoStreamChange",r.AudioStreamChange="audioStreamChange",r))(vt||{}),hs=(r=>(r[r.init=-1]="init",r[r.new=0]="new",r[r.connecting=1]="connecting",r[r.connected=2]="connected",r[r.disconnected=3]="disconnected",r[r.failed=4]="failed",r[r.closed=5]="closed",r))(hs||{});const ps={SizeChange:"sizeChange"};var In=(r=>(r.Portrait="portrait",r.Landscape="landscape",r))(In||{});const fs="720p-1",ms="STANDARD";var xe=(r=>(r[r.DISCONNECTED=0]="DISCONNECTED",r[r.CONNECTING=1]="CONNECTING",r[r.CONNECTED=2]="CONNECTED",r[r.RECONNECTING=3]="RECONNECTING",r))(xe||{}),Mt=(r=>(r[r.START=1]="START",r[r.WAITING=2]="WAITING",r[r.RECONNECTING=3]="RECONNECTING",r[r.SUCCESS=4]="SUCCESS",r[r.FAILED=5]="FAILED",r))(Mt||{}),zn=(r=>(r[r.PushUrlInvalid=1001]="PushUrlInvalid",r[r.ReconnectTimeout=1002]="ReconnectTimeout",r))(zn||{}),K=(r=>(r.TRACK_NOT_AVAILABLE="track-not-available",r.UNEXPECTED_TYPE="unexpected-type",r.PLAY_FAILED="play-failed",r.CAPTURE_FAILED="capture-failed",r.NOT_SUPPORTED="not-supported",r.UNEXPECTED_ERROR="unexpected-error",r))(K||{}),te=(r=>(r.AUDIO="audio",r.VIDEO="video",r))(te||{}),ge=(r=>(r.ENDED="ended",r.MUTE="mute",r.UNMUTE="unmute",r.PLAY_FAILED="play-failed",r.SIZE_CHANGE="size-change",r))(ge||{});const pe=[];for(let r=0;r<256;++r)pe.push((r+256).toString(16).slice(1));function Wc(r,e=0){return(pe[r[e+0]]+pe[r[e+1]]+pe[r[e+2]]+pe[r[e+3]]+"-"+pe[r[e+4]]+pe[r[e+5]]+"-"+pe[r[e+6]]+pe[r[e+7]]+"-"+pe[r[e+8]]+pe[r[e+9]]+"-"+pe[r[e+10]]+pe[r[e+11]]+pe[r[e+12]]+pe[r[e+13]]+pe[r[e+14]]+pe[r[e+15]]).toLowerCase()}let Pn;const Jc=new Uint8Array(16);function Xc(){if(!Pn){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Pn=crypto.getRandomValues.bind(crypto)}return Pn(Jc)}const _s={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function yt(r,e,t){var i;if(_s.randomUUID&&!r)return _s.randomUUID();r=r||{};const n=r.random??((i=r.rng)==null?void 0:i.call(r))??Xc();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Wc(n)}class gs{constructor(){P(this,"id",yt());P(this,"_nextNode");P(this,"_track");P(this,"_destNode")}gain(e){if(this._nextNode instanceof vs)return this._nextNode.g=e,this._nextNode;const t=new vs(this,{g:e});return this._nextNode=t,t}connect(e,t){if(!this.available())return;let{_node:n}=this;n||(n=this.createNode(e)),this._node=n,this.previousNode&&this.previousNode.connect(e,n),t&&n.connect(t)}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}destroy(){var e;(e=this._node)==null||e.disconnect(),delete this._node}}class vs extends gs{constructor(t,n){super();P(this,"previousNode");P(this,"_node");P(this,"_g");this.previousNode=t,this._g=n.g}createNode(t){return new GainNode(t,{gain:this._g})}set g(t){this._g=t,this._node&&(this._node.gain.value=t)}}class Zc extends gs{constructor(t){super();P(this,"previousNode",null);P(this,"source");this.source=t}available(){return this.source.available()}destroy(){super.destroy()}}class Yc extends Zc{constructor(){super(...arguments);P(this,"_node")}createNode(t){if(this._node)return this._node;let n;if(this.source instanceof Rs){const i=this.source.element();n=new MediaElementAudioSourceNode(t,{mediaElement:i}),i.muted=!1}else{const i=this.source.track();n=new MediaStreamAudioSourceNode(t,{mediaStream:new MediaStream([i])})}return n}}class $ extends Error{constructor(t,n,i){super(n);P(this,"code");P(this,"message");P(this,"error");this.code=t,this.message=n,this.error=i,Object.setPrototypeOf(this,$.prototype)}toString(){return`VeCapture Error: ${this.code} ${this.message}`}}const ys={info:{color:"rgba(93, 173, 226, 0)",text:"INFO"},warn:{color:"rgba(255, 119, 0, 0.3)",text:"WARN"},err:{color:"rgba(255, 0, 0, 0.3)",text:"ERR "},succ:{color:"rgba(0, 119, 0, 0.3)",text:"SUCC"}},Ss="__debug__",Qc="[VE-CAPTURE]";function eu(){if(typeof location>"u"||typeof localStorage>"u")return!1;let r=!1;return location.href.includes(Ss)&&(r=!0),localStorage.getItem(Ss)&&(r=!0),r}let Se=class{constructor(e){P(this,"moduleName");this.moduleName=e}print(e,t,...n){const i=tu();eu()&&console.log(`${i}-${Qc}%c[${ys[e].text}]%c[${this.moduleName}][${t}]`,`background-color:${ys[e].color};`,"background-color:rgba(0, 0, 0, 0)",...n)}info(e,...t){this.print("info",e,...t)}warn(e,...t){this.print("warn",e,...t)}error(e,...t){this.print("err",e,...t)}success(e,...t){this.print("succ",e,...t)}invoke(e,t){const n=this;return function(...s){n.info(`${t}-invoke`,...s);try{const a=e(...s);return typeof(a==null?void 0:a.then)=="function"?a.then(o=>(n.success(`${t}-result`,o),o)).catch(o=>{throw n.error(`${t}-result`,o),o}):(n.success(`${t}-result`,a),a)}catch(a){n.error(`[${t}-result`,a)}}}};function tu(){const r=new Date;return`${r.toTimeString().split(" ")[0]}:${r.getMilliseconds().toString().padStart(3,"0")}`}function On(r,e){const t=document.createElement(r);return e.id&&(t.id=e.id),e.classList&&e.classList.forEach(n=>{t.classList.add(n)}),e.style&&Object.assign(t.style,e.style),e.attributes&&Object.entries(e.attributes).forEach(([n,i])=>{n==="muted"&&(t instanceof HTMLVideoElement||t instanceof HTMLAudioElement)?t.muted=!0:t.setAttribute(n,i)}),t}function bs({width:r,height:e}){const t=document.createElement("canvas"),n=t.getContext("2d");if(!n)throw new $(K.NOT_SUPPORTED,"CanvasRenderingContext2D is not supported by user agent");return t.width=r,t.height=e,t.style.width="100%",t.style.height="100%",{context:n,canvas:t}}class Mn{constructor(e){P(this,"target");P(this,"_eventDict",new Map);this.target=e}on(e,t){let n=this._eventDict.get(e);n||(n=[t]),this._eventDict.set(e,n),this.target.addEventListener(e,t)}off(e,t){let n=this._eventDict.get(e);n&&(n=n.filter(i=>i!==t),this._eventDict.set(e,n),this.target.removeEventListener(e,t))}once(e,t){const n=i=>{t(i),this.off(e,n)};this.on(e,n)}clear(e){const t=this._eventDict.get(e);t&&t.forEach(n=>{this.target.removeEventListener(e,n)})}clearAll(){for(const e of this._eventDict.keys())this.clear(e)}}const oe=()=>typeof window>"u";function ie(){return navigator.userAgent.toLowerCase()}function Ln(r=ie()){let e="none";return oe()||(r.match("firefox")!==null?e="firefox":r.match("Chrome")!==null?(e="chrome",r.match("Electron")!==null&&(e="electron")):(r.match("Safari")!==null||r.match("AppleWebKit")!==null)&&(e="safari")),e}const Es=Ln()==="firefox",Hr=Ln()==="safari";Ln(),!oe()&&/crios/i.test(ie()),!oe()&&/edg\//i.test(ie()),!oe()&&/edgA/i.test(ie()),!oe()&&/edgios/i.test(ie()),!oe()&&/dingtalk/i.test(ie()),!oe()&&/opr\//.test(ie()),!oe()&&/(iphone|ipod)/i.exec(ie()),!oe()&&(/(ipad)/i.exec(ie())||/macintosh/i.test(ie())&&"ontouchend"in document),!oe()&&/macintosh/i.test(ie()),!oe()&&/micromessenger/i.test(ie()),!oe()&&ie().includes("mobile"),!oe()&&/sm-\w+/i.test(ie());const ru=!oe()&&!!/(iphone|ipad|ipod)/i.exec(ie());!oe()&&/android/i.test(ie()),!oe()&&/windows/i.test(ie()),!oe()&&/openharmony/i.test(ie());let Cs="0";const nu=!oe()&&((Gc=ie().match(/version\/(\d+)/i))==null?void 0:Gc[1]);Hr&&nu&&(Cs=(Bc=navigator.userAgent.match(/version\/(\d+\.\d+)/i))==null?void 0:Bc[1]),!oe()&&((Fc=ie().match(/firefox\/(\d+)/i))==null||Fc[1]);const Nn=Cs;!oe()&&((jc=(Vc=ie().match(/ ([\d_]+) like mac os x/i))==null?void 0:Vc[1])==null||jc.split("_").map(r=>parseInt(r))),!oe()&&((Hc=ie().match(/chrome\/(\d+)/i))==null||Hc[1]);function iu(){var r;return!!((r=navigator==null?void 0:navigator.permissions)!=null&&r.query)}function Un(){return!!(navigator!=null&&navigator.mediaDevices)}function su(){var r;return Un()&&!!((r=navigator==null?void 0:navigator.mediaDevices)!=null&&r.getUserMedia)}function ou(){return!!Promise.withResolvers}function au(){return!(Hr&&Nn==="16.1")}function cu(){return!(Hr&&Nn&&["16.1","16.2","16.3"].includes(Nn))}function uu(){return!Es}function du(){return typeof CanvasCaptureMediaStreamTrack<"u"}function lu(r){return typeof r.requestFrame=="function"}function hu(){return!!Un()&&typeof navigator.mediaDevices.ondevicechange<"u"&&typeof navigator.mediaDevices.addEventListener=="function"}const Ke={permissionQuery:iu,mediaDevices:Un,settingResolutionInGetDisplayMedia:au,promiseWithResolvers:ou,getUserMedia:su,isolateEnumerateDevices:uu,supportIdealParamsInGetDisplayMedia:cu,canvasCaptureMediaStreamTrack:du,requestFrameOnMediaStream:lu,ondevicechange:hu};function pu(){if(Ke.promiseWithResolvers())return Promise.withResolvers();let r,e;const t=new Promise((n,i)=>{r=n,e=i});if(!r||!e)throw Error("resolver and rejector working unexpected");return{promise:t,resolve:r,reject:e}}function ws(r={}){const{timeout:e,message:t}={timeout:0,message:new $(K.UNEXPECTED_ERROR,"unexpected timeout"),...r},{promise:n,resolve:i,reject:s}=pu();if(e<=0)return{promise:n,resolve:i,reject:s};const a=setTimeout(()=>{s(t)},e);return{promise:n,resolve:d=>{clearTimeout(a),i(d)},reject:s}}const fu={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"metadata",muted:"",crossOrigin:"anonymous"},mu={playsinline:"","webkit-playsinline":"",preload:"metadata",muted:"",crossOrigin:"anonymous"};class Yt{constructor(e,t=[]){P(this,"id",yt());P(this,"_referenceTracks",[]);P(this,"_element");P(this,"_volumeMode",0);P(this,"_readyLock");P(this,"_releaseReadyLock");P(this,"_throwReadyLock");P(this,"_stream");let n;if(e instanceof MediaStreamTrack){const o=new MediaStream([e]);n=_u(o),this._stream=o}else if(e.url)n=gu(e);else throw new $(K.UNEXPECTED_TYPE,`got ${typeof e}, expected: MediaStreamTrack or constraints for creating element`);const{promise:i,resolve:s,reject:a}=ws({timeout:2e3,message:new $(K.PLAY_FAILED,"load media timeout")});this._readyLock=i,this._releaseReadyLock=s,this._throwReadyLock=a,this._element=new Mn(n),this._bindPlayerEvent(this._element),this._referenceTracks=[...t]}addReferenceTrack(e){this._referenceTracks.push(e)}track(e){this._playElement();let t=this._stream;if((!t||!t.active)&&(t=this._element.target.captureStream(),this._stream=t),e===te.AUDIO){this._upgradeVolumeMode(1e-4);const n=t.getAudioTracks();if(n.length<1)throw new $(K.UNEXPECTED_TYPE,"got empty list of audio tracks");return n[0]}if(e===te.VIDEO){const n=t.getVideoTracks();if(n.length<1)throw new $(K.UNEXPECTED_TYPE,"got empty list of video tracks");return n[0]}throw new $(K.UNEXPECTED_TYPE,`got ${e}, expected: audio, video`)}async _playElement(){if(!(!this._element.target.muted&&this._element.target.volume===this._volumeMode&&!this._element.target.paused))try{this._element.target.muted=!1,this._element.target.volume=this._volumeMode,await this._element.target.play()}catch(e){throw this._handlePlayFailed(),new $(K.PLAY_FAILED,"play element failed",e)}}_bindPlayerEvent(e){e.on("loadedmetadata",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new $(K.PLAY_FAILED,"HTMLMediaElement got error when loading file"))})}_handlePlayFailed(){this._referenceTracks.forEach(e=>{e.handlePlayFailed()})}_upgradeVolumeMode(e){console.warn("update volume mode",e);const t=this._volumeMode>e?this._volumeMode:e;this._volumeMode=t,this._playElement()}element(e=!1){return e&&this._upgradeVolumeMode(1),this._playElement(),this._element.target}isReady(){return this._readyLock}removeReference(e){const t=this._referenceTracks.indexOf(e);this._referenceTracks.splice(t,1),this._referenceTracks.length===0&&this.destroy()}destroy(){this._element.target.srcObject=null,this._element.target.src="",this._element.target.load();const e=[...this._referenceTracks];this._referenceTracks=[],e.forEach(t=>{try{t.destroy()}catch{}})}}function _u(r){let e="audio";r.getVideoTracks().length>0&&(e="video");const t=Ts(e==="video"?te.VIDEO:te.AUDIO);return t.srcObject=r,t}function gu(r){const{url:e,kind:t,loop:n}=r,i=Ts(t);return i.src=e,i.loop=n,i}function Ts(r){if(r===te.VIDEO)return On(te.VIDEO,{style:{width:"100%",height:"100%"},attributes:fu});if(r===te.AUDIO)return On(te.AUDIO,{style:{display:"none"},attributes:mu});throw new $(K.UNEXPECTED_TYPE,`got ${r}, expected: audio, video`)}class Gn extends st{emit(e,...t){const n=this.listenerCount(e);return Promise.resolve().then(()=>{super.emit(e,...t)}),!!n}on(e,t,n){const i=(...s)=>{try{return t(...s)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.on(e,i,n)}once(e,t,n){const i=(...s)=>{try{return t(...s)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.once(e,i,n)}}function Bn(r){if(typeof r=="number")return r;if(typeof(r==null?void 0:r.exact)=="number")return r.exact;if(typeof(r==null?void 0:r.ideal)=="number")return r.ideal;if(typeof(r==null?void 0:r.max)=="number")return r.max;if(typeof(r==null?void 0:r.min)=="number")return r.min;throw new $(K.UNEXPECTED_TYPE,"unexpected constraints type")}const qr=1e3;class ks{constructor(e){P(this,"id",yt());P(this,"_context");P(this,"_canvas");P(this,"_image");P(this,"_config");P(this,"_readyLock");P(this,"_releaseReadyLock");P(this,"_throwReadyLock");P(this,"_loopTimer");P(this,"_referenceTracks",[]);P(this,"_stream");const t=Bn(e.width),n=Bn(e.height),i=Bn(e.frameRate);this._config={width:t,height:n,frameRate:i};const{context:s,canvas:a}=bs({width:t,height:n});this._context=s,this._canvas=a;const o=vu({url:e.url,width:t,height:n});this._image=new Mn(o);const{promise:d,resolve:c,reject:u}=ws({timeout:2e3,message:new $(K.PLAY_FAILED,"load image timeout")});this._readyLock=d,this._releaseReadyLock=c,this._throwReadyLock=u,this._bindImageEvent(this._image)}track(){this._paint();const{frameRate:e}=this._config;let t=this._stream;(!t||!t.active)&&(t=this._canvas.captureStream(e),this._stream=t);const n=t.getVideoTracks();if(n.length<1)throw new $(K.UNEXPECTED_TYPE,"got empty list of video tracks");return n[0]}element(){return this._image.target}isReady(){return this._readyLock}_bindImageEvent(e){e.on("load",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new $(K.PLAY_FAILED,"HTMLMediaElement got error when loading file"))})}async _paint(){const{width:e,height:t,frameRate:n}=this._config;this._context.drawImage(this._image.target,0,0,e,t),this._loopTimer&&clearTimeout(this._loopTimer),this._loopTimer=setTimeout(this._paint.bind(this),qr/n)}addReferenceTrack(e){this._referenceTracks.push(e)}removeReference(e){const t=this._referenceTracks.indexOf(e);this._referenceTracks.splice(t,1),console.warn("reference length",this._referenceTracks),this._referenceTracks.length}}function vu({url:r,height:e,width:t}){const n=On("img",{style:{width:`${t}px`,height:`${e}px`},attributes:{crossOrigin:"anonymous"}});return n.src=r,n}class Fn extends Gn{constructor(t){super();P(this,"id",yt());P(this,"_track");P(this,"_element");t instanceof MediaStreamTrack?(this._track=new Mn(t),this._bindTrackEvent(this._track)):t instanceof Yt?(this._element=t,t.addReferenceTrack(this)):t instanceof ks&&(this._element=t)}_bindTrackEvent(t){t.on("ended",this._handleTrackEnded.bind(this)),t.on("mute",()=>{this.emit(ge.MUTE)}),t.on("unmute",()=>{this.emit(ge.UNMUTE)})}_handleTrackEnded(){this.emit(ge.ENDED),this.destroy()}handlePlayFailed(){this.emit(ge.PLAY_FAILED)}track(){if(this.logger.info("track"),!this.available())throw new $(K.TRACK_NOT_AVAILABLE,"track is not available when creating MediaStreamTrack");if(this._track)return this._track.target;if(!this._element)throw new $(K.UNEXPECTED_TYPE,"got this._element falsy");const t=this._element.track(this.kind);return this.logger.success("track",t),t}element(){if(this.logger.info("element"),!this.available())throw new $(K.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element)return this._element.element();if(!this._track)throw new $(K.UNEXPECTED_TYPE,"got this._track falsy");const t=new Yt(this._track.target,[this]);this._element=t;const n=t.element();return this.logger.success("element",n),n}available(){return!!(this._track||this._element)}destroy(){var t,n,i;(t=this._track)==null||t.clearAll(),(n=this._track)==null||n.target.stop(),this._track&&delete this._track,(i=this._element)==null||i.removeReference(this),delete this._element}}class $r extends Fn{constructor(){super(...arguments);P(this,"kind",te.AUDIO);P(this,"_node")}node(){if(this.logger.info("node",this.id),!this.available())throw new $(K.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");if(this._node)return this._node;const t=new Yc(this);return this._node=t,t}element(){if(this.logger.info("element",this.id),!this.available())throw new $(K.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element){const n=this._element.element(!0);if(!(n instanceof HTMLMediaElement))throw new $(K.UNEXPECTED_TYPE,"source should be HTMLMediaElement");return n}if(!this._track)throw new $(K.UNEXPECTED_TYPE,"got this._track falsy");const t=new Yt(this._track.target,[this]);return this._element=t,t.element()}destroy(){var t;this.logger.warn("destroy",this.id),(t=this._node)==null||t.destroy(),super.destroy()}}class yu extends $r{constructor(){super(...arguments);P(this,"logger",new Se("MicrophoneAudioTrack"))}}class Su extends $r{constructor(){super(...arguments);P(this,"logger",new Se("ScreenAudioTrack"))}}class Rs extends $r{constructor(){super(...arguments);P(this,"logger",new Se("MediaAudioTrack"))}handlePlayFailed(){this.emit(ge.PLAY_FAILED)}async play(){if(this._element){if(!(this._element instanceof Yt))throw new $(K.UNEXPECTED_TYPE,"element is not TrackMediaElement");return this._element._playElement()}}}class bu extends $r{constructor(){super(...arguments);P(this,"logger",new Se("CustomAudioTrack"))}}let Eu=1;const Vn=new Se("PromiseQueue");class Cu{constructor(e){P(this,"lockingPromise",Promise.resolve());P(this,"locks",0);P(this,"name","");P(this,"lockId");P(this,"closeReason");this.lockId=Eu++,e&&(this.name=e),Vn.info(`lock-${this.name}-${this.lockId}`,"is created.")}get isLocked(){return this.locks>0}lock(){this.locks+=1,Vn.info(`lock-${this.name}-${this.lockId}`,`locked, current queue ${this.locks}.`);let e;const t=new Promise(i=>{e=()=>{this.locks-=1,Vn.info(`lock-${this.name}-${this.lockId}`,`unlocked, current queue ${this.locks}.`),i()}}),n=this.lockingPromise.then(()=>e);return this.lockingPromise=this.lockingPromise.then(()=>t),n}}const wu=300,Tu=3e3,Fe=new Se("Devices");class ku extends Gn{constructor(){super();P(this,"_deviceMap",{audioinput:[],audiooutput:[],videoinput:[]});P(this,"_permissions",{[te.AUDIO]:!1,[te.VIDEO]:!1});P(this,"_changedQueue",new Cu("device changed queue"));this._init()}async _init(){this._initDeviceChanged(),await this._initPermissionChanged();const t=Is(this._permissions);t.length>0&&this._refreshDevices(t)}_initDeviceChanged(){if(Fe.info("_initDeviceChanged","invoked"),!Ke.ondevicechange()){Fe.error("_initDeviceChanged","no supported, use timer instead"),setInterval(()=>{this._handleDeviceChanged()},Tu);return}Ke.ondevicechange()&&navigator.mediaDevices.addEventListener("devicechange",()=>{Fe.info("devicechange"),setTimeout(()=>{this._handleDeviceChanged()},wu)})}async _initPermissionChanged(){if(!Ke.permissionQuery()){Fe.error("_initPermissionChanged","permission query not supported, silent return");return}try{const t=await navigator.permissions.query({name:"microphone"});this._permissions.audio=t.state==="granted",t.addEventListener("change",()=>{Fe.info("_initPermissionChanged","update permission for audio"),this._permissions.audio=t.state==="granted"})}catch(t){Fe.error("_initPermissionChanged",t)}try{const t=await navigator.permissions.query({name:"camera"});this._permissions.video=t.state==="granted",t.addEventListener("change",()=>{Fe.info("_initPermissionChanged","update permission for video"),this._permissions.video=t.state==="granted"})}catch(t){Fe.error("_initPermissionChanged",t)}}async _refreshDevices(t){if(!Ke.mediaDevices())throw new $(K.NOT_SUPPORTED,"mediaDevices is not supported");if(t.length===0)throw new $(K.UNEXPECTED_TYPE,"kinds expect to containt values");let n;if(!Ke.isolateEnumerateDevices()){const a={};t.forEach(o=>{a[o]=!0}),n=await navigator.mediaDevices.getUserMedia(a)}let i=await navigator.mediaDevices.enumerateDevices();n&&As(n),i=i.filter(({deviceId:a})=>!!a);const s={audioinput:[],audiooutput:[],videoinput:[]};i.forEach(a=>{const{kind:o}=a;s[o].push(a)}),this._deviceMap=s}async _acquireUserPermission(t){let n=!1;if(t.forEach(i=>{n=n||!this._permissions[i]}),!n)return{grant:!0};if(!Ke.getUserMedia())return{grant:!1,reason:new $(K.NOT_SUPPORTED,"getUserMedia is not supported")};try{const i={};t.forEach(a=>{i[a]=!0});const s=await navigator.mediaDevices.getUserMedia(i);return s?(i.audio&&(this._permissions[te.AUDIO]=!0),i.video&&(this._permissions[te.VIDEO]=!0),As(s),{grant:!0}):{grant:!1,reason:new $(K.UNEXPECTED_TYPE,"get stream falsy")}}catch(i){return{grant:!1,reason:new $(K.CAPTURE_FAILED,"acquire user permission failed",i)}}}async _handleDeviceChanged(){Fe.info("_handleDeviceChanged",this._deviceMap,this._permissions);const t=await this._changedQueue.lock();try{const n=xs(this._deviceMap);let i=[];const s=Is(this._permissions);s.length===0?Fe.warn("_handleDeviceChanged","no permission, use empty list"):(await this._refreshDevices(s),i=xs(this._deviceMap)),i.forEach(a=>{n.findIndex(d=>Ds(d,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"active"})}),n.forEach(a=>{i.findIndex(d=>Ds(d,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"inactive"})})}finally{t()}}async enumerateDevices(t){const n=[];t.forEach(o=>{if(o==="audioinput"||o==="audiooutput")n.push(te.AUDIO);else if(o==="videoinput")n.push(te.VIDEO);else throw new $(K.UNEXPECTED_TYPE,"kind in kinds should be enum MediaDeviceKind")});const{grant:i,reason:s}=await this._acquireUserPermission(n);if(!i)throw s;await this._refreshDevices(n);const a=[];return t.forEach(o=>{a.push(...this._deviceMap[o])}),a}async enableDevices(t){return this._acquireUserPermission(t)}}function As(r){r.getTracks().forEach(e=>e.stop())}function Ds(r,e){return r.deviceId===e.deviceId}function xs(r){return Array.from([...r.audioinput.values(),...r.videoinput.values(),...r.audiooutput.values()])}function Is(r){const e=[];return r.audio&&e.push(te.AUDIO),r.video&&e.push(te.VIDEO),e}const jn=new ku,Hn={LeftToRight:"LeftToRight",UpToDown:"UpToDown",All:"All"};class qn{constructor(){P(this,"id",yt())}position(e,t){return new Ru(this,{x:e,y:t})}scale(e){return new zs(this,{s:e})}mirror(e){return new zs(this,{mirrorType:e})}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}}class Ru extends qn{constructor(t,n){super();P(this,"previousNode");P(this,"_x");P(this,"_y");this.previousNode=t,this._x=n.x,this._y=n.y}paint(t){t.translate(this._x,this._y)}}class zs extends qn{constructor(t,n){super();P(this,"previousNode");P(this,"_scaleParams",[1,1]);if(this.previousNode=t,n.mirrorType)switch(n.mirrorType){case Hn.LeftToRight:this._scaleParams=[-1,1];break;case Hn.UpToDown:this._scaleParams=[1,-1];break;case Hn.All:this._scaleParams=[-1,-1];break;default:this._scaleParams=[1,1];break}else n.s&&(this._scaleParams=[n.s,n.s])}paint(t){t.scale(this._scaleParams[0],this._scaleParams[1])}}class Au extends qn{constructor(t){super();P(this,"previousNode",null);P(this,"_source");this._source=t}available(){return this._source.available()}}class Kr extends Au{constructor(t,n){super(t);P(this,"_targetWidth");P(this,"_targetHeight");const{width:i,height:s}=n??{};this._targetWidth=i??this._source.width(),this._targetHeight=s??this._source.height()}size(t,n){return new Kr(this._source,{width:t,height:n})}paint(t){const n=this._targetWidth,i=this._targetHeight;t.drawImage(this._source.element(),-n/2,-i/2,n,i)}}class Du extends Fn{constructor(){super(...arguments);P(this,"logger",new Se("PictureTrack"));P(this,"kind",te.VIDEO)}element(){const t=super.element();if(!(t instanceof HTMLImageElement))throw new $(K.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return this.logger.info("element",t),t}height(){const{height:t}=this.element();return t??0}width(){const{width:t}=this.element();return t??0}node(){if(!this.available())throw new $(K.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");const t=new Kr(this);return this.logger.info("node",t),t}destroy(){this.logger.warn("destroy"),super.destroy()}}const xu=500;class Wr extends Fn{constructor(){super(...arguments);P(this,"kind",te.VIDEO);P(this,"sizeChangeTimer");P(this,"watchSizeChangeOnce",()=>{const t=this.width(),n=this.height();this.sizeChangeTimer=setTimeout(()=>{const i=this.width(),s=this.height();(n!==s||t!==i)&&this.emit(ge.SIZE_CHANGE,{width:i,height:s})},xu)})}element(){const t=super.element();if(!(t instanceof HTMLVideoElement))throw new $(K.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return t}node(){if(!this.available())throw new $(K.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");return new Kr(this)}destroy(){clearTimeout(this.sizeChangeTimer),super.destroy()}}class Iu extends Wr{constructor(t){super(t);P(this,"logger",new Se("CameraVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class zu extends Wr{constructor(t){super(t);P(this,"logger",new Se("ScreenVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class Pu extends Wr{constructor(){super(...arguments);P(this,"logger",new Se("MediaVideoTrack"))}height(){const{videoHeight:t}=this.element();return t??0}width(){const{videoWidth:t}=this.element();return t??0}}class Ou extends Wr{constructor(){super(...arguments);P(this,"logger",new Se("CustomVideoTrack"))}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}async function Ps(r,e){let t;if(e!=null&&e.frameRate&&typeof e.frameRate=="number"&&(t=e.frameRate),t)try{await r.applyConstraints({...e,frameRate:{min:t,ideal:t}})}catch(n){console.warn("[VePusher Error]: frameRate limit failed",n)}}const We=new Se("Capture");async function Mu(r){return jn.enumerateDevices(r)}async function Lu(r){jn.removeAllListeners("onDeviceStateChanged"),jn.on("onDeviceStateChanged",r)}async function Nu(r,e){let t;try{const i={video:r??!0};typeof i.video=="object"&&i.video.facingMode&&delete i.video.deviceId,t=await navigator.mediaDevices.getUserMedia(i)}catch(i){throw new $(K.CAPTURE_FAILED,"got error when capturing camera",i)}const n=t.getVideoTracks()[0];if(r!=null&&r.frameRate&&e&&Ps(n,r),!n)throw new $(K.UNEXPECTED_TYPE,"got falsy in track");return new Iu(n)}async function Uu(r,e,t){const{video:n,audio:i}=r;let s=n===!0?{}:n;e!=null&&e.displaySurface&&(s.displaySurface=e.displaySurface,delete e.displaySurface),Ke.settingResolutionInGetDisplayMedia()||(s=!0),!Ke.supportIdealParamsInGetDisplayMedia()&&typeof s!="boolean"&&(s.width&&typeof s.width=="number"&&(s.width={max:s.width}),s.height&&typeof s.height=="number"&&(s.height={max:s.height}));let a;try{a=await navigator.mediaDevices.getDisplayMedia({video:s,audio:i,...e})}catch(u){throw new $(K.CAPTURE_FAILED,"got error when capture screen",u)}const o=a.getVideoTracks()[0],d=a.getAudioTracks()[0];if(!o)throw new $(K.UNEXPECTED_TYPE,"got falsy in videoTrack");typeof s!="boolean"&&typeof s.frameRate=="number"&&t&&Ps(o,s);const c=[];return c.push(new zu(o)),d&&c.push(new Su(d)),c}async function Gu(r){const{url:e,audio:t,video:n,loop:i}=r,s=new Yt({url:e,kind:n?te.VIDEO:te.AUDIO,loop:i}),a=[];return t&&a.push(new Rs(s)),n&&a.push(new Pu(s)),await s.isReady(),a}async function Bu(r){const e=new ks(r);return await e.isReady(),new Du(e)}async function Fu(r){let e;try{const n={audio:r??!0};e=await navigator.mediaDevices.getUserMedia(n)}catch(n){throw new $(K.CAPTURE_FAILED,"got error when capturing microphone",n)}const t=e.getAudioTracks()[0];if(!t)throw new $(K.UNEXPECTED_TYPE,"got falsy in track");return new yu(t)}function Vu(r){if(!r||r.kind!=="video")throw new $(K.UNEXPECTED_TYPE,"error custom video track type");return new Ou(r)}function ju(r){if(!r||r.kind!=="audio")throw new $(K.UNEXPECTED_TYPE,"error custom audio track type");return new bu(r)}const Hu=We.invoke(Mu,"enumerateInputDevices"),qu=We.invoke(Nu,"createCameraTrack"),$u=We.invoke(Bu,"createPictureTrack"),Os=We.invoke(Gu,"createMediaTracks"),Ku=We.invoke(Fu,"createMicrophoneTrack"),Wu=We.invoke(Uu,"createScreenTracks"),Ju=We.invoke(Lu,"onDeviceChanged"),Xu=We.invoke(Vu,"createCustomVideoTrack"),Zu=We.invoke(ju,"createCustomAudioTrack");var $n=(r=>(r.PAUSING="pausing",r))($n||{});const Yu={sampleRate:48e3,keepAlive:!0},Ms=new Map,Qt=new Se("Mixer");class Qu extends Gn{constructor(t){super();P(this,"id",yt());P(this,"_context");P(this,"_config");P(this,"_nodeList",[]);P(this,"_destNode");P(this,"_bufferNode");P(this,"_track");P(this,"unlockAudioContext",()=>{if(this._context.state!=="suspended")return;const t=document.body,n=["touchstart","touchend","mousedown","keydown"],i=()=>{n.forEach(a=>{t.removeEventListener(a,s)})},s=()=>{er(this._context).then(i)};n.forEach(a=>{t.addEventListener(a,s,!1)})});Qt.info("ctor",t),this._config={...Yu,...t},this._context=ed(this._config),this._bindContextEvent(this._context)}mix(t){Qt.info("mix",t),er(this._context);for(const n of this._nodeList)t.includes(n)||n.destroy();this._nodeList=t,this._connect(t,this._destNode),this._nodeList.length===0&&this._appendSlience(this._context,this._destNode)}resume(){return Qt.info("resume"),er(this._context)}_connect(t,n){for(const i of t)i.connect(this._context,n)}_appendSlience(t,n){if(!n||this._bufferNode)return;const{sampleRate:i}=t,s=new AudioBuffer({length:100,sampleRate:i}),a=new AudioBufferSourceNode(t,{buffer:s,loop:!0});a.connect(n),this._bufferNode=a}_bindContextEvent(t){t.addEventListener("statechange",this._handleContextStateChange.bind(this))}_handleContextStateChange(){const t=this._context;(t.state==="suspended"||t.state==="interrupted")&&(Qt.info("_emit_",$n.PAUSING),this.emit($n.PAUSING))}track(){if(Qt.info("track"),er(this._context),this.unlockAudioContext(),this._track)return this._track;let t=this._destNode;t||(t=new MediaStreamAudioDestinationNode(this._context)),this._nodeList.length===0&&this._appendSlience(this._context,t),this._connect(this._nodeList,t);const n=t.stream.getAudioTracks()[0];return this._destNode=t,this._track=n,n}}function ed(r){const{sampleRate:e,keepAlive:t}=r;let n=Ms.get(e);return(!n||n.state==="closed")&&(n=new AudioContext({sampleRate:e}),Ms.set(e,n)),t&&(n.onstatechange=()=>{er(n)}),n}function er(r){return r.state==="suspended"||r.state==="interrupted"?r.resume():Promise.resolve()}const td=r=>(e,t)=>(r.set(e,t),t),Ls=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Ns=536870912,Us=Ns*2,rd=(r,e)=>t=>{const n=e.get(t);let i=n===void 0?t.size:n<Us?n+1:0;if(!t.has(i))return r(t,i);if(t.size<Ns){for(;t.has(i);)i=Math.floor(Math.random()*Us);return r(t,i)}if(t.size>Ls)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;t.has(i);)i=Math.floor(Math.random()*Ls);return r(t,i)},Gs=new WeakMap,nd=td(Gs),ot=rd(nd,Gs),id=r=>r.method!==void 0&&r.method==="call",sd=r=>typeof r.id=="number"&&typeof r.result=="boolean",Bs=((r,e)=>{let t=null;return()=>{if(t!==null)return t;const n=new Blob([e],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(n);return t=r(i),setTimeout(()=>URL.revokeObjectURL(i)),t}})(r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),n=new Map,i=new Worker(r);return i.addEventListener("message",({data:c})=>{if(id(c)){const{params:{timerId:u,timerType:h}}=c;if(h==="interval"){const l=e.get(u);if(typeof l===void 0)throw new Error("The timer is in an undefined state.");if(typeof l=="number"){const f=n.get(l);if(f===void 0||f.timerId!==u||f.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof l=="function"&&l()}else if(h==="timeout"){const l=t.get(u);if(typeof l===void 0)throw new Error("The timer is in an undefined state.");if(typeof l=="number"){const f=n.get(l);if(f===void 0||f.timerId!==u||f.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof l=="function"&&(l(),t.delete(u))}}else if(sd(c)){const{id:u}=c,h=n.get(u);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:l,timerType:f}=h;n.delete(u),f==="interval"?e.delete(l):t.delete(l)}else{const{error:{message:u}}=c;throw new Error(u)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const u=ot(n);n.set(u,{timerId:c,timerType:"interval"}),e.set(c,u),i.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"interval"}})}},clearTimeout:c=>{if(typeof t.get(c)=="function"){const u=ot(n);n.set(u,{timerId:c,timerType:"timeout"}),t.set(c,u),i.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"timeout"}})}},setInterval:(c,u=0,...h)=>{const l=ot(e);return e.set(l,()=>{c(...h),typeof e.get(l)=="function"&&i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"interval"}}),l},setTimeout:(c,u=0,...h)=>{const l=ot(t);return t.set(l,()=>c(...h)),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"timeout"}}),l}}},`(()=>{"use strict";const e=new Map,t=new Map,r=t=>{const r=e.get(t);return void 0!==r&&(clearTimeout(r),e.delete(t),!0)},s=e=>{const r=t.get(e);return void 0!==r&&(clearTimeout(r),t.delete(e),!0)},o=(e,t)=>{const r=performance.now(),s=e+t-r-performance.timeOrigin;return{expected:r+s,remainingDelay:s}},i=(e,t,r,s)=>{const o=r-performance.now();o>0?e.set(t,setTimeout(i,o,e,t,r,s)):(e.delete(t),postMessage({id:null,method:"call",params:{timerId:t,timerType:s}}))};addEventListener("message",(({data:n})=>{try{if("clear"===n.method){const{id:e,params:{timerId:t,timerType:o}}=n;if("interval"===o)postMessage({id:e,result:r(t)});else{if("timeout"!==o)throw new Error('The given type "'.concat(o,'" is not supported'));postMessage({id:e,result:s(t)})}}else{if("set"!==n.method)throw new Error('The given method "'.concat(n.method,'" is not supported'));{const{params:{delay:r,now:s,timerId:a,timerType:m}}=n;if("interval"===m)((t,r,s)=>{const{expected:n,remainingDelay:a}=o(t,s);e.set(r,setTimeout(i,a,e,r,n,"interval"))})(r,a,s);else{if("timeout"!==m)throw new Error('The given type "'.concat(m,'" is not supported'));((e,r,s)=>{const{expected:n,remainingDelay:a}=o(e,s);t.set(r,setTimeout(i,a,t,r,n,"timeout"))})(r,a,s)}}}}catch(e){postMessage({error:{message:e.message},id:n.id,result:null})}}))})();`),od=r=>Bs().clearTimeout(r),ad=(...r)=>Bs().setTimeout(...r),cd=r=>r.method!==void 0&&r.method==="call",ud=r=>typeof r.id=="number"&&typeof r.result=="boolean",dd=r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),n=new Map,i=new Worker(r,{credentials:"omit"});return i.addEventListener("message",({data:c})=>{if(cd(c)){const{params:{timerId:u,timerType:h}}=c;if(h==="interval"){const l=e.get(u);if(typeof l===void 0)throw new Error("The timer is in an undefined state.");if(typeof l=="number"){const f=n.get(l);if(f===void 0||f.timerId!==u||f.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof l=="function"&&l()}else if(h==="timeout"){const l=t.get(u);if(typeof l===void 0)throw new Error("The timer is in an undefined state.");if(typeof l=="number"){const f=n.get(l);if(f===void 0||f.timerId!==u||f.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof l=="function"&&(l(),t.delete(u))}}else if(ud(c)){const{id:u}=c,h=n.get(u);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:l,timerType:f}=h;n.delete(u),f==="interval"?e.delete(l):t.delete(l)}else{const{error:{message:u}}=c;throw new Error(u)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const u=ot(n);n.set(u,{timerId:c,timerType:"interval"}),e.set(c,u),i.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"interval"}})}},clearTimeout:c=>{if(typeof t.get(c)=="function"){const u=ot(n);n.set(u,{timerId:c,timerType:"timeout"}),t.set(c,u),i.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"timeout"}})}},setInterval:(c,u=0,...h)=>{const l=ot(e);return e.set(l,()=>{c(...h),typeof e.get(l)=="function"&&i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"interval"}}),l},setTimeout:(c,u=0,...h)=>{const l=ot(t);return t.set(l,()=>c(...h)),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:l,timerType:"timeout"}}),l}}},ld={width:640,height:480,frameRate:30,backgroundColor:"#000000"},Jr=new Se("View");class hd{constructor(e){P(this,"id",yt());P(this,"_context");P(this,"_canvas");P(this,"_config");P(this,"_nodeList",[]);P(this,"_track");P(this,"_stopped",!0);P(this,"_nextTime",Date.now());P(this,"_workerTimeoutId");P(this,"_raqId");P(this,"_workerTimerScriptUrl");P(this,"_customSetTimeout");P(this,"_customClearTimeout");P(this,"_drawCount",0);P(this,"_lastSecondDrawCount",0);P(this,"_lastCountResetTime",Date.now());P(this,"_loopTimer");P(this,"_paintLoop",()=>{if(this._stopped){this._workerTimeoutId&&(this._customClearTimeout(this._workerTimeoutId),this._workerTimeoutId=void 0);return}this._drawOnCanvas(),this._workerTimeoutId&&this._customClearTimeout(this._workerTimeoutId),this._workerTimeoutId=this._customSetTimeout(()=>{this._paintLoop(),this._raqId&&(cancelAnimationFrame(this._raqId),this._raqId=void 0)},qr/this._config.frameRate),this._raqId=requestAnimationFrame(this._paintLoop)});Jr.info("ctor",e),this._config={...ld,...e};const{context:t,canvas:n}=bs(this._config);this._context=t,this._canvas=n,this._customSetTimeout=ad,this._customClearTimeout=od}setWorkerTimerScriptUrl(e){if(this._workerTimerScriptUrl=e,this._workerTimerScriptUrl){const t=dd(this._workerTimerScriptUrl);this._customSetTimeout=(...n)=>t.setTimeout(...n),this._customClearTimeout=n=>t.clearTimeout(n)}}_shouldDraw(e){if(e<this._nextTime)return!1;for(;e>this._nextTime;)this._nextTime+=qr/this._config.frameRate;return!0}updateConfig(e){this._config={...this._config,...e},this._canvas.width=this._config.width,this._canvas.height=this._config.height}draw(e=[]){Jr.info("draw",e),this._nodeList=e}_drawOnCanvas(){if(this._shouldDraw(Date.now())){this._drawCount++,this._updateDrawCountPerSecond(),this._drawBackground();for(const e of this._nodeList){let t=e;if(t.available()){for(;t;)t.paint(this._context),t=t.previousNode;this._context.setTransform(1,0,0,1,0,0)}}}}_updateDrawCountPerSecond(){const e=Date.now();e-this._lastCountResetTime>=qr&&(this._lastSecondDrawCount=this._drawCount,this._drawCount=0,this._lastCountResetTime=e)}getDrawCountPerSecond(){return this._updateDrawCountPerSecond(),this._lastSecondDrawCount}_drawBackground(){const{backgroundColor:e,width:t,height:n}=this._config;this._context.clearRect(0,0,t,n),e&&(this._context.fillStyle=e,this._context.fillRect(0,0,t,n))}track(){if(Jr.info("track"),this._stopped&&(this._stopped=!1,this._paintLoop()),this._track)return this._track;const{frameRate:e}=this._config,t=this._canvas.captureStream(e);return this._track=t.getVideoTracks()[0],this._track}updateFps(){if(this._track){const e=this._track,{frameRate:t}=this._config,n=this._canvas.captureStream(t);return this._track=n.getVideoTracks()[0],e.stop(),this._track}else return this.track()}element(){return Jr.info("element"),this._paintLoop(),this._canvas}stop(){this._stopped=!0}}function pd(){return Math.random().toString(36).slice(-8)}const fd=`
|
|
1
|
+
(function(it,Oe){typeof exports=="object"&&typeof module<"u"?module.exports=Oe():typeof define=="function"&&define.amd?define(Oe):(it=typeof globalThis<"u"?globalThis:it||self,it.vePusher=Oe())})(this,function(){"use strict";var mS=Object.defineProperty;var gS=(it,Oe,It)=>Oe in it?mS(it,Oe,{enumerable:!0,configurable:!0,writable:!0,value:It}):it[Oe]=It;var V=(it,Oe,It)=>gS(it,typeof Oe!="symbol"?Oe+"":Oe,It);var _d,vd,yd,Sd,bd,Ed,Rt;function it(r,e){for(var t=0;t<e.length;t++){const n=e[t];if(typeof n!="string"&&!Array.isArray(n)){for(const i in n)if(i!=="default"&&!(i in r)){const o=Object.getOwnPropertyDescriptor(n,i);o&&Object.defineProperty(r,i,o.get?o:{enumerable:!0,get:()=>n[i]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}function Oe(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var It={exports:{}},us;function Cd(){return us||(us=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(d,c,u){this.fn=d,this.context=c,this.once=u||!1}function o(d,c,u,f,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var g=new i(u,f||d,h),k=t?t+c:c;return d._events[k]?d._events[k].fn?d._events[k]=[d._events[k],g]:d._events[k].push(g):(d._events[k]=g,d._eventsCount++),d}function a(d,c){--d._eventsCount===0?d._events=new n:delete d._events[c]}function s(){this._events=new n,this._eventsCount=0}s.prototype.eventNames=function(){var c=[],u,f;if(this._eventsCount===0)return c;for(f in u=this._events)e.call(u,f)&&c.push(t?f.slice(1):f);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},s.prototype.listeners=function(c){var u=t?t+c:c,f=this._events[u];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 u=t?t+c:c,f=this._events[u];return f?f.fn?1:f.length:0},s.prototype.emit=function(c,u,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,u),!0;case 3:return w.fn.call(w.context,u,f),!0;case 4:return w.fn.call(w.context,u,f,h),!0;case 5:return w.fn.call(w.context,u,f,h,g),!0;case 6:return w.fn.call(w.context,u,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,u);break;case 3:w[E].fn.call(w[E].context,u,f);break;case 4:w[E].fn.call(w[E].context,u,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,u,f){return o(this,c,u,f,!1)},s.prototype.once=function(c,u,f){return o(this,c,u,f,!0)},s.prototype.removeListener=function(c,u,f,h){var g=t?t+c:c;if(!this._events[g])return this;if(!u)return a(this,g),this;var k=this._events[g];if(k.fn)k.fn===u&&(!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!==u||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 u;return c?(u=t?t+c:c,this._events[u]&&a(this,u)):(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}(It)),It.exports}var kd=Cd();const xt=Oe(kd);var ds=(r=>(r.LeftToRight="LeftToRight",r.UpToDown="UpToDown",r.All="All",r.None="None",r))(ds||{}),ae=(r=>(r.Camera="camera",r.Screen="screen",r.VideoFile="videoFile",r.Microphone="microphone",r.AudioFile="audioFile",r.Image="image",r.MixAudio="mixAudio",r.MixVideo="mixVideo",r.CustomVideo="customVideo",r.CustomAudio="customAudio",r))(ae||{}),dt=(r=>(r.DeviceCaptured="deviceCaptured",r.DeviceStopCapture="deviceStopCapture",r.Error="error",r.Interrupted="interrupted",r))(dt||{}),Ee=(r=>(r.PushStart="pushStart",r.PushStop="pushStop",r.PushError="pushError",r.RTCConnectStateChanged="rtcConnectStateChanged",r.CaptureFirstVideoFrame="capturefirstvideoframe",r.CaptureFirstAudioFrame="capturefirstaudioframe",r.NotAllowedAutoPlay="notallowedautoplay",r.ReconnectStateChange="reconnectStateChange",r.LiveConnectStateChange="liveConnectStateChange",r))(Ee||{}),ls=(r=>(r["120p"]="160x120x15x200",r["180p"]="320x180x15x350",r["240p"]="320x240x15x400",r["360p"]="640x360x15x800",r["480p"]="640x480x15x900",r["720p-1"]="1280x720x15x1500",r["720p-2"]="1280x720x25x1500",r["720p-3"]="1280x720x30x1500",r["1080p-1"]="1920x1080x15x2080",r["1080p-2"]="1920x1080x25x3000",r["1080p-3"]="1920x1080x30x3150",r))(ls||{}),hs=(r=>(r["120p"]="120x160x15x200",r["180p"]="180x320x15x350",r["240p"]="240x320x15x400",r["360p"]="360x640x15x800",r["480p"]="480x640x15x900",r["720p-1"]="720x1280x15x1500",r["720p-2"]="720x1280x25x1500",r["720p-3"]="720x1280x30x1500",r["1080p-1"]="1080x1920x15x2080",r["1080p-2"]="1080x1920x25x3000",r["1080p-3"]="1080x1920x30x3150",r))(hs||{}),fs=(r=>(r.STANDARD="48000x40",r.HIGH="48000x128",r))(fs||{}),$t=(r=>(r.VideoStreamChange="videoStreamChange",r.AudioStreamChange="audioStreamChange",r))($t||{}),ps=(r=>(r[r.init=-1]="init",r[r.new=0]="new",r[r.connecting=1]="connecting",r[r.connected=2]="connected",r[r.disconnected=3]="disconnected",r[r.failed=4]="failed",r[r.closed=5]="closed",r))(ps||{});const ms={SizeChange:"sizeChange"};var oi=(r=>(r.Portrait="portrait",r.Landscape="landscape",r))(oi||{});const gs="720p-1",_s="STANDARD";var $e=(r=>(r[r.DISCONNECTED=0]="DISCONNECTED",r[r.CONNECTING=1]="CONNECTING",r[r.CONNECTED=2]="CONNECTED",r[r.RECONNECTING=3]="RECONNECTING",r))($e||{}),cr=(r=>(r[r.START=1]="START",r[r.WAITING=2]="WAITING",r[r.RECONNECTING=3]="RECONNECTING",r[r.SUCCESS=4]="SUCCESS",r[r.FAILED=5]="FAILED",r))(cr||{}),si=(r=>(r[r.PushUrlInvalid=1001]="PushUrlInvalid",r[r.ReconnectTimeout=1002]="ReconnectTimeout",r))(si||{}),te=(r=>(r.TRACK_NOT_AVAILABLE="track-not-available",r.UNEXPECTED_TYPE="unexpected-type",r.PLAY_FAILED="play-failed",r.CAPTURE_FAILED="capture-failed",r.NOT_SUPPORTED="not-supported",r.UNEXPECTED_ERROR="unexpected-error",r))(te||{}),he=(r=>(r.AUDIO="audio",r.VIDEO="video",r))(he||{}),Pe=(r=>(r.ENDED="ended",r.MUTE="mute",r.UNMUTE="unmute",r.PLAY_FAILED="play-failed",r.SIZE_CHANGE="size-change",r))(Pe||{});const xe=[];for(let r=0;r<256;++r)xe.push((r+256).toString(16).slice(1));function Td(r,e=0){return(xe[r[e+0]]+xe[r[e+1]]+xe[r[e+2]]+xe[r[e+3]]+"-"+xe[r[e+4]]+xe[r[e+5]]+"-"+xe[r[e+6]]+xe[r[e+7]]+"-"+xe[r[e+8]]+xe[r[e+9]]+"-"+xe[r[e+10]]+xe[r[e+11]]+xe[r[e+12]]+xe[r[e+13]]+xe[r[e+14]]+xe[r[e+15]]).toLowerCase()}let ai;const zd=new Uint8Array(16);function Rd(){if(!ai){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ai=crypto.getRandomValues.bind(crypto)}return ai(zd)}const vs={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function qt(r,e,t){var i;if(vs.randomUUID&&!r)return vs.randomUUID();r=r||{};const n=r.random??((i=r.rng)==null?void 0:i.call(r))??Rd();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Td(n)}class ys{constructor(){V(this,"id",qt());V(this,"_nextNode");V(this,"_track");V(this,"_destNode")}gain(e){if(this._nextNode instanceof Ss)return this._nextNode.g=e,this._nextNode;const t=new Ss(this,{g:e});return this._nextNode=t,t}connect(e,t){if(!this.available())return;let{_node:n}=this;n||(n=this.createNode(e)),this._node=n,this.previousNode&&this.previousNode.connect(e,n),t&&n.connect(t)}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}destroy(){var e;(e=this._node)==null||e.disconnect(),delete this._node}}class Ss extends ys{constructor(t,n){super();V(this,"previousNode");V(this,"_node");V(this,"_g");this.previousNode=t,this._g=n.g}createNode(t){return new GainNode(t,{gain:this._g})}set g(t){this._g=t,this._node&&(this._node.gain.value=t)}}class Dd extends ys{constructor(t){super();V(this,"previousNode",null);V(this,"source");this.source=t}available(){return this.source.available()}destroy(){super.destroy()}}class Ad extends Dd{constructor(){super(...arguments);V(this,"_node")}createNode(t){if(this._node)return this._node;let n;if(this.source instanceof Ds){const i=this.source.element();n=new MediaElementAudioSourceNode(t,{mediaElement:i}),i.muted=!1}else{const i=this.source.track();n=new MediaStreamAudioSourceNode(t,{mediaStream:new MediaStream([i])})}return n}}class ee extends Error{constructor(t,n,i){super(n);V(this,"code");V(this,"message");V(this,"error");this.code=t,this.message=n,this.error=i,Object.setPrototypeOf(this,ee.prototype)}toString(){return`VeCapture Error: ${this.code} ${this.message}`}}const bs={info:{color:"rgba(93, 173, 226, 0)",text:"INFO"},warn:{color:"rgba(255, 119, 0, 0.3)",text:"WARN"},err:{color:"rgba(255, 0, 0, 0.3)",text:"ERR "},succ:{color:"rgba(0, 119, 0, 0.3)",text:"SUCC"}},Es="__debug__",Id="[VE-CAPTURE]";function xd(){if(typeof location>"u"||typeof localStorage>"u")return!1;let r=!1;return location.href.includes(Es)&&(r=!0),localStorage.getItem(Es)&&(r=!0),r}let Ve=class{constructor(e){V(this,"moduleName");this.moduleName=e}print(e,t,...n){const i=Md();xd()&&console.log(`${i}-${Id}%c[${bs[e].text}]%c[${this.moduleName}][${t}]`,`background-color:${bs[e].color};`,"background-color:rgba(0, 0, 0, 0)",...n)}info(e,...t){this.print("info",e,...t)}warn(e,...t){this.print("warn",e,...t)}error(e,...t){this.print("err",e,...t)}success(e,...t){this.print("succ",e,...t)}invoke(e,t){const n=this;return function(...o){n.info(`${t}-invoke`,...o);try{const a=e(...o);return typeof(a==null?void 0:a.then)=="function"?a.then(s=>(n.success(`${t}-result`,s),s)).catch(s=>{throw n.error(`${t}-result`,s),s}):(n.success(`${t}-result`,a),a)}catch(a){n.error(`[${t}-result`,a)}}}};function Md(){const r=new Date;return`${r.toTimeString().split(" ")[0]}:${r.getMilliseconds().toString().padStart(3,"0")}`}function ci(r,e){const t=document.createElement(r);return e.id&&(t.id=e.id),e.classList&&e.classList.forEach(n=>{t.classList.add(n)}),e.style&&Object.assign(t.style,e.style),e.attributes&&Object.entries(e.attributes).forEach(([n,i])=>{n==="muted"&&(t instanceof HTMLVideoElement||t instanceof HTMLAudioElement)?t.muted=!0:t.setAttribute(n,i)}),t}function ws({width:r,height:e}){const t=document.createElement("canvas"),n=t.getContext("2d");if(!n)throw new ee(te.NOT_SUPPORTED,"CanvasRenderingContext2D is not supported by user agent");return t.width=r,t.height=e,t.style.width="100%",t.style.height="100%",{context:n,canvas:t}}class ui{constructor(e){V(this,"target");V(this,"_eventDict",new Map);this.target=e}on(e,t){let n=this._eventDict.get(e);n||(n=[t]),this._eventDict.set(e,n),this.target.addEventListener(e,t)}off(e,t){let n=this._eventDict.get(e);n&&(n=n.filter(i=>i!==t),this._eventDict.set(e,n),this.target.removeEventListener(e,t))}once(e,t){const n=i=>{t(i),this.off(e,n)};this.on(e,n)}clear(e){const t=this._eventDict.get(e);t&&t.forEach(n=>{this.target.removeEventListener(e,n)})}clearAll(){for(const e of this._eventDict.keys())this.clear(e)}}const we=()=>typeof window>"u";function Se(){return navigator.userAgent.toLowerCase()}function di(r=Se()){let e="none";return we()||(r.match("firefox")!==null?e="firefox":r.match("Chrome")!==null?(e="chrome",r.match("Electron")!==null&&(e="electron")):(r.match("Safari")!==null||r.match("AppleWebKit")!==null)&&(e="safari")),e}const Cs=di()==="firefox",Sn=di()==="safari";di(),!we()&&/crios/i.test(Se()),!we()&&/edg\//i.test(Se()),!we()&&/edgA/i.test(Se()),!we()&&/edgios/i.test(Se()),!we()&&/dingtalk/i.test(Se()),!we()&&/opr\//.test(Se()),!we()&&/(iphone|ipod)/i.exec(Se()),!we()&&(/(ipad)/i.exec(Se())||/macintosh/i.test(Se())&&"ontouchend"in document),!we()&&/macintosh/i.test(Se()),!we()&&/micromessenger/i.test(Se()),!we()&&Se().includes("mobile"),!we()&&/sm-\w+/i.test(Se());const Od=!we()&&!!/(iphone|ipad|ipod)/i.exec(Se());!we()&&/android/i.test(Se()),!we()&&/windows/i.test(Se()),!we()&&/openharmony/i.test(Se());let ks="0";const Pd=!we()&&((_d=Se().match(/version\/(\d+)/i))==null?void 0:_d[1]);Sn&&Pd&&(ks=(vd=navigator.userAgent.match(/version\/(\d+\.\d+)/i))==null?void 0:vd[1]),!we()&&((yd=Se().match(/firefox\/(\d+)/i))==null||yd[1]);const li=ks;!we()&&((bd=(Sd=Se().match(/ ([\d_]+) like mac os x/i))==null?void 0:Sd[1])==null||bd.split("_").map(r=>parseInt(r))),!we()&&((Ed=Se().match(/chrome\/(\d+)/i))==null||Ed[1]);function Ld(){var r;return!!((r=navigator==null?void 0:navigator.permissions)!=null&&r.query)}function hi(){return!!(navigator!=null&&navigator.mediaDevices)}function Ud(){var r;return hi()&&!!((r=navigator==null?void 0:navigator.mediaDevices)!=null&&r.getUserMedia)}function Gd(){return!!Promise.withResolvers}function Nd(){return!(Sn&&li==="16.1")}function Bd(){return!(Sn&&li&&["16.1","16.2","16.3"].includes(li))}function Fd(){return!Cs}function Vd(){return typeof CanvasCaptureMediaStreamTrack<"u"}function jd(r){return typeof r.requestFrame=="function"}function Hd(){return!!hi()&&typeof navigator.mediaDevices.ondevicechange<"u"&&typeof navigator.mediaDevices.addEventListener=="function"}const _t={permissionQuery:Ld,mediaDevices:hi,settingResolutionInGetDisplayMedia:Nd,promiseWithResolvers:Gd,getUserMedia:Ud,isolateEnumerateDevices:Fd,supportIdealParamsInGetDisplayMedia:Bd,canvasCaptureMediaStreamTrack:Vd,requestFrameOnMediaStream:jd,ondevicechange:Hd};function $d(){if(_t.promiseWithResolvers())return Promise.withResolvers();let r,e;const t=new Promise((n,i)=>{r=n,e=i});if(!r||!e)throw Error("resolver and rejector working unexpected");return{promise:t,resolve:r,reject:e}}function Ts(r={}){const{timeout:e,message:t}={timeout:0,message:new ee(te.UNEXPECTED_ERROR,"unexpected timeout"),...r},{promise:n,resolve:i,reject:o}=$d();if(e<=0)return{promise:n,resolve:i,reject:o};const a=setTimeout(()=>{o(t)},e);return{promise:n,resolve:d=>{clearTimeout(a),i(d)},reject:o}}const qd={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"metadata",muted:"",crossOrigin:"anonymous"},Kd={playsinline:"","webkit-playsinline":"",preload:"metadata",muted:"",crossOrigin:"anonymous"};class Rr{constructor(e,t=[]){V(this,"id",qt());V(this,"_referenceTracks",[]);V(this,"_element");V(this,"_volumeMode",0);V(this,"_readyLock");V(this,"_releaseReadyLock");V(this,"_throwReadyLock");V(this,"_stream");let n;if(e instanceof MediaStreamTrack){const s=new MediaStream([e]);n=Wd(s),this._stream=s}else if(e.url)n=Jd(e);else throw new ee(te.UNEXPECTED_TYPE,`got ${typeof e}, expected: MediaStreamTrack or constraints for creating element`);const{promise:i,resolve:o,reject:a}=Ts({timeout:2e3,message:new ee(te.PLAY_FAILED,"load media timeout")});this._readyLock=i,this._releaseReadyLock=o,this._throwReadyLock=a,this._element=new ui(n),this._bindPlayerEvent(this._element),this._referenceTracks=[...t]}addReferenceTrack(e){this._referenceTracks.push(e)}track(e){this._playElement();let t=this._stream;if((!t||!t.active)&&(t=this._element.target.captureStream(),this._stream=t),e===he.AUDIO){this._upgradeVolumeMode(1e-4);const n=t.getAudioTracks();if(n.length<1)throw new ee(te.UNEXPECTED_TYPE,"got empty list of audio tracks");return n[0]}if(e===he.VIDEO){const n=t.getVideoTracks();if(n.length<1)throw new ee(te.UNEXPECTED_TYPE,"got empty list of video tracks");return n[0]}throw new ee(te.UNEXPECTED_TYPE,`got ${e}, expected: audio, video`)}async _playElement(){if(!(!this._element.target.muted&&this._element.target.volume===this._volumeMode&&!this._element.target.paused))try{this._element.target.muted=!1,this._element.target.volume=this._volumeMode,await this._element.target.play()}catch(e){throw this._handlePlayFailed(),new ee(te.PLAY_FAILED,"play element failed",e)}}_bindPlayerEvent(e){e.on("loadedmetadata",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new ee(te.PLAY_FAILED,"HTMLMediaElement got error when loading file"))})}_handlePlayFailed(){this._referenceTracks.forEach(e=>{e.handlePlayFailed()})}_upgradeVolumeMode(e){console.warn("update volume mode",e);const t=this._volumeMode>e?this._volumeMode:e;this._volumeMode=t,this._playElement()}element(e=!1){return e&&this._upgradeVolumeMode(1),this._playElement(),this._element.target}isReady(){return this._readyLock}removeReference(e){const t=this._referenceTracks.indexOf(e);this._referenceTracks.splice(t,1),this._referenceTracks.length===0&&this.destroy()}destroy(){this._element.target.srcObject=null,this._element.target.src="",this._element.target.load();const e=[...this._referenceTracks];this._referenceTracks=[],e.forEach(t=>{try{t.destroy()}catch{}})}}function Wd(r){let e="audio";r.getVideoTracks().length>0&&(e="video");const t=zs(e==="video"?he.VIDEO:he.AUDIO);return t.srcObject=r,t}function Jd(r){const{url:e,kind:t,loop:n}=r,i=zs(t);return i.src=e,i.loop=n,i}function zs(r){if(r===he.VIDEO)return ci(he.VIDEO,{style:{width:"100%",height:"100%"},attributes:qd});if(r===he.AUDIO)return ci(he.AUDIO,{style:{display:"none"},attributes:Kd});throw new ee(te.UNEXPECTED_TYPE,`got ${r}, expected: audio, video`)}class fi extends xt{emit(e,...t){const n=this.listenerCount(e);return Promise.resolve().then(()=>{super.emit(e,...t)}),!!n}on(e,t,n){const i=(...o)=>{try{return t(...o)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.on(e,i,n)}once(e,t,n){const i=(...o)=>{try{return t(...o)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.once(e,i,n)}}function pi(r){if(typeof r=="number")return r;if(typeof(r==null?void 0:r.exact)=="number")return r.exact;if(typeof(r==null?void 0:r.ideal)=="number")return r.ideal;if(typeof(r==null?void 0:r.max)=="number")return r.max;if(typeof(r==null?void 0:r.min)=="number")return r.min;throw new ee(te.UNEXPECTED_TYPE,"unexpected constraints type")}const bn=1e3;class Rs{constructor(e){V(this,"id",qt());V(this,"_context");V(this,"_canvas");V(this,"_image");V(this,"_config");V(this,"_readyLock");V(this,"_releaseReadyLock");V(this,"_throwReadyLock");V(this,"_loopTimer");V(this,"_referenceTracks",[]);V(this,"_stream");const t=pi(e.width),n=pi(e.height),i=pi(e.frameRate);this._config={width:t,height:n,frameRate:i};const{context:o,canvas:a}=ws({width:t,height:n});this._context=o,this._canvas=a;const s=Xd({url:e.url,width:t,height:n});this._image=new ui(s);const{promise:d,resolve:c,reject:u}=Ts({timeout:2e3,message:new ee(te.PLAY_FAILED,"load image timeout")});this._readyLock=d,this._releaseReadyLock=c,this._throwReadyLock=u,this._bindImageEvent(this._image)}track(){this._paint();const{frameRate:e}=this._config;let t=this._stream;(!t||!t.active)&&(t=this._canvas.captureStream(e),this._stream=t);const n=t.getVideoTracks();if(n.length<1)throw new ee(te.UNEXPECTED_TYPE,"got empty list of video tracks");return n[0]}element(){return this._image.target}isReady(){return this._readyLock}_bindImageEvent(e){e.on("load",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new ee(te.PLAY_FAILED,"HTMLMediaElement got error when loading file"))})}async _paint(){const{width:e,height:t,frameRate:n}=this._config;this._context.drawImage(this._image.target,0,0,e,t),this._loopTimer&&clearTimeout(this._loopTimer),this._loopTimer=setTimeout(this._paint.bind(this),bn/n)}addReferenceTrack(e){this._referenceTracks.push(e)}removeReference(e){const t=this._referenceTracks.indexOf(e);this._referenceTracks.splice(t,1),console.warn("reference length",this._referenceTracks),this._referenceTracks.length}}function Xd({url:r,height:e,width:t}){const n=ci("img",{style:{width:`${t}px`,height:`${e}px`},attributes:{crossOrigin:"anonymous"}});return n.src=r,n}class mi extends fi{constructor(t){super();V(this,"id",qt());V(this,"_track");V(this,"_element");t instanceof MediaStreamTrack?(this._track=new ui(t),this._bindTrackEvent(this._track)):t instanceof Rr?(this._element=t,t.addReferenceTrack(this)):t instanceof Rs&&(this._element=t)}_bindTrackEvent(t){t.on("ended",this._handleTrackEnded.bind(this)),t.on("mute",()=>{this.emit(Pe.MUTE)}),t.on("unmute",()=>{this.emit(Pe.UNMUTE)})}_handleTrackEnded(){this.emit(Pe.ENDED),this.destroy()}handlePlayFailed(){this.emit(Pe.PLAY_FAILED)}track(){if(this.logger.info("track"),!this.available())throw new ee(te.TRACK_NOT_AVAILABLE,"track is not available when creating MediaStreamTrack");if(this._track)return this._track.target;if(!this._element)throw new ee(te.UNEXPECTED_TYPE,"got this._element falsy");const t=this._element.track(this.kind);return this.logger.success("track",t),t}element(){if(this.logger.info("element"),!this.available())throw new ee(te.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element)return this._element.element();if(!this._track)throw new ee(te.UNEXPECTED_TYPE,"got this._track falsy");const t=new Rr(this._track.target,[this]);this._element=t;const n=t.element();return this.logger.success("element",n),n}available(){return!!(this._track||this._element)}destroy(){var t,n,i;(t=this._track)==null||t.clearAll(),(n=this._track)==null||n.target.stop(),this._track&&delete this._track,(i=this._element)==null||i.removeReference(this),delete this._element}}class En extends mi{constructor(){super(...arguments);V(this,"kind",he.AUDIO);V(this,"_node")}node(){if(this.logger.info("node",this.id),!this.available())throw new ee(te.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");if(this._node)return this._node;const t=new Ad(this);return this._node=t,t}element(){if(this.logger.info("element",this.id),!this.available())throw new ee(te.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element){const n=this._element.element(!0);if(!(n instanceof HTMLMediaElement))throw new ee(te.UNEXPECTED_TYPE,"source should be HTMLMediaElement");return n}if(!this._track)throw new ee(te.UNEXPECTED_TYPE,"got this._track falsy");const t=new Rr(this._track.target,[this]);return this._element=t,t.element()}destroy(){var t;this.logger.warn("destroy",this.id),(t=this._node)==null||t.destroy(),super.destroy()}}class Zd extends En{constructor(){super(...arguments);V(this,"logger",new Ve("MicrophoneAudioTrack"))}}class Yd extends En{constructor(){super(...arguments);V(this,"logger",new Ve("ScreenAudioTrack"))}}class Ds extends En{constructor(){super(...arguments);V(this,"logger",new Ve("MediaAudioTrack"))}handlePlayFailed(){this.emit(Pe.PLAY_FAILED)}async play(){if(this._element){if(!(this._element instanceof Rr))throw new ee(te.UNEXPECTED_TYPE,"element is not TrackMediaElement");return this._element._playElement()}}}class Qd extends En{constructor(){super(...arguments);V(this,"logger",new Ve("CustomAudioTrack"))}}let el=1;const gi=new Ve("PromiseQueue");class tl{constructor(e){V(this,"lockingPromise",Promise.resolve());V(this,"locks",0);V(this,"name","");V(this,"lockId");V(this,"closeReason");this.lockId=el++,e&&(this.name=e),gi.info(`lock-${this.name}-${this.lockId}`,"is created.")}get isLocked(){return this.locks>0}lock(){this.locks+=1,gi.info(`lock-${this.name}-${this.lockId}`,`locked, current queue ${this.locks}.`);let e;const t=new Promise(i=>{e=()=>{this.locks-=1,gi.info(`lock-${this.name}-${this.lockId}`,`unlocked, current queue ${this.locks}.`),i()}}),n=this.lockingPromise.then(()=>e);return this.lockingPromise=this.lockingPromise.then(()=>t),n}}const rl=300,nl=3e3,lt=new Ve("Devices");class il extends fi{constructor(){super();V(this,"_deviceMap",{audioinput:[],audiooutput:[],videoinput:[]});V(this,"_permissions",{[he.AUDIO]:!1,[he.VIDEO]:!1});V(this,"_changedQueue",new tl("device changed queue"));this._init()}async _init(){this._initDeviceChanged(),await this._initPermissionChanged();const t=Ms(this._permissions);t.length>0&&this._refreshDevices(t)}_initDeviceChanged(){if(lt.info("_initDeviceChanged","invoked"),!_t.ondevicechange()){lt.error("_initDeviceChanged","no supported, use timer instead"),setInterval(()=>{this._handleDeviceChanged()},nl);return}_t.ondevicechange()&&navigator.mediaDevices.addEventListener("devicechange",()=>{lt.info("devicechange"),setTimeout(()=>{this._handleDeviceChanged()},rl)})}async _initPermissionChanged(){if(!_t.permissionQuery()){lt.error("_initPermissionChanged","permission query not supported, silent return");return}try{const t=await navigator.permissions.query({name:"microphone"});this._permissions.audio=t.state==="granted",t.addEventListener("change",()=>{lt.info("_initPermissionChanged","update permission for audio"),this._permissions.audio=t.state==="granted"})}catch(t){lt.error("_initPermissionChanged",t)}try{const t=await navigator.permissions.query({name:"camera"});this._permissions.video=t.state==="granted",t.addEventListener("change",()=>{lt.info("_initPermissionChanged","update permission for video"),this._permissions.video=t.state==="granted"})}catch(t){lt.error("_initPermissionChanged",t)}}async _refreshDevices(t){if(!_t.mediaDevices())throw new ee(te.NOT_SUPPORTED,"mediaDevices is not supported");if(t.length===0)throw new ee(te.UNEXPECTED_TYPE,"kinds expect to containt values");let n;if(!_t.isolateEnumerateDevices()){const a={};t.forEach(s=>{a[s]=!0}),n=await navigator.mediaDevices.getUserMedia(a)}let i=await navigator.mediaDevices.enumerateDevices();n&&As(n),i=i.filter(({deviceId:a})=>!!a);const o={audioinput:[],audiooutput:[],videoinput:[]};i.forEach(a=>{const{kind:s}=a;o[s].push(a)}),this._deviceMap=o}async _acquireUserPermission(t){let n=!1;if(t.forEach(i=>{n=n||!this._permissions[i]}),!n)return{grant:!0};if(!_t.getUserMedia())return{grant:!1,reason:new ee(te.NOT_SUPPORTED,"getUserMedia is not supported")};try{const i={};t.forEach(a=>{i[a]=!0});const o=await navigator.mediaDevices.getUserMedia(i);return o?(i.audio&&(this._permissions[he.AUDIO]=!0),i.video&&(this._permissions[he.VIDEO]=!0),As(o),{grant:!0}):{grant:!1,reason:new ee(te.UNEXPECTED_TYPE,"get stream falsy")}}catch(i){return{grant:!1,reason:new ee(te.CAPTURE_FAILED,"acquire user permission failed",i)}}}async _handleDeviceChanged(){lt.info("_handleDeviceChanged",this._deviceMap,this._permissions);const t=await this._changedQueue.lock();try{const n=xs(this._deviceMap);let i=[];const o=Ms(this._permissions);o.length===0?lt.warn("_handleDeviceChanged","no permission, use empty list"):(await this._refreshDevices(o),i=xs(this._deviceMap)),i.forEach(a=>{n.findIndex(d=>Is(d,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"active"})}),n.forEach(a=>{i.findIndex(d=>Is(d,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"inactive"})})}finally{t()}}async enumerateDevices(t){const n=[];t.forEach(s=>{if(s==="audioinput"||s==="audiooutput")n.push(he.AUDIO);else if(s==="videoinput")n.push(he.VIDEO);else throw new ee(te.UNEXPECTED_TYPE,"kind in kinds should be enum MediaDeviceKind")});const{grant:i,reason:o}=await this._acquireUserPermission(n);if(!i)throw o;await this._refreshDevices(n);const a=[];return t.forEach(s=>{a.push(...this._deviceMap[s])}),a}async enableDevices(t){return this._acquireUserPermission(t)}}function As(r){r.getTracks().forEach(e=>e.stop())}function Is(r,e){return r.deviceId===e.deviceId}function xs(r){return Array.from([...r.audioinput.values(),...r.videoinput.values(),...r.audiooutput.values()])}function Ms(r){const e=[];return r.audio&&e.push(he.AUDIO),r.video&&e.push(he.VIDEO),e}const _i=new il,vi={LeftToRight:"LeftToRight",UpToDown:"UpToDown",All:"All"};class yi{constructor(){V(this,"id",qt())}position(e,t){return new ol(this,{x:e,y:t})}scale(e){return new Os(this,{s:e})}mirror(e){return new Os(this,{mirrorType:e})}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}}class ol extends yi{constructor(t,n){super();V(this,"previousNode");V(this,"_x");V(this,"_y");this.previousNode=t,this._x=n.x,this._y=n.y}paint(t){t.translate(this._x,this._y)}}class Os extends yi{constructor(t,n){super();V(this,"previousNode");V(this,"_scaleParams",[1,1]);if(this.previousNode=t,n.mirrorType)switch(n.mirrorType){case vi.LeftToRight:this._scaleParams=[-1,1];break;case vi.UpToDown:this._scaleParams=[1,-1];break;case vi.All:this._scaleParams=[-1,-1];break;default:this._scaleParams=[1,1];break}else n.s&&(this._scaleParams=[n.s,n.s])}paint(t){t.scale(this._scaleParams[0],this._scaleParams[1])}}class sl extends yi{constructor(t){super();V(this,"previousNode",null);V(this,"_source");this._source=t}available(){return this._source.available()}}class wn extends sl{constructor(t,n){super(t);V(this,"_targetWidth");V(this,"_targetHeight");const{width:i,height:o}=n??{};this._targetWidth=i??this._source.width(),this._targetHeight=o??this._source.height()}size(t,n){return new wn(this._source,{width:t,height:n})}paint(t){const n=this._targetWidth,i=this._targetHeight;t.drawImage(this._source.element(),-n/2,-i/2,n,i)}}class al extends mi{constructor(){super(...arguments);V(this,"logger",new Ve("PictureTrack"));V(this,"kind",he.VIDEO)}element(){const t=super.element();if(!(t instanceof HTMLImageElement))throw new ee(te.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return this.logger.info("element",t),t}height(){const{height:t}=this.element();return t??0}width(){const{width:t}=this.element();return t??0}node(){if(!this.available())throw new ee(te.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");const t=new wn(this);return this.logger.info("node",t),t}destroy(){this.logger.warn("destroy"),super.destroy()}}const cl=500;class Cn extends mi{constructor(){super(...arguments);V(this,"kind",he.VIDEO);V(this,"sizeChangeTimer");V(this,"watchSizeChangeOnce",()=>{const t=this.width(),n=this.height();this.sizeChangeTimer=setTimeout(()=>{const i=this.width(),o=this.height();(n!==o||t!==i)&&this.emit(Pe.SIZE_CHANGE,{width:i,height:o})},cl)})}element(){const t=super.element();if(!(t instanceof HTMLVideoElement))throw new ee(te.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return t}node(){if(!this.available())throw new ee(te.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");return new wn(this)}destroy(){clearTimeout(this.sizeChangeTimer),super.destroy()}}class ul extends Cn{constructor(t){super(t);V(this,"logger",new Ve("CameraVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class dl extends Cn{constructor(t){super(t);V(this,"logger",new Ve("ScreenVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class ll extends Cn{constructor(){super(...arguments);V(this,"logger",new Ve("MediaVideoTrack"))}height(){const{videoHeight:t}=this.element();return t??0}width(){const{videoWidth:t}=this.element();return t??0}}class hl extends Cn{constructor(){super(...arguments);V(this,"logger",new Ve("CustomVideoTrack"))}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}async function Ps(r,e){let t;if(e!=null&&e.frameRate&&typeof e.frameRate=="number"&&(t=e.frameRate),t)try{await r.applyConstraints({...e,frameRate:{min:t,ideal:t}})}catch(n){console.warn("[VePusher Error]: frameRate limit failed",n)}}const vt=new Ve("Capture");async function fl(r){return _i.enumerateDevices(r)}async function pl(r){_i.removeAllListeners("onDeviceStateChanged"),_i.on("onDeviceStateChanged",r)}async function ml(r,e){let t;try{const i={video:r??!0};typeof i.video=="object"&&i.video.facingMode&&delete i.video.deviceId,t=await navigator.mediaDevices.getUserMedia(i)}catch(i){throw new ee(te.CAPTURE_FAILED,"got error when capturing camera",i)}const n=t.getVideoTracks()[0];if(r!=null&&r.frameRate&&e&&Ps(n,r),!n)throw new ee(te.UNEXPECTED_TYPE,"got falsy in track");return new ul(n)}async function gl(r,e,t){const{video:n,audio:i}=r;let o=n===!0?{}:n;e!=null&&e.displaySurface&&(o.displaySurface=e.displaySurface,delete e.displaySurface),_t.settingResolutionInGetDisplayMedia()||(o=!0),!_t.supportIdealParamsInGetDisplayMedia()&&typeof o!="boolean"&&(o.width&&typeof o.width=="number"&&(o.width={max:o.width}),o.height&&typeof o.height=="number"&&(o.height={max:o.height}));let a;try{a=await navigator.mediaDevices.getDisplayMedia({video:o,audio:i,...e})}catch(u){throw new ee(te.CAPTURE_FAILED,"got error when capture screen",u)}const s=a.getVideoTracks()[0],d=a.getAudioTracks()[0];if(!s)throw new ee(te.UNEXPECTED_TYPE,"got falsy in videoTrack");typeof o!="boolean"&&typeof o.frameRate=="number"&&t&&Ps(s,o);const c=[];return c.push(new dl(s)),d&&c.push(new Yd(d)),c}async function _l(r){const{url:e,audio:t,video:n,loop:i}=r,o=new Rr({url:e,kind:n?he.VIDEO:he.AUDIO,loop:i}),a=[];return t&&a.push(new Ds(o)),n&&a.push(new ll(o)),await o.isReady(),a}async function vl(r){const e=new Rs(r);return await e.isReady(),new al(e)}async function yl(r){let e;try{const n={audio:r??!0};e=await navigator.mediaDevices.getUserMedia(n)}catch(n){throw new ee(te.CAPTURE_FAILED,"got error when capturing microphone",n)}const t=e.getAudioTracks()[0];if(!t)throw new ee(te.UNEXPECTED_TYPE,"got falsy in track");return new Zd(t)}function Sl(r){if(!r||r.kind!=="video")throw new ee(te.UNEXPECTED_TYPE,"error custom video track type");return new hl(r)}function bl(r){if(!r||r.kind!=="audio")throw new ee(te.UNEXPECTED_TYPE,"error custom audio track type");return new Qd(r)}const El=vt.invoke(fl,"enumerateInputDevices"),wl=vt.invoke(ml,"createCameraTrack"),Cl=vt.invoke(vl,"createPictureTrack"),Ls=vt.invoke(_l,"createMediaTracks"),kl=vt.invoke(yl,"createMicrophoneTrack"),Tl=vt.invoke(gl,"createScreenTracks"),zl=vt.invoke(pl,"onDeviceChanged"),Rl=vt.invoke(Sl,"createCustomVideoTrack"),Dl=vt.invoke(bl,"createCustomAudioTrack");var Si=(r=>(r.PAUSING="pausing",r))(Si||{});const Al={sampleRate:48e3,keepAlive:!0},Us=new Map,Dr=new Ve("Mixer");class Il extends fi{constructor(t){super();V(this,"id",qt());V(this,"_context");V(this,"_config");V(this,"_nodeList",[]);V(this,"_destNode");V(this,"_bufferNode");V(this,"_track");V(this,"unlockAudioContext",()=>{if(this._context.state!=="suspended")return;const t=document.body,n=["touchstart","touchend","mousedown","keydown"],i=()=>{n.forEach(a=>{t.removeEventListener(a,o)})},o=()=>{Ar(this._context).then(i)};n.forEach(a=>{t.addEventListener(a,o,!1)})});Dr.info("ctor",t),this._config={...Al,...t},this._context=xl(this._config),this._bindContextEvent(this._context)}mix(t){Dr.info("mix",t),Ar(this._context);for(const n of this._nodeList)t.includes(n)||n.destroy();this._nodeList=t,this._connect(t,this._destNode),this._nodeList.length===0&&this._appendSlience(this._context,this._destNode)}resume(){return Dr.info("resume"),Ar(this._context)}_connect(t,n){for(const i of t)i.connect(this._context,n)}_appendSlience(t,n){if(!n||this._bufferNode)return;const{sampleRate:i}=t,o=new AudioBuffer({length:100,sampleRate:i}),a=new AudioBufferSourceNode(t,{buffer:o,loop:!0});a.connect(n),this._bufferNode=a}_bindContextEvent(t){t.addEventListener("statechange",this._handleContextStateChange.bind(this))}_handleContextStateChange(){const t=this._context;(t.state==="suspended"||t.state==="interrupted")&&(Dr.info("_emit_",Si.PAUSING),this.emit(Si.PAUSING))}track(){if(Dr.info("track"),Ar(this._context),this.unlockAudioContext(),this._track)return this._track;let t=this._destNode;t||(t=new MediaStreamAudioDestinationNode(this._context)),this._nodeList.length===0&&this._appendSlience(this._context,t),this._connect(this._nodeList,t);const n=t.stream.getAudioTracks()[0];return this._destNode=t,this._track=n,n}}function xl(r){const{sampleRate:e,keepAlive:t}=r;let n=Us.get(e);return(!n||n.state==="closed")&&(n=new AudioContext({sampleRate:e}),Us.set(e,n)),t&&(n.onstatechange=()=>{Ar(n)}),n}function Ar(r){return r.state==="suspended"||r.state==="interrupted"?r.resume():Promise.resolve()}const Ml=r=>(e,t)=>(r.set(e,t),t),Gs=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Ns=536870912,Bs=Ns*2,Ol=(r,e)=>t=>{const n=e.get(t);let i=n===void 0?t.size:n<Bs?n+1:0;if(!t.has(i))return r(t,i);if(t.size<Ns){for(;t.has(i);)i=Math.floor(Math.random()*Bs);return r(t,i)}if(t.size>Gs)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;t.has(i);)i=Math.floor(Math.random()*Gs);return r(t,i)},Fs=new WeakMap,Pl=Ml(Fs),Mt=Ol(Pl,Fs),Ll=r=>r.method!==void 0&&r.method==="call",Ul=r=>typeof r.id=="number"&&typeof r.result=="boolean",Vs=((r,e)=>{let t=null;return()=>{if(t!==null)return t;const n=new Blob([e],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(n);return t=r(i),setTimeout(()=>URL.revokeObjectURL(i)),t}})(r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),n=new Map,i=new Worker(r);return i.addEventListener("message",({data:c})=>{if(Ll(c)){const{params:{timerId:u,timerType:f}}=c;if(f==="interval"){const h=e.get(u);if(typeof h===void 0)throw new Error("The timer is in an undefined state.");if(typeof h=="number"){const g=n.get(h);if(g===void 0||g.timerId!==u||g.timerType!==f)throw new Error("The timer is in an undefined state.")}else typeof h=="function"&&h()}else if(f==="timeout"){const h=t.get(u);if(typeof h===void 0)throw new Error("The timer is in an undefined state.");if(typeof h=="number"){const g=n.get(h);if(g===void 0||g.timerId!==u||g.timerType!==f)throw new Error("The timer is in an undefined state.")}else typeof h=="function"&&(h(),t.delete(u))}}else if(Ul(c)){const{id:u}=c,f=n.get(u);if(f===void 0)throw new Error("The timer is in an undefined state.");const{timerId:h,timerType:g}=f;n.delete(u),g==="interval"?e.delete(h):t.delete(h)}else{const{error:{message:u}}=c;throw new Error(u)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const u=Mt(n);n.set(u,{timerId:c,timerType:"interval"}),e.set(c,u),i.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"interval"}})}},clearTimeout:c=>{if(typeof t.get(c)=="function"){const u=Mt(n);n.set(u,{timerId:c,timerType:"timeout"}),t.set(c,u),i.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"timeout"}})}},setInterval:(c,u=0,...f)=>{const h=Mt(e);return e.set(h,()=>{c(...f),typeof e.get(h)=="function"&&i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"interval"}}),h},setTimeout:(c,u=0,...f)=>{const h=Mt(t);return t.set(h,()=>c(...f)),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"timeout"}}),h}}},`(()=>{"use strict";const e=new Map,t=new Map,r=t=>{const r=e.get(t);return void 0!==r&&(clearTimeout(r),e.delete(t),!0)},s=e=>{const r=t.get(e);return void 0!==r&&(clearTimeout(r),t.delete(e),!0)},o=(e,t)=>{const r=performance.now(),s=e+t-r-performance.timeOrigin;return{expected:r+s,remainingDelay:s}},i=(e,t,r,s)=>{const o=r-performance.now();o>0?e.set(t,setTimeout(i,o,e,t,r,s)):(e.delete(t),postMessage({id:null,method:"call",params:{timerId:t,timerType:s}}))};addEventListener("message",(({data:n})=>{try{if("clear"===n.method){const{id:e,params:{timerId:t,timerType:o}}=n;if("interval"===o)postMessage({id:e,result:r(t)});else{if("timeout"!==o)throw new Error('The given type "'.concat(o,'" is not supported'));postMessage({id:e,result:s(t)})}}else{if("set"!==n.method)throw new Error('The given method "'.concat(n.method,'" is not supported'));{const{params:{delay:r,now:s,timerId:a,timerType:m}}=n;if("interval"===m)((t,r,s)=>{const{expected:n,remainingDelay:a}=o(t,s);e.set(r,setTimeout(i,a,e,r,n,"interval"))})(r,a,s);else{if("timeout"!==m)throw new Error('The given type "'.concat(m,'" is not supported'));((e,r,s)=>{const{expected:n,remainingDelay:a}=o(e,s);t.set(r,setTimeout(i,a,t,r,n,"timeout"))})(r,a,s)}}}}catch(e){postMessage({error:{message:e.message},id:n.id,result:null})}}))})();`),Gl=r=>Vs().clearTimeout(r),Nl=(...r)=>Vs().setTimeout(...r),Bl=r=>r.method!==void 0&&r.method==="call",Fl=r=>typeof r.id=="number"&&typeof r.result=="boolean",Vl=r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),n=new Map,i=new Worker(r,{credentials:"omit"});return i.addEventListener("message",({data:c})=>{if(Bl(c)){const{params:{timerId:u,timerType:f}}=c;if(f==="interval"){const h=e.get(u);if(typeof h===void 0)throw new Error("The timer is in an undefined state.");if(typeof h=="number"){const g=n.get(h);if(g===void 0||g.timerId!==u||g.timerType!==f)throw new Error("The timer is in an undefined state.")}else typeof h=="function"&&h()}else if(f==="timeout"){const h=t.get(u);if(typeof h===void 0)throw new Error("The timer is in an undefined state.");if(typeof h=="number"){const g=n.get(h);if(g===void 0||g.timerId!==u||g.timerType!==f)throw new Error("The timer is in an undefined state.")}else typeof h=="function"&&(h(),t.delete(u))}}else if(Fl(c)){const{id:u}=c,f=n.get(u);if(f===void 0)throw new Error("The timer is in an undefined state.");const{timerId:h,timerType:g}=f;n.delete(u),g==="interval"?e.delete(h):t.delete(h)}else{const{error:{message:u}}=c;throw new Error(u)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const u=Mt(n);n.set(u,{timerId:c,timerType:"interval"}),e.set(c,u),i.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"interval"}})}},clearTimeout:c=>{if(typeof t.get(c)=="function"){const u=Mt(n);n.set(u,{timerId:c,timerType:"timeout"}),t.set(c,u),i.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"timeout"}})}},setInterval:(c,u=0,...f)=>{const h=Mt(e);return e.set(h,()=>{c(...f),typeof e.get(h)=="function"&&i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"interval"}}),h},setTimeout:(c,u=0,...f)=>{const h=Mt(t);return t.set(h,()=>c(...f)),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:h,timerType:"timeout"}}),h}}},jl={width:640,height:480,frameRate:30,backgroundColor:"#000000"},kn=new Ve("View");class Hl{constructor(e){V(this,"id",qt());V(this,"_context");V(this,"_canvas");V(this,"_config");V(this,"_nodeList",[]);V(this,"_track");V(this,"_stopped",!0);V(this,"_nextTime",Date.now());V(this,"_workerTimeoutId");V(this,"_raqId");V(this,"_workerTimerScriptUrl");V(this,"_customSetTimeout");V(this,"_customClearTimeout");V(this,"_drawCount",0);V(this,"_lastSecondDrawCount",0);V(this,"_lastCountResetTime",Date.now());V(this,"_loopTimer");V(this,"_paintLoop",()=>{if(this._stopped){this._workerTimeoutId&&(this._customClearTimeout(this._workerTimeoutId),this._workerTimeoutId=void 0);return}this._drawOnCanvas(),this._workerTimeoutId&&this._customClearTimeout(this._workerTimeoutId),this._workerTimeoutId=this._customSetTimeout(()=>{this._paintLoop(),this._raqId&&(cancelAnimationFrame(this._raqId),this._raqId=void 0)},bn/this._config.frameRate),this._raqId=requestAnimationFrame(this._paintLoop)});kn.info("ctor",e),this._config={...jl,...e};const{context:t,canvas:n}=ws(this._config);this._context=t,this._canvas=n,this._customSetTimeout=Nl,this._customClearTimeout=Gl}setWorkerTimerScriptUrl(e){if(this._workerTimerScriptUrl=e,this._workerTimerScriptUrl){const t=Vl(this._workerTimerScriptUrl);this._customSetTimeout=(...n)=>t.setTimeout(...n),this._customClearTimeout=n=>t.clearTimeout(n)}}_shouldDraw(e){if(e<this._nextTime)return!1;for(;e>this._nextTime;)this._nextTime+=bn/this._config.frameRate;return!0}updateConfig(e){this._config={...this._config,...e},this._canvas.width=this._config.width,this._canvas.height=this._config.height}draw(e=[]){kn.info("draw",e),this._nodeList=e}_drawOnCanvas(){if(this._shouldDraw(Date.now())){this._drawCount++,this._updateDrawCountPerSecond(),this._drawBackground();for(const e of this._nodeList){let t=e;if(t.available()){for(;t;)t.paint(this._context),t=t.previousNode;this._context.setTransform(1,0,0,1,0,0)}}}}_updateDrawCountPerSecond(){const e=Date.now();e-this._lastCountResetTime>=bn&&(this._lastSecondDrawCount=this._drawCount,this._drawCount=0,this._lastCountResetTime=e)}getDrawCountPerSecond(){return this._updateDrawCountPerSecond(),this._lastSecondDrawCount}_drawBackground(){const{backgroundColor:e,width:t,height:n}=this._config;this._context.clearRect(0,0,t,n),e&&(this._context.fillStyle=e,this._context.fillRect(0,0,t,n))}track(){if(kn.info("track"),this._stopped&&(this._stopped=!1,this._paintLoop()),this._track)return this._track;const{frameRate:e}=this._config,t=this._canvas.captureStream(e);return this._track=t.getVideoTracks()[0],this._track}updateFps(){if(this._track){const e=this._track,{frameRate:t}=this._config,n=this._canvas.captureStream(t);return this._track=n.getVideoTracks()[0],e.stop(),this._track}else return this.track()}element(){return kn.info("element"),this._paintLoop(),this._canvas}stop(){this._stopped=!0}}function $l(){return Math.random().toString(36).slice(-8)}const ql=`
|
|
2
2
|
const SMOOTHING_FACTOR = 0.8;
|
|
3
3
|
const MINIMUM_VALUE = 0.00001;
|
|
4
4
|
|
|
@@ -53,51 +53,64 @@ registerProcessor('vumeter', class extends AudioWorkletProcessor {
|
|
|
53
53
|
return true;
|
|
54
54
|
}
|
|
55
55
|
});
|
|
56
|
-
`,md=URL.createObjectURL(new Blob([fd],{type:"application/javascript"}));class _d{constructor(){this._audioCtx=null,this._volume=0}get volume(){return this._volume}async start(e,t){if(this._audioCtx)return;const n=new AudioContext;await n.audioWorklet.addModule(t||md);const i=new MediaStream;i.addTrack(e);const s=n.createMediaStreamSource(i),a=new AudioWorkletNode(n,"vumeter");a.port.onmessage=o=>{const d=o.data.volume||0;this._volume=Math.min(d*100/2,10)},s.connect(a).connect(n.destination),this._audioCtx=n}stop(){var e;(e=this._audioCtx)==null||e.close(),this._audioCtx=null}}class Xr{constructor(){this._volumeDetectScriptUrl=void 0}static get instance(){return this._instance||(this._instance=new Xr),this._instance}get volumeDetectScriptUrl(){return this._volumeDetectScriptUrl}set volumeDetectScriptUrl(e){this._volumeDetectScriptUrl=e}}class Fs extends st{constructor(e){super(),this._width=0,this._height=0,this._mediaStream=null,this._nextStream=null,this._trackMap={},this.type=e.type,this.id=pd(),this._source=e.stream}get source(){return this._source}get videoTrack(){return this._trackMap.video}get audioTrack(){return this._trackMap.audio}get width(){return this._width}get height(){return this._height}get isVideoStream(){return[Q.Camera,Q.Screen,Q.VideoFile].includes(this.type)}get mediaStream(){if(this._mediaStream)return this._mediaStream;const e=new MediaStream;return this._trackMap.audio&&e.addTrack(this._trackMap.audio),this._trackMap.video&&e.addTrack(this._trackMap.video),this._mediaStream=e,e}async startVolumeDetect(){this.audioTrack&&(this._volumeDetector||(this._volumeDetector=new _d),await this._volumeDetector.start(this.audioTrack,Xr.instance.volumeDetectScriptUrl))}stopVolumeDetect(){var e;(e=this._volumeDetector)==null||e.stop(),this._volumeDetector=null}get volume(){var e;return((e=this._volumeDetector)==null?void 0:e.volume)||0}}class Lt extends Fs{constructor(){super(...arguments),this._frameRate=1}get isVideoStream(){return!0}get isAudioStream(){return!1}get frameRate(){return this._frameRate}bindTrackSizeChangeEvent(e){e.on(ge.SIZE_CHANGE,({width:t,height:n})=>{this._width=t,this._height=n,this.emit(ps.SizeChange,{width:t,height:n})})}}class Zr extends Fs{get isVideoStream(){return!1}get isAudioStream(){return!0}}class gd extends Lt{constructor(e,t){super({type:Q.Camera,stream:e}),this._trackMap.video=e.track(),this._width=e.width(),this._height=e.height(),this._frameRate=(t==null?void 0:t.frameRate)??1,this.bindTrackSizeChangeEvent(e)}get source(){return this._source}get viewNode(){return this.source.node()}get mixerNode(){return null}bindTrackEnd(e){this.source.on(ge.ENDED,e)}destroy(){this.source.destroy()}}var Vs=typeof global=="object"&&global&&global.Object===Object&&global,vd=typeof self=="object"&&self&&self.Object===Object&&self,Je=Vs||vd||Function("return this")(),at=Je.Symbol,js=Object.prototype,yd=js.hasOwnProperty,Sd=js.toString,tr=at?at.toStringTag:void 0;function bd(r){var e=yd.call(r,tr),t=r[tr];try{r[tr]=void 0;var n=!0}catch{}var i=Sd.call(r);return n&&(e?r[tr]=t:delete r[tr]),i}var Ed=Object.prototype,Cd=Ed.toString;function wd(r){return Cd.call(r)}var Td="[object Null]",kd="[object Undefined]",Hs=at?at.toStringTag:void 0;function Nt(r){return r==null?r===void 0?kd:Td:Hs&&Hs in Object(r)?bd(r):wd(r)}function Ut(r){return r!=null&&typeof r=="object"}var Rd="[object Symbol]";function Yr(r){return typeof r=="symbol"||Ut(r)&&Nt(r)==Rd}function qs(r,e){for(var t=-1,n=r==null?0:r.length,i=Array(n);++t<n;)i[t]=e(r[t],t,r);return i}var ue=Array.isArray,$s=at?at.prototype:void 0,Ks=$s?$s.toString:void 0;function Ws(r){if(typeof r=="string")return r;if(ue(r))return qs(r,Ws)+"";if(Yr(r))return Ks?Ks.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var Ad=/\s/;function Dd(r){for(var e=r.length;e--&&Ad.test(r.charAt(e)););return e}var xd=/^\s+/;function Id(r){return r&&r.slice(0,Dd(r)+1).replace(xd,"")}function rr(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var Js=NaN,zd=/^[-+]0x[0-9a-f]+$/i,Pd=/^0b[01]+$/i,Od=/^0o[0-7]+$/i,Md=parseInt;function Ld(r){if(typeof r=="number")return r;if(Yr(r))return Js;if(rr(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=rr(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=Id(r);var t=Pd.test(r);return t||Od.test(r)?Md(r.slice(2),t?2:8):zd.test(r)?Js:+r}var Nd=1/0,Ud=17976931348623157e292;function Gd(r){if(!r)return r===0?r:0;if(r=Ld(r),r===Nd||r===-1/0){var e=r<0?-1:1;return e*Ud}return r===r?r:0}function Bd(r){var e=Gd(r),t=e%1;return e===e?t?e-t:e:0}function Fd(r){return r}var Vd="[object AsyncFunction]",jd="[object Function]",Hd="[object GeneratorFunction]",qd="[object Proxy]";function Xs(r){if(!rr(r))return!1;var e=Nt(r);return e==jd||e==Hd||e==Vd||e==qd}var Kn=Je["__core-js_shared__"],Zs=function(){var r=/[^.]+$/.exec(Kn&&Kn.keys&&Kn.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function $d(r){return!!Zs&&Zs in r}var Kd=Function.prototype,Wd=Kd.toString;function St(r){if(r!=null){try{return Wd.call(r)}catch{}try{return r+""}catch{}}return""}var Jd=/[\\^$.*+?()[\]{}|]/g,Xd=/^\[object .+?Constructor\]$/,Zd=Function.prototype,Yd=Object.prototype,Qd=Zd.toString,el=Yd.hasOwnProperty,tl=RegExp("^"+Qd.call(el).replace(Jd,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function rl(r){if(!rr(r)||$d(r))return!1;var e=Xs(r)?tl:Xd;return e.test(St(r))}function nl(r,e){return r==null?void 0:r[e]}function Gt(r,e){var t=nl(r,e);return rl(t)?t:void 0}var Wn=Gt(Je,"WeakMap");function il(r,e,t,n){for(var i=r.length,s=t+-1;++s<i;)if(e(r[s],s,r))return s;return-1}var sl=9007199254740991,ol=/^(?:0|[1-9]\d*)$/;function Ys(r,e){var t=typeof r;return e=e??sl,!!e&&(t=="number"||t!="symbol"&&ol.test(r))&&r>-1&&r%1==0&&r<e}function Qs(r,e){return r===e||r!==r&&e!==e}var al=9007199254740991;function Jn(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=al}function Qr(r){return r!=null&&Jn(r.length)&&!Xs(r)}var cl=Object.prototype;function eo(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||cl;return r===t}function ul(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}var dl="[object Arguments]";function to(r){return Ut(r)&&Nt(r)==dl}var ro=Object.prototype,ll=ro.hasOwnProperty,hl=ro.propertyIsEnumerable,Xn=to(function(){return arguments}())?to:function(r){return Ut(r)&&ll.call(r,"callee")&&!hl.call(r,"callee")};function pl(){return!1}var no=typeof exports=="object"&&exports&&!exports.nodeType&&exports,io=no&&typeof module=="object"&&module&&!module.nodeType&&module,fl=io&&io.exports===no,so=fl?Je.Buffer:void 0,ml=so?so.isBuffer:void 0,en=ml||pl,_l="[object Arguments]",gl="[object Array]",vl="[object Boolean]",yl="[object Date]",Sl="[object Error]",bl="[object Function]",El="[object Map]",Cl="[object Number]",wl="[object Object]",Tl="[object RegExp]",kl="[object Set]",Rl="[object String]",Al="[object WeakMap]",Dl="[object ArrayBuffer]",xl="[object DataView]",Il="[object Float32Array]",zl="[object Float64Array]",Pl="[object Int8Array]",Ol="[object Int16Array]",Ml="[object Int32Array]",Ll="[object Uint8Array]",Nl="[object Uint8ClampedArray]",Ul="[object Uint16Array]",Gl="[object Uint32Array]",re={};re[Il]=re[zl]=re[Pl]=re[Ol]=re[Ml]=re[Ll]=re[Nl]=re[Ul]=re[Gl]=!0,re[_l]=re[gl]=re[Dl]=re[vl]=re[xl]=re[yl]=re[Sl]=re[bl]=re[El]=re[Cl]=re[wl]=re[Tl]=re[kl]=re[Rl]=re[Al]=!1;function Bl(r){return Ut(r)&&Jn(r.length)&&!!re[Nt(r)]}function Fl(r){return function(e){return r(e)}}var oo=typeof exports=="object"&&exports&&!exports.nodeType&&exports,nr=oo&&typeof module=="object"&&module&&!module.nodeType&&module,Vl=nr&&nr.exports===oo,Zn=Vl&&Vs.process,ao=function(){try{var r=nr&&nr.require&&nr.require("util").types;return r||Zn&&Zn.binding&&Zn.binding("util")}catch{}}(),co=ao&&ao.isTypedArray,Yn=co?Fl(co):Bl,jl=Object.prototype,Hl=jl.hasOwnProperty;function ql(r,e){var t=ue(r),n=!t&&Xn(r),i=!t&&!n&&en(r),s=!t&&!n&&!i&&Yn(r),a=t||n||i||s,o=a?ul(r.length,String):[],d=o.length;for(var c in r)Hl.call(r,c)&&!(a&&(c=="length"||i&&(c=="offset"||c=="parent")||s&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||Ys(c,d)))&&o.push(c);return o}function $l(r,e){return function(t){return r(e(t))}}var Kl=$l(Object.keys,Object),Wl=Object.prototype,Jl=Wl.hasOwnProperty;function uo(r){if(!eo(r))return Kl(r);var e=[];for(var t in Object(r))Jl.call(r,t)&&t!="constructor"&&e.push(t);return e}function ir(r){return Qr(r)?ql(r):uo(r)}var Xl=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Zl=/^\w*$/;function Qn(r,e){if(ue(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||Yr(r)?!0:Zl.test(r)||!Xl.test(r)||e!=null&&r in Object(e)}var sr=Gt(Object,"create");function Yl(){this.__data__=sr?sr(null):{},this.size=0}function Ql(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var eh="__lodash_hash_undefined__",th=Object.prototype,rh=th.hasOwnProperty;function nh(r){var e=this.__data__;if(sr){var t=e[r];return t===eh?void 0:t}return rh.call(e,r)?e[r]:void 0}var ih=Object.prototype,sh=ih.hasOwnProperty;function oh(r){var e=this.__data__;return sr?e[r]!==void 0:sh.call(e,r)}var ah="__lodash_hash_undefined__";function ch(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=sr&&e===void 0?ah:e,this}function bt(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}bt.prototype.clear=Yl,bt.prototype.delete=Ql,bt.prototype.get=nh,bt.prototype.has=oh,bt.prototype.set=ch;function uh(){this.__data__=[],this.size=0}function tn(r,e){for(var t=r.length;t--;)if(Qs(r[t][0],e))return t;return-1}var dh=Array.prototype,lh=dh.splice;function hh(r){var e=this.__data__,t=tn(e,r);if(t<0)return!1;var n=e.length-1;return t==n?e.pop():lh.call(e,t,1),--this.size,!0}function ph(r){var e=this.__data__,t=tn(e,r);return t<0?void 0:e[t][1]}function fh(r){return tn(this.__data__,r)>-1}function mh(r,e){var t=this.__data__,n=tn(t,r);return n<0?(++this.size,t.push([r,e])):t[n][1]=e,this}function Xe(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}Xe.prototype.clear=uh,Xe.prototype.delete=hh,Xe.prototype.get=ph,Xe.prototype.has=fh,Xe.prototype.set=mh;var or=Gt(Je,"Map");function _h(){this.size=0,this.__data__={hash:new bt,map:new(or||Xe),string:new bt}}function gh(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function rn(r,e){var t=r.__data__;return gh(e)?t[typeof e=="string"?"string":"hash"]:t.map}function vh(r){var e=rn(this,r).delete(r);return this.size-=e?1:0,e}function yh(r){return rn(this,r).get(r)}function Sh(r){return rn(this,r).has(r)}function bh(r,e){var t=rn(this,r),n=t.size;return t.set(r,e),this.size+=t.size==n?0:1,this}function Ze(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}Ze.prototype.clear=_h,Ze.prototype.delete=vh,Ze.prototype.get=yh,Ze.prototype.has=Sh,Ze.prototype.set=bh;var Eh="Expected a function";function ei(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(Eh);var t=function(){var n=arguments,i=e?e.apply(this,n):n[0],s=t.cache;if(s.has(i))return s.get(i);var a=r.apply(this,n);return t.cache=s.set(i,a)||s,a};return t.cache=new(ei.Cache||Ze),t}ei.Cache=Ze;var Ch=500;function wh(r){var e=ei(r,function(n){return t.size===Ch&&t.clear(),n}),t=e.cache;return e}var Th=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,kh=/\\(\\)?/g,Rh=wh(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(Th,function(t,n,i,s){e.push(i?s.replace(kh,"$1"):n||t)}),e});function Ah(r){return r==null?"":Ws(r)}function lo(r,e){return ue(r)?r:Qn(r,e)?[r]:Rh(Ah(r))}function nn(r){if(typeof r=="string"||Yr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function ho(r,e){e=lo(e,r);for(var t=0,n=e.length;r!=null&&t<n;)r=r[nn(e[t++])];return t&&t==n?r:void 0}function Dh(r,e,t){var n=r==null?void 0:ho(r,e);return n===void 0?t:n}function xh(r,e){for(var t=-1,n=e.length,i=r.length;++t<n;)r[i+t]=e[t];return r}function Ih(){this.__data__=new Xe,this.size=0}function zh(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function Ph(r){return this.__data__.get(r)}function Oh(r){return this.__data__.has(r)}var Mh=200;function Lh(r,e){var t=this.__data__;if(t instanceof Xe){var n=t.__data__;if(!or||n.length<Mh-1)return n.push([r,e]),this.size=++t.size,this;t=this.__data__=new Ze(n)}return t.set(r,e),this.size=t.size,this}function Ye(r){var e=this.__data__=new Xe(r);this.size=e.size}Ye.prototype.clear=Ih,Ye.prototype.delete=zh,Ye.prototype.get=Ph,Ye.prototype.has=Oh,Ye.prototype.set=Lh;function po(r,e){for(var t=-1,n=r==null?0:r.length,i=0,s=[];++t<n;){var a=r[t];e(a,t,r)&&(s[i++]=a)}return s}function Nh(){return[]}var Uh=Object.prototype,Gh=Uh.propertyIsEnumerable,fo=Object.getOwnPropertySymbols,Bh=fo?function(r){return r==null?[]:(r=Object(r),po(fo(r),function(e){return Gh.call(r,e)}))}:Nh;function Fh(r,e,t){var n=e(r);return ue(r)?n:xh(n,t(r))}function mo(r){return Fh(r,ir,Bh)}var ti=Gt(Je,"DataView"),ri=Gt(Je,"Promise"),ni=Gt(Je,"Set"),_o="[object Map]",Vh="[object Object]",go="[object Promise]",vo="[object Set]",yo="[object WeakMap]",So="[object DataView]",jh=St(ti),Hh=St(or),qh=St(ri),$h=St(ni),Kh=St(Wn),Qe=Nt;(ti&&Qe(new ti(new ArrayBuffer(1)))!=So||or&&Qe(new or)!=_o||ri&&Qe(ri.resolve())!=go||ni&&Qe(new ni)!=vo||Wn&&Qe(new Wn)!=yo)&&(Qe=function(r){var e=Nt(r),t=e==Vh?r.constructor:void 0,n=t?St(t):"";if(n)switch(n){case jh:return So;case Hh:return _o;case qh:return go;case $h:return vo;case Kh:return yo}return e});var bo=Je.Uint8Array,Wh="__lodash_hash_undefined__";function Jh(r){return this.__data__.set(r,Wh),this}function Xh(r){return this.__data__.has(r)}function sn(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new Ze;++e<t;)this.add(r[e])}sn.prototype.add=sn.prototype.push=Jh,sn.prototype.has=Xh;function Zh(r,e){for(var t=-1,n=r==null?0:r.length;++t<n;)if(e(r[t],t,r))return!0;return!1}function Yh(r,e){return r.has(e)}var Qh=1,ep=2;function Eo(r,e,t,n,i,s){var a=t&Qh,o=r.length,d=e.length;if(o!=d&&!(a&&d>o))return!1;var c=s.get(r),u=s.get(e);if(c&&u)return c==e&&u==r;var h=-1,l=!0,f=t&ep?new sn:void 0;for(s.set(r,e),s.set(e,r);++h<o;){var y=r[h],C=e[h];if(n)var v=a?n(C,y,h,e,r,s):n(y,C,h,r,e,s);if(v!==void 0){if(v)continue;l=!1;break}if(f){if(!Zh(e,function(E,k){if(!Yh(f,k)&&(y===E||i(y,E,t,n,s)))return f.push(k)})){l=!1;break}}else if(!(y===C||i(y,C,t,n,s))){l=!1;break}}return s.delete(r),s.delete(e),l}function tp(r){var e=-1,t=Array(r.size);return r.forEach(function(n,i){t[++e]=[i,n]}),t}function rp(r){var e=-1,t=Array(r.size);return r.forEach(function(n){t[++e]=n}),t}var np=1,ip=2,sp="[object Boolean]",op="[object Date]",ap="[object Error]",cp="[object Map]",up="[object Number]",dp="[object RegExp]",lp="[object Set]",hp="[object String]",pp="[object Symbol]",fp="[object ArrayBuffer]",mp="[object DataView]",Co=at?at.prototype:void 0,ii=Co?Co.valueOf:void 0;function _p(r,e,t,n,i,s,a){switch(t){case mp:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case fp:return!(r.byteLength!=e.byteLength||!s(new bo(r),new bo(e)));case sp:case op:case up:return Qs(+r,+e);case ap:return r.name==e.name&&r.message==e.message;case dp:case hp:return r==e+"";case cp:var o=tp;case lp:var d=n&np;if(o||(o=rp),r.size!=e.size&&!d)return!1;var c=a.get(r);if(c)return c==e;n|=ip,a.set(r,e);var u=Eo(o(r),o(e),n,i,s,a);return a.delete(r),u;case pp:if(ii)return ii.call(r)==ii.call(e)}return!1}var gp=1,vp=Object.prototype,yp=vp.hasOwnProperty;function Sp(r,e,t,n,i,s){var a=t&gp,o=mo(r),d=o.length,c=mo(e),u=c.length;if(d!=u&&!a)return!1;for(var h=d;h--;){var l=o[h];if(!(a?l in e:yp.call(e,l)))return!1}var f=s.get(r),y=s.get(e);if(f&&y)return f==e&&y==r;var C=!0;s.set(r,e),s.set(e,r);for(var v=a;++h<d;){l=o[h];var E=r[l],k=e[l];if(n)var g=a?n(k,E,l,e,r,s):n(E,k,l,r,e,s);if(!(g===void 0?E===k||i(E,k,t,n,s):g)){C=!1;break}v||(v=l=="constructor")}if(C&&!v){var D=r.constructor,L=e.constructor;D!=L&&"constructor"in r&&"constructor"in e&&!(typeof D=="function"&&D instanceof D&&typeof L=="function"&&L instanceof L)&&(C=!1)}return s.delete(r),s.delete(e),C}var bp=1,wo="[object Arguments]",To="[object Array]",on="[object Object]",Ep=Object.prototype,ko=Ep.hasOwnProperty;function Cp(r,e,t,n,i,s){var a=ue(r),o=ue(e),d=a?To:Qe(r),c=o?To:Qe(e);d=d==wo?on:d,c=c==wo?on:c;var u=d==on,h=c==on,l=d==c;if(l&&en(r)){if(!en(e))return!1;a=!0,u=!1}if(l&&!u)return s||(s=new Ye),a||Yn(r)?Eo(r,e,t,n,i,s):_p(r,e,d,t,n,i,s);if(!(t&bp)){var f=u&&ko.call(r,"__wrapped__"),y=h&&ko.call(e,"__wrapped__");if(f||y){var C=f?r.value():r,v=y?e.value():e;return s||(s=new Ye),i(C,v,t,n,s)}}return l?(s||(s=new Ye),Sp(r,e,t,n,i,s)):!1}function si(r,e,t,n,i){return r===e?!0:r==null||e==null||!Ut(r)&&!Ut(e)?r!==r&&e!==e:Cp(r,e,t,n,si,i)}var wp=1,Tp=2;function kp(r,e,t,n){var i=t.length,s=i;if(r==null)return!s;for(r=Object(r);i--;){var a=t[i];if(a[2]?a[1]!==r[a[0]]:!(a[0]in r))return!1}for(;++i<s;){a=t[i];var o=a[0],d=r[o],c=a[1];if(a[2]){if(d===void 0&&!(o in r))return!1}else{var u=new Ye,h;if(!(h===void 0?si(c,d,wp|Tp,n,u):h))return!1}}return!0}function Ro(r){return r===r&&!rr(r)}function Rp(r){for(var e=ir(r),t=e.length;t--;){var n=e[t],i=r[n];e[t]=[n,i,Ro(i)]}return e}function Ao(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function Ap(r){var e=Rp(r);return e.length==1&&e[0][2]?Ao(e[0][0],e[0][1]):function(t){return t===r||kp(t,r,e)}}function Dp(r,e){return r!=null&&e in Object(r)}function xp(r,e,t){e=lo(e,r);for(var n=-1,i=e.length,s=!1;++n<i;){var a=nn(e[n]);if(!(s=r!=null&&t(r,a)))break;r=r[a]}return s||++n!=i?s:(i=r==null?0:r.length,!!i&&Jn(i)&&Ys(a,i)&&(ue(r)||Xn(r)))}function Ip(r,e){return r!=null&&xp(r,e,Dp)}var zp=1,Pp=2;function Op(r,e){return Qn(r)&&Ro(e)?Ao(nn(r),e):function(t){var n=Dh(t,r);return n===void 0&&n===e?Ip(t,r):si(e,n,zp|Pp)}}function Mp(r){return function(e){return e==null?void 0:e[r]}}function Lp(r){return function(e){return ho(e,r)}}function Np(r){return Qn(r)?Mp(nn(r)):Lp(r)}function oi(r){return typeof r=="function"?r:r==null?Fd:typeof r=="object"?ue(r)?Op(r[0],r[1]):Ap(r):Np(r)}function Up(r){return function(e,t,n){for(var i=-1,s=Object(e),a=n(e),o=a.length;o--;){var d=a[++i];if(t(s[d],d,s)===!1)break}return e}}var Gp=Up();function Bp(r,e){return r&&Gp(r,e,ir)}function Fp(r,e){return function(t,n){if(t==null)return t;if(!Qr(t))return r(t,n);for(var i=t.length,s=-1,a=Object(t);++s<i&&n(a[s],s,a)!==!1;);return t}}var Vp=Fp(Bp);function jp(r,e){var t=[];return Vp(r,function(n,i,s){e(n,i,s)&&t.push(n)}),t}function Do(r,e){var t=ue(r)?po:jp;return t(r,oi(e))}function Hp(r){return function(e,t,n){var i=Object(e);if(!Qr(e)){var s=oi(t);e=ir(e),t=function(o){return s(i[o],o,i)}}var a=r(e,t,n);return a>-1?i[s?e[a]:a]:void 0}}var qp=Math.max;function $p(r,e,t){var n=r==null?0:r.length;if(!n)return-1;var i=t==null?0:Bd(t);return i<0&&(i=qp(n+i,0)),il(r,oi(e),i)}var ar=Hp($p);function Kp(r,e){return qs(e,function(t){return r[t]})}function et(r){return r==null?[]:Kp(r,ir(r))}var Wp="[object Map]",Jp="[object Set]",Xp=Object.prototype,Zp=Xp.hasOwnProperty;function Yp(r){if(r==null)return!0;if(Qr(r)&&(ue(r)||typeof r=="string"||typeof r.splice=="function"||en(r)||Yn(r)||Xn(r)))return!r.length;var e=Qe(r);if(e==Wp||e==Jp)return!r.size;if(eo(r))return!uo(r).length;for(var t in r)if(Zp.call(r,t))return!1;return!0}function Qp(r){return r==null}class ef extends Zr{constructor(e){super({type:Q.Microphone,stream:e}),this._trackMap.audio=e.track()}get source(){return this._source}get mixerNode(){return this.source.node()}bindTrackEnd(e){this.source.on(ge.ENDED,e)}destroy(){this.source.destroy()}}class tf extends Lt{constructor(e){super({type:Q.VideoFile,stream:e});const t=ar(e,i=>i.kind===te.VIDEO),n=ar(e,i=>i.kind===te.AUDIO);this._videoStream=t,this._audioStream=n,this._trackMap.video=t==null?void 0:t.track(),this._trackMap.audio=n==null?void 0:n.track(),t&&(this._height=t==null?void 0:t.height(),this._width=t==null?void 0:t.width())}get viewNode(){var e;return((e=this._videoStream)==null?void 0:e.node())??null}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._videoStream)==null||t.on(ge.ENDED,e)}destroy(){var e,t;(e=this._videoStream)==null||e.destroy(),(t=this._audioStream)==null||t.destroy(),delete this._trackMap.video,delete this._trackMap.audio}}class rf extends Lt{constructor(e,t){super({type:Q.Screen,stream:e});const n=ar(e,s=>s.kind===te.VIDEO),i=ar(e,s=>s.kind===te.AUDIO);this._videoStream=n,this._audioStream=i,this._frameRate=(t==null?void 0:t.frameRate)??1,this._trackMap.video=n==null?void 0:n.track(),this._trackMap.audio=i==null?void 0:i.track(),n&&(this._height=n==null?void 0:n.height(),this._width=n==null?void 0:n.width(),this.bindTrackSizeChangeEvent(n))}get viewNode(){var e;return((e=this._videoStream)==null?void 0:e.node())??null}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._videoStream)==null||t.on(ge.ENDED,e)}destroy(){var e,t;(e=this._videoStream)==null||e.destroy(),(t=this._audioStream)==null||t.destroy(),delete this._trackMap.video,delete this._trackMap.audio}}class nf extends Zr{constructor(e){super({type:Q.AudioFile,stream:e});const t=ar(e,n=>n.kind===te.AUDIO);this._audioStream=t,this._trackMap.audio=t==null?void 0:t.track()}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._audioStream)==null||t.on(ge.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}class sf extends Lt{constructor(e){super({type:Q.Image,stream:e}),this._width=e.width(),this._height=e.height()}get source(){return this._source}get mixerNode(){return null}get viewNode(){return this.source.node()}bindTrackEnd(e){this.source.on(ge.ENDED,e)}destroy(){this.source.destroy()}}class of extends Lt{constructor(e){super({type:Q.CustomVideo,stream:e}),this._trackMap.video=e.track(),this._width=e.width(),this._height=e.height()}get source(){return this._source}get viewNode(){return this.source.node()}get mixerNode(){return null}bindTrackEnd(e){this.source.on(ge.ENDED,e)}destroy(){this.source.destroy()}}class af extends Zr{constructor(e){super({type:Q.CustomAudio,stream:e}),this._trackMap.audio=e==null?void 0:e.track()}get source(){return this._source}get mixerNode(){var e;return((e=this.source)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._audioStream)==null||t.on(ge.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}const cf=["user","environment"],uf=18e4,df=1e4,xo=1e3;var ke=(r=>(r[r.OPEN_CAMERA_FAILED=1001]="OPEN_CAMERA_FAILED",r[r.OPEN_MICROPHONE_FAILED=1002]="OPEN_MICROPHONE_FAILED",r[r.OPEN_SCREEN_FAILED=1003]="OPEN_SCREEN_FAILED",r[r.VIDEO_FILE_CAPTURE_FAILED=1004]="VIDEO_FILE_CAPTURE_FAILED",r[r.AUDIO_FILE_CAPTURE_FAILED=1005]="AUDIO_FILE_CAPTURE_FAILED",r[r.IMAGE_FILE_CAPTURE_FAILED=1006]="IMAGE_FILE_CAPTURE_FAILED",r[r.VOLUME_DETECT_FAILED=1008]="VOLUME_DETECT_FAILED",r[r.PUBLISH_FAILED=2001]="PUBLISH_FAILED",r[r.UPDATE_PUBLISH_FAILED=2002]="UPDATE_PUBLISH_FAILED",r[r.PUSH_CONNECT_FAILED=2003]="PUSH_CONNECT_FAILED",r[r.AUDIO_RESUME_FAILED=2004]="AUDIO_RESUME_FAILED",r))(ke||{});class Bt extends Error{constructor(e,t,n){super(),this.code=e,this.message=t,n&&(this.ext=n)}}function Ft(r,e,t){const n=In.Landscape;if(e==="video"){const d=(n===In.Landscape?us:ds)[r],[c,u,h,l]=d.split("x").map(f=>Number(f));return{width:c,height:u,frameRate:h,bitrate:l*1e3}}const i=ls[r],[s,a]=i.split("x").map(o=>Number(o));return{sampleRate:s,bitrate:a*1e3}}var ne=function(){return(ne=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 ai(r,e,t,n){return new(t||(t=Promise))(function(i,s){function a(c){try{d(n.next(c))}catch(u){s(u)}}function o(c){try{d(n.throw(c))}catch(u){s(u)}}function d(c){c.done?i(c.value):new t(function(u){u(c.value)}).then(a,o)}d((n=n.apply(r,[])).next())})}function ci(r,e){var t,n,i,s,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function o(d){return function(c){return function(u){if(t)throw new TypeError("Generator is already executing.");for(;a;)try{if(t=1,n&&(i=2&u[0]?n.return:u[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,u[1])).done)return i;switch(n=0,i&&(u=[2&u[0],i.value]),u[0]){case 0:case 1:i=u;break;case 4:return a.label++,{value:u[1],done:!1};case 5:a.label++,n=u[1],u=[0];continue;case 7:u=a.ops.pop(),a.trys.pop();continue;default:if(i=a.trys,!((i=i.length>0&&i[i.length-1])||u[0]!==6&&u[0]!==2)){a=0;continue}if(u[0]===3&&(!i||u[1]>i[0]&&u[1]<i[3])){a.label=u[1];break}if(u[0]===6&&a.label<i[1]){a.label=i[1],i=u;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(u);break}i[2]&&a.ops.pop(),a.trys.pop();continue}u=e.call(r,a)}catch(h){u=[6,h],n=0}finally{t=i=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}([d,c])}}}function lf(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n,i,s=t.call(r),a=[];try{for(;(e===void 0||e-- >0)&&!(n=s.next()).done;)a.push(n.value)}catch(o){i={error:o}}finally{try{n&&!n.done&&(t=s.return)&&t.call(s)}finally{if(i)throw i.error}}return a}function cr(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(lf(arguments[e]));return r}var Io,hf=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(s){t(s),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&&cr(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}(),ur=function(r){return r!=null&&Object.prototype.toString.call(r)=="[object Object]"},ui=function(r){return Array.isArray(r)},pf=(Io=+Date.now()+Number((""+Math.random()).slice(2,8)),function(){return Io+=1}),dr=function(r){return function(e,t,n){if(typeof e=="string"&&typeof n=="number"){var i,s=[];n=n<=25?n:n%25;var a=String.fromCharCode(n+97);i=e.split(a);for(var o=0;o<i.length;o++){var d=parseInt(i[o],n);d=1*d^t;var c=String.fromCharCode(d);s.push(c)}return s.join("")}}(r,64,25)},zo=function(){return!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)},lr=function(r){zo()?window.addEventListener("pagehide",r,!1):window.addEventListener("beforeunload",r,!1)},Po=function(){var r=0;return["hidden","msHidden","webkitHidden"].forEach(function(e){document[e]!==void 0&&(r=1)}),r},di=function(r){var e=document.createElement("a");return e.href=r,e},an=function(r){var e={};try{var t=di(r).search;(t=t.slice(1)).split("&").forEach(function(n){var i,s,a=n.split("=");a.length&&(i=a[0],s=a[1]);try{e[i]=decodeURIComponent(s===void 0?"":s)}catch{e[i]=s}})}catch{}return e},cn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function li(){throw new Error("Dynamic requires are not currently supported by rollup-plugin-commonjs")}function Oo(r,e){return r(e={exports:{}},e.exports),e.exports}var hr=Oo(function(r,e){var t;t=function(){function n(){for(var s=0,a={};s<arguments.length;s++){var o=arguments[s];for(var d in o)a[d]=o[d]}return a}function i(s){return s.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function s(a){function o(){}function d(u,h,l){if(typeof document<"u"){typeof(l=n({path:"/"},o.defaults,l)).expires=="number"&&(l.expires=new Date(1*new Date+864e5*l.expires)),l.expires=l.expires?l.expires.toUTCString():"";try{var f=JSON.stringify(h);/^[\{\[]/.test(f)&&(h=f)}catch{}h=a.write?a.write(h,u):encodeURIComponent(String(h)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),u=encodeURIComponent(String(u)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\(\)]/g,escape);var y="";for(var C in l)l[C]&&(y+="; "+C,l[C]!==!0&&(y+="="+l[C].split(";")[0]));return document.cookie=u+"="+h+y}}function c(u,h){if(typeof document<"u"){for(var l={},f=document.cookie?document.cookie.split("; "):[],y=0;y<f.length;y++){var C=f[y].split("="),v=C.slice(1).join("=");h||v.charAt(0)!=='"'||(v=v.slice(1,-1));try{var E=i(C[0]);if(v=(a.read||a)(v,E)||i(v),h)try{v=JSON.parse(v)}catch{}if(l[E]=v,u===E)break}catch{}}return u?l[u]:l}}return o.set=d,o.get=function(u){return c(u,!1)},o.getJSON=function(u){return c(u,!0)},o.remove=function(u,h){d(u,"",n(h,{expires:-1}))},o.defaults={},o.withConverter=s,o}(function(){})},r.exports=t()}),hi=Oo(function(r,e){r.exports=function t(n,i,s){function a(c,u){if(!i[c]){if(!n[c]){if(!u&&li)return li();if(o)return o(c,!0);var h=new Error("Cannot find module '"+c+"'");throw h.code="MODULE_NOT_FOUND",h}var l=i[c]={exports:{}};n[c][0].call(l.exports,function(f){var y=n[c][1][f];return a(y||f)},l,l.exports,t,n,i,s)}return i[c].exports}for(var o=li,d=0;d<s.length;d++)a(s[d]);return a}({1:[function(t,n,i){(function(s){var a,o,d=s.MutationObserver||s.WebKitMutationObserver;if(d){var c=0,u=new d(y),h=s.document.createTextNode("");u.observe(h,{characterData:!0}),a=function(){h.data=c=++c%2}}else if(s.setImmediate||s.MessageChannel===void 0)a="document"in s&&"onreadystatechange"in s.document.createElement("script")?function(){var C=s.document.createElement("script");C.onreadystatechange=function(){y(),C.onreadystatechange=null,C.parentNode.removeChild(C),C=null},s.document.documentElement.appendChild(C)}:function(){setTimeout(y,0)};else{var l=new s.MessageChannel;l.port1.onmessage=y,a=function(){l.port2.postMessage(0)}}var f=[];function y(){var C,v;o=!0;for(var E=f.length;E;){for(v=f,f=[],C=-1;++C<E;)v[C]();E=f.length}o=!1}n.exports=function(C){f.push(C)!==1||o||a()}}).call(this,cn!==void 0?cn:typeof self<"u"?self:typeof window<"u"?window:{})},{}],2:[function(t,n,i){var s=t(1);function a(){}var o={},d=["REJECTED"],c=["FULFILLED"],u=["PENDING"];function h(E){if(typeof E!="function")throw new TypeError("resolver must be a function");this.state=u,this.queue=[],this.outcome=void 0,E!==a&&C(this,E)}function l(E,k,g){this.promise=E,typeof k=="function"&&(this.onFulfilled=k,this.callFulfilled=this.otherCallFulfilled),typeof g=="function"&&(this.onRejected=g,this.callRejected=this.otherCallRejected)}function f(E,k,g){s(function(){var D;try{D=k(g)}catch(L){return o.reject(E,L)}D===E?o.reject(E,new TypeError("Cannot resolve promise with itself")):o.resolve(E,D)})}function y(E){var k=E&&E.then;if(E&&(typeof E=="object"||typeof E=="function")&&typeof k=="function")return function(){k.apply(E,arguments)}}function C(E,k){var g=!1;function D(M){g||(g=!0,o.reject(E,M))}function L(M){g||(g=!0,o.resolve(E,M))}var R=v(function(){k(L,D)});R.status==="error"&&D(R.value)}function v(E,k){var g={};try{g.value=E(k),g.status="success"}catch(D){g.status="error",g.value=D}return g}n.exports=h,h.prototype.catch=function(E){return this.then(null,E)},h.prototype.then=function(E,k){if(typeof E!="function"&&this.state===c||typeof k!="function"&&this.state===d)return this;var g=new this.constructor(a);return this.state!==u?f(g,this.state===c?E:k,this.outcome):this.queue.push(new l(g,E,k)),g},l.prototype.callFulfilled=function(E){o.resolve(this.promise,E)},l.prototype.otherCallFulfilled=function(E){f(this.promise,this.onFulfilled,E)},l.prototype.callRejected=function(E){o.reject(this.promise,E)},l.prototype.otherCallRejected=function(E){f(this.promise,this.onRejected,E)},o.resolve=function(E,k){var g=v(y,k);if(g.status==="error")return o.reject(E,g.value);var D=g.value;if(D)C(E,D);else{E.state=c,E.outcome=k;for(var L=-1,R=E.queue.length;++L<R;)E.queue[L].callFulfilled(k)}return E},o.reject=function(E,k){E.state=d,E.outcome=k;for(var g=-1,D=E.queue.length;++g<D;)E.queue[g].callRejected(k);return E},h.resolve=function(E){return E instanceof this?E:o.resolve(new this(a),E)},h.reject=function(E){var k=new this(a);return o.reject(k,E)},h.all=function(E){var k=this;if(Object.prototype.toString.call(E)!=="[object Array]")return this.reject(new TypeError("must be an array"));var g=E.length,D=!1;if(!g)return this.resolve([]);for(var L=new Array(g),R=0,M=-1,N=new this(a);++M<g;)U(E[M],M);return N;function U(B,H){k.resolve(B).then(function(Y){L[H]=Y,++R!==g||D||(D=!0,o.resolve(N,L))},function(Y){D||(D=!0,o.reject(N,Y))})}},h.race=function(E){var k=this;if(Object.prototype.toString.call(E)!=="[object Array]")return this.reject(new TypeError("must be an array"));var g=E.length,D=!1;if(!g)return this.resolve([]);for(var L,R=-1,M=new this(a);++R<g;)L=E[R],k.resolve(L).then(function(N){D||(D=!0,o.resolve(M,N))},function(N){D||(D=!0,o.reject(M,N))});return M}},{1:1}],3:[function(t,n,i){(function(s){typeof s.Promise!="function"&&(s.Promise=t(2))}).call(this,cn!==void 0?cn:typeof self<"u"?self:typeof window<"u"?window:{})},{2:2}],4:[function(t,n,i){var s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(p){return typeof p}:function(p){return p&&typeof Symbol=="function"&&p.constructor===Symbol&&p!==Symbol.prototype?"symbol":typeof p},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 o(p,m){p=p||[],m=m||{};try{return new Blob(p,m)}catch(S){if(S.name!=="TypeError")throw S;for(var _=new(typeof BlobBuilder<"u"?BlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:WebKitBlobBuilder),w=0;w<p.length;w+=1)_.append(p[w]);return _.getBlob(m.type)}}typeof Promise>"u"&&t(3);var d=Promise;function c(p,m){m&&p.then(function(_){m(null,_)},function(_){m(_)})}function u(p,m,_){typeof m=="function"&&p.then(m),typeof _=="function"&&p.catch(_)}function h(p){return typeof p!="string"&&(console.warn(p+" used as a key, but it is not a string."),p=String(p)),p}function l(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var f=void 0,y={},C=Object.prototype.toString;function v(p){return typeof f=="boolean"?d.resolve(f):function(m){return new d(function(_){var w=m.transaction("local-forage-detect-blob-support","readwrite"),S=o([""]);w.objectStore("local-forage-detect-blob-support").put(S,"key"),w.onabort=function(b){b.preventDefault(),b.stopPropagation(),_(!1)},w.oncomplete=function(){var b=navigator.userAgent.match(/Chrome\/(\d+)/),A=navigator.userAgent.match(/Edge\//);_(A||!b||parseInt(b[1],10)>=43)}}).catch(function(){return!1})}(p).then(function(m){return f=m})}function E(p){var m=y[p.name],_={};_.promise=new d(function(w,S){_.resolve=w,_.reject=S}),m.deferredOperations.push(_),m.dbReady?m.dbReady=m.dbReady.then(function(){return _.promise}):m.dbReady=_.promise}function k(p){var m=y[p.name].deferredOperations.pop();if(m)return m.resolve(),m.promise}function g(p,m){var _=y[p.name].deferredOperations.pop();if(_)return _.reject(m),_.promise}function D(p,m){return new d(function(_,w){if(y[p.name]=y[p.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},p.db){if(!m)return _(p.db);E(p),p.db.close()}var S=[p.name];m&&S.push(p.version);var b=a.open.apply(a,S);m&&(b.onupgradeneeded=function(A){var I=b.result;try{I.createObjectStore(p.storeName),A.oldVersion<=1&&I.createObjectStore("local-forage-detect-blob-support")}catch(z){if(z.name!=="ConstraintError")throw z;console.warn('The database "'+p.name+'" has been upgraded from version '+A.oldVersion+" to version "+A.newVersion+', but the storage "'+p.storeName+'" already exists.')}}),b.onerror=function(A){A.preventDefault(),w(b.error)},b.onsuccess=function(){var A=b.result;A.onversionchange=function(I){I.target.close()},_(A),k(p)}})}function L(p){return D(p,!1)}function R(p){return D(p,!0)}function M(p,m){if(!p.db)return!0;var _=!p.db.objectStoreNames.contains(p.storeName),w=p.version<p.db.version,S=p.version>p.db.version;if(w&&(p.version!==m&&console.warn('The database "'+p.name+`" can't be downgraded from version `+p.db.version+" to version "+p.version+"."),p.version=p.db.version),S||_){if(_){var b=p.db.version+1;b>p.version&&(p.version=b)}return!0}return!1}function N(p){return o([function(m){for(var _=m.length,w=new ArrayBuffer(_),S=new Uint8Array(w),b=0;b<_;b++)S[b]=m.charCodeAt(b);return w}(atob(p.data))],{type:p.type})}function U(p){return p&&p.__local_forage_encoded_blob}function B(p){var m=this,_=m._initReady().then(function(){var w=y[m._dbInfo.name];if(w&&w.dbReady)return w.dbReady});return u(_,p,p),_}function H(p,m,_,w){w===void 0&&(w=1);try{var S=p.db.transaction(p.storeName,m);_(null,S)}catch(b){if(w>0&&(!p.db||b.name==="InvalidStateError"||b.name==="NotFoundError"))return d.resolve().then(function(){if(!p.db||b.name==="NotFoundError"&&!p.db.objectStoreNames.contains(p.storeName)&&p.version<=p.db.version)return p.db&&(p.version=p.db.version+1),R(p)}).then(function(){return function(A){E(A);for(var I=y[A.name],z=I.forages,O=0;O<z.length;O++){var G=z[O];G._dbInfo.db&&(G._dbInfo.db.close(),G._dbInfo.db=null)}return A.db=null,L(A).then(function(F){return A.db=F,M(A)?R(A):F}).then(function(F){A.db=I.db=F;for(var q=0;q<z.length;q++)z[q]._dbInfo.db=F}).catch(function(F){throw g(A,F),F})}(p).then(function(){H(p,m,_,w-1)})}).catch(_);_(b)}}var Y={_driver:"asyncStorage",_initStorage:function(p){var m=this,_={db:null};if(p)for(var w in p)_[w]=p[w];var S=y[_.name];S||(S={forages:[],db:null,dbReady:null,deferredOperations:[]},y[_.name]=S),S.forages.push(m),m._initReady||(m._initReady=m.ready,m.ready=B);var b=[];function A(){return d.resolve()}for(var I=0;I<S.forages.length;I++){var z=S.forages[I];z!==m&&b.push(z._initReady().catch(A))}var O=S.forages.slice(0);return d.all(b).then(function(){return _.db=S.db,L(_)}).then(function(G){return _.db=G,M(_,m._defaultConfig.version)?R(_):G}).then(function(G){_.db=S.db=G,m._dbInfo=_;for(var F=0;F<O.length;F++){var q=O[F];q!==m&&(q._dbInfo.db=_.db,q._dbInfo.version=_.version)}})},_support:function(){try{if(!a||!a.open)return!1;var p=typeof openDatabase<"u"&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),m=typeof fetch=="function"&&fetch.toString().indexOf("[native code")!==-1;return(!p||m)&&typeof indexedDB<"u"&&typeof IDBKeyRange<"u"}catch{return!1}}(),iterate:function(p,m){var _=this,w=new d(function(S,b){_.ready().then(function(){H(_._dbInfo,"readonly",function(A,I){if(A)return b(A);try{var z=I.objectStore(_._dbInfo.storeName).openCursor(),O=1;z.onsuccess=function(){var G=z.result;if(G){var F=G.value;U(F)&&(F=N(F));var q=p(F,G.key,O++);q!==void 0?S(q):G.continue()}else S()},z.onerror=function(){b(z.error)}}catch(G){b(G)}})}).catch(b)});return c(w,m),w},getItem:function(p,m){var _=this;p=h(p);var w=new d(function(S,b){_.ready().then(function(){H(_._dbInfo,"readonly",function(A,I){if(A)return b(A);try{var z=I.objectStore(_._dbInfo.storeName).get(p);z.onsuccess=function(){var O=z.result;O===void 0&&(O=null),U(O)&&(O=N(O)),S(O)},z.onerror=function(){b(z.error)}}catch(O){b(O)}})}).catch(b)});return c(w,m),w},setItem:function(p,m,_){var w=this;p=h(p);var S=new d(function(b,A){var I;w.ready().then(function(){return I=w._dbInfo,C.call(m)==="[object Blob]"?v(I.db).then(function(z){return z?m:(O=m,new d(function(G,F){var q=new FileReader;q.onerror=F,q.onloadend=function(X){var J=btoa(X.target.result||"");G({__local_forage_encoded_blob:!0,data:J,type:O.type})},q.readAsBinaryString(O)}));var O}):m}).then(function(z){H(w._dbInfo,"readwrite",function(O,G){if(O)return A(O);try{var F=G.objectStore(w._dbInfo.storeName);z===null&&(z=void 0);var q=F.put(z,p);G.oncomplete=function(){z===void 0&&(z=null),b(z)},G.onabort=G.onerror=function(){try{var X=q.error?q.error:q.transaction.error;A(X)}catch(J){A(J)}}}catch(X){A(X)}})}).catch(A)});return c(S,_),S},removeItem:function(p,m){var _=this;p=h(p);var w=new d(function(S,b){_.ready().then(function(){H(_._dbInfo,"readwrite",function(A,I){if(A)return b(A);try{var z=I.objectStore(_._dbInfo.storeName).delete(p);I.oncomplete=function(){S()},I.onerror=function(){b(z.error)},I.onabort=function(){try{var O=z.error?z.error:z.transaction.error;b(O)}catch(G){b(G)}}}catch(O){b(O)}})}).catch(b)});return c(w,m),w},clear:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){H(m._dbInfo,"readwrite",function(b,A){if(b)return S(b);try{var I=A.objectStore(m._dbInfo.storeName).clear();A.oncomplete=function(){w()},A.onabort=A.onerror=function(){try{var z=I.error?I.error:I.transaction.error;S(z)}catch(O){S(O)}}}catch(z){S(z)}})}).catch(S)});return c(_,p),_},length:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){H(m._dbInfo,"readonly",function(b,A){if(b)return S(b);try{var I=A.objectStore(m._dbInfo.storeName).count();I.onsuccess=function(){w(I.result)},I.onerror=function(){S(I.error)}}catch(z){S(z)}})}).catch(S)});return c(_,p),_},key:function(p,m){var _=this,w=new d(function(S,b){p<0?S(null):_.ready().then(function(){H(_._dbInfo,"readonly",function(A,I){if(A)return b(A);try{var z=I.objectStore(_._dbInfo.storeName),O=!1,G=(z.openKeyCursor||z.openCursor).call(z);G.onsuccess=function(){var F=G.result;F?p===0||O?S(F.key):(O=!0,F.advance(p)):S(null)},G.onerror=function(){b(G.error)}}catch(F){b(F)}})}).catch(b)});return c(w,m),w},keys:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){H(m._dbInfo,"readonly",function(b,A){if(b)return S(b);try{var I=A.objectStore(m._dbInfo.storeName),z=(I.openKeyCursor||I.openCursor).call(I),O=[];z.onsuccess=function(){var G=z.result;G?(O.push(G.key),G.continue()):w(O)},z.onerror=function(){S(z.error)}}catch(G){S(G)}})}).catch(S)});return c(_,p),_},dropInstance:function(p,m){m=l.apply(this,arguments);var _=this.config();(p=typeof p!="function"&&p||{}).name||(p.name=p.name||_.name,p.storeName=p.storeName||_.storeName);var w,S=this;if(p.name){var b=p.name===_.name&&S._dbInfo.db,A=b?d.resolve(S._dbInfo.db):L(p).then(function(I){var z=y[p.name],O=z.forages;z.db=I;for(var G=0;G<O.length;G++)O[G]._dbInfo.db=I;return I});w=p.storeName?A.then(function(I){if(I.objectStoreNames.contains(p.storeName)){var z=I.version+1;E(p);var O=y[p.name],G=O.forages;I.close();for(var F=0;F<G.length;F++){var q=G[F];q._dbInfo.db=null,q._dbInfo.version=z}return new d(function(X,J){var me=a.open(p.name,z);me.onerror=function(Ot){me.result.close(),J(Ot)},me.onupgradeneeded=function(){me.result.deleteObjectStore(p.storeName)},me.onsuccess=function(){var Ot=me.result;Ot.close(),X(Ot)}}).then(function(X){O.db=X;for(var J=0;J<G.length;J++){var me=G[J];me._dbInfo.db=X,k(me._dbInfo)}}).catch(function(X){throw(g(p,X)||d.resolve()).catch(function(){}),X})}}):A.then(function(I){E(p);var z=y[p.name],O=z.forages;I.close();for(var G=0;G<O.length;G++)O[G]._dbInfo.db=null;return new d(function(F,q){var X=a.deleteDatabase(p.name);X.onerror=function(){var J=X.result;J&&J.close(),q(X.error)},X.onblocked=function(){console.warn('dropInstance blocked for database "'+p.name+'" until all open connections are closed')},X.onsuccess=function(){var J=X.result;J&&J.close(),F(J)}}).then(function(F){z.db=F;for(var q=0;q<O.length;q++)k(O[q]._dbInfo)}).catch(function(F){throw(g(p,F)||d.resolve()).catch(function(){}),F})})}else w=d.reject("Invalid arguments");return c(w,m),w}},W="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",de=/^~~local_forage_type~([^~]+)~/,ce=9,Ee=ce+4,Ce=Object.prototype.toString;function we(p){var m,_,w,S,b,A=.75*p.length,I=p.length,z=0;p[p.length-1]==="="&&(A--,p[p.length-2]==="="&&A--);var O=new ArrayBuffer(A),G=new Uint8Array(O);for(m=0;m<I;m+=4)_=W.indexOf(p[m]),w=W.indexOf(p[m+1]),S=W.indexOf(p[m+2]),b=W.indexOf(p[m+3]),G[z++]=_<<2|w>>4,G[z++]=(15&w)<<4|S>>2,G[z++]=(3&S)<<6|63&b;return O}function ye(p){var m,_=new Uint8Array(p),w="";for(m=0;m<_.length;m+=3)w+=W[_[m]>>2],w+=W[(3&_[m])<<4|_[m+1]>>4],w+=W[(15&_[m+1])<<2|_[m+2]>>6],w+=W[63&_[m+2]];return _.length%3==2?w=w.substring(0,w.length-1)+"=":_.length%3==1&&(w=w.substring(0,w.length-2)+"=="),w}var Le={serialize:function(p,m){var _="";if(p&&(_=Ce.call(p)),p&&(_==="[object ArrayBuffer]"||p.buffer&&Ce.call(p.buffer)==="[object ArrayBuffer]")){var w,S="__lfsc__:";p instanceof ArrayBuffer?(w=p,S+="arbf"):(w=p.buffer,_==="[object Int8Array]"?S+="si08":_==="[object Uint8Array]"?S+="ui08":_==="[object Uint8ClampedArray]"?S+="uic8":_==="[object Int16Array]"?S+="si16":_==="[object Uint16Array]"?S+="ur16":_==="[object Int32Array]"?S+="si32":_==="[object Uint32Array]"?S+="ui32":_==="[object Float32Array]"?S+="fl32":_==="[object Float64Array]"?S+="fl64":m(new Error("Failed to get type for BinaryArray"))),m(S+ye(w))}else if(_==="[object Blob]"){var b=new FileReader;b.onload=function(){var A="~~local_forage_type~"+p.type+"~"+ye(this.result);m("__lfsc__:blob"+A)},b.readAsArrayBuffer(p)}else try{m(JSON.stringify(p))}catch(A){console.error("Couldn't convert value into a JSON string: ",p),m(null,A)}},deserialize:function(p){if(p.substring(0,ce)!=="__lfsc__:")return JSON.parse(p);var m,_=p.substring(Ee),w=p.substring(ce,Ee);if(w==="blob"&&de.test(_)){var S=_.match(de);m=S[1],_=_.substring(S[0].length)}var b=we(_);switch(w){case"arbf":return b;case"blob":return o([b],{type:m});case"si08":return new Int8Array(b);case"ui08":return new Uint8Array(b);case"uic8":return new Uint8ClampedArray(b);case"si16":return new Int16Array(b);case"ur16":return new Uint16Array(b);case"si32":return new Int32Array(b);case"ui32":return new Uint32Array(b);case"fl32":return new Float32Array(b);case"fl64":return new Float64Array(b);default:throw new Error("Unkown type: "+w)}},stringToBuffer:we,bufferToString:ye};function Ge(p,m,_,w){p.executeSql("CREATE TABLE IF NOT EXISTS "+m.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],_,w)}function Te(p,m,_,w,S,b){p.executeSql(_,w,S,function(A,I){I.code===I.SYNTAX_ERR?A.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[m.storeName],function(z,O){O.rows.length?b(z,I):Ge(z,m,function(){z.executeSql(_,w,S,b)},b)},b):b(A,I)},b)}function _t(p,m,_,w){var S=this;p=h(p);var b=new d(function(A,I){S.ready().then(function(){m===void 0&&(m=null);var z=m,O=S._dbInfo;O.serializer.serialize(m,function(G,F){F?I(F):O.db.transaction(function(q){Te(q,O,"INSERT OR REPLACE INTO "+O.storeName+" (key, value) VALUES (?, ?)",[p,G],function(){A(z)},function(X,J){I(J)})},function(q){if(q.code===q.QUOTA_ERR){if(w>0)return void A(_t.apply(S,[p,z,_,w-1]));I(q)}})})}).catch(I)});return c(b,_),b}function It(p){return new d(function(m,_){p.transaction(function(w){w.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",[],function(S,b){for(var A=[],I=0;I<b.rows.length;I++)A.push(b.rows.item(I).name);m({db:p,storeNames:A})},function(S,b){_(b)})},function(w){_(w)})})}var zt={_driver:"webSQLStorage",_initStorage:function(p){var m=this,_={db:null};if(p)for(var w in p)_[w]=typeof p[w]!="string"?p[w].toString():p[w];var S=new d(function(b,A){try{_.db=openDatabase(_.name,String(_.version),_.description,_.size)}catch(I){return A(I)}_.db.transaction(function(I){Ge(I,_,function(){m._dbInfo=_,b()},function(z,O){A(O)})},A)});return _.serializer=Le,S},_support:typeof openDatabase=="function",iterate:function(p,m){var _=this,w=new d(function(S,b){_.ready().then(function(){var A=_._dbInfo;A.db.transaction(function(I){Te(I,A,"SELECT * FROM "+A.storeName,[],function(z,O){for(var G=O.rows,F=G.length,q=0;q<F;q++){var X=G.item(q),J=X.value;if(J&&(J=A.serializer.deserialize(J)),(J=p(J,X.key,q+1))!==void 0)return void S(J)}S()},function(z,O){b(O)})})}).catch(b)});return c(w,m),w},getItem:function(p,m){var _=this;p=h(p);var w=new d(function(S,b){_.ready().then(function(){var A=_._dbInfo;A.db.transaction(function(I){Te(I,A,"SELECT * FROM "+A.storeName+" WHERE key = ? LIMIT 1",[p],function(z,O){var G=O.rows.length?O.rows.item(0).value:null;G&&(G=A.serializer.deserialize(G)),S(G)},function(z,O){b(O)})})}).catch(b)});return c(w,m),w},setItem:function(p,m,_){return _t.apply(this,[p,m,_,1])},removeItem:function(p,m){var _=this;p=h(p);var w=new d(function(S,b){_.ready().then(function(){var A=_._dbInfo;A.db.transaction(function(I){Te(I,A,"DELETE FROM "+A.storeName+" WHERE key = ?",[p],function(){S()},function(z,O){b(O)})})}).catch(b)});return c(w,m),w},clear:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){var b=m._dbInfo;b.db.transaction(function(A){Te(A,b,"DELETE FROM "+b.storeName,[],function(){w()},function(I,z){S(z)})})}).catch(S)});return c(_,p),_},length:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){var b=m._dbInfo;b.db.transaction(function(A){Te(A,b,"SELECT COUNT(key) as c FROM "+b.storeName,[],function(I,z){var O=z.rows.item(0).c;w(O)},function(I,z){S(z)})})}).catch(S)});return c(_,p),_},key:function(p,m){var _=this,w=new d(function(S,b){_.ready().then(function(){var A=_._dbInfo;A.db.transaction(function(I){Te(I,A,"SELECT key FROM "+A.storeName+" WHERE id = ? LIMIT 1",[p+1],function(z,O){var G=O.rows.length?O.rows.item(0).key:null;S(G)},function(z,O){b(O)})})}).catch(b)});return c(w,m),w},keys:function(p){var m=this,_=new d(function(w,S){m.ready().then(function(){var b=m._dbInfo;b.db.transaction(function(A){Te(A,b,"SELECT key FROM "+b.storeName,[],function(I,z){for(var O=[],G=0;G<z.rows.length;G++)O.push(z.rows.item(G).key);w(O)},function(I,z){S(z)})})}).catch(S)});return c(_,p),_},dropInstance:function(p,m){m=l.apply(this,arguments);var _=this.config();(p=typeof p!="function"&&p||{}).name||(p.name=p.name||_.name,p.storeName=p.storeName||_.storeName);var w,S=this;return c(w=p.name?new d(function(b){var A;A=p.name===_.name?S._dbInfo.db:openDatabase(p.name,"","",0),p.storeName?b({db:A,storeNames:[p.storeName]}):b(It(A))}).then(function(b){return new d(function(A,I){b.db.transaction(function(z){function O(X){return new d(function(J,me){z.executeSql("DROP TABLE IF EXISTS "+X,[],function(){J()},function(Ot,jr){me(jr)})})}for(var G=[],F=0,q=b.storeNames.length;F<q;F++)G.push(O(b.storeNames[F]));d.all(G).then(function(){A()}).catch(function(X){I(X)})},function(z){I(z)})})}):d.reject("Invalid arguments"),m),w}};function Nr(p,m){var _=p.name+"/";return p.storeName!==m.storeName&&(_+=p.storeName+"/"),_}function Rn(){return!function(){try{return localStorage.setItem("_localforage_support_test",!0),localStorage.removeItem("_localforage_support_test"),!1}catch{return!0}}()||localStorage.length>0}var An={_driver:"localStorageWrapper",_initStorage:function(p){var m={};if(p)for(var _ in p)m[_]=p[_];return m.keyPrefix=Nr(p,this._defaultConfig),Rn()?(this._dbInfo=m,m.serializer=Le,d.resolve()):d.reject()},_support:function(){try{return typeof localStorage<"u"&&"setItem"in localStorage&&!!localStorage.setItem}catch{return!1}}(),iterate:function(p,m){var _=this,w=_.ready().then(function(){for(var S=_._dbInfo,b=S.keyPrefix,A=b.length,I=localStorage.length,z=1,O=0;O<I;O++){var G=localStorage.key(O);if(G.indexOf(b)===0){var F=localStorage.getItem(G);if(F&&(F=S.serializer.deserialize(F)),(F=p(F,G.substring(A),z++))!==void 0)return F}}});return c(w,m),w},getItem:function(p,m){var _=this;p=h(p);var w=_.ready().then(function(){var S=_._dbInfo,b=localStorage.getItem(S.keyPrefix+p);return b&&(b=S.serializer.deserialize(b)),b});return c(w,m),w},setItem:function(p,m,_){var w=this;p=h(p);var S=w.ready().then(function(){m===void 0&&(m=null);var b=m;return new d(function(A,I){var z=w._dbInfo;z.serializer.serialize(m,function(O,G){if(G)I(G);else try{localStorage.setItem(z.keyPrefix+p,O),A(b)}catch(F){F.name!=="QuotaExceededError"&&F.name!=="NS_ERROR_DOM_QUOTA_REACHED"||I(F),I(F)}})})});return c(S,_),S},removeItem:function(p,m){var _=this;p=h(p);var w=_.ready().then(function(){var S=_._dbInfo;localStorage.removeItem(S.keyPrefix+p)});return c(w,m),w},clear:function(p){var m=this,_=m.ready().then(function(){for(var w=m._dbInfo.keyPrefix,S=localStorage.length-1;S>=0;S--){var b=localStorage.key(S);b.indexOf(w)===0&&localStorage.removeItem(b)}});return c(_,p),_},length:function(p){var m=this.keys().then(function(_){return _.length});return c(m,p),m},key:function(p,m){var _=this,w=_.ready().then(function(){var S,b=_._dbInfo;try{S=localStorage.key(p)}catch{S=null}return S&&(S=S.substring(b.keyPrefix.length)),S});return c(w,m),w},keys:function(p){var m=this,_=m.ready().then(function(){for(var w=m._dbInfo,S=localStorage.length,b=[],A=0;A<S;A++){var I=localStorage.key(A);I.indexOf(w.keyPrefix)===0&&b.push(I.substring(w.keyPrefix.length))}return b});return c(_,p),_},dropInstance:function(p,m){if(m=l.apply(this,arguments),!(p=typeof p!="function"&&p||{}).name){var _=this.config();p.name=p.name||_.name,p.storeName=p.storeName||_.storeName}var w,S=this;return c(w=p.name?new d(function(b){p.storeName?b(Nr(p,S._defaultConfig)):b(p.name+"/")}).then(function(b){for(var A=localStorage.length-1;A>=0;A--){var I=localStorage.key(A);I.indexOf(b)===0&&localStorage.removeItem(I)}}):d.reject("Invalid arguments"),m),w}},Dn=function(p,m){for(var _,w,S=p.length,b=0;b<S;){if((_=p[b])===(w=m)||typeof _=="number"&&typeof w=="number"&&isNaN(_)&&isNaN(w))return!0;b++}return!1},Ur=Array.isArray||function(p){return Object.prototype.toString.call(p)==="[object Array]"},gt={},Gr={},De={INDEXEDDB:Y,WEBSQL:zt,LOCALSTORAGE:An},Br=[De.INDEXEDDB._driver,De.WEBSQL._driver,De.LOCALSTORAGE._driver],nt=["dropInstance"],Pt=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(nt),Fr={description:"",driver:Br.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function xn(p,m){p[m]=function(){var _=arguments;return p.ready().then(function(){return p[m].apply(p,_)})}}function Vr(){for(var p=1;p<arguments.length;p++){var m=arguments[p];if(m)for(var _ in m)m.hasOwnProperty(_)&&(Ur(m[_])?arguments[0][_]=m[_].slice():arguments[0][_]=m[_])}return arguments[0]}var os=new(function(){function p(m){for(var _ in function(b,A){if(!(b instanceof A))throw new TypeError("Cannot call a class as a function")}(this,p),De)if(De.hasOwnProperty(_)){var w=De[_],S=w._driver;this[_]=S,gt[S]||this.defineDriver(w)}this._defaultConfig=Vr({},Fr),this._config=Vr({},this._defaultConfig,m),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch(function(){})}return p.prototype.config=function(m){if((m===void 0?"undefined":s(m))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var _ in m){if(_==="storeName"&&(m[_]=m[_].replace(/\W/g,"_")),_==="version"&&typeof m[_]!="number")return new Error("Database version must be a number.");this._config[_]=m[_]}return!("driver"in m)||!m.driver||this.setDriver(this._config.driver)}return typeof m=="string"?this._config[m]:this._config},p.prototype.defineDriver=function(m,_,w){var S=new d(function(b,A){try{var I=m._driver,z=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!m._driver)return void A(z);for(var O=Pt.concat("_initStorage"),G=0,F=O.length;G<F;G++){var q=O[G];if((!Dn(nt,q)||m[q])&&typeof m[q]!="function")return void A(z)}(function(){for(var J=function(Cg){return function(){var wg=new Error("Method "+Cg+" is not implemented by the current driver"),qc=d.reject(wg);return c(qc,arguments[arguments.length-1]),qc}},me=0,Ot=nt.length;me<Ot;me++){var jr=nt[me];m[jr]||(m[jr]=J(jr))}})();var X=function(J){gt[I]&&console.info("Redefining LocalForage driver: "+I),gt[I]=m,Gr[I]=J,b()};"_support"in m?m._support&&typeof m._support=="function"?m._support().then(X,A):X(!!m._support):X(!0)}catch(J){A(J)}});return u(S,_,w),S},p.prototype.driver=function(){return this._driver||null},p.prototype.getDriver=function(m,_,w){var S=gt[m]?d.resolve(gt[m]):d.reject(new Error("Driver not found."));return u(S,_,w),S},p.prototype.getSerializer=function(m){var _=d.resolve(Le);return u(_,m),_},p.prototype.ready=function(m){var _=this,w=_._driverSet.then(function(){return _._ready===null&&(_._ready=_._initDriver()),_._ready});return u(w,m,m),w},p.prototype.setDriver=function(m,_,w){var S=this;Ur(m)||(m=[m]);var b=this._getSupportedDrivers(m);function A(){S._config.driver=S.driver()}function I(O){return S._extend(O),A(),S._ready=S._initStorage(S._config),S._ready}var z=this._driverSet!==null?this._driverSet.catch(function(){return d.resolve()}):d.resolve();return this._driverSet=z.then(function(){var O=b[0];return S._dbInfo=null,S._ready=null,S.getDriver(O).then(function(G){S._driver=G._driver,A(),S._wrapLibraryMethodsWithReady(),S._initDriver=function(F){return function(){var q=0;return function X(){for(;q<F.length;){var J=F[q];return q++,S._dbInfo=null,S._ready=null,S.getDriver(J).then(I).catch(X)}A();var me=new Error("No available storage method found.");return S._driverSet=d.reject(me),S._driverSet}()}}(b)})}).catch(function(){A();var O=new Error("No available storage method found.");return S._driverSet=d.reject(O),S._driverSet}),u(this._driverSet,_,w),this._driverSet},p.prototype.supports=function(m){return!!Gr[m]},p.prototype._extend=function(m){Vr(this,m)},p.prototype._getSupportedDrivers=function(m){for(var _=[],w=0,S=m.length;w<S;w++){var b=m[w];this.supports(b)&&_.push(b)}return _},p.prototype._wrapLibraryMethodsWithReady=function(){for(var m=0,_=Pt.length;m<_;m++)xn(this,Pt[m])},p.prototype.createInstance=function(m){return new p(m)},p}());n.exports=os},{3:3}]},{},[4])(4)}),ff=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}(),mf=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}(),_f=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}(),gf=function(){function r(e,t){return this.dbStorage=hi.createInstance({driver:[hi.INDEXEDDB,hi.LOCALSTORAGE],name:e,storeName:t}),this.dbStorage}return r.prototype.getItem=function(e){return ai(this,void 0,void 0,function(){var t,n;return ci(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}(),vf=function(){function r(){this.defaultExpireTime=6048e5,this.local=new mf,this.session=new _f,this.cache=new ff}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 hr.get(e)}catch{return""}},r.prototype.setCookie=function(e,t,n,i){n===void 0&&(n=this.defaultExpireTime);try{var s=i||document.domain,a=+new Date+n;hr.set(e,t,{expires:new Date(a),path:"/",domain:s})}catch{}},r.prototype.removeCookie=function(e,t){try{hr.remove(e,{path:"/",domain:t||""})}catch{}},r}(),yf=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,s=i?di(i).hostname:"",a=an(window.location.href),o=/Mobile|htc|mini|Android|iP(ad|od|hone)/.test(this.appVersion)?"wap":"web",d=((e=window.navigator.connection)===null||e===void 0?void 0:e.effectiveType)||"";this.utm=function(h,l,f,y){var C=new vf,v=h?"_tea_utm_cache_"+h:"_tea_utm_cache",E=h?"_$utm_from_url_"+h:"_$utm_from_url",k={},g=["tr_shareuser","tr_admaster","tr_param1","tr_param2","tr_param3","tr_param4","$utm_from_url"],D={ad_id:Number(l.ad_id)||void 0,campaign_id:Number(l.campaign_id)||void 0,creative_id:Number(l.creative_id)||void 0,utm_source:l.utm_source,utm_medium:l.utm_medium,utm_campaign:l.utm_campaign,utm_term:l.utm_term,utm_content:l.utm_content,tr_shareuser:l.tr_shareuser,tr_admaster:l.tr_admaster,tr_param1:l.tr_param1,tr_param2:l.tr_param2,tr_param3:l.tr_param3,tr_param4:l.tr_param4};try{var L=!1;for(var R in D)D[R]&&(g.indexOf(R)!==-1?(k.hasOwnProperty("tracer_data")||(k.tracer_data={}),k.tracer_data[R]=D[R]):k[R]=D[R],L=!0);if(L)C.setSessionItem(E,"1"),C.setCookie(v,JSON.stringify(k),y,f);else{var M=C.getCookie(v,f);M&&(k=JSON.parse(M))}C.getSessionItem(E)==1&&(k.hasOwnProperty("tracer_data")||(k.tracer_data={}),k.tracer_data.$utm_from_url=1)}catch{return D}return k}(this.appid,a,this.domain,this.cookie_expire);var c=this.browser(),u=this.os();return{browser:c.browser,browser_version:c.browser_version,platform:o,os_name:u.os_name,os_version:u.os_version,userAgent:t,screen_width:window.screen&&window.screen.width,screen_height:window.screen&&window.screen.height,device_model:this.getDeviceModel(u.os_name),language:n,referrer:i,referrer_host:s,network_type:d,utm:this.utm,latest_data:this.last(i,s)}},r.prototype.last=function(e,t){var n="",i="",s="",a=location.hostname,o=!1;if(e&&t&&a!==t){n=e,i=t,o=!0;var d=an(e);d.keyword&&(s=d.keyword)}return{$latest_referrer:n,$latest_referrer_host:i,$latest_search_keyword:s,isLast:o}},r.prototype.browser=function(){var e,t,n="",i=""+parseFloat(this.appVersion),s=this.userAgent;return s.indexOf("Edge")!==-1||s.indexOf("Edg")!==-1?(n="Microsoft Edge",s.indexOf("Edge")!==-1?(e=s.indexOf("Edge"),i=s.substring(e+5)):(e=s.indexOf("Edg"),i=s.substring(e+4))):(e=s.indexOf("MSIE"))!==-1?(n="Microsoft Internet Explorer",i=s.substring(e+5)):(e=s.indexOf("Lark"))!==-1?(n="Lark",i=s.substring(e+5,e+11)):s.indexOf("Chrome")!==-1?(e=s.indexOf("TTWebView"))!==-1?(n="TTWebView",i=s.substring(e+10,e+23)):((e=s.indexOf("Chrome"))!==-1||(e=s.indexOf("Chrome"))!==-1)&&(n="Chrome",i=s.substring(e+7)):s.indexOf("Safari")!==-1?(e=s.indexOf("Safari"))!==-1&&(n="Safari",i=s.substring(e+7),(e=s.indexOf("Version"))!==-1&&(i=s.substring(e+8))):(e=s.indexOf("Firefox"))!==-1&&(n="Firefox",i=s.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 s=n[i];if(s.r.test(this.userAgent)){(e=s.s)==="Mac OS X"&&this.isNewIpad()&&(e="iOS");break}}var a=function(h,l){var f=h.exec(l);return f&&f[1]?f[1]:""},o=function(h,l){var f=RegExp("(?:^|[^A-Z0-9-_]|[^A-Z0-9-]_|sprd-)(?:"+h+")","i").exec(l);return f?f.slice(1)[0]:""};/Windows/.test(e)&&(t=a(/Windows (.*)/,e),e="windows");var d,c;switch(e){case"Mac OS X":t=o("Mac[ +]OS[ +]X(?:[ /](?:Version )?(\\d+(?:[_\\.]\\d+)+))?",this.userAgent),e="mac";break;case"Android":d=this.userAgent,(c=a(/Android ([\.\_\d]+)/,d))||(c=a(/Android\/([\.\_\d]+)/,d)),t=c,e="android";break;case"iOS":t=this.isNewIpad()?o("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 u=this.userAgent.indexOf("x86_64");t=this.userAgent.substring(u+7,u+16)}return{os_name:e,os_version:t}},r.prototype.getDeviceModel=function(e){var t="";try{if(e==="android")navigator.userAgent.split(";").forEach(function(s){s.indexOf("Build/")>-1&&(t=s.slice(0,s.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}(),pi=function(r,e){try{return hr.get(r)}catch{return""}},fi=function(r,e,t,n){try{var i=n||document.domain,s=+new Date+(t||6048e5);hr.set(r,e,{expires:new Date(s),path:"/",domain:i})}catch{}},Sf=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 pi(e)},r.prototype.setCookie=function(e,t,n,i){fi(e,t,n,i)},r}(),mi,T,Mo={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 pi(r)},setCookie:function(r,e,t,n){fi(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}}()},bf={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 pi(r)},setCookie:function(r,e,t,n){fi(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}}()},Et=function(){function r(e,t){this._storage=t&&t==="session"?bf:!e&&Mo.isSupportLS?Mo:new Sf}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}(),_i={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"},Lo=function(){return new Set(Object.keys(_i))},gi=function(){return Object.keys(_i)},No={sg:"1fz22z22z1nz21z4mz4bz4bz21z1ez18z1jz1gz49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz18z1jz1gz24z18z49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",my:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z19z1bz49z1kz27z4az1jz18z20z1iz1mz1dz1dz1gz1az1cz4az1az1mz1k"},vi={va:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",in:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k"},Ef={sg:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z21z1ez4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",in:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z49z23z21z1cz18z21z22z4ez18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",ie2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z1gz1cz4ez4az22z1gz1iz22z1mz1iz25z4az1cz23"},Cf={sg:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz25z4az23z21",va:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz24z4az23z21",ie2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z1gz1cz4ez4az22z1gz1iz22z1mz1iz25z4az1cz23"},pr="5.3.11_oversea",wf=["1fz22z22z1nz21z4mz4bz4bz1bz18z22z18z4az19z27z22z1cz1bz18z1lz1az1cz4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z1cz23z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z23z21z22z21z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z21z1ez4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22"].map(function(r){return dr(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.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.SubmitAfter="submit-after",r.SubmitError="submit-error",r.SubmitVerify="submit-verify",r.DestoryInstance="destory-instance",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"})(mi||(mi={})),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"}(T||(T={}));var x=mi,Z=void 0,Uo=new Date().getTimezoneOffset(),Tf=parseInt(""+-Uo/60,10),kf=60*Uo,Rf=function(){function r(e,t){var n=this;this.is_first_time=!0,this.configPersist=!1,this.initConfig=t,this.collect=e;var i=new yf(t.app_id,t.cookie_domain||"",t.cookie_expire||6048e5).init(),s="__tea_cache_first_"+t.app_id;this.configKey="__tea_cache_config_"+t.app_id,this.sessionStorage=new Et(!1,"session"),this.localStorage=new Et(!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(s);a&&a==1?this.is_first_time=!1:(this.is_first_time=!0,this.localStorage.setItem(s,"1")),this.envInfo={user:{user_unique_id:Z,user_type:Z,user_id:Z,user_is_auth:Z,user_is_login:Z,device_id:Z,web_id:Z,ip_addr_id:Z,user_unique_id_type:Z},header:{app_id:Z,app_name:Z,app_install_id:Z,install_id:Z,app_package:Z,app_channel:Z,app_version:Z,ab_version:Z,os_name:i.os_name,os_version:i.os_version,device_model:i.device_model,ab_client:Z,traffic_type:Z,network_type:i.network_type,client_ip:Z,device_brand:Z,os_api:Z,access:Z,language:i.language,region:Z,app_language:Z,app_region:Z,creative_id:i.utm.creative_id,ad_id:i.utm.ad_id,campaign_id:i.utm.campaign_id,log_type:Z,rnd:Z,platform:i.platform,sdk_version:pr,sdk_lib:"js",province:Z,city:Z,timezone:Tf,tz_offset:kf,tz_name:Z,sim_region:Z,carrier:Z,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(o){n.changeReferInfo(o.config)})}return r.prototype.initDomain=function(e){var t=this.initConfig.channel_domain;if(t)this.domain=t;else{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=No.sg),this.domain=dr(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 Lo().has(i)?_i[i]:((t=this.initConfig)===null||t===void 0?void 0:t.channel_type)==="tcpy"?Ef[i]:((n=this.initConfig)===null||n===void 0?void 0:n.channel_type)==="ttp"?Cf[i]:No[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.11_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.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=ne(ne({},t.evtParams||{}),e.evtParams||{});else if(n==="_staging_flag")t.evtParams=ne(ne({},t.evtParams||{}),{_staging_flag:e._staging_flag});else if(n==="reportErrorCallback"&&typeof e[n]=="function")t.reportErrorCallback=e[n];else{var i="",s="";if(n.indexOf(".")>-1){var a=n.split(".");i=a[0],s=a[1]}i?i==="user"||i==="header"?t.envInfo[i][s]=e[n]:(t.envInfo.header.custom[s]=e[n],t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.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(T.DEBUGGER_MESSAGE,{type:T.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(T.DEBUGGER_MESSAGE,{type:T.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(T.DEBUGGER_MESSAGE,{type:T.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(T.DEBUGGER_MESSAGE,{type:T.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(T.DEBUGGER_MESSAGE,{type:T.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(T.DEBUGGER_MESSAGE,{type:T.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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:n.message,infoType:"sdk"}),console.log("delete error")}},r}(),Af=function(){function r(e,t){this.isLog=t||!1,this.name=e||""}return r.prototype.info=function(e){this.isLog&&console.log("%c %s","color: yellow; background-color: black;","[Tea instance: "+this.name+"] "+e)},r.prototype.warn=function(e){this.isLog&&console.warn("%c %s","color: #4D1B00;","[Tea instance: "+this.name+"] "+e)},r.prototype.error=function(e){this.isLog&&console.error("%c %s","color: #FFF; background-color: #F53F3F;","[Tea instance: "+this.name+"] "+e)},r.prototype.throw=function(e){throw this.error(this.name),new Error(e)},r}(),Df=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}(),xf=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(s){console.log("AppLogBridge is started? : "+s),s?n(!0):i(!1)}):i(!1)}catch(s){console.log("AppLogBridge, error:"+JSON.stringify(s.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}(),If=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 gf(this.setKey,"LOGSETTING_DATA_STORE"),this.domain=t.logsetting_domain||this.collect.configManager.getDomain(),this.check()}else e.emit(x.LogSettingReady)},r.prototype.check=function(){return ai(this,void 0,void 0,function(){var e;return ci(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(x.LogSettingReady)):this.fetchSetting(),[3,3];case 2:return t.sent(),this.collect.emit(x.LogSettingReady),this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.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(x.LogSettingReady);else{var n=this.collect.configManager.get("header");n.custom=JSON.stringify(n.custom);var i=this.collect.configManager.get("user"),s={event_filter:0,header:ne(ne({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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch LogSetting Request",logType:"fetch",level:"info",time:Date.now(),data:s,infoType:"sdk"}),this.collect.requestManager.useRequest({url:""+this.domain+this.setUrl+"?device_platform=web",data:s,timeout:5e3,success:function(a){a!=null&&a.config?(t.setLocalData(a.config),t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"LogSetting Request Success",logType:"fetch",level:"info",time:Date.now(),data:a,infoType:"sdk"})):t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"LogSetting Request Response No Data",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"}),t.collect.emit(x.LogSettingReady)},fail:function(){t.collect.emit(x.LogSettingReady),t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"LogSetting Request Fail",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"})}})}},r.prototype.getLocalData=function(){return ai(this,void 0,void 0,function(){return ci(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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Update LogSetting Cache",logType:"info",level:"info",time:Date.now(),infoType:"sdk",data:e})}catch{this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.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}(),zf=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 Et(!0),this.localStorage=new Et(!1),this.logSetting=new If,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(x.Ready,function(){n.reportAll(!1)}),this.collect.on(x.ConfigDomain,function(){n.reportUrl=n.configManager.getUrl("event")}),this.collect.on(x.Event,function(i){n.event(i)}),this.collect.on(x.BeconEvent,function(i){n.beconEvent(i)}),this.collect.on(x.CleanEvents,function(){n.reportAll(!1)}),this.linster()},r.prototype.linster=function(){var e=this;window.addEventListener("unload",function(){e.reportAll(!0)},!1),lr(function(){e.reportAll(!0)}),document.addEventListener("visibilitychange",function(){document.visibilityState==="hidden"&&e.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&&zo())return void this.beconEvent(e);var n=cr(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(s){this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:s.message,infoType:"sdk"})}},r.prototype.beconEvent=function(e){if(!this.collect.destroy&&!this.collect.sdkStop){var t=cr(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(x.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(x.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 s=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(s,!0));this.collect.emit(x.SubmitVerify,a)}}catch{this.send(this.split(this.merge(i)),t)}}else try{s=JSON.parse(JSON.stringify(e)),this.send(this.split(this.merge(e)),t),this.config.event_verify_url&&(a=this.split(this.merge(s,!0)),this.collect.emit(x.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(),s=i.header,a=i.user;s.custom=this.customAllow(s.custom,t);var o=this.configManager.get("evtParams"),d=this.configManager.get("user_unique_id_type"),c=[];try{var u=e.filter(function(l){try{Object.keys(o).length&&(l.params=ne(ne({},o),l.params)),d&&(l.params.$user_unique_id_type=d);var f=n.configManager.getAbCache(),y=a[n.config.ab_user_mode]||a.user_unique_id,C=n.configManager.getAbUuidCache(y);if(f&&f.uuid&&f.uuid===y){var v=n.configManager.getAbVersion();if(n.config.enable_ab_uuid){if(C&&C.length){var E=C.join(",");v&&v.includes(E)&&(l.ab_sdk_version=v)}}else v&&(l.ab_sdk_version=v)}return l.session_id=n.collect.sessionManager.getSessionId(),l.params=n.paramsAllow(l,t),l}catch(k){return console.warn("filter merge event: "+(l&&l.event)+" error, pls check",k&&k.message),n.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Merge Event Something Error",level:"error",time:Date.now(),data:k.message,infoType:"sdk"}),!1}}),h=JSON.parse(JSON.stringify({events:u,user:a,header:s}));h.local_time=Math.floor(Date.now()/1e3),h.user_unique_type=this.config.enable_ttwebid?this.config.user_unique_type:void 0,h.verbose=1,c.push(h)}catch(l){console.warn("event merge error, pls check",l&&l.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(s){return n.indexOf(s)===-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 s=new Set(n);for(var a in e)s.has(a)&&(i[a]=e[a])}return JSON.stringify(i)}return JSON.stringify(e)}catch(o){return this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute customAllow Something Error",level:"error",time:Date.now(),data:o.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,s=e.params;if(!n)return JSON.stringify(e.params);if(n[i]&&n[i].length){var a={},o=new Set(n[i]);for(var d in s)!this.logSetting.getPredefineParamsList().has(d)&&o.has(d)||(a[d]=s[d]);return JSON.stringify(a)}return JSON.stringify(e.params)}catch(c){return this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.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 s=JSON.parse(JSON.stringify(i));n.config.filter&&((s=n.config.filter(s))||console.warn("filter must return data !!")),n.collect.eventFilter&&s&&((s=n.collect.eventFilter(s))||console.warn("filterEvent api must return data !!"));var a=s||i,o=JSON.parse(JSON.stringify(a));if(!a.length)return;var d=!0;if(a.forEach(function(c){c.events.length||(d=!1)}),!d)return;n.collect.emit(x.SubmitBefore,a),n.collect.requestManager.useRequest({url:n.reportUrl,data:a,success:function(c,u){c&&c.e!==0?(n.collect.emit(x.SubmitError,{type:"f_data",eventData:u,errorCode:c.e,response:c}),n.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_EVENT,info:"Event Report Fail",time:Date.now(),data:o,code:c.e,failType:"event data error",status:"fail"})):(n.collect.emit(x.SubmitScuess,{eventData:u,res:c}),n.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_EVENT,info:"Event Report Success",time:Date.now(),data:o,code:200,status:"success"}))},fail:function(c,u){n.configManager.get("reportErrorCallback")(c,u),n.collect.emit(x.SubmitError,{type:"f_net",eventData:c,errorCode:u}),n.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_EVENT,info:"Event Report Network Fail",time:Date.now(),data:o,code:u,failType:"network error",status:"fail"})},timeout:n.timeout,useBeacon:!n.config.disable_sendbeacon&&t,withCredentials:n.enable_ttwebid,zip:!0}),n.collect.emit(x.SubmitAfter,a)}catch(c){console.warn("something error, "+JSON.stringify(c.stack)),n.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Report Event Something Error",level:"error",time:Date.now(),data:c.message})}}))},r}(),un=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)},Pf=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 Et(!1),this.tokenKey="__tea_cache_tokens_"+t.app_id,this.enable_ttwebid=t.enable_ttwebid,this.enableCustomWebid=t.enable_custom_webid,this.collect.on(x.ConfigUuid,function(i){n.setUuid(i)}),this.collect.on(x.ConfigWebId,function(i){n.setWebId(i)}),this.collect.on(x.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(x.CustomWebId,function(){e.tokenReady=!0,e.collect.emit(x.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:un(),user_unique_id:this.configManager.get("user_unique_id")||un()}):this.remoteWebid()},r.prototype.checkEnv=function(){var e=window.navigator.userAgent;if(e.indexOf("miniProgram")!==-1||e.indexOf("MiniProgram")!==-1){var t=an(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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch WebID Request",logType:"fetch",level:"info",time:Date.now(),data:n});var i=un();this.collect.requestManager.useRequest({url:t,data:n,success:function(s){var a;s&&s.e===0?(a=s.web_id,e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Fetch WebID Request Success",logType:"fetch",level:"info",time:Date.now(),data:s})):(a=i,e.collect.configManager.set({localWebId:i}),e.collect.emit(x.TokenError),e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Fetch WebID Request Data Error, Use LocalId",logType:"fetch",level:"warn",time:Date.now(),data:s}),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(x.TokenError),e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.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 s=this.configManager.get("device_id")||i||t;this.collect.configManager.set({device_id:s}),e=ne(ne({},e),{device_id:s})}else delete e.device_id;this.setStorage(e),this.tokenReady=!0,this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.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(x.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(x.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(x.TokenChange,"uuid"),this.collect.emit(x.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(x.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(x.TokenChange,"uuid")),t!==e&&(this.configManager.set({web_id:e}),this.collect.emit(x.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){if(e.config.channel_type!=="tcpy"&&e.config.channel_type!=="ttp"){var n={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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch GetToken Request",logType:"fetch",level:"info",time:Date.now(),data:n,infoType:"sdk"}),e.collect.requestManager.useRequest({url:e.configManager.getUrl("tobid"),data:n,success:function(i){i&&i.e===0?(t(i.tobid),e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Fetch GetToken Request Success",logType:"fetch",level:"info",time:Date.now(),data:i,infoType:"sdk"})):(t(""),e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Fetch GetToken Request Fail",logType:"fetch",level:"error",time:Date.now(),data:i,infoType:"sdk"}))},fail:function(){t(""),e.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Fetch GetToken Request Network Error",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"})},time:3e4,withCredentials:e.enable_ttwebid})}else t("")})},r}(),fr=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)})},Of=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;this.collect=e,this.storage=new Et(!1,"session"),this.sessionKey="__tea_session_id_"+t.app_id,this.expireTime=t.expireTime||18e5,this.disableSession=t.disable_session,this.disableSessionTimeCheck=t.disable_session_check,this.disableSession||(this.setSessionId(),this.collect.on(x.SessionReset,function(i){n.resetSessionId(i)}),this.collect.on(x.SessionResetTime,function(){n.updateSessionIdTime()}))},r.prototype.updateSessionIdTime=function(){var e=this.storage.getItem(this.sessionKey);if(e&&e.sessionId){var t=e.timestamp;Date.now()-t>this.expireTime?e={sessionId:fr(),timestamp:Date.now()}:e.timestamp=Date.now(),this.storage.setItem(this.sessionKey,e),this.resetExpTime()}},r.prototype.setSessionId=function(){var e=this,t=this.storage.getItem(this.sessionKey);t&&t.sessionId?t.timestamp=Date.now():t={sessionId:fr(),timestamp:Date.now()},this.storage.setItem(this.sessionKey,t),this.disableSessionTimeCheck||(this.sessionExp=setInterval(function(){e.checkEXp()},this.expireTime))},r.prototype.getSessionId=function(){var e=this.storage.getItem(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(e){var t={sessionId:e||fr(),timestamp:Date.now()};this.storage.setItem(this.sessionKey,t)},r.prototype.checkEXp=function(){var e=this.storage.getItem(this.sessionKey);e&&e.sessionId&&Date.now()-e.timestamp+30>=this.expireTime&&(e={sessionId:fr(),timestamp:Date.now()},this.storage.setItem(this.sessionKey,e))},r}();function Vt(r){let e=r.length;for(;--e>=0;)r[e]=0}const yi=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),dn=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),Mf=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),Go=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),tt=new Array(576);Vt(tt);const mr=new Array(60);Vt(mr);const _r=new Array(512);Vt(_r);const gr=new Array(256);Vt(gr);const Si=new Array(29);Vt(Si);const ln=new Array(30);function bi(r,e,t,n,i){this.static_tree=r,this.extra_bits=e,this.extra_base=t,this.elems=n,this.max_length=i,this.has_stree=r&&r.length}let Bo,Fo,Vo;function Ei(r,e){this.dyn_tree=r,this.max_code=0,this.stat_desc=e}Vt(ln);const jo=r=>r<256?_r[r]:_r[256+(r>>>7)],vr=(r,e)=>{r.pending_buf[r.pending++]=255&e,r.pending_buf[r.pending++]=e>>>8&255},be=(r,e,t)=>{r.bi_valid>16-t?(r.bi_buf|=e<<r.bi_valid&65535,vr(r,r.bi_buf),r.bi_buf=e>>16-r.bi_valid,r.bi_valid+=t-16):(r.bi_buf|=e<<r.bi_valid&65535,r.bi_valid+=t)},Ve=(r,e,t)=>{be(r,t[2*e],t[2*e+1])},Ho=(r,e)=>{let t=0;do t|=1&r,r>>>=1,t<<=1;while(--e>0);return t>>>1},qo=(r,e,t)=>{const n=new Array(16);let i,s,a=0;for(i=1;i<=15;i++)a=a+t[i-1]<<1,n[i]=a;for(s=0;s<=e;s++){let o=r[2*s+1];o!==0&&(r[2*s]=Ho(n[o]++,o))}},$o=r=>{let e;for(e=0;e<286;e++)r.dyn_ltree[2*e]=0;for(e=0;e<30;e++)r.dyn_dtree[2*e]=0;for(e=0;e<19;e++)r.bl_tree[2*e]=0;r.dyn_ltree[512]=1,r.opt_len=r.static_len=0,r.sym_next=r.matches=0},Ko=r=>{r.bi_valid>8?vr(r,r.bi_buf):r.bi_valid>0&&(r.pending_buf[r.pending++]=r.bi_buf),r.bi_buf=0,r.bi_valid=0},Wo=(r,e,t,n)=>{const i=2*e,s=2*t;return r[i]<r[s]||r[i]===r[s]&&n[e]<=n[t]},Ci=(r,e,t)=>{const n=r.heap[t];let i=t<<1;for(;i<=r.heap_len&&(i<r.heap_len&&Wo(e,r.heap[i+1],r.heap[i],r.depth)&&i++,!Wo(e,n,r.heap[i],r.depth));)r.heap[t]=r.heap[i],t=i,i<<=1;r.heap[t]=n},Jo=(r,e,t)=>{let n,i,s,a,o=0;if(r.sym_next!==0)do n=255&r.pending_buf[r.sym_buf+o++],n+=(255&r.pending_buf[r.sym_buf+o++])<<8,i=r.pending_buf[r.sym_buf+o++],n===0?Ve(r,i,e):(s=gr[i],Ve(r,s+256+1,e),a=yi[s],a!==0&&(i-=Si[s],be(r,i,a)),n--,s=jo(n),Ve(r,s,t),a=dn[s],a!==0&&(n-=ln[s],be(r,n,a)));while(o<r.sym_next);Ve(r,256,e)},wi=(r,e)=>{const t=e.dyn_tree,n=e.stat_desc.static_tree,i=e.stat_desc.has_stree,s=e.stat_desc.elems;let a,o,d,c=-1;for(r.heap_len=0,r.heap_max=573,a=0;a<s;a++)t[2*a]!==0?(r.heap[++r.heap_len]=c=a,r.depth[a]=0):t[2*a+1]=0;for(;r.heap_len<2;)d=r.heap[++r.heap_len]=c<2?++c:0,t[2*d]=1,r.depth[d]=0,r.opt_len--,i&&(r.static_len-=n[2*d+1]);for(e.max_code=c,a=r.heap_len>>1;a>=1;a--)Ci(r,t,a);d=s;do a=r.heap[1],r.heap[1]=r.heap[r.heap_len--],Ci(r,t,1),o=r.heap[1],r.heap[--r.heap_max]=a,r.heap[--r.heap_max]=o,t[2*d]=t[2*a]+t[2*o],r.depth[d]=(r.depth[a]>=r.depth[o]?r.depth[a]:r.depth[o])+1,t[2*a+1]=t[2*o+1]=d,r.heap[1]=d++,Ci(r,t,1);while(r.heap_len>=2);r.heap[--r.heap_max]=r.heap[1],((u,h)=>{const l=h.dyn_tree,f=h.max_code,y=h.stat_desc.static_tree,C=h.stat_desc.has_stree,v=h.stat_desc.extra_bits,E=h.stat_desc.extra_base,k=h.stat_desc.max_length;let g,D,L,R,M,N,U=0;for(R=0;R<=15;R++)u.bl_count[R]=0;for(l[2*u.heap[u.heap_max]+1]=0,g=u.heap_max+1;g<573;g++)D=u.heap[g],R=l[2*l[2*D+1]+1]+1,R>k&&(R=k,U++),l[2*D+1]=R,D>f||(u.bl_count[R]++,M=0,D>=E&&(M=v[D-E]),N=l[2*D],u.opt_len+=N*(R+M),C&&(u.static_len+=N*(y[2*D+1]+M)));if(U!==0){do{for(R=k-1;u.bl_count[R]===0;)R--;u.bl_count[R]--,u.bl_count[R+1]+=2,u.bl_count[k]--,U-=2}while(U>0);for(R=k;R!==0;R--)for(D=u.bl_count[R];D!==0;)L=u.heap[--g],L>f||(l[2*L+1]!==R&&(u.opt_len+=(R-l[2*L+1])*l[2*L],l[2*L+1]=R),D--)}})(r,e),qo(t,c,r.bl_count)},Xo=(r,e,t)=>{let n,i,s=-1,a=e[1],o=0,d=7,c=4;for(a===0&&(d=138,c=3),e[2*(t+1)+1]=65535,n=0;n<=t;n++)i=a,a=e[2*(n+1)+1],++o<d&&i===a||(o<c?r.bl_tree[2*i]+=o:i!==0?(i!==s&&r.bl_tree[2*i]++,r.bl_tree[32]++):o<=10?r.bl_tree[34]++:r.bl_tree[36]++,o=0,s=i,a===0?(d=138,c=3):i===a?(d=6,c=3):(d=7,c=4))},Zo=(r,e,t)=>{let n,i,s=-1,a=e[1],o=0,d=7,c=4;for(a===0&&(d=138,c=3),n=0;n<=t;n++)if(i=a,a=e[2*(n+1)+1],!(++o<d&&i===a)){if(o<c)do Ve(r,i,r.bl_tree);while(--o!=0);else i!==0?(i!==s&&(Ve(r,i,r.bl_tree),o--),Ve(r,16,r.bl_tree),be(r,o-3,2)):o<=10?(Ve(r,17,r.bl_tree),be(r,o-3,3)):(Ve(r,18,r.bl_tree),be(r,o-11,7));o=0,s=i,a===0?(d=138,c=3):i===a?(d=6,c=3):(d=7,c=4)}};let Yo=!1;const Qo=(r,e,t,n)=>{be(r,0+(n?1:0),3),Ko(r),vr(r,t),vr(r,~t),t&&r.pending_buf.set(r.window.subarray(e,e+t),r.pending),r.pending+=t};var Lf={_tr_init:r=>{Yo||((()=>{let e,t,n,i,s;const a=new Array(16);for(n=0,i=0;i<28;i++)for(Si[i]=n,e=0;e<1<<yi[i];e++)gr[n++]=i;for(gr[n-1]=i,s=0,i=0;i<16;i++)for(ln[i]=s,e=0;e<1<<dn[i];e++)_r[s++]=i;for(s>>=7;i<30;i++)for(ln[i]=s<<7,e=0;e<1<<dn[i]-7;e++)_r[256+s++]=i;for(t=0;t<=15;t++)a[t]=0;for(e=0;e<=143;)tt[2*e+1]=8,e++,a[8]++;for(;e<=255;)tt[2*e+1]=9,e++,a[9]++;for(;e<=279;)tt[2*e+1]=7,e++,a[7]++;for(;e<=287;)tt[2*e+1]=8,e++,a[8]++;for(qo(tt,287,a),e=0;e<30;e++)mr[2*e+1]=5,mr[2*e]=Ho(e,5);Bo=new bi(tt,yi,257,286,15),Fo=new bi(mr,dn,0,30,15),Vo=new bi(new Array(0),Mf,0,19,7)})(),Yo=!0),r.l_desc=new Ei(r.dyn_ltree,Bo),r.d_desc=new Ei(r.dyn_dtree,Fo),r.bl_desc=new Ei(r.bl_tree,Vo),r.bi_buf=0,r.bi_valid=0,$o(r)},_tr_stored_block:Qo,_tr_flush_block:(r,e,t,n)=>{let i,s,a=0;r.level>0?(r.strm.data_type===2&&(r.strm.data_type=(o=>{let d,c=4093624447;for(d=0;d<=31;d++,c>>>=1)if(1&c&&o.dyn_ltree[2*d]!==0)return 0;if(o.dyn_ltree[18]!==0||o.dyn_ltree[20]!==0||o.dyn_ltree[26]!==0)return 1;for(d=32;d<256;d++)if(o.dyn_ltree[2*d]!==0)return 1;return 0})(r)),wi(r,r.l_desc),wi(r,r.d_desc),a=(o=>{let d;for(Xo(o,o.dyn_ltree,o.l_desc.max_code),Xo(o,o.dyn_dtree,o.d_desc.max_code),wi(o,o.bl_desc),d=18;d>=3&&o.bl_tree[2*Go[d]+1]===0;d--);return o.opt_len+=3*(d+1)+5+5+4,d})(r),i=r.opt_len+3+7>>>3,s=r.static_len+3+7>>>3,s<=i&&(i=s)):i=s=t+5,t+4<=i&&e!==-1?Qo(r,e,t,n):r.strategy===4||s===i?(be(r,2+(n?1:0),3),Jo(r,tt,mr)):(be(r,4+(n?1:0),3),((o,d,c,u)=>{let h;for(be(o,d-257,5),be(o,c-1,5),be(o,u-4,4),h=0;h<u;h++)be(o,o.bl_tree[2*Go[h]+1],3);Zo(o,o.dyn_ltree,d-1),Zo(o,o.dyn_dtree,c-1)})(r,r.l_desc.max_code+1,r.d_desc.max_code+1,a+1),Jo(r,r.dyn_ltree,r.dyn_dtree)),$o(r),n&&Ko(r)},_tr_tally:(r,e,t)=>(r.pending_buf[r.sym_buf+r.sym_next++]=e,r.pending_buf[r.sym_buf+r.sym_next++]=e>>8,r.pending_buf[r.sym_buf+r.sym_next++]=t,e===0?r.dyn_ltree[2*t]++:(r.matches++,e--,r.dyn_ltree[2*(gr[t]+256+1)]++,r.dyn_dtree[2*jo(e)]++),r.sym_next===r.sym_end),_tr_align:r=>{be(r,2,3),Ve(r,256,tt),(e=>{e.bi_valid===16?(vr(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(r)}},yr=(r,e,t,n)=>{let i=65535&r|0,s=r>>>16&65535|0,a=0;for(;t!==0;){a=t>2e3?2e3:t,t-=a;do i=i+e[n++]|0,s=s+i|0;while(--a);i%=65521,s%=65521}return i|s<<16|0};const Nf=new Uint32Array((()=>{let r,e=[];for(var t=0;t<256;t++){r=t;for(var n=0;n<8;n++)r=1&r?3988292384^r>>>1:r>>>1;e[t]=r}return e})());var le=(r,e,t,n)=>{const i=Nf,s=n+t;r^=-1;for(let a=n;a<s;a++)r=r>>>8^i[255&(r^e[a])];return-1^r},Ct={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},wt={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:Uf,_tr_stored_block:Ti,_tr_flush_block:Gf,_tr_tally:ct,_tr_align:Bf}=Lf,{Z_NO_FLUSH:ut,Z_PARTIAL_FLUSH:Ff,Z_FULL_FLUSH:Vf,Z_FINISH:Ie,Z_BLOCK:ea,Z_OK:fe,Z_STREAM_END:ta,Z_STREAM_ERROR:je,Z_DATA_ERROR:jf,Z_BUF_ERROR:ki,Z_DEFAULT_COMPRESSION:Hf,Z_FILTERED:qf,Z_HUFFMAN_ONLY:hn,Z_RLE:$f,Z_FIXED:Kf,Z_DEFAULT_STRATEGY:Wf,Z_UNKNOWN:Jf,Z_DEFLATED:pn}=wt,Tt=(r,e)=>(r.msg=Ct[e],e),ra=r=>2*r-(r>4?9:0),dt=r=>{let e=r.length;for(;--e>=0;)r[e]=0},Xf=r=>{let e,t,n,i=r.w_size;e=r.hash_size,n=e;do t=r.head[--n],r.head[n]=t>=i?t-i:0;while(--e);e=i,n=e;do t=r.prev[--n],r.prev[n]=t>=i?t-i:0;while(--e)};let lt=(r,e,t)=>(e<<r.hash_shift^t)&r.hash_mask;const Re=r=>{const e=r.state;let t=e.pending;t>r.avail_out&&(t=r.avail_out),t!==0&&(r.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+t),r.next_out),r.next_out+=t,e.pending_out+=t,r.total_out+=t,r.avail_out-=t,e.pending-=t,e.pending===0&&(e.pending_out=0))},Ae=(r,e)=>{Gf(r,r.block_start>=0?r.block_start:-1,r.strstart-r.block_start,e),r.block_start=r.strstart,Re(r.strm)},ee=(r,e)=>{r.pending_buf[r.pending++]=e},Sr=(r,e)=>{r.pending_buf[r.pending++]=e>>>8&255,r.pending_buf[r.pending++]=255&e},Ri=(r,e,t,n)=>{let i=r.avail_in;return i>n&&(i=n),i===0?0:(r.avail_in-=i,e.set(r.input.subarray(r.next_in,r.next_in+i),t),r.state.wrap===1?r.adler=yr(r.adler,e,i,t):r.state.wrap===2&&(r.adler=le(r.adler,e,i,t)),r.next_in+=i,r.total_in+=i,i)},na=(r,e)=>{let t,n,i=r.max_chain_length,s=r.strstart,a=r.prev_length,o=r.nice_match;const d=r.strstart>r.w_size-262?r.strstart-(r.w_size-262):0,c=r.window,u=r.w_mask,h=r.prev,l=r.strstart+258;let f=c[s+a-1],y=c[s+a];r.prev_length>=r.good_match&&(i>>=2),o>r.lookahead&&(o=r.lookahead);do if(t=e,c[t+a]===y&&c[t+a-1]===f&&c[t]===c[s]&&c[++t]===c[s+1]){s+=2,t++;do;while(c[++s]===c[++t]&&c[++s]===c[++t]&&c[++s]===c[++t]&&c[++s]===c[++t]&&c[++s]===c[++t]&&c[++s]===c[++t]&&c[++s]===c[++t]&&c[++s]===c[++t]&&s<l);if(n=258-(l-s),s=l-258,n>a){if(r.match_start=e,a=n,n>=o)break;f=c[s+a-1],y=c[s+a]}}while((e=h[e&u])>d&&--i!=0);return a<=r.lookahead?a:r.lookahead},jt=r=>{const e=r.w_size;let t,n,i;do{if(n=r.window_size-r.lookahead-r.strstart,r.strstart>=e+(e-262)&&(r.window.set(r.window.subarray(e,e+e-n),0),r.match_start-=e,r.strstart-=e,r.block_start-=e,r.insert>r.strstart&&(r.insert=r.strstart),Xf(r),n+=e),r.strm.avail_in===0)break;if(t=Ri(r.strm,r.window,r.strstart+r.lookahead,n),r.lookahead+=t,r.lookahead+r.insert>=3)for(i=r.strstart-r.insert,r.ins_h=r.window[i],r.ins_h=lt(r,r.ins_h,r.window[i+1]);r.insert&&(r.ins_h=lt(r,r.ins_h,r.window[i+3-1]),r.prev[i&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=i,i++,r.insert--,!(r.lookahead+r.insert<3)););}while(r.lookahead<262&&r.strm.avail_in!==0)},ia=(r,e)=>{let t,n,i,s=r.pending_buf_size-5>r.w_size?r.w_size:r.pending_buf_size-5,a=0,o=r.strm.avail_in;do{if(t=65535,i=r.bi_valid+42>>3,r.strm.avail_out<i||(i=r.strm.avail_out-i,n=r.strstart-r.block_start,t>n+r.strm.avail_in&&(t=n+r.strm.avail_in),t>i&&(t=i),t<s&&(t===0&&e!==Ie||e===ut||t!==n+r.strm.avail_in)))break;a=e===Ie&&t===n+r.strm.avail_in?1:0,Ti(r,0,0,a),r.pending_buf[r.pending-4]=t,r.pending_buf[r.pending-3]=t>>8,r.pending_buf[r.pending-2]=~t,r.pending_buf[r.pending-1]=~t>>8,Re(r.strm),n&&(n>t&&(n=t),r.strm.output.set(r.window.subarray(r.block_start,r.block_start+n),r.strm.next_out),r.strm.next_out+=n,r.strm.avail_out-=n,r.strm.total_out+=n,r.block_start+=n,t-=n),t&&(Ri(r.strm,r.strm.output,r.strm.next_out,t),r.strm.next_out+=t,r.strm.avail_out-=t,r.strm.total_out+=t)}while(a===0);return o-=r.strm.avail_in,o&&(o>=r.w_size?(r.matches=2,r.window.set(r.strm.input.subarray(r.strm.next_in-r.w_size,r.strm.next_in),0),r.strstart=r.w_size,r.insert=r.strstart):(r.window_size-r.strstart<=o&&(r.strstart-=r.w_size,r.window.set(r.window.subarray(r.w_size,r.w_size+r.strstart),0),r.matches<2&&r.matches++,r.insert>r.strstart&&(r.insert=r.strstart)),r.window.set(r.strm.input.subarray(r.strm.next_in-o,r.strm.next_in),r.strstart),r.strstart+=o,r.insert+=o>r.w_size-r.insert?r.w_size-r.insert:o),r.block_start=r.strstart),r.high_water<r.strstart&&(r.high_water=r.strstart),a?4:e!==ut&&e!==Ie&&r.strm.avail_in===0&&r.strstart===r.block_start?2:(i=r.window_size-r.strstart,r.strm.avail_in>i&&r.block_start>=r.w_size&&(r.block_start-=r.w_size,r.strstart-=r.w_size,r.window.set(r.window.subarray(r.w_size,r.w_size+r.strstart),0),r.matches<2&&r.matches++,i+=r.w_size,r.insert>r.strstart&&(r.insert=r.strstart)),i>r.strm.avail_in&&(i=r.strm.avail_in),i&&(Ri(r.strm,r.window,r.strstart,i),r.strstart+=i,r.insert+=i>r.w_size-r.insert?r.w_size-r.insert:i),r.high_water<r.strstart&&(r.high_water=r.strstart),i=r.bi_valid+42>>3,i=r.pending_buf_size-i>65535?65535:r.pending_buf_size-i,s=i>r.w_size?r.w_size:i,n=r.strstart-r.block_start,(n>=s||(n||e===Ie)&&e!==ut&&r.strm.avail_in===0&&n<=i)&&(t=n>i?i:n,a=e===Ie&&r.strm.avail_in===0&&t===n?1:0,Ti(r,r.block_start,t,a),r.block_start+=t,Re(r.strm)),a?3:1)},Ai=(r,e)=>{let t,n;for(;;){if(r.lookahead<262){if(jt(r),r.lookahead<262&&e===ut)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=lt(r,r.ins_h,r.window[r.strstart+3-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart),t!==0&&r.strstart-t<=r.w_size-262&&(r.match_length=na(r,t)),r.match_length>=3)if(n=ct(r,r.strstart-r.match_start,r.match_length-3),r.lookahead-=r.match_length,r.match_length<=r.max_lazy_match&&r.lookahead>=3){r.match_length--;do r.strstart++,r.ins_h=lt(r,r.ins_h,r.window[r.strstart+3-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart;while(--r.match_length!=0);r.strstart++}else r.strstart+=r.match_length,r.match_length=0,r.ins_h=r.window[r.strstart],r.ins_h=lt(r,r.ins_h,r.window[r.strstart+1]);else n=ct(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++;if(n&&(Ae(r,!1),r.strm.avail_out===0))return 1}return r.insert=r.strstart<2?r.strstart:2,e===Ie?(Ae(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(Ae(r,!1),r.strm.avail_out===0)?1:2},Ht=(r,e)=>{let t,n,i;for(;;){if(r.lookahead<262){if(jt(r),r.lookahead<262&&e===ut)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=lt(r,r.ins_h,r.window[r.strstart+3-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart),r.prev_length=r.match_length,r.prev_match=r.match_start,r.match_length=2,t!==0&&r.prev_length<r.max_lazy_match&&r.strstart-t<=r.w_size-262&&(r.match_length=na(r,t),r.match_length<=5&&(r.strategy===qf||r.match_length===3&&r.strstart-r.match_start>4096)&&(r.match_length=2)),r.prev_length>=3&&r.match_length<=r.prev_length){i=r.strstart+r.lookahead-3,n=ct(r,r.strstart-1-r.prev_match,r.prev_length-3),r.lookahead-=r.prev_length-1,r.prev_length-=2;do++r.strstart<=i&&(r.ins_h=lt(r,r.ins_h,r.window[r.strstart+3-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart);while(--r.prev_length!=0);if(r.match_available=0,r.match_length=2,r.strstart++,n&&(Ae(r,!1),r.strm.avail_out===0))return 1}else if(r.match_available){if(n=ct(r,0,r.window[r.strstart-1]),n&&Ae(r,!1),r.strstart++,r.lookahead--,r.strm.avail_out===0)return 1}else r.match_available=1,r.strstart++,r.lookahead--}return r.match_available&&(n=ct(r,0,r.window[r.strstart-1]),r.match_available=0),r.insert=r.strstart<2?r.strstart:2,e===Ie?(Ae(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(Ae(r,!1),r.strm.avail_out===0)?1:2};function He(r,e,t,n,i){this.good_length=r,this.max_lazy=e,this.nice_length=t,this.max_chain=n,this.func=i}const br=[new He(0,0,0,0,ia),new He(4,4,8,4,Ai),new He(4,5,16,8,Ai),new He(4,6,32,32,Ai),new He(4,4,16,16,Ht),new He(8,16,32,32,Ht),new He(8,16,128,128,Ht),new He(8,32,128,256,Ht),new He(32,128,258,1024,Ht),new He(32,258,258,4096,Ht)];function Zf(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=pn,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),dt(this.dyn_ltree),dt(this.dyn_dtree),dt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),dt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),dt(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const Er=r=>{if(!r)return 1;const e=r.state;return!e||e.strm!==r||e.status!==42&&e.status!==57&&e.status!==69&&e.status!==73&&e.status!==91&&e.status!==103&&e.status!==113&&e.status!==666?1:0},sa=r=>{if(Er(r))return Tt(r,je);r.total_in=r.total_out=0,r.data_type=Jf;const e=r.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap===2?57:e.wrap?42:113,r.adler=e.wrap===2?0:1,e.last_flush=-2,Uf(e),fe},oa=r=>{const e=sa(r);var t;return e===fe&&((t=r.state).window_size=2*t.w_size,dt(t.head),t.max_lazy_match=br[t.level].max_lazy,t.good_match=br[t.level].good_length,t.nice_match=br[t.level].nice_length,t.max_chain_length=br[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=2,t.match_available=0,t.ins_h=0),e},aa=(r,e,t,n,i,s)=>{if(!r)return je;let a=1;if(e===Hf&&(e=6),n<0?(a=0,n=-n):n>15&&(a=2,n-=16),i<1||i>9||t!==pn||n<8||n>15||e<0||e>9||s<0||s>Kf||n===8&&a!==1)return Tt(r,je);n===8&&(n=9);const o=new Zf;return r.state=o,o.strm=r,o.status=42,o.wrap=a,o.gzhead=null,o.w_bits=n,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=i+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+3-1)/3),o.window=new Uint8Array(2*o.w_size),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<i+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=3*(o.lit_bufsize-1),o.level=e,o.strategy=s,o.method=t,oa(r)};var Cr={deflateInit:(r,e)=>aa(r,e,pn,15,8,Wf),deflateInit2:aa,deflateReset:oa,deflateResetKeep:sa,deflateSetHeader:(r,e)=>Er(r)||r.state.wrap!==2?je:(r.state.gzhead=e,fe),deflate:(r,e)=>{if(Er(r)||e>ea||e<0)return r?Tt(r,je):je;const t=r.state;if(!r.output||r.avail_in!==0&&!r.input||t.status===666&&e!==Ie)return Tt(r,r.avail_out===0?ki:je);const n=t.last_flush;if(t.last_flush=e,t.pending!==0){if(Re(r),r.avail_out===0)return t.last_flush=-1,fe}else if(r.avail_in===0&&ra(e)<=ra(n)&&e!==Ie)return Tt(r,ki);if(t.status===666&&r.avail_in!==0)return Tt(r,ki);if(t.status===42&&t.wrap===0&&(t.status=113),t.status===42){let i=pn+(t.w_bits-8<<4)<<8,s=-1;if(s=t.strategy>=hn||t.level<2?0:t.level<6?1:t.level===6?2:3,i|=s<<6,t.strstart!==0&&(i|=32),i+=31-i%31,Sr(t,i),t.strstart!==0&&(Sr(t,r.adler>>>16),Sr(t,65535&r.adler)),r.adler=1,t.status=113,Re(r),t.pending!==0)return t.last_flush=-1,fe}if(t.status===57){if(r.adler=0,ee(t,31),ee(t,139),ee(t,8),t.gzhead)ee(t,(t.gzhead.text?1:0)+(t.gzhead.hcrc?2:0)+(t.gzhead.extra?4:0)+(t.gzhead.name?8:0)+(t.gzhead.comment?16:0)),ee(t,255&t.gzhead.time),ee(t,t.gzhead.time>>8&255),ee(t,t.gzhead.time>>16&255),ee(t,t.gzhead.time>>24&255),ee(t,t.level===9?2:t.strategy>=hn||t.level<2?4:0),ee(t,255&t.gzhead.os),t.gzhead.extra&&t.gzhead.extra.length&&(ee(t,255&t.gzhead.extra.length),ee(t,t.gzhead.extra.length>>8&255)),t.gzhead.hcrc&&(r.adler=le(r.adler,t.pending_buf,t.pending,0)),t.gzindex=0,t.status=69;else if(ee(t,0),ee(t,0),ee(t,0),ee(t,0),ee(t,0),ee(t,t.level===9?2:t.strategy>=hn||t.level<2?4:0),ee(t,3),t.status=113,Re(r),t.pending!==0)return t.last_flush=-1,fe}if(t.status===69){if(t.gzhead.extra){let i=t.pending,s=(65535&t.gzhead.extra.length)-t.gzindex;for(;t.pending+s>t.pending_buf_size;){let o=t.pending_buf_size-t.pending;if(t.pending_buf.set(t.gzhead.extra.subarray(t.gzindex,t.gzindex+o),t.pending),t.pending=t.pending_buf_size,t.gzhead.hcrc&&t.pending>i&&(r.adler=le(r.adler,t.pending_buf,t.pending-i,i)),t.gzindex+=o,Re(r),t.pending!==0)return t.last_flush=-1,fe;i=0,s-=o}let a=new Uint8Array(t.gzhead.extra);t.pending_buf.set(a.subarray(t.gzindex,t.gzindex+s),t.pending),t.pending+=s,t.gzhead.hcrc&&t.pending>i&&(r.adler=le(r.adler,t.pending_buf,t.pending-i,i)),t.gzindex=0}t.status=73}if(t.status===73){if(t.gzhead.name){let i,s=t.pending;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>s&&(r.adler=le(r.adler,t.pending_buf,t.pending-s,s)),Re(r),t.pending!==0)return t.last_flush=-1,fe;s=0}i=t.gzindex<t.gzhead.name.length?255&t.gzhead.name.charCodeAt(t.gzindex++):0,ee(t,i)}while(i!==0);t.gzhead.hcrc&&t.pending>s&&(r.adler=le(r.adler,t.pending_buf,t.pending-s,s)),t.gzindex=0}t.status=91}if(t.status===91){if(t.gzhead.comment){let i,s=t.pending;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>s&&(r.adler=le(r.adler,t.pending_buf,t.pending-s,s)),Re(r),t.pending!==0)return t.last_flush=-1,fe;s=0}i=t.gzindex<t.gzhead.comment.length?255&t.gzhead.comment.charCodeAt(t.gzindex++):0,ee(t,i)}while(i!==0);t.gzhead.hcrc&&t.pending>s&&(r.adler=le(r.adler,t.pending_buf,t.pending-s,s))}t.status=103}if(t.status===103){if(t.gzhead.hcrc){if(t.pending+2>t.pending_buf_size&&(Re(r),t.pending!==0))return t.last_flush=-1,fe;ee(t,255&r.adler),ee(t,r.adler>>8&255),r.adler=0}if(t.status=113,Re(r),t.pending!==0)return t.last_flush=-1,fe}if(r.avail_in!==0||t.lookahead!==0||e!==ut&&t.status!==666){let i=t.level===0?ia(t,e):t.strategy===hn?((s,a)=>{let o;for(;;){if(s.lookahead===0&&(jt(s),s.lookahead===0)){if(a===ut)return 1;break}if(s.match_length=0,o=ct(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,o&&(Ae(s,!1),s.strm.avail_out===0))return 1}return s.insert=0,a===Ie?(Ae(s,!0),s.strm.avail_out===0?3:4):s.sym_next&&(Ae(s,!1),s.strm.avail_out===0)?1:2})(t,e):t.strategy===$f?((s,a)=>{let o,d,c,u;const h=s.window;for(;;){if(s.lookahead<=258){if(jt(s),s.lookahead<=258&&a===ut)return 1;if(s.lookahead===0)break}if(s.match_length=0,s.lookahead>=3&&s.strstart>0&&(c=s.strstart-1,d=h[c],d===h[++c]&&d===h[++c]&&d===h[++c])){u=s.strstart+258;do;while(d===h[++c]&&d===h[++c]&&d===h[++c]&&d===h[++c]&&d===h[++c]&&d===h[++c]&&d===h[++c]&&d===h[++c]&&c<u);s.match_length=258-(u-c),s.match_length>s.lookahead&&(s.match_length=s.lookahead)}if(s.match_length>=3?(o=ct(s,1,s.match_length-3),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(o=ct(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),o&&(Ae(s,!1),s.strm.avail_out===0))return 1}return s.insert=0,a===Ie?(Ae(s,!0),s.strm.avail_out===0?3:4):s.sym_next&&(Ae(s,!1),s.strm.avail_out===0)?1:2})(t,e):br[t.level].func(t,e);if(i!==3&&i!==4||(t.status=666),i===1||i===3)return r.avail_out===0&&(t.last_flush=-1),fe;if(i===2&&(e===Ff?Bf(t):e!==ea&&(Ti(t,0,0,!1),e===Vf&&(dt(t.head),t.lookahead===0&&(t.strstart=0,t.block_start=0,t.insert=0))),Re(r),r.avail_out===0))return t.last_flush=-1,fe}return e!==Ie?fe:t.wrap<=0?ta:(t.wrap===2?(ee(t,255&r.adler),ee(t,r.adler>>8&255),ee(t,r.adler>>16&255),ee(t,r.adler>>24&255),ee(t,255&r.total_in),ee(t,r.total_in>>8&255),ee(t,r.total_in>>16&255),ee(t,r.total_in>>24&255)):(Sr(t,r.adler>>>16),Sr(t,65535&r.adler)),Re(r),t.wrap>0&&(t.wrap=-t.wrap),t.pending!==0?fe:ta)},deflateEnd:r=>{if(Er(r))return je;const e=r.state.status;return r.state=null,e===113?Tt(r,jf):fe},deflateSetDictionary:(r,e)=>{let t=e.length;if(Er(r))return je;const n=r.state,i=n.wrap;if(i===2||i===1&&n.status!==42||n.lookahead)return je;if(i===1&&(r.adler=yr(r.adler,e,t,0)),n.wrap=0,t>=n.w_size){i===0&&(dt(n.head),n.strstart=0,n.block_start=0,n.insert=0);let d=new Uint8Array(n.w_size);d.set(e.subarray(t-n.w_size,t),0),e=d,t=n.w_size}const s=r.avail_in,a=r.next_in,o=r.input;for(r.avail_in=t,r.next_in=0,r.input=e,jt(n);n.lookahead>=3;){let d=n.strstart,c=n.lookahead-2;do n.ins_h=lt(n,n.ins_h,n.window[d+3-1]),n.prev[d&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=d,d++;while(--c);n.strstart=d,n.lookahead=2,jt(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,r.next_in=a,r.input=o,r.avail_in=s,n.wrap=i,fe},deflateInfo:"pako deflate (from Nodeca project)"};const Yf=(r,e)=>Object.prototype.hasOwnProperty.call(r,e);var ca=function(r){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const t=e.shift();if(t){if(typeof t!="object")throw new TypeError(t+"must be non-object");for(const n in t)Yf(t,n)&&(r[n]=t[n])}}return r},ua=r=>{let e=0;for(let n=0,i=r.length;n<i;n++)e+=r[n].length;const t=new Uint8Array(e);for(let n=0,i=0,s=r.length;n<s;n++){let a=r[n];t.set(a,i),i+=a.length}return t};let da=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{da=!1}const wr=new Uint8Array(256);for(let r=0;r<256;r++)wr[r]=r>=252?6:r>=248?5:r>=240?4:r>=224?3:r>=192?2:1;wr[254]=wr[254]=1;var Di=r=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(r);let e,t,n,i,s,a=r.length,o=0;for(i=0;i<a;i++)t=r.charCodeAt(i),(64512&t)==55296&&i+1<a&&(n=r.charCodeAt(i+1),(64512&n)==56320&&(t=65536+(t-55296<<10)+(n-56320),i++)),o+=t<128?1:t<2048?2:t<65536?3:4;for(e=new Uint8Array(o),s=0,i=0;s<o;i++)t=r.charCodeAt(i),(64512&t)==55296&&i+1<a&&(n=r.charCodeAt(i+1),(64512&n)==56320&&(t=65536+(t-55296<<10)+(n-56320),i++)),t<128?e[s++]=t:t<2048?(e[s++]=192|t>>>6,e[s++]=128|63&t):t<65536?(e[s++]=224|t>>>12,e[s++]=128|t>>>6&63,e[s++]=128|63&t):(e[s++]=240|t>>>18,e[s++]=128|t>>>12&63,e[s++]=128|t>>>6&63,e[s++]=128|63&t);return e},Qf=(r,e)=>{const t=e||r.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(r.subarray(0,e));let n,i;const s=new Array(2*t);for(i=0,n=0;n<t;){let a=r[n++];if(a<128){s[i++]=a;continue}let o=wr[a];if(o>4)s[i++]=65533,n+=o-1;else{for(a&=o===2?31:o===3?15:7;o>1&&n<t;)a=a<<6|63&r[n++],o--;o>1?s[i++]=65533:a<65536?s[i++]=a:(a-=65536,s[i++]=55296|a>>10&1023,s[i++]=56320|1023&a)}}return((a,o)=>{if(o<65534&&a.subarray&&da)return String.fromCharCode.apply(null,a.length===o?a:a.subarray(0,o));let d="";for(let c=0;c<o;c++)d+=String.fromCharCode(a[c]);return d})(s,i)},em=(r,e)=>{(e=e||r.length)>r.length&&(e=r.length);let t=e-1;for(;t>=0&&(192&r[t])==128;)t--;return t<0||t===0?e:t+wr[r[t]]>e?t:e},la=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const ha=Object.prototype.toString,{Z_NO_FLUSH:tm,Z_SYNC_FLUSH:rm,Z_FULL_FLUSH:nm,Z_FINISH:im,Z_OK:fn,Z_STREAM_END:sm,Z_DEFAULT_COMPRESSION:om,Z_DEFAULT_STRATEGY:am,Z_DEFLATED:cm}=wt;function Tr(r){this.options=ca({level:om,method:cm,chunkSize:16384,windowBits:15,memLevel:8,strategy:am},r||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new la,this.strm.avail_out=0;let t=Cr.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(t!==fn)throw new Error(Ct[t]);if(e.header&&Cr.deflateSetHeader(this.strm,e.header),e.dictionary){let n;if(n=typeof e.dictionary=="string"?Di(e.dictionary):ha.call(e.dictionary)==="[object ArrayBuffer]"?new Uint8Array(e.dictionary):e.dictionary,t=Cr.deflateSetDictionary(this.strm,n),t!==fn)throw new Error(Ct[t]);this._dict_set=!0}}function xi(r,e){const t=new Tr(e);if(t.push(r,!0),t.err)throw t.msg||Ct[t.err];return t.result}Tr.prototype.push=function(r,e){const t=this.strm,n=this.options.chunkSize;let i,s;if(this.ended)return!1;for(s=e===~~e?e:e===!0?im:tm,typeof r=="string"?t.input=Di(r):ha.call(r)==="[object ArrayBuffer]"?t.input=new Uint8Array(r):t.input=r,t.next_in=0,t.avail_in=t.input.length;;)if(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),(s===rm||s===nm)&&t.avail_out<=6)this.onData(t.output.subarray(0,t.next_out)),t.avail_out=0;else{if(i=Cr.deflate(t,s),i===sm)return t.next_out>0&&this.onData(t.output.subarray(0,t.next_out)),i=Cr.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===fn;if(t.avail_out!==0){if(s>0&&t.next_out>0)this.onData(t.output.subarray(0,t.next_out)),t.avail_out=0;else if(t.avail_in===0)break}else this.onData(t.output)}return!0},Tr.prototype.onData=function(r){this.chunks.push(r)},Tr.prototype.onEnd=function(r){r===fn&&(this.result=ua(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var um={Deflate:Tr,deflate:xi,deflateRaw:function(r,e){return(e=e||{}).raw=!0,xi(r,e)},gzip:function(r,e){return(e=e||{}).gzip=!0,xi(r,e)},constants:wt},dm=function(r,e){let t,n,i,s,a,o,d,c,u,h,l,f,y,C,v,E,k,g,D,L,R,M,N,U;const B=r.state;t=r.next_in,N=r.input,n=t+(r.avail_in-5),i=r.next_out,U=r.output,s=i-(e-r.avail_out),a=i+(r.avail_out-257),o=B.dmax,d=B.wsize,c=B.whave,u=B.wnext,h=B.window,l=B.hold,f=B.bits,y=B.lencode,C=B.distcode,v=(1<<B.lenbits)-1,E=(1<<B.distbits)-1;e:do{f<15&&(l+=N[t++]<<f,f+=8,l+=N[t++]<<f,f+=8),k=y[l&v];t:for(;;){if(g=k>>>24,l>>>=g,f-=g,g=k>>>16&255,g===0)U[i++]=65535&k;else{if(!(16&g)){if(!(64&g)){k=y[(65535&k)+(l&(1<<g)-1)];continue t}if(32&g){B.mode=16191;break e}r.msg="invalid literal/length code",B.mode=16209;break e}D=65535&k,g&=15,g&&(f<g&&(l+=N[t++]<<f,f+=8),D+=l&(1<<g)-1,l>>>=g,f-=g),f<15&&(l+=N[t++]<<f,f+=8,l+=N[t++]<<f,f+=8),k=C[l&E];r:for(;;){if(g=k>>>24,l>>>=g,f-=g,g=k>>>16&255,!(16&g)){if(!(64&g)){k=C[(65535&k)+(l&(1<<g)-1)];continue r}r.msg="invalid distance code",B.mode=16209;break e}if(L=65535&k,g&=15,f<g&&(l+=N[t++]<<f,f+=8,f<g&&(l+=N[t++]<<f,f+=8)),L+=l&(1<<g)-1,L>o){r.msg="invalid distance too far back",B.mode=16209;break e}if(l>>>=g,f-=g,g=i-s,L>g){if(g=L-g,g>c&&B.sane){r.msg="invalid distance too far back",B.mode=16209;break e}if(R=0,M=h,u===0){if(R+=d-g,g<D){D-=g;do U[i++]=h[R++];while(--g);R=i-L,M=U}}else if(u<g){if(R+=d+u-g,g-=u,g<D){D-=g;do U[i++]=h[R++];while(--g);if(R=0,u<D){g=u,D-=g;do U[i++]=h[R++];while(--g);R=i-L,M=U}}}else if(R+=u-g,g<D){D-=g;do U[i++]=h[R++];while(--g);R=i-L,M=U}for(;D>2;)U[i++]=M[R++],U[i++]=M[R++],U[i++]=M[R++],D-=3;D&&(U[i++]=M[R++],D>1&&(U[i++]=M[R++]))}else{R=i-L;do U[i++]=U[R++],U[i++]=U[R++],U[i++]=U[R++],D-=3;while(D>2);D&&(U[i++]=U[R++],D>1&&(U[i++]=U[R++]))}break}}break}}while(t<n&&i<a);D=f>>3,t-=D,f-=D<<3,l&=(1<<f)-1,r.next_in=t,r.next_out=i,r.avail_in=t<n?n-t+5:5-(t-n),r.avail_out=i<a?a-i+257:257-(i-a),B.hold=l,B.bits=f};const lm=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),hm=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),pm=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),fm=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var kr=(r,e,t,n,i,s,a,o)=>{const d=o.bits;let c,u,h,l,f,y,C=0,v=0,E=0,k=0,g=0,D=0,L=0,R=0,M=0,N=0,U=null;const B=new Uint16Array(16),H=new Uint16Array(16);let Y,W,de,ce=null;for(C=0;C<=15;C++)B[C]=0;for(v=0;v<n;v++)B[e[t+v]]++;for(g=d,k=15;k>=1&&B[k]===0;k--);if(g>k&&(g=k),k===0)return i[s++]=20971520,i[s++]=20971520,o.bits=1,0;for(E=1;E<k&&B[E]===0;E++);for(g<E&&(g=E),R=1,C=1;C<=15;C++)if(R<<=1,R-=B[C],R<0)return-1;if(R>0&&(r===0||k!==1))return-1;for(H[1]=0,C=1;C<15;C++)H[C+1]=H[C]+B[C];for(v=0;v<n;v++)e[t+v]!==0&&(a[H[e[t+v]]++]=v);if(r===0?(U=ce=a,y=20):r===1?(U=lm,ce=hm,y=257):(U=pm,ce=fm,y=0),N=0,v=0,C=E,f=s,D=g,L=0,h=-1,M=1<<g,l=M-1,r===1&&M>852||r===2&&M>592)return 1;for(;;){Y=C-L,a[v]+1<y?(W=0,de=a[v]):a[v]>=y?(W=ce[a[v]-y],de=U[a[v]-y]):(W=96,de=0),c=1<<C-L,u=1<<D,E=u;do u-=c,i[f+(N>>L)+u]=Y<<24|W<<16|de|0;while(u!==0);for(c=1<<C-1;N&c;)c>>=1;if(c!==0?(N&=c-1,N+=c):N=0,v++,--B[C]==0){if(C===k)break;C=e[t+a[v]]}if(C>g&&(N&l)!==h){for(L===0&&(L=g),f+=E,D=C-L,R=1<<D;D+L<k&&(R-=B[D+L],!(R<=0));)D++,R<<=1;if(M+=1<<D,r===1&&M>852||r===2&&M>592)return 1;h=N&l,i[h]=g<<24|D<<16|f-s|0}}return N!==0&&(i[f+N]=C-L<<24|64<<16|0),o.bits=g,0};const{Z_FINISH:pa,Z_BLOCK:mm,Z_TREES:mn,Z_OK:kt,Z_STREAM_END:_m,Z_NEED_DICT:gm,Z_STREAM_ERROR:ze,Z_DATA_ERROR:fa,Z_MEM_ERROR:ma,Z_BUF_ERROR:vm,Z_DEFLATED:_a}=wt,ga=r=>(r>>>24&255)+(r>>>8&65280)+((65280&r)<<8)+((255&r)<<24);function ym(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const Rt=r=>{if(!r)return 1;const e=r.state;return!e||e.strm!==r||e.mode<16180||e.mode>16211?1:0},va=r=>{if(Rt(r))return ze;const e=r.state;return r.total_in=r.total_out=e.total=0,r.msg="",e.wrap&&(r.adler=1&e.wrap),e.mode=16180,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,kt},ya=r=>{if(Rt(r))return ze;const e=r.state;return e.wsize=0,e.whave=0,e.wnext=0,va(r)},Sa=(r,e)=>{let t;if(Rt(r))return ze;const n=r.state;return e<0?(t=0,e=-e):(t=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?ze:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=t,n.wbits=e,ya(r))},ba=(r,e)=>{if(!r)return ze;const t=new ym;r.state=t,t.strm=r,t.window=null,t.mode=16180;const n=Sa(r,e);return n!==kt&&(r.state=null),n};let Ii,zi,Ea=!0;const Sm=r=>{if(Ea){Ii=new Int32Array(512),zi=new Int32Array(32);let e=0;for(;e<144;)r.lens[e++]=8;for(;e<256;)r.lens[e++]=9;for(;e<280;)r.lens[e++]=7;for(;e<288;)r.lens[e++]=8;for(kr(1,r.lens,0,288,Ii,0,r.work,{bits:9}),e=0;e<32;)r.lens[e++]=5;kr(2,r.lens,0,32,zi,0,r.work,{bits:5}),Ea=!1}r.lencode=Ii,r.lenbits=9,r.distcode=zi,r.distbits=5},Ca=(r,e,t,n)=>{let i;const s=r.state;return s.window===null&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),n>=s.wsize?(s.window.set(e.subarray(t-s.wsize,t),0),s.wnext=0,s.whave=s.wsize):(i=s.wsize-s.wnext,i>n&&(i=n),s.window.set(e.subarray(t-n,t-n+i),s.wnext),(n-=i)?(s.window.set(e.subarray(t-n,t),0),s.wnext=n,s.whave=s.wsize):(s.wnext+=i,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=i))),0};var rt={inflateReset:ya,inflateReset2:Sa,inflateResetKeep:va,inflateInit:r=>ba(r,15),inflateInit2:ba,inflate:(r,e)=>{let t,n,i,s,a,o,d,c,u,h,l,f,y,C,v,E,k,g,D,L,R,M,N=0;const U=new Uint8Array(4);let B,H;const Y=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(Rt(r)||!r.output||!r.input&&r.avail_in!==0)return ze;t=r.state,t.mode===16191&&(t.mode=16192),a=r.next_out,i=r.output,d=r.avail_out,s=r.next_in,n=r.input,o=r.avail_in,c=t.hold,u=t.bits,h=o,l=d,M=kt;e:for(;;)switch(t.mode){case 16180:if(t.wrap===0){t.mode=16192;break}for(;u<16;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(2&t.wrap&&c===35615){t.wbits===0&&(t.wbits=15),t.check=0,U[0]=255&c,U[1]=c>>>8&255,t.check=le(t.check,U,2,0),c=0,u=0,t.mode=16181;break}if(t.head&&(t.head.done=!1),!(1&t.wrap)||(((255&c)<<8)+(c>>8))%31){r.msg="incorrect header check",t.mode=16209;break}if((15&c)!==_a){r.msg="unknown compression method",t.mode=16209;break}if(c>>>=4,u-=4,R=8+(15&c),t.wbits===0&&(t.wbits=R),R>15||R>t.wbits){r.msg="invalid window size",t.mode=16209;break}t.dmax=1<<t.wbits,t.flags=0,r.adler=t.check=1,t.mode=512&c?16189:16191,c=0,u=0;break;case 16181:for(;u<16;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(t.flags=c,(255&t.flags)!==_a){r.msg="unknown compression method",t.mode=16209;break}if(57344&t.flags){r.msg="unknown header flags set",t.mode=16209;break}t.head&&(t.head.text=c>>8&1),512&t.flags&&4&t.wrap&&(U[0]=255&c,U[1]=c>>>8&255,t.check=le(t.check,U,2,0)),c=0,u=0,t.mode=16182;case 16182:for(;u<32;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}t.head&&(t.head.time=c),512&t.flags&&4&t.wrap&&(U[0]=255&c,U[1]=c>>>8&255,U[2]=c>>>16&255,U[3]=c>>>24&255,t.check=le(t.check,U,4,0)),c=0,u=0,t.mode=16183;case 16183:for(;u<16;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}t.head&&(t.head.xflags=255&c,t.head.os=c>>8),512&t.flags&&4&t.wrap&&(U[0]=255&c,U[1]=c>>>8&255,t.check=le(t.check,U,2,0)),c=0,u=0,t.mode=16184;case 16184:if(1024&t.flags){for(;u<16;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}t.length=c,t.head&&(t.head.extra_len=c),512&t.flags&&4&t.wrap&&(U[0]=255&c,U[1]=c>>>8&255,t.check=le(t.check,U,2,0)),c=0,u=0}else t.head&&(t.head.extra=null);t.mode=16185;case 16185:if(1024&t.flags&&(f=t.length,f>o&&(f=o),f&&(t.head&&(R=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Uint8Array(t.head.extra_len)),t.head.extra.set(n.subarray(s,s+f),R)),512&t.flags&&4&t.wrap&&(t.check=le(t.check,n,f,s)),o-=f,s+=f,t.length-=f),t.length))break e;t.length=0,t.mode=16186;case 16186:if(2048&t.flags){if(o===0)break e;f=0;do R=n[s+f++],t.head&&R&&t.length<65536&&(t.head.name+=String.fromCharCode(R));while(R&&f<o);if(512&t.flags&&4&t.wrap&&(t.check=le(t.check,n,f,s)),o-=f,s+=f,R)break e}else t.head&&(t.head.name=null);t.length=0,t.mode=16187;case 16187:if(4096&t.flags){if(o===0)break e;f=0;do R=n[s+f++],t.head&&R&&t.length<65536&&(t.head.comment+=String.fromCharCode(R));while(R&&f<o);if(512&t.flags&&4&t.wrap&&(t.check=le(t.check,n,f,s)),o-=f,s+=f,R)break e}else t.head&&(t.head.comment=null);t.mode=16188;case 16188:if(512&t.flags){for(;u<16;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(4&t.wrap&&c!==(65535&t.check)){r.msg="header crc mismatch",t.mode=16209;break}c=0,u=0}t.head&&(t.head.hcrc=t.flags>>9&1,t.head.done=!0),r.adler=t.check=0,t.mode=16191;break;case 16189:for(;u<32;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}r.adler=t.check=ga(c),c=0,u=0,t.mode=16190;case 16190:if(t.havedict===0)return r.next_out=a,r.avail_out=d,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,gm;r.adler=t.check=1,t.mode=16191;case 16191:if(e===mm||e===mn)break e;case 16192:if(t.last){c>>>=7&u,u-=7&u,t.mode=16206;break}for(;u<3;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}switch(t.last=1&c,c>>>=1,u-=1,3&c){case 0:t.mode=16193;break;case 1:if(Sm(t),t.mode=16199,e===mn){c>>>=2,u-=2;break e}break;case 2:t.mode=16196;break;case 3:r.msg="invalid block type",t.mode=16209}c>>>=2,u-=2;break;case 16193:for(c>>>=7&u,u-=7&u;u<32;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if((65535&c)!=(c>>>16^65535)){r.msg="invalid stored block lengths",t.mode=16209;break}if(t.length=65535&c,c=0,u=0,t.mode=16194,e===mn)break e;case 16194:t.mode=16195;case 16195:if(f=t.length,f){if(f>o&&(f=o),f>d&&(f=d),f===0)break e;i.set(n.subarray(s,s+f),a),o-=f,s+=f,d-=f,a+=f,t.length-=f;break}t.mode=16191;break;case 16196:for(;u<14;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(t.nlen=257+(31&c),c>>>=5,u-=5,t.ndist=1+(31&c),c>>>=5,u-=5,t.ncode=4+(15&c),c>>>=4,u-=4,t.nlen>286||t.ndist>30){r.msg="too many length or distance symbols",t.mode=16209;break}t.have=0,t.mode=16197;case 16197:for(;t.have<t.ncode;){for(;u<3;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}t.lens[Y[t.have++]]=7&c,c>>>=3,u-=3}for(;t.have<19;)t.lens[Y[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,B={bits:t.lenbits},M=kr(0,t.lens,0,19,t.lencode,0,t.work,B),t.lenbits=B.bits,M){r.msg="invalid code lengths set",t.mode=16209;break}t.have=0,t.mode=16198;case 16198:for(;t.have<t.nlen+t.ndist;){for(;N=t.lencode[c&(1<<t.lenbits)-1],v=N>>>24,E=N>>>16&255,k=65535&N,!(v<=u);){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(k<16)c>>>=v,u-=v,t.lens[t.have++]=k;else{if(k===16){for(H=v+2;u<H;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(c>>>=v,u-=v,t.have===0){r.msg="invalid bit length repeat",t.mode=16209;break}R=t.lens[t.have-1],f=3+(3&c),c>>>=2,u-=2}else if(k===17){for(H=v+3;u<H;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}c>>>=v,u-=v,R=0,f=3+(7&c),c>>>=3,u-=3}else{for(H=v+7;u<H;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}c>>>=v,u-=v,R=0,f=11+(127&c),c>>>=7,u-=7}if(t.have+f>t.nlen+t.ndist){r.msg="invalid bit length repeat",t.mode=16209;break}for(;f--;)t.lens[t.have++]=R}}if(t.mode===16209)break;if(t.lens[256]===0){r.msg="invalid code -- missing end-of-block",t.mode=16209;break}if(t.lenbits=9,B={bits:t.lenbits},M=kr(1,t.lens,0,t.nlen,t.lencode,0,t.work,B),t.lenbits=B.bits,M){r.msg="invalid literal/lengths set",t.mode=16209;break}if(t.distbits=6,t.distcode=t.distdyn,B={bits:t.distbits},M=kr(2,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,B),t.distbits=B.bits,M){r.msg="invalid distances set",t.mode=16209;break}if(t.mode=16199,e===mn)break e;case 16199:t.mode=16200;case 16200:if(o>=6&&d>=258){r.next_out=a,r.avail_out=d,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,dm(r,l),a=r.next_out,i=r.output,d=r.avail_out,s=r.next_in,n=r.input,o=r.avail_in,c=t.hold,u=t.bits,t.mode===16191&&(t.back=-1);break}for(t.back=0;N=t.lencode[c&(1<<t.lenbits)-1],v=N>>>24,E=N>>>16&255,k=65535&N,!(v<=u);){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(E&&!(240&E)){for(g=v,D=E,L=k;N=t.lencode[L+((c&(1<<g+D)-1)>>g)],v=N>>>24,E=N>>>16&255,k=65535&N,!(g+v<=u);){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}c>>>=g,u-=g,t.back+=g}if(c>>>=v,u-=v,t.back+=v,t.length=k,E===0){t.mode=16205;break}if(32&E){t.back=-1,t.mode=16191;break}if(64&E){r.msg="invalid literal/length code",t.mode=16209;break}t.extra=15&E,t.mode=16201;case 16201:if(t.extra){for(H=t.extra;u<H;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}t.length+=c&(1<<t.extra)-1,c>>>=t.extra,u-=t.extra,t.back+=t.extra}t.was=t.length,t.mode=16202;case 16202:for(;N=t.distcode[c&(1<<t.distbits)-1],v=N>>>24,E=N>>>16&255,k=65535&N,!(v<=u);){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(!(240&E)){for(g=v,D=E,L=k;N=t.distcode[L+((c&(1<<g+D)-1)>>g)],v=N>>>24,E=N>>>16&255,k=65535&N,!(g+v<=u);){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}c>>>=g,u-=g,t.back+=g}if(c>>>=v,u-=v,t.back+=v,64&E){r.msg="invalid distance code",t.mode=16209;break}t.offset=k,t.extra=15&E,t.mode=16203;case 16203:if(t.extra){for(H=t.extra;u<H;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}t.offset+=c&(1<<t.extra)-1,c>>>=t.extra,u-=t.extra,t.back+=t.extra}if(t.offset>t.dmax){r.msg="invalid distance too far back",t.mode=16209;break}t.mode=16204;case 16204:if(d===0)break e;if(f=l-d,t.offset>f){if(f=t.offset-f,f>t.whave&&t.sane){r.msg="invalid distance too far back",t.mode=16209;break}f>t.wnext?(f-=t.wnext,y=t.wsize-f):y=t.wnext-f,f>t.length&&(f=t.length),C=t.window}else C=i,y=a-t.offset,f=t.length;f>d&&(f=d),d-=f,t.length-=f;do i[a++]=C[y++];while(--f);t.length===0&&(t.mode=16200);break;case 16205:if(d===0)break e;i[a++]=t.length,d--,t.mode=16200;break;case 16206:if(t.wrap){for(;u<32;){if(o===0)break e;o--,c|=n[s++]<<u,u+=8}if(l-=d,r.total_out+=l,t.total+=l,4&t.wrap&&l&&(r.adler=t.check=t.flags?le(t.check,i,l,a-l):yr(t.check,i,l,a-l)),l=d,4&t.wrap&&(t.flags?c:ga(c))!==t.check){r.msg="incorrect data check",t.mode=16209;break}c=0,u=0}t.mode=16207;case 16207:if(t.wrap&&t.flags){for(;u<32;){if(o===0)break e;o--,c+=n[s++]<<u,u+=8}if(4&t.wrap&&c!==(4294967295&t.total)){r.msg="incorrect length check",t.mode=16209;break}c=0,u=0}t.mode=16208;case 16208:M=_m;break e;case 16209:M=fa;break e;case 16210:return ma;case 16211:default:return ze}return r.next_out=a,r.avail_out=d,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,(t.wsize||l!==r.avail_out&&t.mode<16209&&(t.mode<16206||e!==pa))&&Ca(r,r.output,r.next_out,l-r.avail_out),h-=r.avail_in,l-=r.avail_out,r.total_in+=h,r.total_out+=l,t.total+=l,4&t.wrap&&l&&(r.adler=t.check=t.flags?le(t.check,i,l,r.next_out-l):yr(t.check,i,l,r.next_out-l)),r.data_type=t.bits+(t.last?64:0)+(t.mode===16191?128:0)+(t.mode===16199||t.mode===16194?256:0),(h===0&&l===0||e===pa)&&M===kt&&(M=vm),M},inflateEnd:r=>{if(Rt(r))return ze;let e=r.state;return e.window&&(e.window=null),r.state=null,kt},inflateGetHeader:(r,e)=>{if(Rt(r))return ze;const t=r.state;return 2&t.wrap?(t.head=e,e.done=!1,kt):ze},inflateSetDictionary:(r,e)=>{const t=e.length;let n,i,s;return Rt(r)?ze:(n=r.state,n.wrap!==0&&n.mode!==16190?ze:n.mode===16190&&(i=1,i=yr(i,e,t,0),i!==n.check)?fa:(s=Ca(r,e,t,t),s?(n.mode=16210,ma):(n.havedict=1,kt)))},inflateInfo:"pako inflate (from Nodeca project)"},bm=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const wa=Object.prototype.toString,{Z_NO_FLUSH:Em,Z_FINISH:Cm,Z_OK:Rr,Z_STREAM_END:Pi,Z_NEED_DICT:Oi,Z_STREAM_ERROR:wm,Z_DATA_ERROR:Ta,Z_MEM_ERROR:Tm}=wt;function Ar(r){this.options=ca({chunkSize:65536,windowBits:15,to:""},r||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||r&&r.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&!(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new la,this.strm.avail_out=0;let t=rt.inflateInit2(this.strm,e.windowBits);if(t!==Rr)throw new Error(Ct[t]);if(this.header=new bm,rt.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=Di(e.dictionary):wa.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=rt.inflateSetDictionary(this.strm,e.dictionary),t!==Rr)))throw new Error(Ct[t])}function Mi(r,e){const t=new Ar(e);if(t.push(r),t.err)throw t.msg||Ct[t.err];return t.result}Ar.prototype.push=function(r,e){const t=this.strm,n=this.options.chunkSize,i=this.options.dictionary;let s,a,o;if(this.ended)return!1;for(a=e===~~e?e:e===!0?Cm:Em,wa.call(r)==="[object ArrayBuffer]"?t.input=new Uint8Array(r):t.input=r,t.next_in=0,t.avail_in=t.input.length;;){for(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),s=rt.inflate(t,a),s===Oi&&i&&(s=rt.inflateSetDictionary(t,i),s===Rr?s=rt.inflate(t,a):s===Ta&&(s=Oi));t.avail_in>0&&s===Pi&&t.state.wrap>0&&r[t.next_in]!==0;)rt.inflateReset(t),s=rt.inflate(t,a);switch(s){case wm:case Ta:case Oi:case Tm:return this.onEnd(s),this.ended=!0,!1}if(o=t.avail_out,t.next_out&&(t.avail_out===0||s===Pi))if(this.options.to==="string"){let d=em(t.output,t.next_out),c=t.next_out-d,u=Qf(t.output,d);t.next_out=c,t.avail_out=n-c,c&&t.output.set(t.output.subarray(d,d+c),0),this.onData(u)}else this.onData(t.output.length===t.next_out?t.output:t.output.subarray(0,t.next_out));if(s!==Rr||o!==0){if(s===Pi)return s=rt.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(t.avail_in===0)break}}return!0},Ar.prototype.onData=function(r){this.chunks.push(r)},Ar.prototype.onEnd=function(r){r===Rr&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=ua(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var km={Inflate:Ar,inflate:Mi,inflateRaw:function(r,e){return(e=e||{}).raw=!0,Mi(r,e)},ungzip:Mi,constants:wt};const{Deflate:Rm,deflate:Am,deflateRaw:Dm,gzip:xm}=um,{Inflate:Im,inflate:zm,inflateRaw:Pm,ungzip:Om}=km;var Mm={Deflate:Rm,deflate:Am,deflateRaw:Dm,gzip:xm,Inflate:Im,inflate:zm,inflateRaw:Pm,ungzip:Om,constants:wt},Lm=function(){function r(e,t){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_ON:500,RESPONSE:5001,TIMEOUT:5005},this.customHeader=t.custom_request_header||{}}return r.prototype.useFetch=function(e){var t=e.url,n=e.data,i=e.method,s=e.success,a=e.fail,o={"Content-Type":"application/json; charset=utf-8"};if(Object.keys(this.customHeader).length)for(var d in this.customHeader)o[d]=this.customHeader[d];window.fetch?fetch(t,{method:i||"POST",headers:o,body:JSON.stringify(n)}).then(function(c){return c.json()}).then(function(c){s&&s(c)}).catch(function(c){a&&a(n,c)}):(this.requestType="xhr",console.log("your brwoser not support fetch, use xhr"),this.useRequest({url:t,data:n,method:i,success:s,fail:a}))},r.prototype.useBeacon=function(e){var t=e.url,n=e.data,i=e.success,s=e.fail;this.requestType!=="xhr"?window.navigator.sendBeacon(t,JSON.stringify(n))?i&&i():s&&s(n,this.errorCode.BEACON_FALSE):this.useXhr(e)},r.prototype.useXhr=function(e){var t=this,n=e.url,i=e.data,s=e.method,a=e.success,o=e.fail,d=e.timeout,c=e.withCredentials,u=e.app_key,h=e.zip;try{var l=new XMLHttpRequest,f=s||"POST";if(l.open(f,""+n,!0),l.setRequestHeader("Content-Type","application/json; charset=utf-8"),u&&l.setRequestHeader("X-MCS-AppKey",""+u),Object.keys(this.customHeader).length)for(var y in this.customHeader)l.setRequestHeader(y,this.customHeader[y]);c&&(l.withCredentials=!0),d&&(l.timeout=d,l.ontimeout=function(){o&&o(i,t.errorCode.TIMEOUT)}),l.onload=function(){if(a){var g=null;if(l.responseText){try{g=JSON.parse(l.responseText)}catch{g={}}a(g,i)}}},l.onerror=function(){l.abort(),o&&o(i,t.errorCode.XHR_ON)};try{var C=JSON.stringify(i),v=this.collector.configManager.getCurrentEnv();if(this.config.need_zip&&h)if(v==="row"){var E=new TextEncoder().encode(C),k=Mm.gzip(E);l.setRequestHeader("Content-Encoding","gzip"),l.send(k)}else l.send(C),this.collector.logger.warn("your channel do not support gzip, use normal data!");else l.send(C)}catch(g){l.send(JSON.stringify(i)),this.collector.emit("sdk-inner-error",{type:"sdk_error_send",eventData:i,errorCode:1e3,msg:g.message||g.stack||"sdk_error_send"})}}catch(g){this.collector.emit("sdk-inner-error",{type:"sdk_error_request",eventData:i,errorCode:1001,msg:g.message||g.stack||"sdk_error_request"})}},r.prototype.useRequest=function(e){var t=e.useBeacon,n=e.forceXhr;if(this.requestType==="xhr")this.useXhr(e);else{if(t&&this.supportBeacon)return void this.useBeacon(e);if(this.requestType==="fetch"&&!n)return void this.useFetch(e);this.useXhr(e)}},r}(),Nm=function(){function r(e,t){if(this.devToolReady=!1,this.sendAlready=!1,t.enable_debug&&e.configManager.get("browser")!=="Microsoft Internet Explorer"){this.collect=e,this.config=t,this.app_id=t.app_id;var n=e.adapters.storage;this.cacheStorgae=new n(!1),this.devToolOrigin=window.location.origin,this.currentInstance=t.current_instance||"",this.loadUrl=t.devtool_url||"https://sf16-website-login.neutral.ttwstatic.com/obj/tiktok_web_login_static/log-sdk/collect/devtool/debug-web.v2.0.0.js",this.filterEvent=new Set(["__bav_page","__bav_beat","__bav_page_statistics","__bav_click","__bav_page_exposure","bav2b_page","bav2b_beat","bav2b_page_statistics","bav2b_click","bav2b_page_exposure","_be_active","predefine_pageview","__profile_set","__profile_set_once","__profile_increment","__profile_unset","__profile_append","predefine_page_alive","predefine_page_close","abtest_exposure"]),this.load()}}return r.prototype.loadScript=function(e){try{var t=document.createElement("script");t.src=e,t.onerror=function(){console.log("load DevTool render fail")},t.onload=function(){console.log("load DevTool render success")},document.getElementsByTagName("body")[0].appendChild(t)}catch(n){console.log("devTool load fail, "+n.message)}},r.prototype.parseUrl=function(){var e={};try{var t=window.location.href.split("?")[1].split("&");t.length&&t.forEach(function(n){var i=n.split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])})}catch{}return e},r.prototype.load=function(){try{var e=this.parseUrl();if(e.open_devtool_web&&e.app_id){if(parseInt(e.app_id)!==this.app_id||e.current_instance&&e.current_instance!==this.currentInstance)return}else if(!this.getStorage())return;this.loadBaseInfo(),this.loadHook(),this.setStorage(),this.addLintener(),this.loadDebuggerModule(),this.loadDevTool()}catch(t){console.log("debug fail, "+t.message)}},r.prototype.getStorage=function(){var e=this.cacheStorgae.getItem("__applog_open_devtool_web");return e&&parseInt(e)===this.app_id},r.prototype.setStorage=function(){this.cacheStorgae.setItem("__applog_open_devtool_web",this.app_id)},r.prototype.loadDevTool=function(){this.loadScript(this.loadUrl)},r.prototype.loadBaseInfo=function(){if(this.log=[],this.event=[],this.info=[{title:"BaseInfo",key:"base",type:1,content:[{name:"app_id",desc:"APPID",value:this.config.app_id},{name:"channel",desc:"CHANNEL",value:this.config.channel},{name:"domain",desc:"Domain",value:this.collect.configManager.getDomain()},{name:"sdk_version",desc:"SDK Version",value:pr},{name:"sdk_type",desc:"SDK Import Type",value:"npm"}]},{title:"UserInfo",key:"user",type:2,content:[{name:"uuid",desc:"UserUniqueId",value:this.collect.configManager.get("user").user_unique_id||""},{name:"web_id",desc:"WEB_ID",value:this.collect.configManager.get("user").web_id||""}]},{title:"CommonInfo",type:2,key:"common",content:[{name:"browser",desc:"Browser",value:this.collect.configManager.get("browser")},{name:"browser_version",desc:"Browser Version",value:this.collect.configManager.get("browser_version")},{name:"platform",desc:"Platform",value:this.collect.configManager.get("platform")},{name:"device_model",desc:"Devide Model",value:this.collect.configManager.get("device_model")},{name:"os_name",desc:"Os Name",value:this.collect.configManager.get("os_name")},{name:"os_version",desc:"Os Version",value:this.collect.configManager.get("os_version")},{name:"resolution",desc:"Screen Resolution",value:this.collect.configManager.get("resolution")},{name:"referrer",desc:"Referrer",value:this.collect.configManager.get("referrer")},{name:"custom",desc:"Custom Info",value:JSON.stringify(this.collect.configManager.get("custom"))}]},{title:"Config Info",key:"config",type:3,content:[{name:"autotrack",desc:"AutoTrackEvent",value:!!this.config.autotrack},{name:"stay",desc:"StayDuration",value:!!this.config.enable_stay_duration}]},{title:"A/B Config Info",key:"ab",type:4,content:[{name:"ab",desc:"A/BTester",value:!!this.config.enable_ab_test}]}],this.config.enable_ab_test){var e=this.getInfo("ab"),t=[{name:"ab",desc:"A/BTester",value:!!this.config.enable_ab_test},{name:"vid",desc:"A/B VID",value:this.collect.configManager.getAbVersion()},{name:"ab_domain",desc:"Domain",value:this.config.ab_channel_domain||dr(vi[this.config.channel])},{name:"all_values",desc:"A/B ALL Values",value:this.collect.configManager.getAbCache()}];e.content=t,this.setInfo("ab",e)}},r.prototype.getInfo=function(e){var t=null;return this.info.forEach(function(n){n.key===e&&(t=n)}),t},r.prototype.setInfo=function(e,t){var n=!1;this.info.forEach(function(i){i.key===e&&(n=!0,i=t)}),n||this.info.push(t)},r.prototype.getSecondInfo=function(e,t){var n=this.getInfo(e),i=null;return n.content.forEach(function(s){s.name===t&&(i=s)}),i},r.prototype.setSecondInfo=function(e,t,n){var i=this.getInfo(e),s=!1;if(i.content.forEach(function(o){o.name===t&&(o.value=n,s=!0)}),!s){var a={name:t,value:n,desc:t.toLocaleUpperCase()};i.content.push(a)}this.setInfo(e,i)},r.prototype.loadHook=function(){var e=this;this.collect.on(T.DEBUGGER_MESSAGE,function(t){switch(t.type){case T.DEBUGGER_MESSAGE_SDK:var n={time:t.time,type:t.logType||"sdk",infoType:t.infoType||"sdk",level:t.level,name:t.info,show:!0,levelShow:!0,needDesc:!!t.data};if(t.data&&(n.desc={content:JSON.stringify(t.data)}),e.updateLog(n),t.secType&&t.secType==="AB")e.setSecondInfo("ab","vid",e.collect.configManager.getAbVersion()),e.setSecondInfo("ab","all_values",e.collect.configManager.getAbCache());else if(t.secType==="USER")e.setSecondInfo("user",t.common==="user_unique_id"?"uuid":t.common,e.collect.configManager.get(t.common));else if(t.secType==="HEADER"){var i=e.collect.configManager.get(t.common);e.setSecondInfo("common",t.common,t.common==="custom"?JSON.stringify(i):i)}return void e.updateInfo();case T.DEBUGGER_MESSAGE_EVENT:if(t.data&&t.data.length){var s=t.data[0],a=s.events;if(!a.length)return;a.forEach(function(o){o.checkShow=!0,o.searchShow=!0,o.focusShow=!0,o.status=t.status,o.type=e.filterEvent.has(o.event)?"sdk":"cus",o.verifyType=t.verifyType?"verify":"no",o.info="",t.status==="fail"&&(o.info={message:"code: "+t.code+", msg: "+(t.msg||t.failType)})}),e.updateEvent(s)}return}})},r.prototype.addLintener=function(){var e=this;window.addEventListener("message",function(t){if(e.devToolOrigin===t.origin){if(t&&t.data&&t.data.type==="devtool:web:ready"){if(e.devToolOrigin=t.origin,e.devToolReady=!0,e.sendAlready)return;e.sendData("devtool:web:init",{info:e.info,log:e.log,event:e.event,sdk_type:pr.includes("tob")?"tob":"inner",appId:e.app_id}),e.sendAlready=!0}t&&t.data&&t.data.type==="devtool:web:ssid"&&e.collect.getToken(function(n){e.setSecondInfo("user","sid",n.tobid),e.updateInfo()})}})},r.prototype.sendData=function(e,t){try{var n={type:e,payload:t};window&&window.postMessage(n,this.devToolOrigin)}catch{}},r.prototype.updateInfo=function(){this.devToolReady&&this.sendData("devtool:web:info",this.info)},r.prototype.updateLog=function(e){this.devToolReady?this.sendData("devtool:web:log",e):this.log.push(e)},r.prototype.updateEvent=function(e){this.devToolReady?this.sendData("devtool:web:event",e):this.event.push(e)},r.prototype.loadDebuggerModule=function(){var e=`#debugger-applog-web {
|
|
56
|
+
`,Kl=URL.createObjectURL(new Blob([ql],{type:"application/javascript"}));class Wl{constructor(){this._audioCtx=null,this._volume=0}get volume(){return this._volume}async start(e,t){if(this._audioCtx)return;const n=new AudioContext;await n.audioWorklet.addModule(t||Kl);const i=new MediaStream;i.addTrack(e);const o=n.createMediaStreamSource(i),a=new AudioWorkletNode(n,"vumeter");a.port.onmessage=s=>{const d=s.data.volume||0;this._volume=Math.min(d*100/2,10)},o.connect(a).connect(n.destination),this._audioCtx=n}stop(){var e;(e=this._audioCtx)==null||e.close(),this._audioCtx=null}}class Kt{constructor(){this._userId=void 0,this._deviceId=void 0,this._volumeDetectScriptUrl=void 0}static get instance(){return this._instance||(this._instance=new Kt),this._instance}get userId(){return this._userId}set userId(e){this._userId=e}get deviceId(){return this._deviceId}set deviceId(e){this._deviceId=e}get volumeDetectScriptUrl(){return this._volumeDetectScriptUrl}set volumeDetectScriptUrl(e){this._volumeDetectScriptUrl=e}}class js extends xt{constructor(e){super(),this._width=0,this._height=0,this._mediaStream=null,this._nextStream=null,this._trackMap={},this.type=e.type,this.id=$l(),this._source=e.stream}get source(){return this._source}get videoTrack(){return this._trackMap.video}get audioTrack(){return this._trackMap.audio}get width(){return this._width}get height(){return this._height}get isVideoStream(){return[ae.Camera,ae.Screen,ae.VideoFile].includes(this.type)}get mediaStream(){if(this._mediaStream)return this._mediaStream;const e=new MediaStream;return this._trackMap.audio&&e.addTrack(this._trackMap.audio),this._trackMap.video&&e.addTrack(this._trackMap.video),this._mediaStream=e,e}async startVolumeDetect(){this.audioTrack&&(this._volumeDetector||(this._volumeDetector=new Wl),await this._volumeDetector.start(this.audioTrack,Kt.instance.volumeDetectScriptUrl))}stopVolumeDetect(){var e;(e=this._volumeDetector)==null||e.stop(),this._volumeDetector=null}get volume(){var e;return((e=this._volumeDetector)==null?void 0:e.volume)||0}}class ur extends js{constructor(){super(...arguments),this._frameRate=1}get isVideoStream(){return!0}get isAudioStream(){return!1}get frameRate(){return this._frameRate}bindTrackSizeChangeEvent(e){e.on(Pe.SIZE_CHANGE,({width:t,height:n})=>{this._width=t,this._height=n,this.emit(ms.SizeChange,{width:t,height:n})})}}class Tn extends js{get isVideoStream(){return!1}get isAudioStream(){return!0}}class Jl extends ur{constructor(e,t){super({type:ae.Camera,stream:e}),this._trackMap.video=e.track(),this._width=e.width(),this._height=e.height(),this._frameRate=(t==null?void 0:t.frameRate)??1,this.bindTrackSizeChangeEvent(e)}get source(){return this._source}get viewNode(){return this.source.node()}get mixerNode(){return null}bindTrackEnd(e){this.source.on(Pe.ENDED,e)}destroy(){this.source.destroy()}}var Hs=typeof global=="object"&&global&&global.Object===Object&&global,Xl=typeof self=="object"&&self&&self.Object===Object&&self,yt=Hs||Xl||Function("return this")(),Ot=yt.Symbol,$s=Object.prototype,Zl=$s.hasOwnProperty,Yl=$s.toString,Ir=Ot?Ot.toStringTag:void 0;function Ql(r){var e=Zl.call(r,Ir),t=r[Ir];try{r[Ir]=void 0;var n=!0}catch{}var i=Yl.call(r);return n&&(e?r[Ir]=t:delete r[Ir]),i}var eh=Object.prototype,th=eh.toString;function rh(r){return th.call(r)}var nh="[object Null]",ih="[object Undefined]",qs=Ot?Ot.toStringTag:void 0;function dr(r){return r==null?r===void 0?ih:nh:qs&&qs in Object(r)?Ql(r):rh(r)}function lr(r){return r!=null&&typeof r=="object"}var oh="[object Symbol]";function zn(r){return typeof r=="symbol"||lr(r)&&dr(r)==oh}function Ks(r,e){for(var t=-1,n=r==null?0:r.length,i=Array(n);++t<n;)i[t]=e(r[t],t,r);return i}var ze=Array.isArray,Ws=Ot?Ot.prototype:void 0,Js=Ws?Ws.toString:void 0;function Xs(r){if(typeof r=="string")return r;if(ze(r))return Ks(r,Xs)+"";if(zn(r))return Js?Js.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var sh=/\s/;function ah(r){for(var e=r.length;e--&&sh.test(r.charAt(e)););return e}var ch=/^\s+/;function uh(r){return r&&r.slice(0,ah(r)+1).replace(ch,"")}function xr(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var Zs=NaN,dh=/^[-+]0x[0-9a-f]+$/i,lh=/^0b[01]+$/i,hh=/^0o[0-7]+$/i,fh=parseInt;function ph(r){if(typeof r=="number")return r;if(zn(r))return Zs;if(xr(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=xr(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=uh(r);var t=lh.test(r);return t||hh.test(r)?fh(r.slice(2),t?2:8):dh.test(r)?Zs:+r}var mh=1/0,gh=17976931348623157e292;function _h(r){if(!r)return r===0?r:0;if(r=ph(r),r===mh||r===-1/0){var e=r<0?-1:1;return e*gh}return r===r?r:0}function vh(r){var e=_h(r),t=e%1;return e===e?t?e-t:e:0}function yh(r){return r}var Sh="[object AsyncFunction]",bh="[object Function]",Eh="[object GeneratorFunction]",wh="[object Proxy]";function Ys(r){if(!xr(r))return!1;var e=dr(r);return e==bh||e==Eh||e==Sh||e==wh}var bi=yt["__core-js_shared__"],Qs=function(){var r=/[^.]+$/.exec(bi&&bi.keys&&bi.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function Ch(r){return!!Qs&&Qs in r}var kh=Function.prototype,Th=kh.toString;function Wt(r){if(r!=null){try{return Th.call(r)}catch{}try{return r+""}catch{}}return""}var zh=/[\\^$.*+?()[\]{}|]/g,Rh=/^\[object .+?Constructor\]$/,Dh=Function.prototype,Ah=Object.prototype,Ih=Dh.toString,xh=Ah.hasOwnProperty,Mh=RegExp("^"+Ih.call(xh).replace(zh,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Oh(r){if(!xr(r)||Ch(r))return!1;var e=Ys(r)?Mh:Rh;return e.test(Wt(r))}function Ph(r,e){return r==null?void 0:r[e]}function hr(r,e){var t=Ph(r,e);return Oh(t)?t:void 0}var Ei=hr(yt,"WeakMap");function Lh(r,e,t,n){for(var i=r.length,o=t+-1;++o<i;)if(e(r[o],o,r))return o;return-1}var Uh=9007199254740991,Gh=/^(?:0|[1-9]\d*)$/;function ea(r,e){var t=typeof r;return e=e??Uh,!!e&&(t=="number"||t!="symbol"&&Gh.test(r))&&r>-1&&r%1==0&&r<e}function ta(r,e){return r===e||r!==r&&e!==e}var Nh=9007199254740991;function wi(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Nh}function Rn(r){return r!=null&&wi(r.length)&&!Ys(r)}var Bh=Object.prototype;function ra(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Bh;return r===t}function Fh(r,e){for(var t=-1,n=Array(r);++t<r;)n[t]=e(t);return n}var Vh="[object Arguments]";function na(r){return lr(r)&&dr(r)==Vh}var ia=Object.prototype,jh=ia.hasOwnProperty,Hh=ia.propertyIsEnumerable,Ci=na(function(){return arguments}())?na:function(r){return lr(r)&&jh.call(r,"callee")&&!Hh.call(r,"callee")};function $h(){return!1}var oa=typeof exports=="object"&&exports&&!exports.nodeType&&exports,sa=oa&&typeof module=="object"&&module&&!module.nodeType&&module,qh=sa&&sa.exports===oa,aa=qh?yt.Buffer:void 0,Kh=aa?aa.isBuffer:void 0,Dn=Kh||$h,Wh="[object Arguments]",Jh="[object Array]",Xh="[object Boolean]",Zh="[object Date]",Yh="[object Error]",Qh="[object Function]",ef="[object Map]",tf="[object Number]",rf="[object Object]",nf="[object RegExp]",of="[object Set]",sf="[object String]",af="[object WeakMap]",cf="[object ArrayBuffer]",uf="[object DataView]",df="[object Float32Array]",lf="[object Float64Array]",hf="[object Int8Array]",ff="[object Int16Array]",pf="[object Int32Array]",mf="[object Uint8Array]",gf="[object Uint8ClampedArray]",_f="[object Uint16Array]",vf="[object Uint32Array]",pe={};pe[df]=pe[lf]=pe[hf]=pe[ff]=pe[pf]=pe[mf]=pe[gf]=pe[_f]=pe[vf]=!0,pe[Wh]=pe[Jh]=pe[cf]=pe[Xh]=pe[uf]=pe[Zh]=pe[Yh]=pe[Qh]=pe[ef]=pe[tf]=pe[rf]=pe[nf]=pe[of]=pe[sf]=pe[af]=!1;function yf(r){return lr(r)&&wi(r.length)&&!!pe[dr(r)]}function Sf(r){return function(e){return r(e)}}var ca=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Mr=ca&&typeof module=="object"&&module&&!module.nodeType&&module,bf=Mr&&Mr.exports===ca,ki=bf&&Hs.process,ua=function(){try{var r=Mr&&Mr.require&&Mr.require("util").types;return r||ki&&ki.binding&&ki.binding("util")}catch{}}(),da=ua&&ua.isTypedArray,Ti=da?Sf(da):yf,Ef=Object.prototype,wf=Ef.hasOwnProperty;function Cf(r,e){var t=ze(r),n=!t&&Ci(r),i=!t&&!n&&Dn(r),o=!t&&!n&&!i&&Ti(r),a=t||n||i||o,s=a?Fh(r.length,String):[],d=s.length;for(var c in r)wf.call(r,c)&&!(a&&(c=="length"||i&&(c=="offset"||c=="parent")||o&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||ea(c,d)))&&s.push(c);return s}function kf(r,e){return function(t){return r(e(t))}}var Tf=kf(Object.keys,Object),zf=Object.prototype,Rf=zf.hasOwnProperty;function la(r){if(!ra(r))return Tf(r);var e=[];for(var t in Object(r))Rf.call(r,t)&&t!="constructor"&&e.push(t);return e}function Or(r){return Rn(r)?Cf(r):la(r)}var Df=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Af=/^\w*$/;function zi(r,e){if(ze(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||zn(r)?!0:Af.test(r)||!Df.test(r)||e!=null&&r in Object(e)}var Pr=hr(Object,"create");function If(){this.__data__=Pr?Pr(null):{},this.size=0}function xf(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var Mf="__lodash_hash_undefined__",Of=Object.prototype,Pf=Of.hasOwnProperty;function Lf(r){var e=this.__data__;if(Pr){var t=e[r];return t===Mf?void 0:t}return Pf.call(e,r)?e[r]:void 0}var Uf=Object.prototype,Gf=Uf.hasOwnProperty;function Nf(r){var e=this.__data__;return Pr?e[r]!==void 0:Gf.call(e,r)}var Bf="__lodash_hash_undefined__";function Ff(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=Pr&&e===void 0?Bf:e,this}function Jt(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}Jt.prototype.clear=If,Jt.prototype.delete=xf,Jt.prototype.get=Lf,Jt.prototype.has=Nf,Jt.prototype.set=Ff;function Vf(){this.__data__=[],this.size=0}function An(r,e){for(var t=r.length;t--;)if(ta(r[t][0],e))return t;return-1}var jf=Array.prototype,Hf=jf.splice;function $f(r){var e=this.__data__,t=An(e,r);if(t<0)return!1;var n=e.length-1;return t==n?e.pop():Hf.call(e,t,1),--this.size,!0}function qf(r){var e=this.__data__,t=An(e,r);return t<0?void 0:e[t][1]}function Kf(r){return An(this.__data__,r)>-1}function Wf(r,e){var t=this.__data__,n=An(t,r);return n<0?(++this.size,t.push([r,e])):t[n][1]=e,this}function St(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}St.prototype.clear=Vf,St.prototype.delete=$f,St.prototype.get=qf,St.prototype.has=Kf,St.prototype.set=Wf;var Lr=hr(yt,"Map");function Jf(){this.size=0,this.__data__={hash:new Jt,map:new(Lr||St),string:new Jt}}function Xf(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function In(r,e){var t=r.__data__;return Xf(e)?t[typeof e=="string"?"string":"hash"]:t.map}function Zf(r){var e=In(this,r).delete(r);return this.size-=e?1:0,e}function Yf(r){return In(this,r).get(r)}function Qf(r){return In(this,r).has(r)}function ep(r,e){var t=In(this,r),n=t.size;return t.set(r,e),this.size+=t.size==n?0:1,this}function bt(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}bt.prototype.clear=Jf,bt.prototype.delete=Zf,bt.prototype.get=Yf,bt.prototype.has=Qf,bt.prototype.set=ep;var tp="Expected a function";function Ri(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(tp);var t=function(){var n=arguments,i=e?e.apply(this,n):n[0],o=t.cache;if(o.has(i))return o.get(i);var a=r.apply(this,n);return t.cache=o.set(i,a)||o,a};return t.cache=new(Ri.Cache||bt),t}Ri.Cache=bt;var rp=500;function np(r){var e=Ri(r,function(n){return t.size===rp&&t.clear(),n}),t=e.cache;return e}var ip=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,op=/\\(\\)?/g,sp=np(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(ip,function(t,n,i,o){e.push(i?o.replace(op,"$1"):n||t)}),e});function ap(r){return r==null?"":Xs(r)}function ha(r,e){return ze(r)?r:zi(r,e)?[r]:sp(ap(r))}function xn(r){if(typeof r=="string"||zn(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function fa(r,e){e=ha(e,r);for(var t=0,n=e.length;r!=null&&t<n;)r=r[xn(e[t++])];return t&&t==n?r:void 0}function cp(r,e,t){var n=r==null?void 0:fa(r,e);return n===void 0?t:n}function up(r,e){for(var t=-1,n=e.length,i=r.length;++t<n;)r[i+t]=e[t];return r}function dp(){this.__data__=new St,this.size=0}function lp(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function hp(r){return this.__data__.get(r)}function fp(r){return this.__data__.has(r)}var pp=200;function mp(r,e){var t=this.__data__;if(t instanceof St){var n=t.__data__;if(!Lr||n.length<pp-1)return n.push([r,e]),this.size=++t.size,this;t=this.__data__=new bt(n)}return t.set(r,e),this.size=t.size,this}function Et(r){var e=this.__data__=new St(r);this.size=e.size}Et.prototype.clear=dp,Et.prototype.delete=lp,Et.prototype.get=hp,Et.prototype.has=fp,Et.prototype.set=mp;function pa(r,e){for(var t=-1,n=r==null?0:r.length,i=0,o=[];++t<n;){var a=r[t];e(a,t,r)&&(o[i++]=a)}return o}function gp(){return[]}var _p=Object.prototype,vp=_p.propertyIsEnumerable,ma=Object.getOwnPropertySymbols,yp=ma?function(r){return r==null?[]:(r=Object(r),pa(ma(r),function(e){return vp.call(r,e)}))}:gp;function Sp(r,e,t){var n=e(r);return ze(r)?n:up(n,t(r))}function ga(r){return Sp(r,Or,yp)}var Di=hr(yt,"DataView"),Ai=hr(yt,"Promise"),Ii=hr(yt,"Set"),_a="[object Map]",bp="[object Object]",va="[object Promise]",ya="[object Set]",Sa="[object WeakMap]",ba="[object DataView]",Ep=Wt(Di),wp=Wt(Lr),Cp=Wt(Ai),kp=Wt(Ii),Tp=Wt(Ei),wt=dr;(Di&&wt(new Di(new ArrayBuffer(1)))!=ba||Lr&&wt(new Lr)!=_a||Ai&&wt(Ai.resolve())!=va||Ii&&wt(new Ii)!=ya||Ei&&wt(new Ei)!=Sa)&&(wt=function(r){var e=dr(r),t=e==bp?r.constructor:void 0,n=t?Wt(t):"";if(n)switch(n){case Ep:return ba;case wp:return _a;case Cp:return va;case kp:return ya;case Tp:return Sa}return e});var Ea=yt.Uint8Array,zp="__lodash_hash_undefined__";function Rp(r){return this.__data__.set(r,zp),this}function Dp(r){return this.__data__.has(r)}function Mn(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new bt;++e<t;)this.add(r[e])}Mn.prototype.add=Mn.prototype.push=Rp,Mn.prototype.has=Dp;function Ap(r,e){for(var t=-1,n=r==null?0:r.length;++t<n;)if(e(r[t],t,r))return!0;return!1}function Ip(r,e){return r.has(e)}var xp=1,Mp=2;function wa(r,e,t,n,i,o){var a=t&xp,s=r.length,d=e.length;if(s!=d&&!(a&&d>s))return!1;var c=o.get(r),u=o.get(e);if(c&&u)return c==e&&u==r;var f=-1,h=!0,g=t&Mp?new Mn:void 0;for(o.set(r,e),o.set(e,r);++f<s;){var k=r[f],z=e[f];if(n)var w=a?n(z,k,f,e,r,o):n(k,z,f,r,e,o);if(w!==void 0){if(w)continue;h=!1;break}if(g){if(!Ap(e,function(b,T){if(!Ip(g,T)&&(k===b||i(k,b,t,n,o)))return g.push(T)})){h=!1;break}}else if(!(k===z||i(k,z,t,n,o))){h=!1;break}}return o.delete(r),o.delete(e),h}function Op(r){var e=-1,t=Array(r.size);return r.forEach(function(n,i){t[++e]=[i,n]}),t}function Pp(r){var e=-1,t=Array(r.size);return r.forEach(function(n){t[++e]=n}),t}var Lp=1,Up=2,Gp="[object Boolean]",Np="[object Date]",Bp="[object Error]",Fp="[object Map]",Vp="[object Number]",jp="[object RegExp]",Hp="[object Set]",$p="[object String]",qp="[object Symbol]",Kp="[object ArrayBuffer]",Wp="[object DataView]",Ca=Ot?Ot.prototype:void 0,xi=Ca?Ca.valueOf:void 0;function Jp(r,e,t,n,i,o,a){switch(t){case Wp:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case Kp:return!(r.byteLength!=e.byteLength||!o(new Ea(r),new Ea(e)));case Gp:case Np:case Vp:return ta(+r,+e);case Bp:return r.name==e.name&&r.message==e.message;case jp:case $p:return r==e+"";case Fp:var s=Op;case Hp:var d=n&Lp;if(s||(s=Pp),r.size!=e.size&&!d)return!1;var c=a.get(r);if(c)return c==e;n|=Up,a.set(r,e);var u=wa(s(r),s(e),n,i,o,a);return a.delete(r),u;case qp:if(xi)return xi.call(r)==xi.call(e)}return!1}var Xp=1,Zp=Object.prototype,Yp=Zp.hasOwnProperty;function Qp(r,e,t,n,i,o){var a=t&Xp,s=ga(r),d=s.length,c=ga(e),u=c.length;if(d!=u&&!a)return!1;for(var f=d;f--;){var h=s[f];if(!(a?h in e:Yp.call(e,h)))return!1}var g=o.get(r),k=o.get(e);if(g&&k)return g==e&&k==r;var z=!0;o.set(r,e),o.set(e,r);for(var w=a;++f<d;){h=s[f];var b=r[h],T=e[h];if(n)var E=a?n(T,b,h,e,r,o):n(b,T,h,r,e,o);if(!(E===void 0?b===T||i(b,T,t,n,o):E)){z=!1;break}w||(w=h=="constructor")}if(z&&!w){var O=r.constructor,G=e.constructor;O!=G&&"constructor"in r&&"constructor"in e&&!(typeof O=="function"&&O instanceof O&&typeof G=="function"&&G instanceof G)&&(z=!1)}return o.delete(r),o.delete(e),z}var em=1,ka="[object Arguments]",Ta="[object Array]",On="[object Object]",tm=Object.prototype,za=tm.hasOwnProperty;function rm(r,e,t,n,i,o){var a=ze(r),s=ze(e),d=a?Ta:wt(r),c=s?Ta:wt(e);d=d==ka?On:d,c=c==ka?On:c;var u=d==On,f=c==On,h=d==c;if(h&&Dn(r)){if(!Dn(e))return!1;a=!0,u=!1}if(h&&!u)return o||(o=new Et),a||Ti(r)?wa(r,e,t,n,i,o):Jp(r,e,d,t,n,i,o);if(!(t&em)){var g=u&&za.call(r,"__wrapped__"),k=f&&za.call(e,"__wrapped__");if(g||k){var z=g?r.value():r,w=k?e.value():e;return o||(o=new Et),i(z,w,t,n,o)}}return h?(o||(o=new Et),Qp(r,e,t,n,i,o)):!1}function Mi(r,e,t,n,i){return r===e?!0:r==null||e==null||!lr(r)&&!lr(e)?r!==r&&e!==e:rm(r,e,t,n,Mi,i)}var nm=1,im=2;function om(r,e,t,n){var i=t.length,o=i;if(r==null)return!o;for(r=Object(r);i--;){var a=t[i];if(a[2]?a[1]!==r[a[0]]:!(a[0]in r))return!1}for(;++i<o;){a=t[i];var s=a[0],d=r[s],c=a[1];if(a[2]){if(d===void 0&&!(s in r))return!1}else{var u=new Et,f;if(!(f===void 0?Mi(c,d,nm|im,n,u):f))return!1}}return!0}function Ra(r){return r===r&&!xr(r)}function sm(r){for(var e=Or(r),t=e.length;t--;){var n=e[t],i=r[n];e[t]=[n,i,Ra(i)]}return e}function Da(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function am(r){var e=sm(r);return e.length==1&&e[0][2]?Da(e[0][0],e[0][1]):function(t){return t===r||om(t,r,e)}}function cm(r,e){return r!=null&&e in Object(r)}function um(r,e,t){e=ha(e,r);for(var n=-1,i=e.length,o=!1;++n<i;){var a=xn(e[n]);if(!(o=r!=null&&t(r,a)))break;r=r[a]}return o||++n!=i?o:(i=r==null?0:r.length,!!i&&wi(i)&&ea(a,i)&&(ze(r)||Ci(r)))}function dm(r,e){return r!=null&&um(r,e,cm)}var lm=1,hm=2;function fm(r,e){return zi(r)&&Ra(e)?Da(xn(r),e):function(t){var n=cp(t,r);return n===void 0&&n===e?dm(t,r):Mi(e,n,lm|hm)}}function pm(r){return function(e){return e==null?void 0:e[r]}}function mm(r){return function(e){return fa(e,r)}}function gm(r){return zi(r)?pm(xn(r)):mm(r)}function Oi(r){return typeof r=="function"?r:r==null?yh:typeof r=="object"?ze(r)?fm(r[0],r[1]):am(r):gm(r)}function _m(r){return function(e,t,n){for(var i=-1,o=Object(e),a=n(e),s=a.length;s--;){var d=a[++i];if(t(o[d],d,o)===!1)break}return e}}var vm=_m();function ym(r,e){return r&&vm(r,e,Or)}function Sm(r,e){return function(t,n){if(t==null)return t;if(!Rn(t))return r(t,n);for(var i=t.length,o=-1,a=Object(t);++o<i&&n(a[o],o,a)!==!1;);return t}}var bm=Sm(ym);function Em(r,e){var t=[];return bm(r,function(n,i,o){e(n,i,o)&&t.push(n)}),t}function Aa(r,e){var t=ze(r)?pa:Em;return t(r,Oi(e))}function wm(r){return function(e,t,n){var i=Object(e);if(!Rn(e)){var o=Oi(t);e=Or(e),t=function(s){return o(i[s],s,i)}}var a=r(e,t,n);return a>-1?i[o?e[a]:a]:void 0}}var Cm=Math.max;function km(r,e,t){var n=r==null?0:r.length;if(!n)return-1;var i=t==null?0:vh(t);return i<0&&(i=Cm(n+i,0)),Lh(r,Oi(e),i)}var Ur=wm(km);function Tm(r,e){return Ks(e,function(t){return r[t]})}function Ct(r){return r==null?[]:Tm(r,Or(r))}var zm="[object Map]",Rm="[object Set]",Dm=Object.prototype,Am=Dm.hasOwnProperty;function Im(r){if(r==null)return!0;if(Rn(r)&&(ze(r)||typeof r=="string"||typeof r.splice=="function"||Dn(r)||Ti(r)||Ci(r)))return!r.length;var e=wt(r);if(e==zm||e==Rm)return!r.size;if(ra(r))return!la(r).length;for(var t in r)if(Am.call(r,t))return!1;return!0}function xm(r){return r==null}class Mm extends Tn{constructor(e){super({type:ae.Microphone,stream:e}),this._trackMap.audio=e.track()}get source(){return this._source}get mixerNode(){return this.source.node()}bindTrackEnd(e){this.source.on(Pe.ENDED,e)}destroy(){this.source.destroy()}}class Om extends ur{constructor(e){super({type:ae.VideoFile,stream:e});const t=Ur(e,i=>i.kind===he.VIDEO),n=Ur(e,i=>i.kind===he.AUDIO);this._videoStream=t,this._audioStream=n,this._trackMap.video=t==null?void 0:t.track(),this._trackMap.audio=n==null?void 0:n.track(),t&&(this._height=t==null?void 0:t.height(),this._width=t==null?void 0:t.width())}get viewNode(){var e;return((e=this._videoStream)==null?void 0:e.node())??null}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._videoStream)==null||t.on(Pe.ENDED,e)}destroy(){var e,t;(e=this._videoStream)==null||e.destroy(),(t=this._audioStream)==null||t.destroy(),delete this._trackMap.video,delete this._trackMap.audio}}class Pm extends ur{constructor(e,t){super({type:ae.Screen,stream:e});const n=Ur(e,o=>o.kind===he.VIDEO),i=Ur(e,o=>o.kind===he.AUDIO);this._videoStream=n,this._audioStream=i,this._frameRate=(t==null?void 0:t.frameRate)??1,this._trackMap.video=n==null?void 0:n.track(),this._trackMap.audio=i==null?void 0:i.track(),n&&(this._height=n==null?void 0:n.height(),this._width=n==null?void 0:n.width(),this.bindTrackSizeChangeEvent(n))}get viewNode(){var e;return((e=this._videoStream)==null?void 0:e.node())??null}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._videoStream)==null||t.on(Pe.ENDED,e)}destroy(){var e,t;(e=this._videoStream)==null||e.destroy(),(t=this._audioStream)==null||t.destroy(),delete this._trackMap.video,delete this._trackMap.audio}}class Lm extends Tn{constructor(e){super({type:ae.AudioFile,stream:e});const t=Ur(e,n=>n.kind===he.AUDIO);this._audioStream=t,this._trackMap.audio=t==null?void 0:t.track()}get mixerNode(){var e;return((e=this._audioStream)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._audioStream)==null||t.on(Pe.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}class Um extends ur{constructor(e){super({type:ae.Image,stream:e}),this._width=e.width(),this._height=e.height()}get source(){return this._source}get mixerNode(){return null}get viewNode(){return this.source.node()}bindTrackEnd(e){this.source.on(Pe.ENDED,e)}destroy(){this.source.destroy()}}class Gm extends ur{constructor(e){super({type:ae.CustomVideo,stream:e}),this._trackMap.video=e.track(),this._width=e.width(),this._height=e.height()}get source(){return this._source}get viewNode(){return this.source.node()}get mixerNode(){return null}bindTrackEnd(e){this.source.on(Pe.ENDED,e)}destroy(){this.source.destroy()}}class Nm extends Tn{constructor(e){super({type:ae.CustomAudio,stream:e}),this._trackMap.audio=e==null?void 0:e.track()}get source(){return this._source}get mixerNode(){var e;return((e=this.source)==null?void 0:e.node())??null}bindTrackEnd(e){var t;(t=this._audioStream)==null||t.on(Pe.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}const Bm=["user","environment"],Fm=18e4,Vm=1e4,Ia=1e3,jm=15;var qe=(r=>(r[r.OPEN_CAMERA_FAILED=1001]="OPEN_CAMERA_FAILED",r[r.OPEN_MICROPHONE_FAILED=1002]="OPEN_MICROPHONE_FAILED",r[r.OPEN_SCREEN_FAILED=1003]="OPEN_SCREEN_FAILED",r[r.VIDEO_FILE_CAPTURE_FAILED=1004]="VIDEO_FILE_CAPTURE_FAILED",r[r.AUDIO_FILE_CAPTURE_FAILED=1005]="AUDIO_FILE_CAPTURE_FAILED",r[r.IMAGE_FILE_CAPTURE_FAILED=1006]="IMAGE_FILE_CAPTURE_FAILED",r[r.VOLUME_DETECT_FAILED=1008]="VOLUME_DETECT_FAILED",r[r.PUBLISH_FAILED=2001]="PUBLISH_FAILED",r[r.UPDATE_PUBLISH_FAILED=2002]="UPDATE_PUBLISH_FAILED",r[r.PUSH_CONNECT_FAILED=2003]="PUSH_CONNECT_FAILED",r[r.AUDIO_RESUME_FAILED=2004]="AUDIO_RESUME_FAILED",r))(qe||{});class fr extends Error{constructor(e,t,n){super(),this.code=e,this.message=t,n&&(this.ext=n)}}function pr(r,e,t){const n=oi.Landscape;if(e==="video"){const d=(n===oi.Landscape?ls:hs)[r],[c,u,f,h]=d.split("x").map(g=>Number(g));return{width:c,height:u,frameRate:f,bitrate:h*1e3}}const i=fs[r],[o,a]=i.split("x").map(s=>Number(s));return{sampleRate:o,bitrate:a*1e3}}var me=function(){return(me=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 Pi(r,e,t,n){return new(t||(t=Promise))(function(i,o){function a(c){try{d(n.next(c))}catch(u){o(u)}}function s(c){try{d(n.throw(c))}catch(u){o(u)}}function d(c){c.done?i(c.value):new t(function(u){u(c.value)}).then(a,s)}d((n=n.apply(r,[])).next())})}function Li(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(d){return function(c){return function(u){if(t)throw new TypeError("Generator is already executing.");for(;a;)try{if(t=1,n&&(i=2&u[0]?n.return:u[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,u[1])).done)return i;switch(n=0,i&&(u=[2&u[0],i.value]),u[0]){case 0:case 1:i=u;break;case 4:return a.label++,{value:u[1],done:!1};case 5:a.label++,n=u[1],u=[0];continue;case 7:u=a.ops.pop(),a.trys.pop();continue;default:if(i=a.trys,!((i=i.length>0&&i[i.length-1])||u[0]!==6&&u[0]!==2)){a=0;continue}if(u[0]===3&&(!i||u[1]>i[0]&&u[1]<i[3])){a.label=u[1];break}if(u[0]===6&&a.label<i[1]){a.label=i[1],i=u;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(u);break}i[2]&&a.ops.pop(),a.trys.pop();continue}u=e.call(r,a)}catch(f){u=[6,f],n=0}finally{t=i=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}([d,c])}}}function Hm(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 Gr(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(Hm(arguments[e]));return r}var xa,$m=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&&Gr(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}(),Nr=function(r){return r!=null&&Object.prototype.toString.call(r)=="[object Object]"},Ui=function(r){return Array.isArray(r)},qm=(xa=+Date.now()+Number((""+Math.random()).slice(2,8)),function(){return xa+=1}),Br=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 d=parseInt(i[s],n);d=1*d^t;var c=String.fromCharCode(d);o.push(c)}return o.join("")}}(r,64,25)},Ma=function(){return!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)},Fr=function(r){Ma()?window.addEventListener("pagehide",r,!1):window.addEventListener("beforeunload",r,!1)},Oa=function(){var r=0;return["hidden","msHidden","webkitHidden"].forEach(function(e){document[e]!==void 0&&(r=1)}),r},Gi=function(r){var e=document.createElement("a");return e.href=r,e},Pn=function(r){var e={};try{var t=Gi(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},Ln=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ni(){throw new Error("Dynamic requires are not currently supported by rollup-plugin-commonjs")}function Pa(r,e){return r(e={exports:{}},e.exports),e.exports}var Vr=Pa(function(r,e){var t;t=function(){function n(){for(var o=0,a={};o<arguments.length;o++){var s=arguments[o];for(var d in s)a[d]=s[d]}return a}function i(o){return o.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function o(a){function s(){}function d(u,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,u):encodeURIComponent(String(f)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),u=encodeURIComponent(String(u)).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=u+"="+f+k}}function c(u,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,u===b)break}catch{}}return u?h[u]:h}}return s.set=d,s.get=function(u){return c(u,!1)},s.getJSON=function(u){return c(u,!0)},s.remove=function(u,f){d(u,"",n(f,{expires:-1}))},s.defaults={},s.withConverter=o,s}(function(){})},r.exports=t()}),Bi=Pa(function(r,e){r.exports=function t(n,i,o){function a(c,u){if(!i[c]){if(!n[c]){if(!u&&Ni)return Ni();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=Ni,d=0;d<o.length;d++)a(o[d]);return a}({1:[function(t,n,i){(function(o){var a,s,d=o.MutationObserver||o.WebKitMutationObserver;if(d){var c=0,u=new d(k),f=o.document.createTextNode("");u.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,Ln!==void 0?Ln:typeof self<"u"?self:typeof window<"u"?window:{})},{}],2:[function(t,n,i){var o=t(1);function a(){}var s={},d=["REJECTED"],c=["FULFILLED"],u=["PENDING"];function f(b){if(typeof b!="function")throw new TypeError("resolver must be a function");this.state=u,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===d)return this;var E=new this.constructor(a);return this.state!==u?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=d,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,Ln!==void 0?Ln: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(y){return typeof y}:function(y){return y&&typeof Symbol=="function"&&y.constructor===Symbol&&y!==Symbol.prototype?"symbol":typeof y},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(y,l){y=y||[],l=l||{};try{return new Blob(y,l)}catch(v){if(v.name!=="TypeError")throw v;for(var p=new(typeof BlobBuilder<"u"?BlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:WebKitBlobBuilder),m=0;m<y.length;m+=1)p.append(y[m]);return p.getBlob(l.type)}}typeof Promise>"u"&&t(3);var d=Promise;function c(y,l){l&&y.then(function(p){l(null,p)},function(p){l(p)})}function u(y,l,p){typeof l=="function"&&y.then(l),typeof p=="function"&&y.catch(p)}function f(y){return typeof y!="string"&&(console.warn(y+" used as a key, but it is not a string."),y=String(y)),y}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(y){return typeof g=="boolean"?d.resolve(g):function(l){return new d(function(p){var m=l.transaction("local-forage-detect-blob-support","readwrite"),v=s([""]);m.objectStore("local-forage-detect-blob-support").put(v,"key"),m.onabort=function(_){_.preventDefault(),_.stopPropagation(),p(!1)},m.oncomplete=function(){var _=navigator.userAgent.match(/Chrome\/(\d+)/),S=navigator.userAgent.match(/Edge\//);p(S||!_||parseInt(_[1],10)>=43)}}).catch(function(){return!1})}(y).then(function(l){return g=l})}function b(y){var l=k[y.name],p={};p.promise=new d(function(m,v){p.resolve=m,p.reject=v}),l.deferredOperations.push(p),l.dbReady?l.dbReady=l.dbReady.then(function(){return p.promise}):l.dbReady=p.promise}function T(y){var l=k[y.name].deferredOperations.pop();if(l)return l.resolve(),l.promise}function E(y,l){var p=k[y.name].deferredOperations.pop();if(p)return p.reject(l),p.promise}function O(y,l){return new d(function(p,m){if(k[y.name]=k[y.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},y.db){if(!l)return p(y.db);b(y),y.db.close()}var v=[y.name];l&&v.push(y.version);var _=a.open.apply(a,v);l&&(_.onupgradeneeded=function(S){var C=_.result;try{C.createObjectStore(y.storeName),S.oldVersion<=1&&C.createObjectStore("local-forage-detect-blob-support")}catch(R){if(R.name!=="ConstraintError")throw R;console.warn('The database "'+y.name+'" has been upgraded from version '+S.oldVersion+" to version "+S.newVersion+', but the storage "'+y.storeName+'" already exists.')}}),_.onerror=function(S){S.preventDefault(),m(_.error)},_.onsuccess=function(){var S=_.result;S.onversionchange=function(C){C.target.close()},p(S),T(y)}})}function G(y){return O(y,!1)}function I(y){return O(y,!0)}function U(y,l){if(!y.db)return!0;var p=!y.db.objectStoreNames.contains(y.storeName),m=y.version<y.db.version,v=y.version>y.db.version;if(m&&(y.version!==l&&console.warn('The database "'+y.name+`" can't be downgraded from version `+y.db.version+" to version "+y.version+"."),y.version=y.db.version),v||p){if(p){var _=y.db.version+1;_>y.version&&(y.version=_)}return!0}return!1}function L(y){return s([function(l){for(var p=l.length,m=new ArrayBuffer(p),v=new Uint8Array(m),_=0;_<p;_++)v[_]=l.charCodeAt(_);return m}(atob(y.data))],{type:y.type})}function j(y){return y&&y.__local_forage_encoded_blob}function $(y){var l=this,p=l._initReady().then(function(){var m=k[l._dbInfo.name];if(m&&m.dbReady)return m.dbReady});return u(p,y,y),p}function K(y,l,p,m){m===void 0&&(m=1);try{var v=y.db.transaction(y.storeName,l);p(null,v)}catch(_){if(m>0&&(!y.db||_.name==="InvalidStateError"||_.name==="NotFoundError"))return d.resolve().then(function(){if(!y.db||_.name==="NotFoundError"&&!y.db.objectStoreNames.contains(y.storeName)&&y.version<=y.db.version)return y.db&&(y.version=y.db.version+1),I(y)}).then(function(){return function(S){b(S);for(var C=k[S.name],R=C.forages,D=0;D<R.length;D++){var A=R[D];A._dbInfo.db&&(A._dbInfo.db.close(),A._dbInfo.db=null)}return S.db=null,G(S).then(function(M){return S.db=M,U(S)?I(S):M}).then(function(M){S.db=C.db=M;for(var N=0;N<R.length;N++)R[N]._dbInfo.db=M}).catch(function(M){throw E(S,M),M})}(y).then(function(){K(y,l,p,m-1)})}).catch(p);p(_)}}var Z={_driver:"asyncStorage",_initStorage:function(y){var l=this,p={db:null};if(y)for(var m in y)p[m]=y[m];var v=k[p.name];v||(v={forages:[],db:null,dbReady:null,deferredOperations:[]},k[p.name]=v),v.forages.push(l),l._initReady||(l._initReady=l.ready,l.ready=$);var _=[];function S(){return d.resolve()}for(var C=0;C<v.forages.length;C++){var R=v.forages[C];R!==l&&_.push(R._initReady().catch(S))}var D=v.forages.slice(0);return d.all(_).then(function(){return p.db=v.db,G(p)}).then(function(A){return p.db=A,U(p,l._defaultConfig.version)?I(p):A}).then(function(A){p.db=v.db=A,l._dbInfo=p;for(var M=0;M<D.length;M++){var N=D[M];N!==l&&(N._dbInfo.db=p.db,N._dbInfo.version=p.version)}})},_support:function(){try{if(!a||!a.open)return!1;var y=typeof openDatabase<"u"&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),l=typeof fetch=="function"&&fetch.toString().indexOf("[native code")!==-1;return(!y||l)&&typeof indexedDB<"u"&&typeof IDBKeyRange<"u"}catch{return!1}}(),iterate:function(y,l){var p=this,m=new d(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).openCursor(),D=1;R.onsuccess=function(){var A=R.result;if(A){var M=A.value;j(M)&&(M=L(M));var N=y(M,A.key,D++);N!==void 0?v(N):A.continue()}else v()},R.onerror=function(){_(R.error)}}catch(A){_(A)}})}).catch(_)});return c(m,l),m},getItem:function(y,l){var p=this;y=f(y);var m=new d(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).get(y);R.onsuccess=function(){var D=R.result;D===void 0&&(D=null),j(D)&&(D=L(D)),v(D)},R.onerror=function(){_(R.error)}}catch(D){_(D)}})}).catch(_)});return c(m,l),m},setItem:function(y,l,p){var m=this;y=f(y);var v=new d(function(_,S){var C;m.ready().then(function(){return C=m._dbInfo,z.call(l)==="[object Blob]"?w(C.db).then(function(R){return R?l:(D=l,new d(function(A,M){var N=new FileReader;N.onerror=M,N.onloadend=function(H){var q=btoa(H.target.result||"");A({__local_forage_encoded_blob:!0,data:q,type:D.type})},N.readAsBinaryString(D)}));var D}):l}).then(function(R){K(m._dbInfo,"readwrite",function(D,A){if(D)return S(D);try{var M=A.objectStore(m._dbInfo.storeName);R===null&&(R=void 0);var N=M.put(R,y);A.oncomplete=function(){R===void 0&&(R=null),_(R)},A.onabort=A.onerror=function(){try{var H=N.error?N.error:N.transaction.error;S(H)}catch(q){S(q)}}}catch(H){S(H)}})}).catch(S)});return c(v,p),v},removeItem:function(y,l){var p=this;y=f(y);var m=new d(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).delete(y);C.oncomplete=function(){v()},C.onerror=function(){_(R.error)},C.onabort=function(){try{var D=R.error?R.error:R.transaction.error;_(D)}catch(A){_(A)}}}catch(D){_(D)}})}).catch(_)});return c(m,l),m},clear:function(y){var l=this,p=new d(function(m,v){l.ready().then(function(){K(l._dbInfo,"readwrite",function(_,S){if(_)return v(_);try{var C=S.objectStore(l._dbInfo.storeName).clear();S.oncomplete=function(){m()},S.onabort=S.onerror=function(){try{var R=C.error?C.error:C.transaction.error;v(R)}catch(D){v(D)}}}catch(R){v(R)}})}).catch(v)});return c(p,y),p},length:function(y){var l=this,p=new d(function(m,v){l.ready().then(function(){K(l._dbInfo,"readonly",function(_,S){if(_)return v(_);try{var C=S.objectStore(l._dbInfo.storeName).count();C.onsuccess=function(){m(C.result)},C.onerror=function(){v(C.error)}}catch(R){v(R)}})}).catch(v)});return c(p,y),p},key:function(y,l){var p=this,m=new d(function(v,_){y<0?v(null):p.ready().then(function(){K(p._dbInfo,"readonly",function(S,C){if(S)return _(S);try{var R=C.objectStore(p._dbInfo.storeName),D=!1,A=(R.openKeyCursor||R.openCursor).call(R);A.onsuccess=function(){var M=A.result;M?y===0||D?v(M.key):(D=!0,M.advance(y)):v(null)},A.onerror=function(){_(A.error)}}catch(M){_(M)}})}).catch(_)});return c(m,l),m},keys:function(y){var l=this,p=new d(function(m,v){l.ready().then(function(){K(l._dbInfo,"readonly",function(_,S){if(_)return v(_);try{var C=S.objectStore(l._dbInfo.storeName),R=(C.openKeyCursor||C.openCursor).call(C),D=[];R.onsuccess=function(){var A=R.result;A?(D.push(A.key),A.continue()):m(D)},R.onerror=function(){v(R.error)}}catch(A){v(A)}})}).catch(v)});return c(p,y),p},dropInstance:function(y,l){l=h.apply(this,arguments);var p=this.config();(y=typeof y!="function"&&y||{}).name||(y.name=y.name||p.name,y.storeName=y.storeName||p.storeName);var m,v=this;if(y.name){var _=y.name===p.name&&v._dbInfo.db,S=_?d.resolve(v._dbInfo.db):G(y).then(function(C){var R=k[y.name],D=R.forages;R.db=C;for(var A=0;A<D.length;A++)D[A]._dbInfo.db=C;return C});m=y.storeName?S.then(function(C){if(C.objectStoreNames.contains(y.storeName)){var R=C.version+1;b(y);var D=k[y.name],A=D.forages;C.close();for(var M=0;M<A.length;M++){var N=A[M];N._dbInfo.db=null,N._dbInfo.version=R}return new d(function(H,q){var Q=a.open(y.name,R);Q.onerror=function(ve){Q.result.close(),q(ve)},Q.onupgradeneeded=function(){Q.result.deleteObjectStore(y.storeName)},Q.onsuccess=function(){var ve=Q.result;ve.close(),H(ve)}}).then(function(H){D.db=H;for(var q=0;q<A.length;q++){var Q=A[q];Q._dbInfo.db=H,T(Q._dbInfo)}}).catch(function(H){throw(E(y,H)||d.resolve()).catch(function(){}),H})}}):S.then(function(C){b(y);var R=k[y.name],D=R.forages;C.close();for(var A=0;A<D.length;A++)D[A]._dbInfo.db=null;return new d(function(M,N){var H=a.deleteDatabase(y.name);H.onerror=function(){var q=H.result;q&&q.close(),N(H.error)},H.onblocked=function(){console.warn('dropInstance blocked for database "'+y.name+'" until all open connections are closed')},H.onsuccess=function(){var q=H.result;q&&q.close(),M(q)}}).then(function(M){R.db=M;for(var N=0;N<D.length;N++)T(D[N]._dbInfo)}).catch(function(M){throw(E(y,M)||d.resolve()).catch(function(){}),M})})}else m=d.reject("Invalid arguments");return c(m,l),m}},W="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",se=/^~~local_forage_type~([^~]+)~/,oe=9,Y=oe+4,le=Object.prototype.toString;function fe(y){var l,p,m,v,_,S=.75*y.length,C=y.length,R=0;y[y.length-1]==="="&&(S--,y[y.length-2]==="="&&S--);var D=new ArrayBuffer(S),A=new Uint8Array(D);for(l=0;l<C;l+=4)p=W.indexOf(y[l]),m=W.indexOf(y[l+1]),v=W.indexOf(y[l+2]),_=W.indexOf(y[l+3]),A[R++]=p<<2|m>>4,A[R++]=(15&m)<<4|v>>2,A[R++]=(3&v)<<6|63&_;return D}function ue(y){var l,p=new Uint8Array(y),m="";for(l=0;l<p.length;l+=3)m+=W[p[l]>>2],m+=W[(3&p[l])<<4|p[l+1]>>4],m+=W[(15&p[l+1])<<2|p[l+2]>>6],m+=W[63&p[l+2]];return p.length%3==2?m=m.substring(0,m.length-1)+"=":p.length%3==1&&(m=m.substring(0,m.length-2)+"=="),m}var be={serialize:function(y,l){var p="";if(y&&(p=le.call(y)),y&&(p==="[object ArrayBuffer]"||y.buffer&&le.call(y.buffer)==="[object ArrayBuffer]")){var m,v="__lfsc__:";y instanceof ArrayBuffer?(m=y,v+="arbf"):(m=y.buffer,p==="[object Int8Array]"?v+="si08":p==="[object Uint8Array]"?v+="ui08":p==="[object Uint8ClampedArray]"?v+="uic8":p==="[object Int16Array]"?v+="si16":p==="[object Uint16Array]"?v+="ur16":p==="[object Int32Array]"?v+="si32":p==="[object Uint32Array]"?v+="ui32":p==="[object Float32Array]"?v+="fl32":p==="[object Float64Array]"?v+="fl64":l(new Error("Failed to get type for BinaryArray"))),l(v+ue(m))}else if(p==="[object Blob]"){var _=new FileReader;_.onload=function(){var S="~~local_forage_type~"+y.type+"~"+ue(this.result);l("__lfsc__:blob"+S)},_.readAsArrayBuffer(y)}else try{l(JSON.stringify(y))}catch(S){console.error("Couldn't convert value into a JSON string: ",y),l(null,S)}},deserialize:function(y){if(y.substring(0,oe)!=="__lfsc__:")return JSON.parse(y);var l,p=y.substring(Y),m=y.substring(oe,Y);if(m==="blob"&&se.test(p)){var v=p.match(se);l=v[1],p=p.substring(v[0].length)}var _=fe(p);switch(m){case"arbf":return _;case"blob":return s([_],{type:l});case"si08":return new Int8Array(_);case"ui08":return new Uint8Array(_);case"uic8":return new Uint8ClampedArray(_);case"si16":return new Int16Array(_);case"ur16":return new Uint16Array(_);case"si32":return new Int32Array(_);case"ui32":return new Uint32Array(_);case"fl32":return new Float32Array(_);case"fl64":return new Float64Array(_);default:throw new Error("Unkown type: "+m)}},stringToBuffer:fe,bufferToString:ue};function ye(y,l,p,m){y.executeSql("CREATE TABLE IF NOT EXISTS "+l.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],p,m)}function re(y,l,p,m,v,_){y.executeSql(p,m,v,function(S,C){C.code===C.SYNTAX_ERR?S.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[l.storeName],function(R,D){D.rows.length?_(R,C):ye(R,l,function(){R.executeSql(p,m,v,_)},_)},_):_(S,C)},_)}function ke(y,l,p,m){var v=this;y=f(y);var _=new d(function(S,C){v.ready().then(function(){l===void 0&&(l=null);var R=l,D=v._dbInfo;D.serializer.serialize(l,function(A,M){M?C(M):D.db.transaction(function(N){re(N,D,"INSERT OR REPLACE INTO "+D.storeName+" (key, value) VALUES (?, ?)",[y,A],function(){S(R)},function(H,q){C(q)})},function(N){if(N.code===N.QUOTA_ERR){if(m>0)return void S(ke.apply(v,[y,R,p,m-1]));C(N)}})})}).catch(C)});return c(_,p),_}function de(y){return new d(function(l,p){y.transaction(function(m){m.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",[],function(v,_){for(var S=[],C=0;C<_.rows.length;C++)S.push(_.rows.item(C).name);l({db:y,storeNames:S})},function(v,_){p(_)})},function(m){p(m)})})}var _e={_driver:"webSQLStorage",_initStorage:function(y){var l=this,p={db:null};if(y)for(var m in y)p[m]=typeof y[m]!="string"?y[m].toString():y[m];var v=new d(function(_,S){try{p.db=openDatabase(p.name,String(p.version),p.description,p.size)}catch(C){return S(C)}p.db.transaction(function(C){ye(C,p,function(){l._dbInfo=p,_()},function(R,D){S(D)})},S)});return p.serializer=be,v},_support:typeof openDatabase=="function",iterate:function(y,l){var p=this,m=new d(function(v,_){p.ready().then(function(){var S=p._dbInfo;S.db.transaction(function(C){re(C,S,"SELECT * FROM "+S.storeName,[],function(R,D){for(var A=D.rows,M=A.length,N=0;N<M;N++){var H=A.item(N),q=H.value;if(q&&(q=S.serializer.deserialize(q)),(q=y(q,H.key,N+1))!==void 0)return void v(q)}v()},function(R,D){_(D)})})}).catch(_)});return c(m,l),m},getItem:function(y,l){var p=this;y=f(y);var m=new d(function(v,_){p.ready().then(function(){var S=p._dbInfo;S.db.transaction(function(C){re(C,S,"SELECT * FROM "+S.storeName+" WHERE key = ? LIMIT 1",[y],function(R,D){var A=D.rows.length?D.rows.item(0).value:null;A&&(A=S.serializer.deserialize(A)),v(A)},function(R,D){_(D)})})}).catch(_)});return c(m,l),m},setItem:function(y,l,p){return ke.apply(this,[y,l,p,1])},removeItem:function(y,l){var p=this;y=f(y);var m=new d(function(v,_){p.ready().then(function(){var S=p._dbInfo;S.db.transaction(function(C){re(C,S,"DELETE FROM "+S.storeName+" WHERE key = ?",[y],function(){v()},function(R,D){_(D)})})}).catch(_)});return c(m,l),m},clear:function(y){var l=this,p=new d(function(m,v){l.ready().then(function(){var _=l._dbInfo;_.db.transaction(function(S){re(S,_,"DELETE FROM "+_.storeName,[],function(){m()},function(C,R){v(R)})})}).catch(v)});return c(p,y),p},length:function(y){var l=this,p=new d(function(m,v){l.ready().then(function(){var _=l._dbInfo;_.db.transaction(function(S){re(S,_,"SELECT COUNT(key) as c FROM "+_.storeName,[],function(C,R){var D=R.rows.item(0).c;m(D)},function(C,R){v(R)})})}).catch(v)});return c(p,y),p},key:function(y,l){var p=this,m=new d(function(v,_){p.ready().then(function(){var S=p._dbInfo;S.db.transaction(function(C){re(C,S,"SELECT key FROM "+S.storeName+" WHERE id = ? LIMIT 1",[y+1],function(R,D){var A=D.rows.length?D.rows.item(0).key:null;v(A)},function(R,D){_(D)})})}).catch(_)});return c(m,l),m},keys:function(y){var l=this,p=new d(function(m,v){l.ready().then(function(){var _=l._dbInfo;_.db.transaction(function(S){re(S,_,"SELECT key FROM "+_.storeName,[],function(C,R){for(var D=[],A=0;A<R.rows.length;A++)D.push(R.rows.item(A).key);m(D)},function(C,R){v(R)})})}).catch(v)});return c(p,y),p},dropInstance:function(y,l){l=h.apply(this,arguments);var p=this.config();(y=typeof y!="function"&&y||{}).name||(y.name=y.name||p.name,y.storeName=y.storeName||p.storeName);var m,v=this;return c(m=y.name?new d(function(_){var S;S=y.name===p.name?v._dbInfo.db:openDatabase(y.name,"","",0),y.storeName?_({db:S,storeNames:[y.storeName]}):_(de(S))}).then(function(_){return new d(function(S,C){_.db.transaction(function(R){function D(H){return new d(function(q,Q){R.executeSql("DROP TABLE IF EXISTS "+H,[],function(){q()},function(ve,Ze){Q(Ze)})})}for(var A=[],M=0,N=_.storeNames.length;M<N;M++)A.push(D(_.storeNames[M]));d.all(A).then(function(){S()}).catch(function(H){C(H)})},function(R){C(R)})})}):d.reject("Invalid arguments"),l),m}};function Ae(y,l){var p=y.name+"/";return y.storeName!==l.storeName&&(p+=y.storeName+"/"),p}function jt(){return!function(){try{return localStorage.setItem("_localforage_support_test",!0),localStorage.removeItem("_localforage_support_test"),!1}catch{return!0}}()||localStorage.length>0}var Ge={_driver:"localStorageWrapper",_initStorage:function(y){var l={};if(y)for(var p in y)l[p]=y[p];return l.keyPrefix=Ae(y,this._defaultConfig),jt()?(this._dbInfo=l,l.serializer=be,d.resolve()):d.reject()},_support:function(){try{return typeof localStorage<"u"&&"setItem"in localStorage&&!!localStorage.setItem}catch{return!1}}(),iterate:function(y,l){var p=this,m=p.ready().then(function(){for(var v=p._dbInfo,_=v.keyPrefix,S=_.length,C=localStorage.length,R=1,D=0;D<C;D++){var A=localStorage.key(D);if(A.indexOf(_)===0){var M=localStorage.getItem(A);if(M&&(M=v.serializer.deserialize(M)),(M=y(M,A.substring(S),R++))!==void 0)return M}}});return c(m,l),m},getItem:function(y,l){var p=this;y=f(y);var m=p.ready().then(function(){var v=p._dbInfo,_=localStorage.getItem(v.keyPrefix+y);return _&&(_=v.serializer.deserialize(_)),_});return c(m,l),m},setItem:function(y,l,p){var m=this;y=f(y);var v=m.ready().then(function(){l===void 0&&(l=null);var _=l;return new d(function(S,C){var R=m._dbInfo;R.serializer.serialize(l,function(D,A){if(A)C(A);else try{localStorage.setItem(R.keyPrefix+y,D),S(_)}catch(M){M.name!=="QuotaExceededError"&&M.name!=="NS_ERROR_DOM_QUOTA_REACHED"||C(M),C(M)}})})});return c(v,p),v},removeItem:function(y,l){var p=this;y=f(y);var m=p.ready().then(function(){var v=p._dbInfo;localStorage.removeItem(v.keyPrefix+y)});return c(m,l),m},clear:function(y){var l=this,p=l.ready().then(function(){for(var m=l._dbInfo.keyPrefix,v=localStorage.length-1;v>=0;v--){var _=localStorage.key(v);_.indexOf(m)===0&&localStorage.removeItem(_)}});return c(p,y),p},length:function(y){var l=this.keys().then(function(p){return p.length});return c(l,y),l},key:function(y,l){var p=this,m=p.ready().then(function(){var v,_=p._dbInfo;try{v=localStorage.key(y)}catch{v=null}return v&&(v=v.substring(_.keyPrefix.length)),v});return c(m,l),m},keys:function(y){var l=this,p=l.ready().then(function(){for(var m=l._dbInfo,v=localStorage.length,_=[],S=0;S<v;S++){var C=localStorage.key(S);C.indexOf(m.keyPrefix)===0&&_.push(C.substring(m.keyPrefix.length))}return _});return c(p,y),p},dropInstance:function(y,l){if(l=h.apply(this,arguments),!(y=typeof y!="function"&&y||{}).name){var p=this.config();y.name=y.name||p.name,y.storeName=y.storeName||p.storeName}var m,v=this;return c(m=y.name?new d(function(_){y.storeName?_(Ae(y,v._defaultConfig)):_(y.name+"/")}).then(function(_){for(var S=localStorage.length-1;S>=0;S--){var C=localStorage.key(S);C.indexOf(_)===0&&localStorage.removeItem(C)}}):d.reject("Invalid arguments"),l),m}},Ht=function(y,l){for(var p,m,v=y.length,_=0;_<v;){if((p=y[_])===(m=l)||typeof p=="number"&&typeof m=="number"&&isNaN(p)&&isNaN(m))return!0;_++}return!1},Dt=Array.isArray||function(y){return Object.prototype.toString.call(y)==="[object Array]"},Xe={},Te={},Ie={INDEXEDDB:Z,WEBSQL:_e,LOCALSTORAGE:Ge},Ne=[Ie.INDEXEDDB._driver,Ie.WEBSQL._driver,Ie.LOCALSTORAGE._driver],Be=["dropInstance"],Fe=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(Be),nt={description:"",driver:Ne.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function At(y,l){y[l]=function(){var p=arguments;return y.ready().then(function(){return y[l].apply(y,p)})}}function ct(){for(var y=1;y<arguments.length;y++){var l=arguments[y];if(l)for(var p in l)l.hasOwnProperty(p)&&(Dt(l[p])?arguments[0][p]=l[p].slice():arguments[0][p]=l[p])}return arguments[0]}var ut=new(function(){function y(l){for(var p in function(_,S){if(!(_ instanceof S))throw new TypeError("Cannot call a class as a function")}(this,y),Ie)if(Ie.hasOwnProperty(p)){var m=Ie[p],v=m._driver;this[p]=v,Xe[v]||this.defineDriver(m)}this._defaultConfig=ct({},nt),this._config=ct({},this._defaultConfig,l),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch(function(){})}return y.prototype.config=function(l){if((l===void 0?"undefined":o(l))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var p in l){if(p==="storeName"&&(l[p]=l[p].replace(/\W/g,"_")),p==="version"&&typeof l[p]!="number")return new Error("Database version must be a number.");this._config[p]=l[p]}return!("driver"in l)||!l.driver||this.setDriver(this._config.driver)}return typeof l=="string"?this._config[l]:this._config},y.prototype.defineDriver=function(l,p,m){var v=new d(function(_,S){try{var C=l._driver,R=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!l._driver)return void S(R);for(var D=Fe.concat("_initStorage"),A=0,M=D.length;A<M;A++){var N=D[A];if((!Ht(Be,N)||l[N])&&typeof l[N]!="function")return void S(R)}(function(){for(var q=function(ar){return function(){var cs=new Error("Method "+ar+" is not implemented by the current driver"),ii=d.reject(cs);return c(ii,arguments[arguments.length-1]),ii}},Q=0,ve=Be.length;Q<ve;Q++){var Ze=Be[Q];l[Ze]||(l[Ze]=q(Ze))}})();var H=function(q){Xe[C]&&console.info("Redefining LocalForage driver: "+C),Xe[C]=l,Te[C]=q,_()};"_support"in l?l._support&&typeof l._support=="function"?l._support().then(H,S):H(!!l._support):H(!0)}catch(q){S(q)}});return u(v,p,m),v},y.prototype.driver=function(){return this._driver||null},y.prototype.getDriver=function(l,p,m){var v=Xe[l]?d.resolve(Xe[l]):d.reject(new Error("Driver not found."));return u(v,p,m),v},y.prototype.getSerializer=function(l){var p=d.resolve(be);return u(p,l),p},y.prototype.ready=function(l){var p=this,m=p._driverSet.then(function(){return p._ready===null&&(p._ready=p._initDriver()),p._ready});return u(m,l,l),m},y.prototype.setDriver=function(l,p,m){var v=this;Dt(l)||(l=[l]);var _=this._getSupportedDrivers(l);function S(){v._config.driver=v.driver()}function C(D){return v._extend(D),S(),v._ready=v._initStorage(v._config),v._ready}var R=this._driverSet!==null?this._driverSet.catch(function(){return d.resolve()}):d.resolve();return this._driverSet=R.then(function(){var D=_[0];return v._dbInfo=null,v._ready=null,v.getDriver(D).then(function(A){v._driver=A._driver,S(),v._wrapLibraryMethodsWithReady(),v._initDriver=function(M){return function(){var N=0;return function H(){for(;N<M.length;){var q=M[N];return N++,v._dbInfo=null,v._ready=null,v.getDriver(q).then(C).catch(H)}S();var Q=new Error("No available storage method found.");return v._driverSet=d.reject(Q),v._driverSet}()}}(_)})}).catch(function(){S();var D=new Error("No available storage method found.");return v._driverSet=d.reject(D),v._driverSet}),u(this._driverSet,p,m),this._driverSet},y.prototype.supports=function(l){return!!Te[l]},y.prototype._extend=function(l){ct(this,l)},y.prototype._getSupportedDrivers=function(l){for(var p=[],m=0,v=l.length;m<v;m++){var _=l[m];this.supports(_)&&p.push(_)}return p},y.prototype._wrapLibraryMethodsWithReady=function(){for(var l=0,p=Fe.length;l<p;l++)At(this,Fe[l])},y.prototype.createInstance=function(l){return new y(l)},y}());n.exports=ut},{3:3}]},{},[4])(4)}),Km=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}(),Wm=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}(),Jm=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}(),Xm=function(){function r(e,t){return this.dbStorage=Bi.createInstance({driver:[Bi.INDEXEDDB,Bi.LOCALSTORAGE],name:e,storeName:t}),this.dbStorage}return r.prototype.getItem=function(e){return Pi(this,void 0,void 0,function(){var t,n;return Li(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}(),Zm=function(){function r(){this.defaultExpireTime=6048e5,this.local=new Wm,this.session=new Jm,this.cache=new Km}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 Vr.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;Vr.set(e,t,{expires:new Date(a),path:"/",domain:o})}catch{}},r.prototype.removeCookie=function(e,t){try{Vr.remove(e,{path:"/",domain:t||""})}catch{}},r}(),Ym=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?Gi(i).hostname:"",a=Pn(window.location.href),s=/Mobile|htc|mini|Android|iP(ad|od|hone)/.test(this.appVersion)?"wap":"web",d=((e=window.navigator.connection)===null||e===void 0?void 0:e.effectiveType)||"";this.utm=function(f,h,g,k){var z=new Zm,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(),u=this.os();return{browser:c.browser,browser_version:c.browser_version,platform:s,os_name:u.os_name,os_version:u.os_version,userAgent:t,screen_width:window.screen&&window.screen.width,screen_height:window.screen&&window.screen.height,device_model:this.getDeviceModel(u.os_name),language:n,referrer:i,referrer_host:o,network_type:d,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 d=Pn(e);d.keyword&&(o=d.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 d,c;switch(e){case"Mac OS X":t=s("Mac[ +]OS[ +]X(?:[ /](?:Version )?(\\d+(?:[_\\.]\\d+)+))?",this.userAgent),e="mac";break;case"Android":d=this.userAgent,(c=a(/Android ([\.\_\d]+)/,d))||(c=a(/Android\/([\.\_\d]+)/,d)),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 u=this.userAgent.indexOf("x86_64");t=this.userAgent.substring(u+7,u+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}(),Fi=function(r,e){try{return Vr.get(r)}catch{return""}},Vi=function(r,e,t,n){try{var i=n||document.domain,o=+new Date+(t||6048e5);Vr.set(r,e,{expires:new Date(o),path:"/",domain:i})}catch{}},Qm=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 Fi(e)},r.prototype.setCookie=function(e,t,n,i){Vi(e,t,n,i)},r}(),ji,x,La={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 Fi(r)},setCookie:function(r,e,t,n){Vi(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}}()},eg={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 Fi(r)},setCookie:function(r,e,t,n){Vi(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}}()},Xt=function(){function r(e,t){this._storage=t&&t==="session"?eg:!e&&La.isSupportLS?La:new Qm}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}(),Hi={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"},Ua=function(){return new Set(Object.keys(Hi))},$i=function(){return Object.keys(Hi)},Ga={sg:"1fz22z22z1nz21z4mz4bz4bz21z1ez18z1jz1gz49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz18z1jz1gz24z18z49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",my:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z19z1bz49z1kz27z4az1jz18z20z1iz1mz1dz1dz1gz1az1cz4az1az1mz1k"},qi={va:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",in:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k"},tg={sg:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z21z1ez4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",in:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z49z23z21z1cz18z21z22z4ez18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",ie2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z1gz1cz4ez4az22z1gz1iz22z1mz1iz25z4az1cz23"},rg={sg:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz25z4az23z21",va:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az22z1gz1iz22z1mz1iz24z4az23z21",ie2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z1gz1cz4ez4az22z1gz1iz22z1mz1iz25z4az1cz23"},jr="5.3.11_oversea",ng=["1fz22z22z1nz21z4mz4bz4bz1bz18z22z18z4az19z27z22z1cz1bz18z1lz1az1cz4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z1cz23z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z23z21z22z21z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z21z1ez4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22"].map(function(r){return Br(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.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.SubmitAfter="submit-after",r.SubmitError="submit-error",r.SubmitVerify="submit-verify",r.DestoryInstance="destory-instance",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"})(ji||(ji={})),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"}(x||(x={}));var F=ji,ne=void 0,Na=new Date().getTimezoneOffset(),ig=parseInt(""+-Na/60,10),og=60*Na,sg=function(){function r(e,t){var n=this;this.is_first_time=!0,this.configPersist=!1,this.initConfig=t,this.collect=e;var i=new Ym(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 Xt(!1,"session"),this.localStorage=new Xt(!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:ne,user_type:ne,user_id:ne,user_is_auth:ne,user_is_login:ne,device_id:ne,web_id:ne,ip_addr_id:ne,user_unique_id_type:ne},header:{app_id:ne,app_name:ne,app_install_id:ne,install_id:ne,app_package:ne,app_channel:ne,app_version:ne,ab_version:ne,os_name:i.os_name,os_version:i.os_version,device_model:i.device_model,ab_client:ne,traffic_type:ne,network_type:i.network_type,client_ip:ne,device_brand:ne,os_api:ne,access:ne,language:i.language,region:ne,app_language:ne,app_region:ne,creative_id:i.utm.creative_id,ad_id:i.utm.ad_id,campaign_id:i.utm.campaign_id,log_type:ne,rnd:ne,platform:i.platform,sdk_version:jr,sdk_lib:"js",province:ne,city:ne,timezone:ig,tz_offset:og,tz_name:ne,sim_region:ne,carrier:ne,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)})}return r.prototype.initDomain=function(e){var t=this.initConfig.channel_domain;if(t)this.domain=t;else{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=Ga.sg),this.domain=Br(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 Ua().has(i)?Hi[i]:((t=this.initConfig)===null||t===void 0?void 0:t.channel_type)==="tcpy"?tg[i]:((n=this.initConfig)===null||n===void 0?void 0:n.channel_type)==="ttp"?rg[i]:Ga[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.11_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.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=me(me({},t.evtParams||{}),e.evtParams||{});else if(n==="_staging_flag")t.evtParams=me(me({},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(x.DEBUGGER_MESSAGE,{type:x.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(x.DEBUGGER_MESSAGE,{type:x.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(x.DEBUGGER_MESSAGE,{type:x.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(x.DEBUGGER_MESSAGE,{type:x.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(x.DEBUGGER_MESSAGE,{type:x.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(x.DEBUGGER_MESSAGE,{type:x.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(x.DEBUGGER_MESSAGE,{type:x.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(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:n.message,infoType:"sdk"}),console.log("delete error")}},r}(),ag=function(){function r(e,t){this.isLog=t||!1,this.name=e||""}return r.prototype.info=function(e){this.isLog&&console.log("%c %s","color: yellow; background-color: black;","[Tea instance: "+this.name+"] "+e)},r.prototype.warn=function(e){this.isLog&&console.warn("%c %s","color: #4D1B00;","[Tea instance: "+this.name+"] "+e)},r.prototype.error=function(e){this.isLog&&console.error("%c %s","color: #FFF; background-color: #F53F3F;","[Tea instance: "+this.name+"] "+e)},r.prototype.throw=function(e){throw this.error(this.name),new Error(e)},r}(),cg=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}(),ug=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}(),dg=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 Xm(this.setKey,"LOGSETTING_DATA_STORE"),this.domain=t.logsetting_domain||this.collect.configManager.getDomain(),this.check()}else e.emit(F.LogSettingReady)},r.prototype.check=function(){return Pi(this,void 0,void 0,function(){var e;return Li(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(F.LogSettingReady)):this.fetchSetting(),[3,3];case 2:return t.sent(),this.collect.emit(F.LogSettingReady),this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.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(F.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:me(me({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(x.DEBUGGER_MESSAGE,{type:x.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(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"LogSetting Request Success",logType:"fetch",level:"info",time:Date.now(),data:a,infoType:"sdk"})):t.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"LogSetting Request Response No Data",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"}),t.collect.emit(F.LogSettingReady)},fail:function(){t.collect.emit(F.LogSettingReady),t.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"LogSetting Request Fail",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"})}})}},r.prototype.getLocalData=function(){return Pi(this,void 0,void 0,function(){return Li(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(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Update LogSetting Cache",logType:"info",level:"info",time:Date.now(),infoType:"sdk",data:e})}catch{this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.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}(),lg=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 Xt(!0),this.localStorage=new Xt(!1),this.logSetting=new dg,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(F.Ready,function(){n.reportAll(!1)}),this.collect.on(F.ConfigDomain,function(){n.reportUrl=n.configManager.getUrl("event")}),this.collect.on(F.Event,function(i){n.event(i)}),this.collect.on(F.BeconEvent,function(i){n.beconEvent(i)}),this.collect.on(F.CleanEvents,function(){n.reportAll(!1)}),this.linster()},r.prototype.linster=function(){var e=this;window.addEventListener("unload",function(){e.reportAll(!0)},!1),Fr(function(){e.reportAll(!0)}),document.addEventListener("visibilitychange",function(){document.visibilityState==="hidden"&&e.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&&Ma())return void this.beconEvent(e);var n=Gr(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(x.DEBUGGER_MESSAGE,{type:x.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=Gr(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(F.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(F.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(F.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(F.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"),d=this.configManager.get("user_unique_id_type"),c=[];try{var u=e.filter(function(h){try{Object.keys(s).length&&(h.params=me(me({},s),h.params)),d&&(h.params.$user_unique_id_type=d);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(x.DEBUGGER_MESSAGE,{type:x.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:u,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(x.DEBUGGER_MESSAGE,{type:x.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 d in o)!this.logSetting.getPredefineParamsList().has(d)&&s.has(d)||(a[d]=o[d]);return JSON.stringify(a)}return JSON.stringify(e.params)}catch(c){return this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.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 d=!0;if(a.forEach(function(c){c.events.length||(d=!1)}),!d)return;n.collect.emit(F.SubmitBefore,a),n.collect.requestManager.useRequest({url:n.reportUrl,data:a,success:function(c,u){c&&c.e!==0?(n.collect.emit(F.SubmitError,{type:"f_data",eventData:u,errorCode:c.e,response:c}),n.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_EVENT,info:"Event Report Fail",time:Date.now(),data:s,code:c.e,failType:"event data error",status:"fail"})):(n.collect.emit(F.SubmitScuess,{eventData:u,res:c}),n.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_EVENT,info:"Event Report Success",time:Date.now(),data:s,code:200,status:"success"}))},fail:function(c,u){n.configManager.get("reportErrorCallback")(c,u),n.collect.emit(F.SubmitError,{type:"f_net",eventData:c,errorCode:u}),n.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_EVENT,info:"Event Report Network Fail",time:Date.now(),data:s,code:u,failType:"network error",status:"fail"})},timeout:n.timeout,useBeacon:!n.config.disable_sendbeacon&&t,withCredentials:n.enable_ttwebid,zip:!0}),n.collect.emit(F.SubmitAfter,a)}catch(c){console.warn("something error, "+JSON.stringify(c.stack)),n.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Report Event Something Error",level:"error",time:Date.now(),data:c.message})}}))},r}(),Un=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)},hg=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 Xt(!1),this.tokenKey="__tea_cache_tokens_"+t.app_id,this.enable_ttwebid=t.enable_ttwebid,this.enableCustomWebid=t.enable_custom_webid,this.collect.on(F.ConfigUuid,function(i){n.setUuid(i)}),this.collect.on(F.ConfigWebId,function(i){n.setWebId(i)}),this.collect.on(F.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(F.CustomWebId,function(){e.tokenReady=!0,e.collect.emit(F.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:Un(),user_unique_id:this.configManager.get("user_unique_id")||Un()}):this.remoteWebid()},r.prototype.checkEnv=function(){var e=window.navigator.userAgent;if(e.indexOf("miniProgram")!==-1||e.indexOf("MiniProgram")!==-1){var t=Pn(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(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch WebID Request",logType:"fetch",level:"info",time:Date.now(),data:n});var i=Un();this.collect.requestManager.useRequest({url:t,data:n,success:function(o){var a;o&&o.e===0?(a=o.web_id,e.collect.emit(x.DEBUGGER_MESSAGE,{type:x.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(F.TokenError),e.collect.emit(x.DEBUGGER_MESSAGE,{type:x.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(F.TokenError),e.collect.emit(x.DEBUGGER_MESSAGE,{type:x.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=me(me({},e),{device_id:o})}else delete e.device_id;this.setStorage(e),this.tokenReady=!0,this.collect.emit(x.DEBUGGER_MESSAGE,{type:x.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(F.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(F.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(F.TokenChange,"uuid"),this.collect.emit(F.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(F.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(F.TokenChange,"uuid")),t!==e&&(this.configManager.set({web_id:e}),this.collect.emit(F.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){if(e.config.channel_type!=="tcpy"&&e.config.channel_type!=="ttp"){var n={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(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch GetToken Request",logType:"fetch",level:"info",time:Date.now(),data:n,infoType:"sdk"}),e.collect.requestManager.useRequest({url:e.configManager.getUrl("tobid"),data:n,success:function(i){i&&i.e===0?(t(i.tobid),e.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"Fetch GetToken Request Success",logType:"fetch",level:"info",time:Date.now(),data:i,infoType:"sdk"})):(t(""),e.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"Fetch GetToken Request Fail",logType:"fetch",level:"error",time:Date.now(),data:i,infoType:"sdk"}))},fail:function(){t(""),e.collect.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"Fetch GetToken Request Network Error",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"})},time:3e4,withCredentials:e.enable_ttwebid})}else t("")})},r}(),Hr=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)})},fg=function(){function r(){}return r.prototype.apply=function(e,t){var n=this;this.collect=e,this.storage=new Xt(!1,"session"),this.sessionKey="__tea_session_id_"+t.app_id,this.expireTime=t.expireTime||18e5,this.disableSession=t.disable_session,this.disableSessionTimeCheck=t.disable_session_check,this.disableSession||(this.setSessionId(),this.collect.on(F.SessionReset,function(i){n.resetSessionId(i)}),this.collect.on(F.SessionResetTime,function(){n.updateSessionIdTime()}))},r.prototype.updateSessionIdTime=function(){var e=this.storage.getItem(this.sessionKey);if(e&&e.sessionId){var t=e.timestamp;Date.now()-t>this.expireTime?e={sessionId:Hr(),timestamp:Date.now()}:e.timestamp=Date.now(),this.storage.setItem(this.sessionKey,e),this.resetExpTime()}},r.prototype.setSessionId=function(){var e=this,t=this.storage.getItem(this.sessionKey);t&&t.sessionId?t.timestamp=Date.now():t={sessionId:Hr(),timestamp:Date.now()},this.storage.setItem(this.sessionKey,t),this.disableSessionTimeCheck||(this.sessionExp=setInterval(function(){e.checkEXp()},this.expireTime))},r.prototype.getSessionId=function(){var e=this.storage.getItem(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(e){var t={sessionId:e||Hr(),timestamp:Date.now()};this.storage.setItem(this.sessionKey,t)},r.prototype.checkEXp=function(){var e=this.storage.getItem(this.sessionKey);e&&e.sessionId&&Date.now()-e.timestamp+30>=this.expireTime&&(e={sessionId:Hr(),timestamp:Date.now()},this.storage.setItem(this.sessionKey,e))},r}();function mr(r){let e=r.length;for(;--e>=0;)r[e]=0}const Ki=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Gn=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),pg=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),Ba=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),kt=new Array(576);mr(kt);const $r=new Array(60);mr($r);const qr=new Array(512);mr(qr);const Kr=new Array(256);mr(Kr);const Wi=new Array(29);mr(Wi);const Nn=new Array(30);function Ji(r,e,t,n,i){this.static_tree=r,this.extra_bits=e,this.extra_base=t,this.elems=n,this.max_length=i,this.has_stree=r&&r.length}let Fa,Va,ja;function Xi(r,e){this.dyn_tree=r,this.max_code=0,this.stat_desc=e}mr(Nn);const Ha=r=>r<256?qr[r]:qr[256+(r>>>7)],Wr=(r,e)=>{r.pending_buf[r.pending++]=255&e,r.pending_buf[r.pending++]=e>>>8&255},je=(r,e,t)=>{r.bi_valid>16-t?(r.bi_buf|=e<<r.bi_valid&65535,Wr(r,r.bi_buf),r.bi_buf=e>>16-r.bi_valid,r.bi_valid+=t-16):(r.bi_buf|=e<<r.bi_valid&65535,r.bi_valid+=t)},ht=(r,e,t)=>{je(r,t[2*e],t[2*e+1])},$a=(r,e)=>{let t=0;do t|=1&r,r>>>=1,t<<=1;while(--e>0);return t>>>1},qa=(r,e,t)=>{const n=new Array(16);let i,o,a=0;for(i=1;i<=15;i++)a=a+t[i-1]<<1,n[i]=a;for(o=0;o<=e;o++){let s=r[2*o+1];s!==0&&(r[2*o]=$a(n[s]++,s))}},Ka=r=>{let e;for(e=0;e<286;e++)r.dyn_ltree[2*e]=0;for(e=0;e<30;e++)r.dyn_dtree[2*e]=0;for(e=0;e<19;e++)r.bl_tree[2*e]=0;r.dyn_ltree[512]=1,r.opt_len=r.static_len=0,r.sym_next=r.matches=0},Wa=r=>{r.bi_valid>8?Wr(r,r.bi_buf):r.bi_valid>0&&(r.pending_buf[r.pending++]=r.bi_buf),r.bi_buf=0,r.bi_valid=0},Ja=(r,e,t,n)=>{const i=2*e,o=2*t;return r[i]<r[o]||r[i]===r[o]&&n[e]<=n[t]},Zi=(r,e,t)=>{const n=r.heap[t];let i=t<<1;for(;i<=r.heap_len&&(i<r.heap_len&&Ja(e,r.heap[i+1],r.heap[i],r.depth)&&i++,!Ja(e,n,r.heap[i],r.depth));)r.heap[t]=r.heap[i],t=i,i<<=1;r.heap[t]=n},Xa=(r,e,t)=>{let n,i,o,a,s=0;if(r.sym_next!==0)do n=255&r.pending_buf[r.sym_buf+s++],n+=(255&r.pending_buf[r.sym_buf+s++])<<8,i=r.pending_buf[r.sym_buf+s++],n===0?ht(r,i,e):(o=Kr[i],ht(r,o+256+1,e),a=Ki[o],a!==0&&(i-=Wi[o],je(r,i,a)),n--,o=Ha(n),ht(r,o,t),a=Gn[o],a!==0&&(n-=Nn[o],je(r,n,a)));while(s<r.sym_next);ht(r,256,e)},Yi=(r,e)=>{const t=e.dyn_tree,n=e.stat_desc.static_tree,i=e.stat_desc.has_stree,o=e.stat_desc.elems;let a,s,d,c=-1;for(r.heap_len=0,r.heap_max=573,a=0;a<o;a++)t[2*a]!==0?(r.heap[++r.heap_len]=c=a,r.depth[a]=0):t[2*a+1]=0;for(;r.heap_len<2;)d=r.heap[++r.heap_len]=c<2?++c:0,t[2*d]=1,r.depth[d]=0,r.opt_len--,i&&(r.static_len-=n[2*d+1]);for(e.max_code=c,a=r.heap_len>>1;a>=1;a--)Zi(r,t,a);d=o;do a=r.heap[1],r.heap[1]=r.heap[r.heap_len--],Zi(r,t,1),s=r.heap[1],r.heap[--r.heap_max]=a,r.heap[--r.heap_max]=s,t[2*d]=t[2*a]+t[2*s],r.depth[d]=(r.depth[a]>=r.depth[s]?r.depth[a]:r.depth[s])+1,t[2*a+1]=t[2*s+1]=d,r.heap[1]=d++,Zi(r,t,1);while(r.heap_len>=2);r.heap[--r.heap_max]=r.heap[1],((u,f)=>{const h=f.dyn_tree,g=f.max_code,k=f.stat_desc.static_tree,z=f.stat_desc.has_stree,w=f.stat_desc.extra_bits,b=f.stat_desc.extra_base,T=f.stat_desc.max_length;let E,O,G,I,U,L,j=0;for(I=0;I<=15;I++)u.bl_count[I]=0;for(h[2*u.heap[u.heap_max]+1]=0,E=u.heap_max+1;E<573;E++)O=u.heap[E],I=h[2*h[2*O+1]+1]+1,I>T&&(I=T,j++),h[2*O+1]=I,O>g||(u.bl_count[I]++,U=0,O>=b&&(U=w[O-b]),L=h[2*O],u.opt_len+=L*(I+U),z&&(u.static_len+=L*(k[2*O+1]+U)));if(j!==0){do{for(I=T-1;u.bl_count[I]===0;)I--;u.bl_count[I]--,u.bl_count[I+1]+=2,u.bl_count[T]--,j-=2}while(j>0);for(I=T;I!==0;I--)for(O=u.bl_count[I];O!==0;)G=u.heap[--E],G>g||(h[2*G+1]!==I&&(u.opt_len+=(I-h[2*G+1])*h[2*G],h[2*G+1]=I),O--)}})(r,e),qa(t,c,r.bl_count)},Za=(r,e,t)=>{let n,i,o=-1,a=e[1],s=0,d=7,c=4;for(a===0&&(d=138,c=3),e[2*(t+1)+1]=65535,n=0;n<=t;n++)i=a,a=e[2*(n+1)+1],++s<d&&i===a||(s<c?r.bl_tree[2*i]+=s:i!==0?(i!==o&&r.bl_tree[2*i]++,r.bl_tree[32]++):s<=10?r.bl_tree[34]++:r.bl_tree[36]++,s=0,o=i,a===0?(d=138,c=3):i===a?(d=6,c=3):(d=7,c=4))},Ya=(r,e,t)=>{let n,i,o=-1,a=e[1],s=0,d=7,c=4;for(a===0&&(d=138,c=3),n=0;n<=t;n++)if(i=a,a=e[2*(n+1)+1],!(++s<d&&i===a)){if(s<c)do ht(r,i,r.bl_tree);while(--s!=0);else i!==0?(i!==o&&(ht(r,i,r.bl_tree),s--),ht(r,16,r.bl_tree),je(r,s-3,2)):s<=10?(ht(r,17,r.bl_tree),je(r,s-3,3)):(ht(r,18,r.bl_tree),je(r,s-11,7));s=0,o=i,a===0?(d=138,c=3):i===a?(d=6,c=3):(d=7,c=4)}};let Qa=!1;const ec=(r,e,t,n)=>{je(r,0+(n?1:0),3),Wa(r),Wr(r,t),Wr(r,~t),t&&r.pending_buf.set(r.window.subarray(e,e+t),r.pending),r.pending+=t};var mg={_tr_init:r=>{Qa||((()=>{let e,t,n,i,o;const a=new Array(16);for(n=0,i=0;i<28;i++)for(Wi[i]=n,e=0;e<1<<Ki[i];e++)Kr[n++]=i;for(Kr[n-1]=i,o=0,i=0;i<16;i++)for(Nn[i]=o,e=0;e<1<<Gn[i];e++)qr[o++]=i;for(o>>=7;i<30;i++)for(Nn[i]=o<<7,e=0;e<1<<Gn[i]-7;e++)qr[256+o++]=i;for(t=0;t<=15;t++)a[t]=0;for(e=0;e<=143;)kt[2*e+1]=8,e++,a[8]++;for(;e<=255;)kt[2*e+1]=9,e++,a[9]++;for(;e<=279;)kt[2*e+1]=7,e++,a[7]++;for(;e<=287;)kt[2*e+1]=8,e++,a[8]++;for(qa(kt,287,a),e=0;e<30;e++)$r[2*e+1]=5,$r[2*e]=$a(e,5);Fa=new Ji(kt,Ki,257,286,15),Va=new Ji($r,Gn,0,30,15),ja=new Ji(new Array(0),pg,0,19,7)})(),Qa=!0),r.l_desc=new Xi(r.dyn_ltree,Fa),r.d_desc=new Xi(r.dyn_dtree,Va),r.bl_desc=new Xi(r.bl_tree,ja),r.bi_buf=0,r.bi_valid=0,Ka(r)},_tr_stored_block:ec,_tr_flush_block:(r,e,t,n)=>{let i,o,a=0;r.level>0?(r.strm.data_type===2&&(r.strm.data_type=(s=>{let d,c=4093624447;for(d=0;d<=31;d++,c>>>=1)if(1&c&&s.dyn_ltree[2*d]!==0)return 0;if(s.dyn_ltree[18]!==0||s.dyn_ltree[20]!==0||s.dyn_ltree[26]!==0)return 1;for(d=32;d<256;d++)if(s.dyn_ltree[2*d]!==0)return 1;return 0})(r)),Yi(r,r.l_desc),Yi(r,r.d_desc),a=(s=>{let d;for(Za(s,s.dyn_ltree,s.l_desc.max_code),Za(s,s.dyn_dtree,s.d_desc.max_code),Yi(s,s.bl_desc),d=18;d>=3&&s.bl_tree[2*Ba[d]+1]===0;d--);return s.opt_len+=3*(d+1)+5+5+4,d})(r),i=r.opt_len+3+7>>>3,o=r.static_len+3+7>>>3,o<=i&&(i=o)):i=o=t+5,t+4<=i&&e!==-1?ec(r,e,t,n):r.strategy===4||o===i?(je(r,2+(n?1:0),3),Xa(r,kt,$r)):(je(r,4+(n?1:0),3),((s,d,c,u)=>{let f;for(je(s,d-257,5),je(s,c-1,5),je(s,u-4,4),f=0;f<u;f++)je(s,s.bl_tree[2*Ba[f]+1],3);Ya(s,s.dyn_ltree,d-1),Ya(s,s.dyn_dtree,c-1)})(r,r.l_desc.max_code+1,r.d_desc.max_code+1,a+1),Xa(r,r.dyn_ltree,r.dyn_dtree)),Ka(r),n&&Wa(r)},_tr_tally:(r,e,t)=>(r.pending_buf[r.sym_buf+r.sym_next++]=e,r.pending_buf[r.sym_buf+r.sym_next++]=e>>8,r.pending_buf[r.sym_buf+r.sym_next++]=t,e===0?r.dyn_ltree[2*t]++:(r.matches++,e--,r.dyn_ltree[2*(Kr[t]+256+1)]++,r.dyn_dtree[2*Ha(e)]++),r.sym_next===r.sym_end),_tr_align:r=>{je(r,2,3),ht(r,256,kt),(e=>{e.bi_valid===16?(Wr(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(r)}},Jr=(r,e,t,n)=>{let i=65535&r|0,o=r>>>16&65535|0,a=0;for(;t!==0;){a=t>2e3?2e3:t,t-=a;do i=i+e[n++]|0,o=o+i|0;while(--a);i%=65521,o%=65521}return i|o<<16|0};const gg=new Uint32Array((()=>{let r,e=[];for(var t=0;t<256;t++){r=t;for(var n=0;n<8;n++)r=1&r?3988292384^r>>>1:r>>>1;e[t]=r}return e})());var Re=(r,e,t,n)=>{const i=gg,o=n+t;r^=-1;for(let a=n;a<o;a++)r=r>>>8^i[255&(r^e[a])];return-1^r},Zt={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},Yt={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:_g,_tr_stored_block:Qi,_tr_flush_block:vg,_tr_tally:Pt,_tr_align:yg}=mg,{Z_NO_FLUSH:Lt,Z_PARTIAL_FLUSH:Sg,Z_FULL_FLUSH:bg,Z_FINISH:Ye,Z_BLOCK:tc,Z_OK:Me,Z_STREAM_END:rc,Z_STREAM_ERROR:ft,Z_DATA_ERROR:Eg,Z_BUF_ERROR:eo,Z_DEFAULT_COMPRESSION:wg,Z_FILTERED:Cg,Z_HUFFMAN_ONLY:Bn,Z_RLE:kg,Z_FIXED:Tg,Z_DEFAULT_STRATEGY:zg,Z_UNKNOWN:Rg,Z_DEFLATED:Fn}=Yt,Qt=(r,e)=>(r.msg=Zt[e],e),nc=r=>2*r-(r>4?9:0),Ut=r=>{let e=r.length;for(;--e>=0;)r[e]=0},Dg=r=>{let e,t,n,i=r.w_size;e=r.hash_size,n=e;do t=r.head[--n],r.head[n]=t>=i?t-i:0;while(--e);e=i,n=e;do t=r.prev[--n],r.prev[n]=t>=i?t-i:0;while(--e)};let Gt=(r,e,t)=>(e<<r.hash_shift^t)&r.hash_mask;const Ke=r=>{const e=r.state;let t=e.pending;t>r.avail_out&&(t=r.avail_out),t!==0&&(r.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+t),r.next_out),r.next_out+=t,e.pending_out+=t,r.total_out+=t,r.avail_out-=t,e.pending-=t,e.pending===0&&(e.pending_out=0))},We=(r,e)=>{vg(r,r.block_start>=0?r.block_start:-1,r.strstart-r.block_start,e),r.block_start=r.strstart,Ke(r.strm)},ce=(r,e)=>{r.pending_buf[r.pending++]=e},Xr=(r,e)=>{r.pending_buf[r.pending++]=e>>>8&255,r.pending_buf[r.pending++]=255&e},to=(r,e,t,n)=>{let i=r.avail_in;return i>n&&(i=n),i===0?0:(r.avail_in-=i,e.set(r.input.subarray(r.next_in,r.next_in+i),t),r.state.wrap===1?r.adler=Jr(r.adler,e,i,t):r.state.wrap===2&&(r.adler=Re(r.adler,e,i,t)),r.next_in+=i,r.total_in+=i,i)},ic=(r,e)=>{let t,n,i=r.max_chain_length,o=r.strstart,a=r.prev_length,s=r.nice_match;const d=r.strstart>r.w_size-262?r.strstart-(r.w_size-262):0,c=r.window,u=r.w_mask,f=r.prev,h=r.strstart+258;let g=c[o+a-1],k=c[o+a];r.prev_length>=r.good_match&&(i>>=2),s>r.lookahead&&(s=r.lookahead);do if(t=e,c[t+a]===k&&c[t+a-1]===g&&c[t]===c[o]&&c[++t]===c[o+1]){o+=2,t++;do;while(c[++o]===c[++t]&&c[++o]===c[++t]&&c[++o]===c[++t]&&c[++o]===c[++t]&&c[++o]===c[++t]&&c[++o]===c[++t]&&c[++o]===c[++t]&&c[++o]===c[++t]&&o<h);if(n=258-(h-o),o=h-258,n>a){if(r.match_start=e,a=n,n>=s)break;g=c[o+a-1],k=c[o+a]}}while((e=f[e&u])>d&&--i!=0);return a<=r.lookahead?a:r.lookahead},gr=r=>{const e=r.w_size;let t,n,i;do{if(n=r.window_size-r.lookahead-r.strstart,r.strstart>=e+(e-262)&&(r.window.set(r.window.subarray(e,e+e-n),0),r.match_start-=e,r.strstart-=e,r.block_start-=e,r.insert>r.strstart&&(r.insert=r.strstart),Dg(r),n+=e),r.strm.avail_in===0)break;if(t=to(r.strm,r.window,r.strstart+r.lookahead,n),r.lookahead+=t,r.lookahead+r.insert>=3)for(i=r.strstart-r.insert,r.ins_h=r.window[i],r.ins_h=Gt(r,r.ins_h,r.window[i+1]);r.insert&&(r.ins_h=Gt(r,r.ins_h,r.window[i+3-1]),r.prev[i&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=i,i++,r.insert--,!(r.lookahead+r.insert<3)););}while(r.lookahead<262&&r.strm.avail_in!==0)},oc=(r,e)=>{let t,n,i,o=r.pending_buf_size-5>r.w_size?r.w_size:r.pending_buf_size-5,a=0,s=r.strm.avail_in;do{if(t=65535,i=r.bi_valid+42>>3,r.strm.avail_out<i||(i=r.strm.avail_out-i,n=r.strstart-r.block_start,t>n+r.strm.avail_in&&(t=n+r.strm.avail_in),t>i&&(t=i),t<o&&(t===0&&e!==Ye||e===Lt||t!==n+r.strm.avail_in)))break;a=e===Ye&&t===n+r.strm.avail_in?1:0,Qi(r,0,0,a),r.pending_buf[r.pending-4]=t,r.pending_buf[r.pending-3]=t>>8,r.pending_buf[r.pending-2]=~t,r.pending_buf[r.pending-1]=~t>>8,Ke(r.strm),n&&(n>t&&(n=t),r.strm.output.set(r.window.subarray(r.block_start,r.block_start+n),r.strm.next_out),r.strm.next_out+=n,r.strm.avail_out-=n,r.strm.total_out+=n,r.block_start+=n,t-=n),t&&(to(r.strm,r.strm.output,r.strm.next_out,t),r.strm.next_out+=t,r.strm.avail_out-=t,r.strm.total_out+=t)}while(a===0);return s-=r.strm.avail_in,s&&(s>=r.w_size?(r.matches=2,r.window.set(r.strm.input.subarray(r.strm.next_in-r.w_size,r.strm.next_in),0),r.strstart=r.w_size,r.insert=r.strstart):(r.window_size-r.strstart<=s&&(r.strstart-=r.w_size,r.window.set(r.window.subarray(r.w_size,r.w_size+r.strstart),0),r.matches<2&&r.matches++,r.insert>r.strstart&&(r.insert=r.strstart)),r.window.set(r.strm.input.subarray(r.strm.next_in-s,r.strm.next_in),r.strstart),r.strstart+=s,r.insert+=s>r.w_size-r.insert?r.w_size-r.insert:s),r.block_start=r.strstart),r.high_water<r.strstart&&(r.high_water=r.strstart),a?4:e!==Lt&&e!==Ye&&r.strm.avail_in===0&&r.strstart===r.block_start?2:(i=r.window_size-r.strstart,r.strm.avail_in>i&&r.block_start>=r.w_size&&(r.block_start-=r.w_size,r.strstart-=r.w_size,r.window.set(r.window.subarray(r.w_size,r.w_size+r.strstart),0),r.matches<2&&r.matches++,i+=r.w_size,r.insert>r.strstart&&(r.insert=r.strstart)),i>r.strm.avail_in&&(i=r.strm.avail_in),i&&(to(r.strm,r.window,r.strstart,i),r.strstart+=i,r.insert+=i>r.w_size-r.insert?r.w_size-r.insert:i),r.high_water<r.strstart&&(r.high_water=r.strstart),i=r.bi_valid+42>>3,i=r.pending_buf_size-i>65535?65535:r.pending_buf_size-i,o=i>r.w_size?r.w_size:i,n=r.strstart-r.block_start,(n>=o||(n||e===Ye)&&e!==Lt&&r.strm.avail_in===0&&n<=i)&&(t=n>i?i:n,a=e===Ye&&r.strm.avail_in===0&&t===n?1:0,Qi(r,r.block_start,t,a),r.block_start+=t,Ke(r.strm)),a?3:1)},ro=(r,e)=>{let t,n;for(;;){if(r.lookahead<262){if(gr(r),r.lookahead<262&&e===Lt)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=Gt(r,r.ins_h,r.window[r.strstart+3-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart),t!==0&&r.strstart-t<=r.w_size-262&&(r.match_length=ic(r,t)),r.match_length>=3)if(n=Pt(r,r.strstart-r.match_start,r.match_length-3),r.lookahead-=r.match_length,r.match_length<=r.max_lazy_match&&r.lookahead>=3){r.match_length--;do r.strstart++,r.ins_h=Gt(r,r.ins_h,r.window[r.strstart+3-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart;while(--r.match_length!=0);r.strstart++}else r.strstart+=r.match_length,r.match_length=0,r.ins_h=r.window[r.strstart],r.ins_h=Gt(r,r.ins_h,r.window[r.strstart+1]);else n=Pt(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++;if(n&&(We(r,!1),r.strm.avail_out===0))return 1}return r.insert=r.strstart<2?r.strstart:2,e===Ye?(We(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(We(r,!1),r.strm.avail_out===0)?1:2},_r=(r,e)=>{let t,n,i;for(;;){if(r.lookahead<262){if(gr(r),r.lookahead<262&&e===Lt)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=Gt(r,r.ins_h,r.window[r.strstart+3-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart),r.prev_length=r.match_length,r.prev_match=r.match_start,r.match_length=2,t!==0&&r.prev_length<r.max_lazy_match&&r.strstart-t<=r.w_size-262&&(r.match_length=ic(r,t),r.match_length<=5&&(r.strategy===Cg||r.match_length===3&&r.strstart-r.match_start>4096)&&(r.match_length=2)),r.prev_length>=3&&r.match_length<=r.prev_length){i=r.strstart+r.lookahead-3,n=Pt(r,r.strstart-1-r.prev_match,r.prev_length-3),r.lookahead-=r.prev_length-1,r.prev_length-=2;do++r.strstart<=i&&(r.ins_h=Gt(r,r.ins_h,r.window[r.strstart+3-1]),t=r.prev[r.strstart&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=r.strstart);while(--r.prev_length!=0);if(r.match_available=0,r.match_length=2,r.strstart++,n&&(We(r,!1),r.strm.avail_out===0))return 1}else if(r.match_available){if(n=Pt(r,0,r.window[r.strstart-1]),n&&We(r,!1),r.strstart++,r.lookahead--,r.strm.avail_out===0)return 1}else r.match_available=1,r.strstart++,r.lookahead--}return r.match_available&&(n=Pt(r,0,r.window[r.strstart-1]),r.match_available=0),r.insert=r.strstart<2?r.strstart:2,e===Ye?(We(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(We(r,!1),r.strm.avail_out===0)?1:2};function pt(r,e,t,n,i){this.good_length=r,this.max_lazy=e,this.nice_length=t,this.max_chain=n,this.func=i}const Zr=[new pt(0,0,0,0,oc),new pt(4,4,8,4,ro),new pt(4,5,16,8,ro),new pt(4,6,32,32,ro),new pt(4,4,16,16,_r),new pt(8,16,32,32,_r),new pt(8,16,128,128,_r),new pt(8,32,128,256,_r),new pt(32,128,258,1024,_r),new pt(32,258,258,4096,_r)];function Ag(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Fn,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),Ut(this.dyn_ltree),Ut(this.dyn_dtree),Ut(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),Ut(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),Ut(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const Yr=r=>{if(!r)return 1;const e=r.state;return!e||e.strm!==r||e.status!==42&&e.status!==57&&e.status!==69&&e.status!==73&&e.status!==91&&e.status!==103&&e.status!==113&&e.status!==666?1:0},sc=r=>{if(Yr(r))return Qt(r,ft);r.total_in=r.total_out=0,r.data_type=Rg;const e=r.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap===2?57:e.wrap?42:113,r.adler=e.wrap===2?0:1,e.last_flush=-2,_g(e),Me},ac=r=>{const e=sc(r);var t;return e===Me&&((t=r.state).window_size=2*t.w_size,Ut(t.head),t.max_lazy_match=Zr[t.level].max_lazy,t.good_match=Zr[t.level].good_length,t.nice_match=Zr[t.level].nice_length,t.max_chain_length=Zr[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=2,t.match_available=0,t.ins_h=0),e},cc=(r,e,t,n,i,o)=>{if(!r)return ft;let a=1;if(e===wg&&(e=6),n<0?(a=0,n=-n):n>15&&(a=2,n-=16),i<1||i>9||t!==Fn||n<8||n>15||e<0||e>9||o<0||o>Tg||n===8&&a!==1)return Qt(r,ft);n===8&&(n=9);const s=new Ag;return r.state=s,s.strm=r,s.status=42,s.wrap=a,s.gzhead=null,s.w_bits=n,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=i+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+3-1)/3),s.window=new Uint8Array(2*s.w_size),s.head=new Uint16Array(s.hash_size),s.prev=new Uint16Array(s.w_size),s.lit_bufsize=1<<i+6,s.pending_buf_size=4*s.lit_bufsize,s.pending_buf=new Uint8Array(s.pending_buf_size),s.sym_buf=s.lit_bufsize,s.sym_end=3*(s.lit_bufsize-1),s.level=e,s.strategy=o,s.method=t,ac(r)};var Qr={deflateInit:(r,e)=>cc(r,e,Fn,15,8,zg),deflateInit2:cc,deflateReset:ac,deflateResetKeep:sc,deflateSetHeader:(r,e)=>Yr(r)||r.state.wrap!==2?ft:(r.state.gzhead=e,Me),deflate:(r,e)=>{if(Yr(r)||e>tc||e<0)return r?Qt(r,ft):ft;const t=r.state;if(!r.output||r.avail_in!==0&&!r.input||t.status===666&&e!==Ye)return Qt(r,r.avail_out===0?eo:ft);const n=t.last_flush;if(t.last_flush=e,t.pending!==0){if(Ke(r),r.avail_out===0)return t.last_flush=-1,Me}else if(r.avail_in===0&&nc(e)<=nc(n)&&e!==Ye)return Qt(r,eo);if(t.status===666&&r.avail_in!==0)return Qt(r,eo);if(t.status===42&&t.wrap===0&&(t.status=113),t.status===42){let i=Fn+(t.w_bits-8<<4)<<8,o=-1;if(o=t.strategy>=Bn||t.level<2?0:t.level<6?1:t.level===6?2:3,i|=o<<6,t.strstart!==0&&(i|=32),i+=31-i%31,Xr(t,i),t.strstart!==0&&(Xr(t,r.adler>>>16),Xr(t,65535&r.adler)),r.adler=1,t.status=113,Ke(r),t.pending!==0)return t.last_flush=-1,Me}if(t.status===57){if(r.adler=0,ce(t,31),ce(t,139),ce(t,8),t.gzhead)ce(t,(t.gzhead.text?1:0)+(t.gzhead.hcrc?2:0)+(t.gzhead.extra?4:0)+(t.gzhead.name?8:0)+(t.gzhead.comment?16:0)),ce(t,255&t.gzhead.time),ce(t,t.gzhead.time>>8&255),ce(t,t.gzhead.time>>16&255),ce(t,t.gzhead.time>>24&255),ce(t,t.level===9?2:t.strategy>=Bn||t.level<2?4:0),ce(t,255&t.gzhead.os),t.gzhead.extra&&t.gzhead.extra.length&&(ce(t,255&t.gzhead.extra.length),ce(t,t.gzhead.extra.length>>8&255)),t.gzhead.hcrc&&(r.adler=Re(r.adler,t.pending_buf,t.pending,0)),t.gzindex=0,t.status=69;else if(ce(t,0),ce(t,0),ce(t,0),ce(t,0),ce(t,0),ce(t,t.level===9?2:t.strategy>=Bn||t.level<2?4:0),ce(t,3),t.status=113,Ke(r),t.pending!==0)return t.last_flush=-1,Me}if(t.status===69){if(t.gzhead.extra){let i=t.pending,o=(65535&t.gzhead.extra.length)-t.gzindex;for(;t.pending+o>t.pending_buf_size;){let s=t.pending_buf_size-t.pending;if(t.pending_buf.set(t.gzhead.extra.subarray(t.gzindex,t.gzindex+s),t.pending),t.pending=t.pending_buf_size,t.gzhead.hcrc&&t.pending>i&&(r.adler=Re(r.adler,t.pending_buf,t.pending-i,i)),t.gzindex+=s,Ke(r),t.pending!==0)return t.last_flush=-1,Me;i=0,o-=s}let a=new Uint8Array(t.gzhead.extra);t.pending_buf.set(a.subarray(t.gzindex,t.gzindex+o),t.pending),t.pending+=o,t.gzhead.hcrc&&t.pending>i&&(r.adler=Re(r.adler,t.pending_buf,t.pending-i,i)),t.gzindex=0}t.status=73}if(t.status===73){if(t.gzhead.name){let i,o=t.pending;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>o&&(r.adler=Re(r.adler,t.pending_buf,t.pending-o,o)),Ke(r),t.pending!==0)return t.last_flush=-1,Me;o=0}i=t.gzindex<t.gzhead.name.length?255&t.gzhead.name.charCodeAt(t.gzindex++):0,ce(t,i)}while(i!==0);t.gzhead.hcrc&&t.pending>o&&(r.adler=Re(r.adler,t.pending_buf,t.pending-o,o)),t.gzindex=0}t.status=91}if(t.status===91){if(t.gzhead.comment){let i,o=t.pending;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>o&&(r.adler=Re(r.adler,t.pending_buf,t.pending-o,o)),Ke(r),t.pending!==0)return t.last_flush=-1,Me;o=0}i=t.gzindex<t.gzhead.comment.length?255&t.gzhead.comment.charCodeAt(t.gzindex++):0,ce(t,i)}while(i!==0);t.gzhead.hcrc&&t.pending>o&&(r.adler=Re(r.adler,t.pending_buf,t.pending-o,o))}t.status=103}if(t.status===103){if(t.gzhead.hcrc){if(t.pending+2>t.pending_buf_size&&(Ke(r),t.pending!==0))return t.last_flush=-1,Me;ce(t,255&r.adler),ce(t,r.adler>>8&255),r.adler=0}if(t.status=113,Ke(r),t.pending!==0)return t.last_flush=-1,Me}if(r.avail_in!==0||t.lookahead!==0||e!==Lt&&t.status!==666){let i=t.level===0?oc(t,e):t.strategy===Bn?((o,a)=>{let s;for(;;){if(o.lookahead===0&&(gr(o),o.lookahead===0)){if(a===Lt)return 1;break}if(o.match_length=0,s=Pt(o,0,o.window[o.strstart]),o.lookahead--,o.strstart++,s&&(We(o,!1),o.strm.avail_out===0))return 1}return o.insert=0,a===Ye?(We(o,!0),o.strm.avail_out===0?3:4):o.sym_next&&(We(o,!1),o.strm.avail_out===0)?1:2})(t,e):t.strategy===kg?((o,a)=>{let s,d,c,u;const f=o.window;for(;;){if(o.lookahead<=258){if(gr(o),o.lookahead<=258&&a===Lt)return 1;if(o.lookahead===0)break}if(o.match_length=0,o.lookahead>=3&&o.strstart>0&&(c=o.strstart-1,d=f[c],d===f[++c]&&d===f[++c]&&d===f[++c])){u=o.strstart+258;do;while(d===f[++c]&&d===f[++c]&&d===f[++c]&&d===f[++c]&&d===f[++c]&&d===f[++c]&&d===f[++c]&&d===f[++c]&&c<u);o.match_length=258-(u-c),o.match_length>o.lookahead&&(o.match_length=o.lookahead)}if(o.match_length>=3?(s=Pt(o,1,o.match_length-3),o.lookahead-=o.match_length,o.strstart+=o.match_length,o.match_length=0):(s=Pt(o,0,o.window[o.strstart]),o.lookahead--,o.strstart++),s&&(We(o,!1),o.strm.avail_out===0))return 1}return o.insert=0,a===Ye?(We(o,!0),o.strm.avail_out===0?3:4):o.sym_next&&(We(o,!1),o.strm.avail_out===0)?1:2})(t,e):Zr[t.level].func(t,e);if(i!==3&&i!==4||(t.status=666),i===1||i===3)return r.avail_out===0&&(t.last_flush=-1),Me;if(i===2&&(e===Sg?yg(t):e!==tc&&(Qi(t,0,0,!1),e===bg&&(Ut(t.head),t.lookahead===0&&(t.strstart=0,t.block_start=0,t.insert=0))),Ke(r),r.avail_out===0))return t.last_flush=-1,Me}return e!==Ye?Me:t.wrap<=0?rc:(t.wrap===2?(ce(t,255&r.adler),ce(t,r.adler>>8&255),ce(t,r.adler>>16&255),ce(t,r.adler>>24&255),ce(t,255&r.total_in),ce(t,r.total_in>>8&255),ce(t,r.total_in>>16&255),ce(t,r.total_in>>24&255)):(Xr(t,r.adler>>>16),Xr(t,65535&r.adler)),Ke(r),t.wrap>0&&(t.wrap=-t.wrap),t.pending!==0?Me:rc)},deflateEnd:r=>{if(Yr(r))return ft;const e=r.state.status;return r.state=null,e===113?Qt(r,Eg):Me},deflateSetDictionary:(r,e)=>{let t=e.length;if(Yr(r))return ft;const n=r.state,i=n.wrap;if(i===2||i===1&&n.status!==42||n.lookahead)return ft;if(i===1&&(r.adler=Jr(r.adler,e,t,0)),n.wrap=0,t>=n.w_size){i===0&&(Ut(n.head),n.strstart=0,n.block_start=0,n.insert=0);let d=new Uint8Array(n.w_size);d.set(e.subarray(t-n.w_size,t),0),e=d,t=n.w_size}const o=r.avail_in,a=r.next_in,s=r.input;for(r.avail_in=t,r.next_in=0,r.input=e,gr(n);n.lookahead>=3;){let d=n.strstart,c=n.lookahead-2;do n.ins_h=Gt(n,n.ins_h,n.window[d+3-1]),n.prev[d&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=d,d++;while(--c);n.strstart=d,n.lookahead=2,gr(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,r.next_in=a,r.input=s,r.avail_in=o,n.wrap=i,Me},deflateInfo:"pako deflate (from Nodeca project)"};const Ig=(r,e)=>Object.prototype.hasOwnProperty.call(r,e);var uc=function(r){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const t=e.shift();if(t){if(typeof t!="object")throw new TypeError(t+"must be non-object");for(const n in t)Ig(t,n)&&(r[n]=t[n])}}return r},dc=r=>{let e=0;for(let n=0,i=r.length;n<i;n++)e+=r[n].length;const t=new Uint8Array(e);for(let n=0,i=0,o=r.length;n<o;n++){let a=r[n];t.set(a,i),i+=a.length}return t};let lc=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{lc=!1}const en=new Uint8Array(256);for(let r=0;r<256;r++)en[r]=r>=252?6:r>=248?5:r>=240?4:r>=224?3:r>=192?2:1;en[254]=en[254]=1;var no=r=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(r);let e,t,n,i,o,a=r.length,s=0;for(i=0;i<a;i++)t=r.charCodeAt(i),(64512&t)==55296&&i+1<a&&(n=r.charCodeAt(i+1),(64512&n)==56320&&(t=65536+(t-55296<<10)+(n-56320),i++)),s+=t<128?1:t<2048?2:t<65536?3:4;for(e=new Uint8Array(s),o=0,i=0;o<s;i++)t=r.charCodeAt(i),(64512&t)==55296&&i+1<a&&(n=r.charCodeAt(i+1),(64512&n)==56320&&(t=65536+(t-55296<<10)+(n-56320),i++)),t<128?e[o++]=t:t<2048?(e[o++]=192|t>>>6,e[o++]=128|63&t):t<65536?(e[o++]=224|t>>>12,e[o++]=128|t>>>6&63,e[o++]=128|63&t):(e[o++]=240|t>>>18,e[o++]=128|t>>>12&63,e[o++]=128|t>>>6&63,e[o++]=128|63&t);return e},xg=(r,e)=>{const t=e||r.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(r.subarray(0,e));let n,i;const o=new Array(2*t);for(i=0,n=0;n<t;){let a=r[n++];if(a<128){o[i++]=a;continue}let s=en[a];if(s>4)o[i++]=65533,n+=s-1;else{for(a&=s===2?31:s===3?15:7;s>1&&n<t;)a=a<<6|63&r[n++],s--;s>1?o[i++]=65533:a<65536?o[i++]=a:(a-=65536,o[i++]=55296|a>>10&1023,o[i++]=56320|1023&a)}}return((a,s)=>{if(s<65534&&a.subarray&&lc)return String.fromCharCode.apply(null,a.length===s?a:a.subarray(0,s));let d="";for(let c=0;c<s;c++)d+=String.fromCharCode(a[c]);return d})(o,i)},Mg=(r,e)=>{(e=e||r.length)>r.length&&(e=r.length);let t=e-1;for(;t>=0&&(192&r[t])==128;)t--;return t<0||t===0?e:t+en[r[t]]>e?t:e},hc=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const fc=Object.prototype.toString,{Z_NO_FLUSH:Og,Z_SYNC_FLUSH:Pg,Z_FULL_FLUSH:Lg,Z_FINISH:Ug,Z_OK:Vn,Z_STREAM_END:Gg,Z_DEFAULT_COMPRESSION:Ng,Z_DEFAULT_STRATEGY:Bg,Z_DEFLATED:Fg}=Yt;function tn(r){this.options=uc({level:Ng,method:Fg,chunkSize:16384,windowBits:15,memLevel:8,strategy:Bg},r||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new hc,this.strm.avail_out=0;let t=Qr.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(t!==Vn)throw new Error(Zt[t]);if(e.header&&Qr.deflateSetHeader(this.strm,e.header),e.dictionary){let n;if(n=typeof e.dictionary=="string"?no(e.dictionary):fc.call(e.dictionary)==="[object ArrayBuffer]"?new Uint8Array(e.dictionary):e.dictionary,t=Qr.deflateSetDictionary(this.strm,n),t!==Vn)throw new Error(Zt[t]);this._dict_set=!0}}function io(r,e){const t=new tn(e);if(t.push(r,!0),t.err)throw t.msg||Zt[t.err];return t.result}tn.prototype.push=function(r,e){const t=this.strm,n=this.options.chunkSize;let i,o;if(this.ended)return!1;for(o=e===~~e?e:e===!0?Ug:Og,typeof r=="string"?t.input=no(r):fc.call(r)==="[object ArrayBuffer]"?t.input=new Uint8Array(r):t.input=r,t.next_in=0,t.avail_in=t.input.length;;)if(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),(o===Pg||o===Lg)&&t.avail_out<=6)this.onData(t.output.subarray(0,t.next_out)),t.avail_out=0;else{if(i=Qr.deflate(t,o),i===Gg)return t.next_out>0&&this.onData(t.output.subarray(0,t.next_out)),i=Qr.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===Vn;if(t.avail_out!==0){if(o>0&&t.next_out>0)this.onData(t.output.subarray(0,t.next_out)),t.avail_out=0;else if(t.avail_in===0)break}else this.onData(t.output)}return!0},tn.prototype.onData=function(r){this.chunks.push(r)},tn.prototype.onEnd=function(r){r===Vn&&(this.result=dc(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var Vg={Deflate:tn,deflate:io,deflateRaw:function(r,e){return(e=e||{}).raw=!0,io(r,e)},gzip:function(r,e){return(e=e||{}).gzip=!0,io(r,e)},constants:Yt},jg=function(r,e){let t,n,i,o,a,s,d,c,u,f,h,g,k,z,w,b,T,E,O,G,I,U,L,j;const $=r.state;t=r.next_in,L=r.input,n=t+(r.avail_in-5),i=r.next_out,j=r.output,o=i-(e-r.avail_out),a=i+(r.avail_out-257),s=$.dmax,d=$.wsize,c=$.whave,u=$.wnext,f=$.window,h=$.hold,g=$.bits,k=$.lencode,z=$.distcode,w=(1<<$.lenbits)-1,b=(1<<$.distbits)-1;e:do{g<15&&(h+=L[t++]<<g,g+=8,h+=L[t++]<<g,g+=8),T=k[h&w];t:for(;;){if(E=T>>>24,h>>>=E,g-=E,E=T>>>16&255,E===0)j[i++]=65535&T;else{if(!(16&E)){if(!(64&E)){T=k[(65535&T)+(h&(1<<E)-1)];continue t}if(32&E){$.mode=16191;break e}r.msg="invalid literal/length code",$.mode=16209;break e}O=65535&T,E&=15,E&&(g<E&&(h+=L[t++]<<g,g+=8),O+=h&(1<<E)-1,h>>>=E,g-=E),g<15&&(h+=L[t++]<<g,g+=8,h+=L[t++]<<g,g+=8),T=z[h&b];r:for(;;){if(E=T>>>24,h>>>=E,g-=E,E=T>>>16&255,!(16&E)){if(!(64&E)){T=z[(65535&T)+(h&(1<<E)-1)];continue r}r.msg="invalid distance code",$.mode=16209;break e}if(G=65535&T,E&=15,g<E&&(h+=L[t++]<<g,g+=8,g<E&&(h+=L[t++]<<g,g+=8)),G+=h&(1<<E)-1,G>s){r.msg="invalid distance too far back",$.mode=16209;break e}if(h>>>=E,g-=E,E=i-o,G>E){if(E=G-E,E>c&&$.sane){r.msg="invalid distance too far back",$.mode=16209;break e}if(I=0,U=f,u===0){if(I+=d-E,E<O){O-=E;do j[i++]=f[I++];while(--E);I=i-G,U=j}}else if(u<E){if(I+=d+u-E,E-=u,E<O){O-=E;do j[i++]=f[I++];while(--E);if(I=0,u<O){E=u,O-=E;do j[i++]=f[I++];while(--E);I=i-G,U=j}}}else if(I+=u-E,E<O){O-=E;do j[i++]=f[I++];while(--E);I=i-G,U=j}for(;O>2;)j[i++]=U[I++],j[i++]=U[I++],j[i++]=U[I++],O-=3;O&&(j[i++]=U[I++],O>1&&(j[i++]=U[I++]))}else{I=i-G;do j[i++]=j[I++],j[i++]=j[I++],j[i++]=j[I++],O-=3;while(O>2);O&&(j[i++]=j[I++],O>1&&(j[i++]=j[I++]))}break}}break}}while(t<n&&i<a);O=g>>3,t-=O,g-=O<<3,h&=(1<<g)-1,r.next_in=t,r.next_out=i,r.avail_in=t<n?n-t+5:5-(t-n),r.avail_out=i<a?a-i+257:257-(i-a),$.hold=h,$.bits=g};const Hg=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),$g=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),qg=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),Kg=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var rn=(r,e,t,n,i,o,a,s)=>{const d=s.bits;let c,u,f,h,g,k,z=0,w=0,b=0,T=0,E=0,O=0,G=0,I=0,U=0,L=0,j=null;const $=new Uint16Array(16),K=new Uint16Array(16);let Z,W,se,oe=null;for(z=0;z<=15;z++)$[z]=0;for(w=0;w<n;w++)$[e[t+w]]++;for(E=d,T=15;T>=1&&$[T]===0;T--);if(E>T&&(E=T),T===0)return i[o++]=20971520,i[o++]=20971520,s.bits=1,0;for(b=1;b<T&&$[b]===0;b++);for(E<b&&(E=b),I=1,z=1;z<=15;z++)if(I<<=1,I-=$[z],I<0)return-1;if(I>0&&(r===0||T!==1))return-1;for(K[1]=0,z=1;z<15;z++)K[z+1]=K[z]+$[z];for(w=0;w<n;w++)e[t+w]!==0&&(a[K[e[t+w]]++]=w);if(r===0?(j=oe=a,k=20):r===1?(j=Hg,oe=$g,k=257):(j=qg,oe=Kg,k=0),L=0,w=0,z=b,g=o,O=E,G=0,f=-1,U=1<<E,h=U-1,r===1&&U>852||r===2&&U>592)return 1;for(;;){Z=z-G,a[w]+1<k?(W=0,se=a[w]):a[w]>=k?(W=oe[a[w]-k],se=j[a[w]-k]):(W=96,se=0),c=1<<z-G,u=1<<O,b=u;do u-=c,i[g+(L>>G)+u]=Z<<24|W<<16|se|0;while(u!==0);for(c=1<<z-1;L&c;)c>>=1;if(c!==0?(L&=c-1,L+=c):L=0,w++,--$[z]==0){if(z===T)break;z=e[t+a[w]]}if(z>E&&(L&h)!==f){for(G===0&&(G=E),g+=b,O=z-G,I=1<<O;O+G<T&&(I-=$[O+G],!(I<=0));)O++,I<<=1;if(U+=1<<O,r===1&&U>852||r===2&&U>592)return 1;f=L&h,i[f]=E<<24|O<<16|g-o|0}}return L!==0&&(i[g+L]=z-G<<24|64<<16|0),s.bits=E,0};const{Z_FINISH:pc,Z_BLOCK:Wg,Z_TREES:jn,Z_OK:er,Z_STREAM_END:Jg,Z_NEED_DICT:Xg,Z_STREAM_ERROR:Qe,Z_DATA_ERROR:mc,Z_MEM_ERROR:gc,Z_BUF_ERROR:Zg,Z_DEFLATED:_c}=Yt,vc=r=>(r>>>24&255)+(r>>>8&65280)+((65280&r)<<8)+((255&r)<<24);function Yg(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const tr=r=>{if(!r)return 1;const e=r.state;return!e||e.strm!==r||e.mode<16180||e.mode>16211?1:0},yc=r=>{if(tr(r))return Qe;const e=r.state;return r.total_in=r.total_out=e.total=0,r.msg="",e.wrap&&(r.adler=1&e.wrap),e.mode=16180,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,er},Sc=r=>{if(tr(r))return Qe;const e=r.state;return e.wsize=0,e.whave=0,e.wnext=0,yc(r)},bc=(r,e)=>{let t;if(tr(r))return Qe;const n=r.state;return e<0?(t=0,e=-e):(t=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?Qe:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=t,n.wbits=e,Sc(r))},Ec=(r,e)=>{if(!r)return Qe;const t=new Yg;r.state=t,t.strm=r,t.window=null,t.mode=16180;const n=bc(r,e);return n!==er&&(r.state=null),n};let oo,so,wc=!0;const Qg=r=>{if(wc){oo=new Int32Array(512),so=new Int32Array(32);let e=0;for(;e<144;)r.lens[e++]=8;for(;e<256;)r.lens[e++]=9;for(;e<280;)r.lens[e++]=7;for(;e<288;)r.lens[e++]=8;for(rn(1,r.lens,0,288,oo,0,r.work,{bits:9}),e=0;e<32;)r.lens[e++]=5;rn(2,r.lens,0,32,so,0,r.work,{bits:5}),wc=!1}r.lencode=oo,r.lenbits=9,r.distcode=so,r.distbits=5},Cc=(r,e,t,n)=>{let i;const o=r.state;return o.window===null&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new Uint8Array(o.wsize)),n>=o.wsize?(o.window.set(e.subarray(t-o.wsize,t),0),o.wnext=0,o.whave=o.wsize):(i=o.wsize-o.wnext,i>n&&(i=n),o.window.set(e.subarray(t-n,t-n+i),o.wnext),(n-=i)?(o.window.set(e.subarray(t-n,t),0),o.wnext=n,o.whave=o.wsize):(o.wnext+=i,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=i))),0};var Tt={inflateReset:Sc,inflateReset2:bc,inflateResetKeep:yc,inflateInit:r=>Ec(r,15),inflateInit2:Ec,inflate:(r,e)=>{let t,n,i,o,a,s,d,c,u,f,h,g,k,z,w,b,T,E,O,G,I,U,L=0;const j=new Uint8Array(4);let $,K;const Z=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(tr(r)||!r.output||!r.input&&r.avail_in!==0)return Qe;t=r.state,t.mode===16191&&(t.mode=16192),a=r.next_out,i=r.output,d=r.avail_out,o=r.next_in,n=r.input,s=r.avail_in,c=t.hold,u=t.bits,f=s,h=d,U=er;e:for(;;)switch(t.mode){case 16180:if(t.wrap===0){t.mode=16192;break}for(;u<16;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}if(2&t.wrap&&c===35615){t.wbits===0&&(t.wbits=15),t.check=0,j[0]=255&c,j[1]=c>>>8&255,t.check=Re(t.check,j,2,0),c=0,u=0,t.mode=16181;break}if(t.head&&(t.head.done=!1),!(1&t.wrap)||(((255&c)<<8)+(c>>8))%31){r.msg="incorrect header check",t.mode=16209;break}if((15&c)!==_c){r.msg="unknown compression method",t.mode=16209;break}if(c>>>=4,u-=4,I=8+(15&c),t.wbits===0&&(t.wbits=I),I>15||I>t.wbits){r.msg="invalid window size",t.mode=16209;break}t.dmax=1<<t.wbits,t.flags=0,r.adler=t.check=1,t.mode=512&c?16189:16191,c=0,u=0;break;case 16181:for(;u<16;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}if(t.flags=c,(255&t.flags)!==_c){r.msg="unknown compression method",t.mode=16209;break}if(57344&t.flags){r.msg="unknown header flags set",t.mode=16209;break}t.head&&(t.head.text=c>>8&1),512&t.flags&&4&t.wrap&&(j[0]=255&c,j[1]=c>>>8&255,t.check=Re(t.check,j,2,0)),c=0,u=0,t.mode=16182;case 16182:for(;u<32;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}t.head&&(t.head.time=c),512&t.flags&&4&t.wrap&&(j[0]=255&c,j[1]=c>>>8&255,j[2]=c>>>16&255,j[3]=c>>>24&255,t.check=Re(t.check,j,4,0)),c=0,u=0,t.mode=16183;case 16183:for(;u<16;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}t.head&&(t.head.xflags=255&c,t.head.os=c>>8),512&t.flags&&4&t.wrap&&(j[0]=255&c,j[1]=c>>>8&255,t.check=Re(t.check,j,2,0)),c=0,u=0,t.mode=16184;case 16184:if(1024&t.flags){for(;u<16;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}t.length=c,t.head&&(t.head.extra_len=c),512&t.flags&&4&t.wrap&&(j[0]=255&c,j[1]=c>>>8&255,t.check=Re(t.check,j,2,0)),c=0,u=0}else t.head&&(t.head.extra=null);t.mode=16185;case 16185:if(1024&t.flags&&(g=t.length,g>s&&(g=s),g&&(t.head&&(I=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Uint8Array(t.head.extra_len)),t.head.extra.set(n.subarray(o,o+g),I)),512&t.flags&&4&t.wrap&&(t.check=Re(t.check,n,g,o)),s-=g,o+=g,t.length-=g),t.length))break e;t.length=0,t.mode=16186;case 16186:if(2048&t.flags){if(s===0)break e;g=0;do I=n[o+g++],t.head&&I&&t.length<65536&&(t.head.name+=String.fromCharCode(I));while(I&&g<s);if(512&t.flags&&4&t.wrap&&(t.check=Re(t.check,n,g,o)),s-=g,o+=g,I)break e}else t.head&&(t.head.name=null);t.length=0,t.mode=16187;case 16187:if(4096&t.flags){if(s===0)break e;g=0;do I=n[o+g++],t.head&&I&&t.length<65536&&(t.head.comment+=String.fromCharCode(I));while(I&&g<s);if(512&t.flags&&4&t.wrap&&(t.check=Re(t.check,n,g,o)),s-=g,o+=g,I)break e}else t.head&&(t.head.comment=null);t.mode=16188;case 16188:if(512&t.flags){for(;u<16;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}if(4&t.wrap&&c!==(65535&t.check)){r.msg="header crc mismatch",t.mode=16209;break}c=0,u=0}t.head&&(t.head.hcrc=t.flags>>9&1,t.head.done=!0),r.adler=t.check=0,t.mode=16191;break;case 16189:for(;u<32;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}r.adler=t.check=vc(c),c=0,u=0,t.mode=16190;case 16190:if(t.havedict===0)return r.next_out=a,r.avail_out=d,r.next_in=o,r.avail_in=s,t.hold=c,t.bits=u,Xg;r.adler=t.check=1,t.mode=16191;case 16191:if(e===Wg||e===jn)break e;case 16192:if(t.last){c>>>=7&u,u-=7&u,t.mode=16206;break}for(;u<3;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}switch(t.last=1&c,c>>>=1,u-=1,3&c){case 0:t.mode=16193;break;case 1:if(Qg(t),t.mode=16199,e===jn){c>>>=2,u-=2;break e}break;case 2:t.mode=16196;break;case 3:r.msg="invalid block type",t.mode=16209}c>>>=2,u-=2;break;case 16193:for(c>>>=7&u,u-=7&u;u<32;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}if((65535&c)!=(c>>>16^65535)){r.msg="invalid stored block lengths",t.mode=16209;break}if(t.length=65535&c,c=0,u=0,t.mode=16194,e===jn)break e;case 16194:t.mode=16195;case 16195:if(g=t.length,g){if(g>s&&(g=s),g>d&&(g=d),g===0)break e;i.set(n.subarray(o,o+g),a),s-=g,o+=g,d-=g,a+=g,t.length-=g;break}t.mode=16191;break;case 16196:for(;u<14;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}if(t.nlen=257+(31&c),c>>>=5,u-=5,t.ndist=1+(31&c),c>>>=5,u-=5,t.ncode=4+(15&c),c>>>=4,u-=4,t.nlen>286||t.ndist>30){r.msg="too many length or distance symbols",t.mode=16209;break}t.have=0,t.mode=16197;case 16197:for(;t.have<t.ncode;){for(;u<3;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}t.lens[Z[t.have++]]=7&c,c>>>=3,u-=3}for(;t.have<19;)t.lens[Z[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,$={bits:t.lenbits},U=rn(0,t.lens,0,19,t.lencode,0,t.work,$),t.lenbits=$.bits,U){r.msg="invalid code lengths set",t.mode=16209;break}t.have=0,t.mode=16198;case 16198:for(;t.have<t.nlen+t.ndist;){for(;L=t.lencode[c&(1<<t.lenbits)-1],w=L>>>24,b=L>>>16&255,T=65535&L,!(w<=u);){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}if(T<16)c>>>=w,u-=w,t.lens[t.have++]=T;else{if(T===16){for(K=w+2;u<K;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}if(c>>>=w,u-=w,t.have===0){r.msg="invalid bit length repeat",t.mode=16209;break}I=t.lens[t.have-1],g=3+(3&c),c>>>=2,u-=2}else if(T===17){for(K=w+3;u<K;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}c>>>=w,u-=w,I=0,g=3+(7&c),c>>>=3,u-=3}else{for(K=w+7;u<K;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}c>>>=w,u-=w,I=0,g=11+(127&c),c>>>=7,u-=7}if(t.have+g>t.nlen+t.ndist){r.msg="invalid bit length repeat",t.mode=16209;break}for(;g--;)t.lens[t.have++]=I}}if(t.mode===16209)break;if(t.lens[256]===0){r.msg="invalid code -- missing end-of-block",t.mode=16209;break}if(t.lenbits=9,$={bits:t.lenbits},U=rn(1,t.lens,0,t.nlen,t.lencode,0,t.work,$),t.lenbits=$.bits,U){r.msg="invalid literal/lengths set",t.mode=16209;break}if(t.distbits=6,t.distcode=t.distdyn,$={bits:t.distbits},U=rn(2,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,$),t.distbits=$.bits,U){r.msg="invalid distances set",t.mode=16209;break}if(t.mode=16199,e===jn)break e;case 16199:t.mode=16200;case 16200:if(s>=6&&d>=258){r.next_out=a,r.avail_out=d,r.next_in=o,r.avail_in=s,t.hold=c,t.bits=u,jg(r,h),a=r.next_out,i=r.output,d=r.avail_out,o=r.next_in,n=r.input,s=r.avail_in,c=t.hold,u=t.bits,t.mode===16191&&(t.back=-1);break}for(t.back=0;L=t.lencode[c&(1<<t.lenbits)-1],w=L>>>24,b=L>>>16&255,T=65535&L,!(w<=u);){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}if(b&&!(240&b)){for(E=w,O=b,G=T;L=t.lencode[G+((c&(1<<E+O)-1)>>E)],w=L>>>24,b=L>>>16&255,T=65535&L,!(E+w<=u);){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}c>>>=E,u-=E,t.back+=E}if(c>>>=w,u-=w,t.back+=w,t.length=T,b===0){t.mode=16205;break}if(32&b){t.back=-1,t.mode=16191;break}if(64&b){r.msg="invalid literal/length code",t.mode=16209;break}t.extra=15&b,t.mode=16201;case 16201:if(t.extra){for(K=t.extra;u<K;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}t.length+=c&(1<<t.extra)-1,c>>>=t.extra,u-=t.extra,t.back+=t.extra}t.was=t.length,t.mode=16202;case 16202:for(;L=t.distcode[c&(1<<t.distbits)-1],w=L>>>24,b=L>>>16&255,T=65535&L,!(w<=u);){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}if(!(240&b)){for(E=w,O=b,G=T;L=t.distcode[G+((c&(1<<E+O)-1)>>E)],w=L>>>24,b=L>>>16&255,T=65535&L,!(E+w<=u);){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}c>>>=E,u-=E,t.back+=E}if(c>>>=w,u-=w,t.back+=w,64&b){r.msg="invalid distance code",t.mode=16209;break}t.offset=T,t.extra=15&b,t.mode=16203;case 16203:if(t.extra){for(K=t.extra;u<K;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}t.offset+=c&(1<<t.extra)-1,c>>>=t.extra,u-=t.extra,t.back+=t.extra}if(t.offset>t.dmax){r.msg="invalid distance too far back",t.mode=16209;break}t.mode=16204;case 16204:if(d===0)break e;if(g=h-d,t.offset>g){if(g=t.offset-g,g>t.whave&&t.sane){r.msg="invalid distance too far back",t.mode=16209;break}g>t.wnext?(g-=t.wnext,k=t.wsize-g):k=t.wnext-g,g>t.length&&(g=t.length),z=t.window}else z=i,k=a-t.offset,g=t.length;g>d&&(g=d),d-=g,t.length-=g;do i[a++]=z[k++];while(--g);t.length===0&&(t.mode=16200);break;case 16205:if(d===0)break e;i[a++]=t.length,d--,t.mode=16200;break;case 16206:if(t.wrap){for(;u<32;){if(s===0)break e;s--,c|=n[o++]<<u,u+=8}if(h-=d,r.total_out+=h,t.total+=h,4&t.wrap&&h&&(r.adler=t.check=t.flags?Re(t.check,i,h,a-h):Jr(t.check,i,h,a-h)),h=d,4&t.wrap&&(t.flags?c:vc(c))!==t.check){r.msg="incorrect data check",t.mode=16209;break}c=0,u=0}t.mode=16207;case 16207:if(t.wrap&&t.flags){for(;u<32;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8}if(4&t.wrap&&c!==(4294967295&t.total)){r.msg="incorrect length check",t.mode=16209;break}c=0,u=0}t.mode=16208;case 16208:U=Jg;break e;case 16209:U=mc;break e;case 16210:return gc;case 16211:default:return Qe}return r.next_out=a,r.avail_out=d,r.next_in=o,r.avail_in=s,t.hold=c,t.bits=u,(t.wsize||h!==r.avail_out&&t.mode<16209&&(t.mode<16206||e!==pc))&&Cc(r,r.output,r.next_out,h-r.avail_out),f-=r.avail_in,h-=r.avail_out,r.total_in+=f,r.total_out+=h,t.total+=h,4&t.wrap&&h&&(r.adler=t.check=t.flags?Re(t.check,i,h,r.next_out-h):Jr(t.check,i,h,r.next_out-h)),r.data_type=t.bits+(t.last?64:0)+(t.mode===16191?128:0)+(t.mode===16199||t.mode===16194?256:0),(f===0&&h===0||e===pc)&&U===er&&(U=Zg),U},inflateEnd:r=>{if(tr(r))return Qe;let e=r.state;return e.window&&(e.window=null),r.state=null,er},inflateGetHeader:(r,e)=>{if(tr(r))return Qe;const t=r.state;return 2&t.wrap?(t.head=e,e.done=!1,er):Qe},inflateSetDictionary:(r,e)=>{const t=e.length;let n,i,o;return tr(r)?Qe:(n=r.state,n.wrap!==0&&n.mode!==16190?Qe:n.mode===16190&&(i=1,i=Jr(i,e,t,0),i!==n.check)?mc:(o=Cc(r,e,t,t),o?(n.mode=16210,gc):(n.havedict=1,er)))},inflateInfo:"pako inflate (from Nodeca project)"},e_=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const kc=Object.prototype.toString,{Z_NO_FLUSH:t_,Z_FINISH:r_,Z_OK:nn,Z_STREAM_END:ao,Z_NEED_DICT:co,Z_STREAM_ERROR:n_,Z_DATA_ERROR:Tc,Z_MEM_ERROR:i_}=Yt;function on(r){this.options=uc({chunkSize:65536,windowBits:15,to:""},r||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||r&&r.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&!(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new hc,this.strm.avail_out=0;let t=Tt.inflateInit2(this.strm,e.windowBits);if(t!==nn)throw new Error(Zt[t]);if(this.header=new e_,Tt.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=no(e.dictionary):kc.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=Tt.inflateSetDictionary(this.strm,e.dictionary),t!==nn)))throw new Error(Zt[t])}function uo(r,e){const t=new on(e);if(t.push(r),t.err)throw t.msg||Zt[t.err];return t.result}on.prototype.push=function(r,e){const t=this.strm,n=this.options.chunkSize,i=this.options.dictionary;let o,a,s;if(this.ended)return!1;for(a=e===~~e?e:e===!0?r_:t_,kc.call(r)==="[object ArrayBuffer]"?t.input=new Uint8Array(r):t.input=r,t.next_in=0,t.avail_in=t.input.length;;){for(t.avail_out===0&&(t.output=new Uint8Array(n),t.next_out=0,t.avail_out=n),o=Tt.inflate(t,a),o===co&&i&&(o=Tt.inflateSetDictionary(t,i),o===nn?o=Tt.inflate(t,a):o===Tc&&(o=co));t.avail_in>0&&o===ao&&t.state.wrap>0&&r[t.next_in]!==0;)Tt.inflateReset(t),o=Tt.inflate(t,a);switch(o){case n_:case Tc:case co:case i_:return this.onEnd(o),this.ended=!0,!1}if(s=t.avail_out,t.next_out&&(t.avail_out===0||o===ao))if(this.options.to==="string"){let d=Mg(t.output,t.next_out),c=t.next_out-d,u=xg(t.output,d);t.next_out=c,t.avail_out=n-c,c&&t.output.set(t.output.subarray(d,d+c),0),this.onData(u)}else this.onData(t.output.length===t.next_out?t.output:t.output.subarray(0,t.next_out));if(o!==nn||s!==0){if(o===ao)return o=Tt.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,!0;if(t.avail_in===0)break}}return!0},on.prototype.onData=function(r){this.chunks.push(r)},on.prototype.onEnd=function(r){r===nn&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=dc(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var o_={Inflate:on,inflate:uo,inflateRaw:function(r,e){return(e=e||{}).raw=!0,uo(r,e)},ungzip:uo,constants:Yt};const{Deflate:s_,deflate:a_,deflateRaw:c_,gzip:u_}=Vg,{Inflate:d_,inflate:l_,inflateRaw:h_,ungzip:f_}=o_;var p_={Deflate:s_,deflate:a_,deflateRaw:c_,gzip:u_,Inflate:d_,inflate:l_,inflateRaw:h_,ungzip:f_,constants:Yt},m_=function(){function r(e,t){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_ON:500,RESPONSE:5001,TIMEOUT:5005},this.customHeader=t.custom_request_header||{}}return r.prototype.useFetch=function(e){var t=e.url,n=e.data,i=e.method,o=e.success,a=e.fail,s={"Content-Type":"application/json; charset=utf-8"};if(Object.keys(this.customHeader).length)for(var d in this.customHeader)s[d]=this.customHeader[d];window.fetch?fetch(t,{method:i||"POST",headers:s,body:JSON.stringify(n)}).then(function(c){return c.json()}).then(function(c){o&&o(c)}).catch(function(c){a&&a(n,c)}):(this.requestType="xhr",console.log("your brwoser not support fetch, use xhr"),this.useRequest({url:t,data:n,method:i,success:o,fail:a}))},r.prototype.useBeacon=function(e){var t=e.url,n=e.data,i=e.success,o=e.fail;this.requestType!=="xhr"?window.navigator.sendBeacon(t,JSON.stringify(n))?i&&i():o&&o(n,this.errorCode.BEACON_FALSE):this.useXhr(e)},r.prototype.useXhr=function(e){var t=this,n=e.url,i=e.data,o=e.method,a=e.success,s=e.fail,d=e.timeout,c=e.withCredentials,u=e.app_key,f=e.zip;try{var h=new XMLHttpRequest,g=o||"POST";if(h.open(g,""+n,!0),h.setRequestHeader("Content-Type","application/json; charset=utf-8"),u&&h.setRequestHeader("X-MCS-AppKey",""+u),Object.keys(this.customHeader).length)for(var k in this.customHeader)h.setRequestHeader(k,this.customHeader[k]);c&&(h.withCredentials=!0),d&&(h.timeout=d,h.ontimeout=function(){s&&s(i,t.errorCode.TIMEOUT)}),h.onload=function(){if(a){var E=null;if(h.responseText){try{E=JSON.parse(h.responseText)}catch{E={}}a(E,i)}}},h.onerror=function(){h.abort(),s&&s(i,t.errorCode.XHR_ON)};try{var z=JSON.stringify(i),w=this.collector.configManager.getCurrentEnv();if(this.config.need_zip&&f)if(w==="row"){var b=new TextEncoder().encode(z),T=p_.gzip(b);h.setRequestHeader("Content-Encoding","gzip"),h.send(T)}else h.send(z),this.collector.logger.warn("your channel do not support gzip, use normal data!");else h.send(z)}catch(E){h.send(JSON.stringify(i)),this.collector.emit("sdk-inner-error",{type:"sdk_error_send",eventData:i,errorCode:1e3,msg:E.message||E.stack||"sdk_error_send"})}}catch(E){this.collector.emit("sdk-inner-error",{type:"sdk_error_request",eventData:i,errorCode:1001,msg:E.message||E.stack||"sdk_error_request"})}},r.prototype.useRequest=function(e){var t=e.useBeacon,n=e.forceXhr;if(this.requestType==="xhr")this.useXhr(e);else{if(t&&this.supportBeacon)return void this.useBeacon(e);if(this.requestType==="fetch"&&!n)return void this.useFetch(e);this.useXhr(e)}},r}(),g_=function(){function r(e,t){if(this.devToolReady=!1,this.sendAlready=!1,t.enable_debug&&e.configManager.get("browser")!=="Microsoft Internet Explorer"){this.collect=e,this.config=t,this.app_id=t.app_id;var n=e.adapters.storage;this.cacheStorgae=new n(!1),this.devToolOrigin=window.location.origin,this.currentInstance=t.current_instance||"",this.loadUrl=t.devtool_url||"https://sf16-website-login.neutral.ttwstatic.com/obj/tiktok_web_login_static/log-sdk/collect/devtool/debug-web.v2.0.0.js",this.filterEvent=new Set(["__bav_page","__bav_beat","__bav_page_statistics","__bav_click","__bav_page_exposure","bav2b_page","bav2b_beat","bav2b_page_statistics","bav2b_click","bav2b_page_exposure","_be_active","predefine_pageview","__profile_set","__profile_set_once","__profile_increment","__profile_unset","__profile_append","predefine_page_alive","predefine_page_close","abtest_exposure"]),this.load()}}return r.prototype.loadScript=function(e){try{var t=document.createElement("script");t.src=e,t.onerror=function(){console.log("load DevTool render fail")},t.onload=function(){console.log("load DevTool render success")},document.getElementsByTagName("body")[0].appendChild(t)}catch(n){console.log("devTool load fail, "+n.message)}},r.prototype.parseUrl=function(){var e={};try{var t=window.location.href.split("?")[1].split("&");t.length&&t.forEach(function(n){var i=n.split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])})}catch{}return e},r.prototype.load=function(){try{var e=this.parseUrl();if(e.open_devtool_web&&e.app_id){if(parseInt(e.app_id)!==this.app_id||e.current_instance&&e.current_instance!==this.currentInstance)return}else if(!this.getStorage())return;this.loadBaseInfo(),this.loadHook(),this.setStorage(),this.addLintener(),this.loadDebuggerModule(),this.loadDevTool()}catch(t){console.log("debug fail, "+t.message)}},r.prototype.getStorage=function(){var e=this.cacheStorgae.getItem("__applog_open_devtool_web");return e&&parseInt(e)===this.app_id},r.prototype.setStorage=function(){this.cacheStorgae.setItem("__applog_open_devtool_web",this.app_id)},r.prototype.loadDevTool=function(){this.loadScript(this.loadUrl)},r.prototype.loadBaseInfo=function(){if(this.log=[],this.event=[],this.info=[{title:"BaseInfo",key:"base",type:1,content:[{name:"app_id",desc:"APPID",value:this.config.app_id},{name:"channel",desc:"CHANNEL",value:this.config.channel},{name:"domain",desc:"Domain",value:this.collect.configManager.getDomain()},{name:"sdk_version",desc:"SDK Version",value:jr},{name:"sdk_type",desc:"SDK Import Type",value:"npm"}]},{title:"UserInfo",key:"user",type:2,content:[{name:"uuid",desc:"UserUniqueId",value:this.collect.configManager.get("user").user_unique_id||""},{name:"web_id",desc:"WEB_ID",value:this.collect.configManager.get("user").web_id||""}]},{title:"CommonInfo",type:2,key:"common",content:[{name:"browser",desc:"Browser",value:this.collect.configManager.get("browser")},{name:"browser_version",desc:"Browser Version",value:this.collect.configManager.get("browser_version")},{name:"platform",desc:"Platform",value:this.collect.configManager.get("platform")},{name:"device_model",desc:"Devide Model",value:this.collect.configManager.get("device_model")},{name:"os_name",desc:"Os Name",value:this.collect.configManager.get("os_name")},{name:"os_version",desc:"Os Version",value:this.collect.configManager.get("os_version")},{name:"resolution",desc:"Screen Resolution",value:this.collect.configManager.get("resolution")},{name:"referrer",desc:"Referrer",value:this.collect.configManager.get("referrer")},{name:"custom",desc:"Custom Info",value:JSON.stringify(this.collect.configManager.get("custom"))}]},{title:"Config Info",key:"config",type:3,content:[{name:"autotrack",desc:"AutoTrackEvent",value:!!this.config.autotrack},{name:"stay",desc:"StayDuration",value:!!this.config.enable_stay_duration}]},{title:"A/B Config Info",key:"ab",type:4,content:[{name:"ab",desc:"A/BTester",value:!!this.config.enable_ab_test}]}],this.config.enable_ab_test){var e=this.getInfo("ab"),t=[{name:"ab",desc:"A/BTester",value:!!this.config.enable_ab_test},{name:"vid",desc:"A/B VID",value:this.collect.configManager.getAbVersion()},{name:"ab_domain",desc:"Domain",value:this.config.ab_channel_domain||Br(qi[this.config.channel])},{name:"all_values",desc:"A/B ALL Values",value:this.collect.configManager.getAbCache()}];e.content=t,this.setInfo("ab",e)}},r.prototype.getInfo=function(e){var t=null;return this.info.forEach(function(n){n.key===e&&(t=n)}),t},r.prototype.setInfo=function(e,t){var n=!1;this.info.forEach(function(i){i.key===e&&(n=!0,i=t)}),n||this.info.push(t)},r.prototype.getSecondInfo=function(e,t){var n=this.getInfo(e),i=null;return n.content.forEach(function(o){o.name===t&&(i=o)}),i},r.prototype.setSecondInfo=function(e,t,n){var i=this.getInfo(e),o=!1;if(i.content.forEach(function(s){s.name===t&&(s.value=n,o=!0)}),!o){var a={name:t,value:n,desc:t.toLocaleUpperCase()};i.content.push(a)}this.setInfo(e,i)},r.prototype.loadHook=function(){var e=this;this.collect.on(x.DEBUGGER_MESSAGE,function(t){switch(t.type){case x.DEBUGGER_MESSAGE_SDK:var n={time:t.time,type:t.logType||"sdk",infoType:t.infoType||"sdk",level:t.level,name:t.info,show:!0,levelShow:!0,needDesc:!!t.data};if(t.data&&(n.desc={content:JSON.stringify(t.data)}),e.updateLog(n),t.secType&&t.secType==="AB")e.setSecondInfo("ab","vid",e.collect.configManager.getAbVersion()),e.setSecondInfo("ab","all_values",e.collect.configManager.getAbCache());else if(t.secType==="USER")e.setSecondInfo("user",t.common==="user_unique_id"?"uuid":t.common,e.collect.configManager.get(t.common));else if(t.secType==="HEADER"){var i=e.collect.configManager.get(t.common);e.setSecondInfo("common",t.common,t.common==="custom"?JSON.stringify(i):i)}return void e.updateInfo();case x.DEBUGGER_MESSAGE_EVENT:if(t.data&&t.data.length){var o=t.data[0],a=o.events;if(!a.length)return;a.forEach(function(s){s.checkShow=!0,s.searchShow=!0,s.focusShow=!0,s.status=t.status,s.type=e.filterEvent.has(s.event)?"sdk":"cus",s.verifyType=t.verifyType?"verify":"no",s.info="",t.status==="fail"&&(s.info={message:"code: "+t.code+", msg: "+(t.msg||t.failType)})}),e.updateEvent(o)}return}})},r.prototype.addLintener=function(){var e=this;window.addEventListener("message",function(t){if(e.devToolOrigin===t.origin){if(t&&t.data&&t.data.type==="devtool:web:ready"){if(e.devToolOrigin=t.origin,e.devToolReady=!0,e.sendAlready)return;e.sendData("devtool:web:init",{info:e.info,log:e.log,event:e.event,sdk_type:jr.includes("tob")?"tob":"inner",appId:e.app_id}),e.sendAlready=!0}t&&t.data&&t.data.type==="devtool:web:ssid"&&e.collect.getToken(function(n){e.setSecondInfo("user","sid",n.tobid),e.updateInfo()})}})},r.prototype.sendData=function(e,t){try{var n={type:e,payload:t};window&&window.postMessage(n,this.devToolOrigin)}catch{}},r.prototype.updateInfo=function(){this.devToolReady&&this.sendData("devtool:web:info",this.info)},r.prototype.updateLog=function(e){this.devToolReady?this.sendData("devtool:web:log",e):this.log.push(e)},r.prototype.updateEvent=function(e){this.devToolReady?this.sendData("devtool:web:event",e):this.event.push(e)},r.prototype.loadDebuggerModule=function(){var e=`#debugger-applog-web {
|
|
57
57
|
position: fixed;
|
|
58
58
|
width: 45px;
|
|
59
59
|
height: 45px;
|
|
60
|
-
background-image: url(`+
|
|
60
|
+
background-image: url(`+Br("1fz22z22z1nz21z4mz4bz4bz21z1dz4dz4iz49z25z1cz19z21z1gz22z1cz49z1jz1mz1ez1gz1lz4az1lz1cz23z22z20z18z1jz4az22z22z25z21z22z18z22z1gz1az4az1az1mz1kz4bz1mz19z1hz4bz22z1gz1iz22z1mz1iz16z25z1cz19z16z1jz1mz1ez1gz1lz16z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz1bz1cz24z22z1mz1mz1jz4bz18z1nz1nz1jz1mz1ez4az1nz1lz1e")+`);
|
|
61
61
|
bottom: 5%;
|
|
62
62
|
right: 10%;
|
|
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 s=document.createElement("div");s.innerHTML='<div id="debugger-container" class="debugger-container"></div>',document.getElementsByTagName("body")[0].appendChild(i),document.getElementsByTagName("body")[0].appendChild(s);var a=document.getElementById("debugger-applog-web");a&&a.addEventListener("click",function(){window&&window.postMessage({type:"devtool:web:open-draw"},location.origin)})},r}(),Li={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"}},Um=["ab","autotrack","Stay","store","et","profile","cep","heartbeat","monitor","route","tracer"],Pe=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 hf,this.remotePlugin=new Map,this.Types=x,this.adapters.storage=Et,this.loadType="full"}return r.usePlugin=function(e,t,n){if(t){for(var i=!1,s=0,a=r.plugins.length;s<a;s++)if(r.plugins[s].name===t){r.plugins[s].plugin=e,r.plugins[s].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"&&Um.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 Af(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&&ur(t))if(t.app_id&&typeof(n=t.app_id)=="number"&&!isNaN(n))if(!t.app_key||function(s){return typeof s=="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&&!Lo().has(t.report_channel)?(this.logger.warn("your report_channel: "+t.report_channel+" is not exist. report_channel must be one of "+gi().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 "+gi().join(",")+", use default report_channel: us_east instead, please check!!!"),t.report_channel="us_east"),this.emit(T.DEBUGGER_MESSAGE,{type:T.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 "+gi().join(",")+", use us_east instead, please check!!!",infoType:"sdk"})),this.spider=new Df,this.spider.checkSpider(t))return this.logger.warn("The current environment may be a spider, can not report!"),void this.emit(T.DEBUGGER_MESSAGE,{type:T.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 xf(this,t.enable_native),this.requestManager=new Lm(this,t),this.bridgeReport=this.appBridge.bridgeInject(),this.configManager=new Rf(this,t),this.debugger=new Nm(this,t),this.initConfig=t,this.emit(x.Init),this.emit(T.DEBUGGER_MESSAGE,{type:T.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 zf,this.tokenManager=new Pf,this.sessionManager=new Of,Promise.all([new Promise(function(s){i.once(x.TokenComplete,function(){s(!0)})}),new Promise(function(s){i.once(x.Start,function(){s(!0)})}),new Promise(function(s){i.once(x.LogSettingReady,function(){s(!0)})})]).then(function(){try{r.plugins.reduce(function(s,a){var o=a.plugin,d=a.options,c=Object.assign(i.initConfig,d);i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Load "+a.name+" Plugin",level:"info",time:Date.now(),infoType:"sdk"});var u=new o;return u.apply(i,c),s.push(u),s},i.pluginInstances)}catch(s){console.warn("load plugin error, "+s.message),i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Load Plugin Error",level:"error",time:Date.now(),data:s.message,infoType:"sdk"})}i.sdkReady=!0,i.emit(x.Ready),i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK UserInfo Init Completed",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"}),i.emit(T.DEBUGGER_MESSAGE,{type:T.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 "+pr+", 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(s){i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Something Error",level:"error",time:Date.now(),data:s.message,infoType:"sdk"})}i.pageView(),i.on(x.TokenChange,function(s){s==="webid"&&i.pageView(),i.logger.info("appid: "+t.app_id+" token change, new userInfo:"+JSON.stringify(i.configManager.get("user"))),i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Set UserInfo",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(x.TokenReset,function(){i.logger.info("appid: "+t.app_id+" token reset, new userInfo:"+JSON.stringify(i.configManager.get("user"))),i.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Reset UserInfo",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(x.RouteChange,function(s){s.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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Config Error",level:"error",time:Date.now(),data:"config must be use after function init",infoType:"sdk"});if(!e||!ur(e))return console.warn("config params is error, please check"),void this.emit(T.DEBUGGER_MESSAGE,{type:T.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=ne({},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 s=function(a,o){var d={};for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&o.indexOf(c)<0&&(d[c]=a[c]);if(a!=null&&typeof Object.getOwnPropertySymbols=="function"){var u=0;for(c=Object.getOwnPropertySymbols(a);u<c.length;u++)o.indexOf(c[u])<0&&(d[c[u]]=a[c[u]])}return d}(n,["web_id","user_unique_id","device_id"]);n.hasOwnProperty("web_id")&&this.emit(x.ConfigWebId,n.web_id),n.hasOwnProperty("user_unique_id")&&this.emit(x.ConfigUuid,n.user_unique_id),n.hasOwnProperty("device_id")&&this.emit(x.ConfigDiD,n.device_id),this.configManager.set(s),this.emit(T.DEBUGGER_MESSAGE,{type:T.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(x.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(x.Start),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute Start",level:"info",time:Date.now(),infoType:"cus"}),this.bridgeReport&&(this.pageView(),this.emit(x.Ready)))},r.prototype.event=function(e,t){var n=this;try{var i=[];if(Array.isArray(e))e.forEach(function(a){var o=n.processEvent(a[0],a[1]||{});o&&i.push(o)});else{var s=this.processEvent(e,t);if(!s)return;i.push(s)}this.bridgeReport?i.forEach(function(a){var o=a.event,d=a.params;n.appBridge.onEventV3(o,JSON.stringify(d))}):i.length&&(this.emit(x.Event,i),this.emit(x.SessionResetTime)),this.emit(T.DEBUGGER_MESSAGE,{type:T.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(T.DEBUGGER_MESSAGE,{type:T.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(T.DEBUGGER_MESSAGE,{type:T.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(x.BeconEvent,n),this.emit(x.SessionResetTime)),this.emit(T.DEBUGGER_MESSAGE,{type:T.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=pf();var s=void 0;return i.local_ms?(s=i.local_ms,delete i.local_ms):s=+new Date,{event:n,params:i,local_time_ms:s,is_bav:this.initConfig&&this.initConfig.autotrack?1:0}}catch(a){return this.emit(T.DEBUGGER_MESSAGE,{type:T.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=ne(ne({},t),e);this.emit(T.DEBUGGER_MESSAGE,{type:T.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(x.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 fr()},r.prototype.setSessionId=function(e){this.emit(x.SessionReset,e)},r.prototype.resetStayDuration=function(e,t,n){this.emit(x.ResetStay,{url_path:e,title:t,url:n},x.Stay)},r.prototype.resetStayParams=function(e,t,n){e===void 0&&(e=""),t===void 0&&(t=""),n===void 0&&(n=""),this.emit(x.SetStay,{url_path:e,title:t,url:n},x.Stay)},r.prototype.getToken=function(e,t){var n=this;if(this.inited){var i=!1,s=function(o){if(!i){i=!0;var d=n.configManager.get().user;return o&&(d.tobid=o,d["diss".split("").reverse().join("")]=o),e(ne({},d))}},a=function(){n.tokenManager.getTobId().then(function(o){s(o)})};this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute GetToken",level:"info",time:Date.now(),infoType:"cus"}),this.sdkReady?a():(t&&setTimeout(function(){s()},t),this.on(x.Ready,function(){a()}))}else console.warn("predefinePageView should call after init")},r.prototype.startTrackEvent=function(e){e&&this.emit(x.TrackEventDurationStart,e,x.TrackEventDuration)},r.prototype.endTrackEvent=function(e,t){t===void 0&&(t={}),e&&this.emit(x.TrackEventDurationEnd,{eventName:e,params:t},x.TrackEventDuration)},r.prototype.pauseTrackEvent=function(e){e&&this.emit(x.TrackEventDurationPause,e,x.TrackEventDuration)},r.prototype.resumeTrackEvent=function(e){e&&this.emit(x.TrackEventDurationResume,e,x.TrackEventDuration)},r.prototype.profileSet=function(e){this.bridgeReport?this.appBridge.profileSet(JSON.stringify(e)):this.emit(x.ProfileSet,e,x.Profile),this.emit(T.DEBUGGER_MESSAGE,{type:T.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(x.ProfileSetOnce,e,x.Profile),this.emit(T.DEBUGGER_MESSAGE,{type:T.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(x.ProfileIncrement,e,x.Profile),this.emit(T.DEBUGGER_MESSAGE,{type:T.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(x.ProfileUnset,e,x.Profile),this.emit(T.DEBUGGER_MESSAGE,{type:T.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(x.ProfileAppend,e,x.Profile),this.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute profileAppend",level:"info",time:Date.now(),data:e})},r.prototype.setExternalAbVersion=function(e){this.emit(x.AbExternalVersion,typeof e=="string"&&e?(""+e).trim():null,x.Ab)},r.prototype.getVar=function(e,t,n,i){this.emit(x.AbVar,{name:e,defaultValue:t,callback:n,uuid:i},x.Ab)},r.prototype.getABconfig=function(e,t){this.emit(x.AbConfig,{params:e,callback:t},x.Ab)},r.prototype.getABConfig=function(e,t){this.emit(x.AbConfig,{params:e,callback:t},x.Ab)},r.prototype.getAbSdkVersion=function(){return this.configManager.getAbVersion()},r.prototype.onAbSdkVersionChange=function(e){var t=this;return this.emit(x.AbVersionChangeOn,e,x.Ab),function(){t.emit(x.AbVersionChangeOff,e,x.Ab)}},r.prototype.offAbSdkVersionChange=function(e){this.emit(x.AbVersionChangeOff,e,x.Ab)},r.prototype.openOverlayer=function(){this.emit(x.AbOpenLayer,"",x.Ab)},r.prototype.closeOverlayer=function(){this.emit(x.AbCloseLayer,"",x.Ab)},r.prototype.getAllVars=function(e,t){this.emit(x.AbAllVars,{callback:e,timeout:t},x.Ab)},r.prototype.destoryInstace=function(){this.destroy||(this.destroy=!0,this.off(x.TokenComplete),this.emit(x.DestoryInstance))},r.prototype.destroyInstance=function(){this.destroy||(this.destroy=!0,this.off(x.TokenComplete),this.emit(x.DestoryInstance))},r.plugins=[],r}(),Dr={},ka=[];function Ra(r,e,t,n){var i=r&&r.source||window.opener||window.parent,s=r&&r.origin||n||window.location.origin,a={type:e,payload:t};i.postMessage(JSON.stringify(a),s)}function Gm(r){if(ka.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;Dr[t]&&Dr[t].forEach(function(i){typeof i=="function"&&i(r,n)})}}var xr,Ni="__rangers_ab_style__";(function(r){r[r.Var=0]="Var",r[r.All=1]="All"})(xr||(xr={}));var Bm=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,s=t.ab_channel_domain,a=t.enable_ab_visual,o=t.ab_cross,d=t.ab_cookie_domain,c=t.ab_timeout,u=t.disable_auto_ab,h=vi[t.channel||"sg"]||vi.sg,l=s||dr(h),f=e.adapters.storage;this.cacheStorgae=new f(!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=o,this.ab_cookie_domain=d||"",this.fetchUrl=l+"/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 y=this.collect.Types;this.types=y,this.collect.on(y.TokenChange,function(C){C==="uuid"&&n.readyStatus&&(n.clearCache(),n.fetchAB())}),this.collect.on(y.AbVar,function(C){var v=C.name,E=C.defaultValue,k=C.callback;n.getVar(v,E,k)}),this.collect.on(y.AbAllVars,function(C){var v=C.callback,E=C.timeout;n.getAllVars(v,E)}),this.collect.on(y.AbConfig,function(C){var v=C.params,E=C.callback;n.getABconfig(v,E)}),this.collect.on(y.AbExternalVersion,function(C){n.setExternalAbVersion(C)}),this.collect.on(y.AbOpenLayer,function(){n.openOverlayer()}),this.collect.on(y.AbCloseLayer,function(){n.closeOverlayer()}),this.collect.on(y.AbVersionChangeOn,function(C){n.changeListener.set(C,C)}),this.collect.on(y.AbVersionChangeOff,function(C){n.changeListener.get(C)&&n.changeListener.delete(C)}),this.loadMode(),(this.enable_ab_visual||this.enable_multilink)&&this.openOverlayer(this.config.multilink_timeout_ms||500),this.checkLocal(),this.ready("ab"),this.readyStatus||(!u&&this.fetchAB(),this.readyStatus=!0),this.collect.emit(y.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(o){t.collect.hook.emit(a,o)})};for(var s in n)i(s)}},r.prototype.loadMode=function(){var e=function(){try{var s=JSON.parse(atob(window.name));return s||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,s=(e.data,this.checkFromUrl());s?this.mulilinkVersions.push(s):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=an(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 s={name:e,defaultValue:t,callback:n,type:xr.Var};this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.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(s,e,i):this.callbackMap.set(e,s)},r.prototype.setAbUuid=function(e,t){this.collect.configManager.setAbUuidCache(e,t)},r.prototype.getRealVar=function(e,t,n){var i=e.name,s=e.defaultValue,a=e.callback,o=this.data;if(o){var d=o[i];if(d&&ur(d)){var c=d.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,s,a,d.val),void this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetVar, Exposure Experiment "+i,level:"info",time:Date.now(),data:o[i],infoType:"sdk"})}this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GerVar Default Callback",level:"info",time:Date.now(),data:this.data,infoType:"sdk"}),a(s)}else a(s)},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,s={callback:e,type:xr.All,timer:i};this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Execute GetAllVars",level:"info",time:Date.now(),infoType:"cus"}),t&&(i=setTimeout(function(){s.timer=null,n.getRealAllVars(s),clearTimeout(i)},t),s.timer=i),this.fetchStatus==="complete"&&this.refreshFetchStatus==="complete"?(s.timer=null,this.getRealAllVars(s),i&&clearTimeout(i)):this.callbackMap.set("allVars",s)},r.prototype.getRealAllVars=function(e,t){var n=e.callback,i=e.timer;i&&(clearTimeout(i),e.timer=null);var s=(t??this.data)||{};try{n(JSON.parse(JSON.stringify(s)))}catch{n(s)}this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.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,s){try{if(this.config.disable_track_event||!e)return;var a=this.collect.configManager.get(),o=a.header,d=a.user,c=this.getABCache(),u=d[this.ab_user_mode]||d.user_unique_id;if(c&&c.uuid&&c.uuid!==u)return;var h={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()};o.custom=JSON.stringify(o.custom);var l={events:[h],user:d,header:o};this.reportExposure(l,t),i&&i(s)}catch(f){this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Something Error",level:"error",time:Date.now(),data:f.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(T.DEBUGGER_MESSAGE,{type:T.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(Ni)){var i="body { opacity: 0 !important; }",s=document.head||document.getElementsByTagName("head")[0],a=document.createElement("style");a.id=Ni,a.type="text/css",a.styleSheet?a.styleSheet.cssText=i:a.appendChild(document.createTextNode(i)),s.appendChild(a)}}(),e)var n=setTimeout(function(){t.closeOverlayer(),clearTimeout(n)},e)},r.prototype.closeOverlayer=function(){var e;(e=document.getElementById(Ni))&&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 s=[];Object.keys(e).forEach(function(u){var h=e[u].vid;h&&s.push(h)}),this.versions=this.versions.filter(function(u){return s.includes(u)});var a=e.$ab_url,o=e.$ab_modification;if(o&&o.val&&this.enable_ab_visual){if(this.collect.destroy)return}else if(a&&this.enable_multilink){this.mulilinkVersions=this.mulilinkVersions.filter(function(u){return s.includes(u)});var d=a.val,c=a.vid;d&&c&&this.getVar("$ab_url",d,function(){n.editMode||(d!==window.location.href?setTimeout(function(){if(!n.collect.destroy){var u=""+d;u=u.indexOf("http")===-1?"https://"+u:u,di(u).host!==location.host?u=u+"&vid="+c:window.history.replaceState("","",u),window.location.href=u}},100):n.closeOverlayer())})}this.updateVersions()}else this.closeOverlayer();this.callbackMap.forEach(function(u){u.type===xr.Var?n.getRealVar(u,""):n.getRealAllVars(u,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:ne(ne(ne({aid:this.config.app_id},n.user||{}),n.header||{}),{ab_sdk_version:this.collect.configManager.getAbVersion(),ab_url:window.location.href})};this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Fetch AB Request",level:"info",logType:"fetch",time:Date.now(),data:i,infoType:"sdk"});var s=n.user[this.ab_user_mode]||n.user.user_unique_id;this.pushFetchToQueue(s),this.collect.requestManager.useRequest({url:this.fetchUrl,data:i,success:function(a){t.fetchStatus="complete",t.refreshFetchStatus="complete";var o=a.data;a.message==="success"?(t.fetchComplete(o,s),e&&e(o)):(t.fetchComplete(null,s),e&&e(null)),t.collect.emit(t.types.AbComplete,o),t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK Fetch AB Request Success",level:"info",logType:"fetch",time:Date.now(),data:o,infoType:"sdk"})},fail:function(){t.fetchStatus="complete",t.refreshFetchStatus="complete",t.fetchComplete(null,s),t.collect.emit(t.types.AbTimeout),e&&e(null),t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.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}(),Fm=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(s){n.verify(s)}),e.on(i.AbVerify,function(s){n.verify(s)})}}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 s=i||n,a=JSON.parse(JSON.stringify(s));if(!s.length)return;var o=!0;if(s.forEach(function(d){d.events.length||(o=!1)}),!o)return;t.collect.requestManager.useBeacon({url:t.url,data:s}),t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_EVENT,info:"SDK Report ByteIo Verify Request",time:Date.now(),data:a,code:200,status:"success",verifyType:!0})}catch(d){console.warn("something error, "+JSON.stringify(d.stack)),t.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Report ByteIo Verify Request Error",level:"error",time:Date.now(),data:d.message})}})},r}(),Vm=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,ur(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,ne({url_path:this.getParams("url_path"),title:this.getParams("title"),url:this.getParams("url"),duration:n,is_support_visibility_change:Po(),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),lr(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}(),jm=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(),ur(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,ne({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:Po(),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),lr(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}(),Hm=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 Vm(e,t),this.pageClose=new jm(e,t);var i=this.collect.Types;this.collect.on(i.ResetStay,function(s){var a=s.url_path,o=s.title,d=s.url;n.resetStayDuration(a,o,d)}),this.collect.on(i.RouteChange,function(s){s.init||t.disable_route_report||n.resetStayDuration()}),this.collect.on(i.SetStay,function(s){var a=s.url_path,o=s.title,d=s.url;n.setStayParmas(a,o,d)}),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(o){t.collect.hook.emit(a,o)})};for(var s in n)i(s)}},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(T.DEBUGGER_MESSAGE,{type:T.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(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"SDK Execute resetStayDuration",level:"info",time:Date.now(),data:{url_path:e,title:t,url:n}})},r}(),qm=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,s=Date.now()+n;return i=window.setTimeout(function a(){var o=Date.now()-s;t(),s+=n,i=window.setTimeout(a,Math.max(0,n-o))},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}(),$m=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(s){var a=s.type,o=s.eventData,d=s.errorCode,c=s.response;a==="f_data"&&n.sdkError(o,d,c)}),this.collect.on(e.Types.SDKInnerError,function(s){var a=s.type,o=s.eventData,d=s.errorCode,c=s.msg;n.sdkInnerError(a,o,d,c)})}},r.prototype.sdkOnload=function(){var e=this;try{var t=this.collect.configManager.get(),n=t.header,i=t.user,s=n.app_id,a=n.app_name,o=n.sdk_version,d=(i.web_id,{events:[{event:"onload",params:JSON.stringify({app_id:s,app_name:a||"",sdk_version:o,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:[d],timeout:3e4,forceXhr:!0})},16)}catch{}},r.prototype.sdkError=function(e,t,n){var i=this;try{var s=e[0],a=s.user,o=s.header,d=[];e.forEach(function(u){u.events.forEach(function(h){d.push(h)})});var c={events:d.map(function(u){return{event:"on_error",params:JSON.stringify({type:"sdk_event_error",error_code:t,app_id:o.app_id,app_name:o.app_name||"",error_event:u.event,sdk_version:o.sdk_version,local_time_ms:u.local_time_ms,tea_event_index:Date.now(),params:u.params,header:o,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 s=this;try{var a=t[0],o=a.user,d=a.header,c=[];t.forEach(function(h){h.events.forEach(function(l){c.push(l)})});var u={events:c.map(function(h){return{event:"on_error",params:JSON.stringify({type:e,error_code:n,app_id:d.app_id,app_name:d.app_name||"",error_event:h.event,sdk_version:d.sdk_version,local_time_ms:h.local_time_ms,tea_event_index:Date.now(),params:h.params,header:d,user:o,ua:window.navigator.userAgent,err_msg:i}),local_time_ms:Date.now()}}),user:o,header:{}};setTimeout(function(){s.collect.requestManager.useRequest({url:s.url,data:[u],timeout:3e4,app_key:"566f58151b0ed37e",forceXhr:!0})},16)}catch{}},r}();function Ui(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 Gi(r){for(var e=r;e&&!Ui(e,"container");){if(e.nodeName==="HTML"||e.nodeName==="BODY")return r;e=e.parentElement}return e||r}function Aa(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 Da(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 _n=function(r,e){return r.hasAttribute?r.hasAttribute(e):r.attributes?!(!r.attributes[e]||!r.attributes[e].specified):void 0},Km=function(r,e){if(typeof e=="string")return _n(r,e);if(ui(e)){for(var t=!1,n=0;n<e.length;n++)if(_n(r,e[n])){t=!0;break}return t}},Wm=function(){function r(e,t,n){var i=this;this.statistics=!1,this.pageView=!1,this.clickEvent=function(s){(function(a,o){if(a.nodeType!==1||!o.svg&&function(c){if(c.tagName.toLowerCase()==="svg")return!0;for(var u=c.parentElement,h=!1;u;)u.tagName.toLowerCase()==="svg"?(u=null,h=!0):u=u.parentElement;return h}(a)||["HTML","BODY"].includes(a.tagName.toUpperCase()))return!1;var d=a;return d.style.display!=="none"&&(!!Ui(d,"container")||!(!function(c){if(c.children.length){var u=c.children;return![].slice.call(u).some(function(h){return h.children.length>0})}return!0}(d)&&!o.svg))})(s.target,i.options)&&i.eventHandel({eventType:"dom",eventName:"click"},s)},this.changeEvent=function(s){i.eventHandel({eventType:"dom",eventName:"change"},s)},this.submitEvent=function(s){i.eventHandel({eventType:"dom",eventName:"submit"},s)},this.getPageViewEvent=function(s,a){a&&a==="pushState"&&i.eventHandel({eventType:"dom",eventName:"beat"},ne({beat_type:0},s)),i.eventHandel({eventType:"dom",eventName:"page_view"},s)},this.getPageLoadEvent=function(s){i.eventHandel({eventType:"dom",eventName:"page_statistics"},{lcp:s})},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(d){var c=d.config,u=d.name;t.getPageViewEvent(c,u),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,s=null;window.addEventListener("scroll",function(){clearTimeout(s),s=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 o=window.performance&&window.performance.getEntriesByType("paint");o&&o.length?(new PerformanceObserver(function(d){var c=d.getEntries(),u=c[c.length-1],h=u.renderTime||u.loadTime;t.statistics||(t.getPageLoadEvent(h),t.statistics=!0)}).observe({entryTypes:["largest-contentful-paint"]}),setTimeout(function(){t.statistics||(t.getPageLoadEvent(o[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)),lr(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}(),Jm={eventConfig:{mode:"proxy-capturing",submit:!1,click:!0,change:!1,pv:!0,beat:!0,hashTag:!1,impr:!1},scoutConfig:{mode:"xpath"}},Xm=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 Zm(r){for(var e=[];r.parentElement!==null;)e.push(r),r=r.parentElement;var t=[],n=[];return e.forEach(function(i){var s=function(d){if(d===null)return{str:"",index:0};var c=0,u=d.parentElement;if(u)for(var h=u.children,l=0;l<h.length&&h[l]!==d;l++)h[l].nodeName===d.nodeName&&c++;return{str:[d.nodeName.toLowerCase(),Ui(d,"list")?"[]":""].join(""),index:c}}(i),a=s.str,o=s.index;t.unshift(a),n.unshift(o)}),{element_path:"/"+t.join("/"),positions:n}}function Ym(r,e,t,n){var i={},s=function(R){if(R){var M=R.getBoundingClientRect(),N=M.width,U=M.height;return{left:M.left,top:M.top,element_width:N,element_height:U}}}(e),a=function(R,M){R===void 0&&(R={}),M===void 0&&(M={});var N=R.clientX,U=R.clientY,B=M.left,H=M.top,Y=N-B>=0?N-B:0,W=U-H>=0?U-H:0;return{touch_x:Math.floor(Y),touch_y:Math.floor(W)}}(r,s),o=s.element_width,d=s.element_height,c=a.touch_x,u=a.touch_y,h=Zm(e),l=h.element_path,f=h.positions,y=function(R){var M=Gi(R),N=[];return function U(B){var H=Aa(B);if(H&&N.indexOf(H)===-1&&N.push(H),B.childNodes.length>0)for(var Y=B.childNodes,W=0;W<Y.length;W++)Y[W].nodeType!==8&&U(Y[W])}(M),N}(e),C=window.performance.timing.navigationStart,v=Date.now()-C,E=f.map(function(R){return""+R}),k=null;if(window.TEAVisualEditor&&window.TEAVisualEditor.getOriginXpath&&(k=window.TEAVisualEditor.getOriginXpath({xpath:l,positions:E})),i.element_path=k&&k.xpath||l,i.positions=k&&k.positions||E,n&&!n.text&&(i.texts=y,i.element_title=function(R){var M=Gi(R),N="";return function U(B){var H=Aa(B);if(H&&(N+=H),B.childNodes.length>0)for(var Y=B.childNodes,W=0;W<Y.length;W++)Y[W].nodeType===3&&U(Y[W])}(M),N}(e)),i.element_id=e.getAttribute("id")||"",i.element_class_name=e.getAttribute("class")||"",i.element_type=e.nodeType,i.element_width=Math.floor(o),i.element_height=Math.floor(d),i.touch_x=c,i.touch_y=u,i.page_manual_key="",i.elememt_manual_key="",i.since_page_start_ms=v,i.page_start_ms=C,i.page_path=location.pathname,i.page_host=location.host,t.track_attr&&function(R,M){return!!Km(R,M)}(e,t.track_attr)){var g=function(R,M){var N={};if(typeof M=="string")_n(R,M)&&(N.attrs=R.getAttribute(M));else if(ui(M))for(var U=0;U<M.length;U++)_n(R,M[U])&&(N[M[U]]=R.getAttribute(M[U]));return N}(e,t.track_attr);for(var D in g)i[D]=g[D]}var L=Gi(e);return L.tagName==="A"&&(i.href=L.getAttribute("href")),e.tagName==="IMG"&&(i.src=e.getAttribute("src")),i}var Ir=function(r,e,t,n,i){return ne(ne({event:r},Ym(e,t,n,i)),{is_html:1,page_key:window.location.href,page_title:document.title})},Qm=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(Da(e.target))return null;var n="bav2b_click";switch(t){case"click":return n=e.target.getAttribute("data-applog-click-event")||this.eventName.click,Ir(n,e,e.target,this.options,this.ignore);case"change":return ne(ne({},Ir(n="bav2b_change",e,e.target,this.options)),function(i,s){try{if(i==="bav2b_change")return s.hasAttribute("data-tea-track")?{value:s.value}:{}}catch{return{}}}(n,e.target));case"submit":return Ir(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,s=i.loadEventEnd-i.navigationStart;t.page_init_cost_ms=parseInt(n||(s>0?s: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(Da(t.target))return null;var n=Ir(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=Ir(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}(),e_=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}(),Bi=!1;function t_(r){var e,t,n,i,s=r.event,a=r.editorUrl,o=r.autoTrackInstance;Bi||(Bi=!0,e=a,t=function(){Ra(s,"editorScriptloadSuccess"),o.destroy()},n=function(){s&&Ra(s,"editorScriptloadError"),Bi=!1},(i=document.createElement("script")).src=e,i.onerror=function(){n(e)},i.onload=function(){t()},document.getElementsByTagName("head")[0].appendChild(i))}function r_(r,e){window.TEAVisualEditor=window.TEAVisualEditor||{},window.TEAVisualEditor.appId=e.app_id;var t,n,i,s=e.channel_domain,a="";if((t=wf).length&&t.forEach(function(l){ka.push(l)}),s){var o=void 0,d="";try{var c=window.performance.getEntriesByType("resource");if(c&&c.length&&(c.forEach(function(l){l.initiatorType==="script"&&l.name&&l.name.indexOf("collect")!==-1&&(d=l.name)}),d&&(o=d.split("/"))&&o.length)){a="https:/";for(var u=2;u<o.length&&u!==o.length-1;u++)a=a+"/"+o[u];if(a&&a.indexOf("/5.0")){var h=a.split("/5.0");a=h[0]||a}}}catch{}}window.addEventListener("message",Gm,!1);try{i=function(l){var f=l.data.app_id;f&&f!==e.app_id||t_({event:l,editorUrl:"https://sf16-website-login.neutral.ttwstatic.com/obj/tiktok_web_login_static/log-sdk/collect/heatmap-core.js?query="+Date.now(),autoTrackInstance:r})},Dr[n="tea:openHeatMapCore"]=Dr[n]||[],Dr[n].push(i)}catch{console.log("openHeatMapCore error")}}var qe,n_=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"})(qe||(qe={}));var At,i_=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=qe.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(s){var a=s.target.observeId,o=e.observeMap.get(a),d=(s.target,s.isIntersecting,s.intersectionRatio);if(o.intersectionRatio=d,d<=.1&&(s.target.backStatus=!1),e.observeMap.set(a,o),d<e.ratio)return o.isIntersecting=!1,o.added=!1,o.exposured=!1,o.startTime=Date.now(),void e.observeMap.set(a,o);if(!o.added){if(o.startTime=Date.now(),o.added=!0,o.isIntersecting=!0,e.timeLimit){var c=setTimeout(function(){try{if(o.isIntersecting&&!o.exposured&&e.observeMap.get(a)){var u=e.observeMap.get(a).intersectionRatio;e.exposureEvent(s,u,a,o)}}catch(h){console.log("IntersectionObserver setTimeout error,msg: "+JSON.stringify(h))}},e.timeLimit);o.wait=c}e.observeMap.set(a,o)}Date.now()-o.startTime>=e.timeLimit&&!o.exposured&&e.exposureEvent(s,d,a,o)})},{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,s=un();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=s,n.visible=!1,this.observeMap.set(s,{instance:n.cloneNode(!0),isIntersecting:!1}),this.observe(n);else{if(n.visible===!0)return;this.handleBoundingExposure(n)}}else n.observeId=s,n.visible=!1,this.observeMap.set(s,{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 s=e.target.getAttribute("data-applog-exposure-event");this.eventHandle({eventType:"dom",eventName:"exposure",event:s,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||qe.RESUME_FORM_BACK},e)}},r.prototype.getBoundingRatio=function(e){var t=e.getBoundingClientRect(),n=t.top,i=t.left,s=t.width,a=t.height,o=window.innerWidth||document.documentElement.clientWidth,d=window.innerHeight||document.documentElement.clientHeight;return n>=0&&i>=0&&n<=d&&i<=o?(s>o?o:s)*(d-n)/(s*a):0},r.prototype.getExposureType=function(e){return e.visible?e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=qe.RESUME_FORM_PAGE:this.exposureType=qe.LIFECYCLE_SHOW_NEW:(e.hasExposure,e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=qe.RESUME_FORM_PAGE:this.exposureType=qe.EXPOSURE_ONCE),this.exposureType},r.prototype.addListen=function(){var e=this;this.collect.on("set-exposure-type",function(o){e.customType=o});var t,n,i,s,a=this.visibilitychange.bind(this);return t=document,n="visibilitychange",i=a,s=!1,t.addEventListener?t.addEventListener(n,i,s):t.attachEven?t.attachEven("on"+n,i):t["on"+n]=i,window.addEventListener("hashchange",function(o){var d=e.hashMap.get(o.oldURL);d&&location.href===d.prev?(e.backStatus=!0,e.exposureType=qe.RESUME_FORM_PAGE):(e.backStatus=!1,e.hashMap.set(location.href,{current:o.newURL,prev:o.oldURL}))}),this.collect.on("STATE_CHANGE",function(o){e.lastState=o}),window.addEventListener("popstate",function(o){var d=o.state;d&&d.current&&e.lastState&&e.lastState.back&&d.current===e.lastState.back?(e.backStatus=!0,e.exposureType=qe.RESUME_FORM_PAGE):e.backStatus=!1}),function(){(function(o,d,c,u){o.addEventListener?o.removeEventListener(d,c,u):o.attachEven&&o.detachEven("on"+d,c)})(document,"visibilitychange",a,!1)}},r._observer_instance=null,r._observer_map=new Map,r}(),s_=function(){function r(e,t,n){t.autotrack&&t.autotrack.exposure&&(this._intersection=new i_(e,t,n),this._observer=new n_(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"})(At||(At={}));var xa,o_=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,s=e.scrollLeft,a=null,o=0,d=0,c=function(u){clearTimeout(a),a=setTimeout(function(){var y=e.scrollTop,C=e.scrollLeft,v=u.target&&u.target.getAttribute("data-scroll-event")||"";f===1||f===2?y===h&&(d=h-i,Math.abs(d)>=n.distance&&n.distance&&n.eventHandle({eventType:"dom",eventName:"scroll",event:v,params:{$direction:f,$offsetY:d,$offsetX:o}},u)):f!==3&&f!==4||C===l&&(o=l-s,Math.abs(o)>=n.distance&&n.distance&&n.eventHandle({eventType:"dom",eventName:"scroll",event:v,params:{$direction:f,$offsetY:d,$offsetX:o}},u)),i=h,s=l},100);var h=e.scrollTop,l=e.scrollLeft,f=At.NOT_SCROLL;h>i?f=At.SCROLL_DOWN:h<i?f=At.SCROLL_UP:l>s?f=At.SCROLL_LEFT:l<s&&(f=At.SCROLL_RIGHT)};return t==="remove"?e.removeEventListener("scroll",c,!1):e.addEventListener("scroll",c,!1),function(){e.removeEventListener("scroll",c,!1)}}catch(u){console.warn("scroll event error",JSON.stringify(u))}},r}(),a_={hashTag:!1,impr:!1},c_=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(a_,t),this.destroyed=!1,this.options=t,this.Config=new Xm(Jm,this.options),this.Exposure=new s_(this.collect,this.config,this.handle.bind(this)),this.Scroll=new o_(this.config,this.handle.bind(this)),this.Listener=new Wm(t,this.collect,this.Config),this.EventHandle=new Qm(this.config,t),this.Request=new e_(this.collect),this.autoTrackStart=!0,this.init(),r_(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")(o=this.EventHandle.handleEvent(t,n))&&this.Request.send({eventType:"custom"},o);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 s=this.EventHandle.handleBeadtEvent(t),a=e.eventSend;s&&this.Request.send({eventType:"custom",eventSend:a},s)}else if(n==="exposure")(o=this.EventHandle.handleExposureEvent(e,t))&&this.Request.send({eventType:"custom"},o);else if(n==="scroll"){var o;(o=this.EventHandle.handleScrollEvent(e,t))&&this.Request.send({eventType:"custom"},o)}}catch(d){console.log("handel dom event error "+JSON.stringify(d))}},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"})(xa||(xa={}));var Ia={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"]},u_=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(s){ui(s)?s.forEach(function(a){n.addCount("log")}):n.addCount("log")}),this.collect.on(i.SubmitError,function(s){var a=s.type,o=s.eventDate,d=s.errorCode,c=s.response;n.addErrorCount(o,a,d,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))(s=this.tracerCache.get(e)).has(t)?(i=s.get(t).params.count,i++,s.set(t,this.processTracer(i,e,t))):(i=n,s.set(t,this.processTracer(n,e,t)));else{var s=new Map;i=n,s.set(t,this.processTracer(n,e,t)),this.tracerCache.set(e,s)}t==="net"&&i>=this.limit[e]&&this.report(!1)}catch(a){console.log(a)}},r.prototype.addErrorCount=function(e,t,n,i){var s=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(o){var d="log";for(var c in Ia)if(Ia[c].indexOf(o.event)!==-1){d=c;break}s.addCount(d,t,1),s.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:pr};n!=="f_net"&&n!=="f_data"||(i.errorCode=this.errorCode[n]);var s=this.collect.processEvent("applog_trace",i);if(s&&s.event)return delete s.is_bav,s}catch{console.warn("something error")}},r.prototype.listener=function(){var e=this;document.addEventListener("visibilitychange",function(){document.visibilityState==="hidden"&&e.leavePage()}),lr(function(){e.leavePage()})},r.prototype.leavePage=function(){this.report(!0)},r}(),d_=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,s=e.adapters.storage;this.storage=new s(!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 s=e.eventData;t.fetchData(s,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)),s=function(o){e.fetchData(t[o],function(){delete i[o],e.storage.setItem(e.eventKey,i)},function(){},!1)};for(var a in t)s(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}(),Fi=typeof window<"u"?(window.LogPluginObject||(window.LogPluginObject={}),window.LogPluginObject):null,l_=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(Li.hasOwnProperty(n)){var i=Li[n].object,s=""+Li[n].src[e.channel];e.exist(n,i,s)}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(T.DEBUGGER_MESSAGE,{type:T.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;Fi[t]?(this.process(e,Fi[t]),console.log("already has "+e+" plugin~")):this.loadPlugin(e,n,function(){i.process(e,Fi[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(s){this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Extend Process Fail",level:"error",time:Date.now(),data:s.message}),console.log("excude "+e+" error, message:"+s.message)}},r.prototype.loadPlugin=function(e,t,n,i){var s=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(){s._plugin[e].forEach(function(o){o()})},document.getElementsByTagName("head")[0].appendChild(a)}catch(o){this.collect.emit(T.DEBUGGER_MESSAGE,{type:T.DEBUGGER_MESSAGE_SDK,info:"Extend LoadPlugin Fail",level:"error",time:Date.now(),data:o.message})}},r}(),h_=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 s=[],a=1;a<arguments.length;a++)s[a-1]=arguments[a];typeof history.onpushstate=="function"&&history.onpushstate({state:i});var o=t.call.apply(t,cr([history,i],s));if(e.collect.sdkStop||e.collect.destroy)return o;if(!(e.lastLocation===location.href||e.config.disable_spa_query&&e.pathEquel())){e.setReferCache(e.lastLocation);var d=e.getPopStateChangeEventData();return e.lastLocation=location.href,e.sendPv(d,"pushState"),o}};var n=history.replaceState;history.replaceState=function(i){for(var s=[],a=1;a<arguments.length;a++)s[a-1]=arguments[a];typeof history.onreplacestate=="function"&&history.onreplacestate({state:i});var o=n.call.apply(n,cr([history,i],s));if(e.collect.sdkStop||e.collect.destroy)return o;if(!(e.lastLocation===location.href||e.config.disable_spa_query&&e.pathEquel())){e.setReferCache(e.lastLocation);var d=e.getPopStateChangeEventData();return e.lastLocation=location.href,e.sendPv(d),o}}},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(T.DEBUGGER_MESSAGE,{type:T.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}(),p_=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(s){n.trackEventStart(s)}),e.on(i.TrackDurationEnd,function(s){n.trackEventEnd(s)}),e.on(i.TrackDurationPause,function(s){n.trackEventPause(s)}),e.on(i.TrackDurationResume,function(s){n.trackEventResume(s)}),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(o){t.collect.hook.emit(a,o)})};for(var s in n)i(s)}},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),s=0;s=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:s});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}();Pe.usePlugin(l_,"extend"),Pe.usePlugin(Fm,"et"),Pe.usePlugin(d_,"retry"),Pe.usePlugin(Bm,"ab"),Pe.usePlugin(Hm,"stay"),Pe.usePlugin(c_,"autotrack"),Pe.usePlugin(p_,"trackeventduration"),Pe.usePlugin(qm,"heartbeat"),Pe.usePlugin($m,"monitor"),Pe.usePlugin(h_,"route"),Pe.usePlugin(u_,"tracer");var zr=new Pe("default");const Vi="VEPUSHER_DEVICE_ID",ji="VEPUSHER_USER_ID",za=r=>Math.floor((Math.random()*9+1)*Math.pow(10,r-1)).toString();function f_(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 m_(r){if(r)return localStorage.setItem(ji,r),r;const e=localStorage.getItem(ji);if(e)return e;const t=za(12);return localStorage.setItem(ji,t),r}function __(r){if(r)return localStorage.setItem(Vi,r),r;const e=localStorage.getItem(Vi);if(e)return e;const t=za(11);return localStorage.setItem(Vi,t),t}const V={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",...{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",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 g_{constructor({showLogInConsole:e=!1}){this._showLogInConsole=!1,this.markCollectTeaEventReady=()=>{this.isReady=!0,zr.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.94",...n}};zr.config(i),this.markCollectTeaEventReady()},this.isReady=!1,this.queueTeaEvent=[],zr.init({app_id:778494,channel:"sg"}),this._showLogInConsole=e}sendTeaEvent(e,t,n=!1){if(e)if(this.isReady)try{const i={...f_(t||{})};zr.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 zr}}let Pr;function v_({showLogInConsole:r}){Pr=new g_({showLogInConsole:r})}function j(r,e,t=!1){Pr&&Pr.sendTeaEvent(r,e,t)}function y_(r,e){Pr&&Pr.configTea(r,e)}const Pa=()=>{j(V.PAGE_VISIBLE_CHANGE,{page_visible:!document.hidden})},S_=()=>{document.addEventListener("visibilitychange",Pa)},b_=()=>{document.removeEventListener("visibilitychange",Pa)};function qt(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 E_ extends st{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}=Ft(fs,"video"),{sampleRate:s}=Ft(ms,"audio");this._videoConstraints={width:t,height:n,frameRate:i},this._audioConstraints={sampleRate:s,enableAutoGainControl:!0,enableNoiseSuppression:!0,enableEchoCancellation:!0},this._livePusher=e}_notifyCaptured(e){this.emit(Be.DeviceCaptured,e)}_notifyStopCapture(e){this.emit(Be.DeviceStopCapture,e)}_bindStreamEvent(e){e.bindTrackEnd(()=>{this.emit(Be.Interrupted,e),this.stopCapture({streamId:e.id,type:e.type})})}_handleError(e,t){const n=new Bt(t,e.message);this.emit(Be.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 Hu(e?[e]:["audioinput","videoinput"]);return j(V.GET_DEVICES_RESULT,{type:e,is_success:!0,devices:t}),t}catch(t){return j(V.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 Q.Camera:n="_cameraStreams";break;case Q.Screen:n="_screenStreams";break;case Q.VideoFile:n="_videoFileStreams";break;case Q.Microphone:n="_microphoneStreams";break;case Q.AudioFile:n="_audioFileStreams";break;case Q.Image:n="_imageStreams";break;case Q.CustomVideo:n="_customVideoStreams";break;case Q.CustomAudio:n="_customAudioStreams";break}if(n){let i=[];if(e){const s=this[n][e];i.push(s)}else i=et(this[n]);j(V.STOP_CAPTURE,{stream_id:e,type:t,number:i.length}),i.forEach(s=>{this._notifyStopCapture(s),s.destroy(),delete this[n][s.id]})}}async startCameraCapture(e){let t={};cf.includes(e)?t={facingMode:e}:e&&(t={deviceId:{exact:e}});const n={...t,...this._videoConstraints};try{const i=await qu(n,!this._livePusher.isEnableMixing),s=new gd(i,{frameRate:this._videoConstraints.frameRate});return this._cameraStreams[s.id]=s,this._notifyCaptured(s),this._bindStreamEvent(s),j(V.CAMERA_CAPTURE_RESULT,{is_success:!0,stream_id:s.id,device_id:e,capture_params:n}),s.id}catch(i){throw j(V.CAMERA_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:n,...qt(i)}),this._handleError(i,ke.OPEN_CAMERA_FAILED),i}}async startMicrophoneCapture(e){let t={};e&&(t={deviceId:{exact:e}});const n={...this._audioConstraints,...t};try{const i=await Ku(n),s=new ef(i);return this._microphoneStreams[s.id]=s,this._notifyCaptured(s),this._bindStreamEvent(s),j(V.MICROPHONE_CAPTURE_RESULT,{is_success:!0,stream_id:s.id,device_id:e,capture_params:n}),s.id}catch(i){throw j(V.MICROPHONE_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:n,...qt(i)}),this._handleError(i,ke.OPEN_MICROPHONE_FAILED),i}}async startScreenCapture(e){const t={audio:e,video:this._videoConstraints};try{const n=await Wu(t,void 0,!this._livePusher.isEnableMixing),i=new rf(n,{frameRate:this._videoConstraints.frameRate});return this._screenStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),j(V.SCREEN_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,capture_params:t}),i.id}catch(n){throw j(V.SCREEN_CAPTURE_RESULT,{is_success:!1,capture_params:t,...qt(n)}),this._handleError(n,ke.OPEN_SCREEN_FAILED),n}}async startVideoFileCapture(e){try{const t=await Os({url:e,video:!0,audio:!0,loop:!0}),n=new tf(t);return this._videoFileStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),j(V.VIDEO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,file_url:e}),n.id}catch(t){throw this._handleError(t,ke.VIDEO_FILE_CAPTURE_FAILED),j(V.VIDEO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...qt(t)}),t}}async startAudioFileCapture(e){try{const t=await Os({url:e,video:!1,audio:!0,loop:!0}),n=new nf(t);return this._audioFileStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),j(V.AUDIO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,file_url:e}),n.id}catch(t){throw j(V.AUDIO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...qt(t)}),this._handleError(t,ke.AUDIO_FILE_CAPTURE_FAILED),t}}async startImageCapture(e){try{const t=await $u({url:e,width:0,height:0,frameRate:30}),n=new sf(t);return this._imageStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),j(V.IMAGE_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,file_url:e}),n.id}catch(t){throw j(V.IMAGE_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...qt(t)}),this._handleError(t,ke.IMAGE_FILE_CAPTURE_FAILED),t}}startCustomVideoCapture(e){const t=Xu(e);if(t){const n=new of(t);return this._customVideoStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),n.id}}startCustomAudioCapture(e){const t=Zu(e);if(t){const n=new af(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(),j(V.VOLUME_DETECTOR_START_RESULT,{is_success:!0,stream_id:t.id})}catch(n){j(V.VOLUME_DETECTOR_START_RESULT,{is_success:!1,stream_id:t.id,error_message:n.message}),this._handleError(n,ke.VOLUME_DETECT_FAILED)}}stopVolumeDetect(e){const t=this.getStreamById(e);t&&t.stopVolumeDetect()}getDefaultVideoStream(){return et(this._cameraStreams)[0]||et(this._screenStreams)[0]||et(this._videoFileStreams)[0]||et(this._imageStreams)[0]||et(this._customVideoStreams)[0]}getDefaultAudioStream(){return et(this._microphoneStreams)[0]||et(this._audioFileStreams)[0]||et(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(Q).forEach(e=>{this.stopCapture({type:e})})}}let ht=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 Hi{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(Be.DeviceCaptured,e=>{this._active&&this.onStreamCapture(e)}),this._streamManagerController.on(Be.DeviceStopCapture,e=>{this._active&&this.onStreamStopCapture(e)})}getComposedStream(){return this._composedStream}enable(){this._active=!0}disable(){this._active=!1}}const Oa=new ht("SingleComposer");class C_ extends Hi{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,s;if(this._active)try{await((s=(i=this._composedStream.videoStream)==null?void 0:i.videoTrack)==null?void 0:s.applyConstraints({width:{min:e,ideal:e},height:{min:t,ideal:t},frameRate:{min:n,ideal:n}}))}catch(a){Oa.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):Oa.error("all video stream stop capture")}}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class w_ extends st{constructor(e,{width:t,height:n,x:i,y:s,zOrder:a,keepRatio:o,mirrorType:d}){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=s??0,this._rect.zOrder=a??0,this._rect.sourceHeight=e.height,this._rect.sourceWidth=e.width,this._rect.keepRatio=o??!1,this._rect.mirrorType=d,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 s=e/t,a=n/i;let o=n,d=i;return s>a?(o=n,d=2*Math.round(n/s/2)):s<a&&(o=2*Math.round(i*s/2),d=i),{width:o,height:d}}_bindVideoTrackSizeChange(){this._stream.on(ps.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!==cs.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 Ma extends Lt{constructor(e,t){super({type:Q.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 T_=Object.defineProperty,k_=Object.getOwnPropertyDescriptor,Or=(r,e,t,n)=>{for(var i=k_(e,t),s=r.length-1,a;s>=0;s--)(a=r[s])&&(i=a(e,t,i)||i);return i&&T_(e,t,i),i};const La=new ht("composition-composer");function Mr(r,e,t){const n=t.value;return t.value=function(...i){return this._active||La.error("composer is not active"),n.apply(this,i)},t}class $t extends Hi{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new hd}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 Ma(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=Do(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=>{Qp(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 Ma(i,{frameRate:this._compositionViewConfig.frameRate}),this._composedStream.setVideoStream(this._mixedVideoStream),n.destroy()}}getMixingConfig(){return this._compositionViewConfig}addVideoStream(e,t){if(!e.viewNode){La.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const n=new w_(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()}}Or([Mr],$t.prototype,"addVideoStream"),Or([Mr],$t.prototype,"updateVideoStream"),Or([Mr],$t.prototype,"removeVideoStream"),Or([Mr],$t.prototype,"muteVideoStream"),Or([Mr],$t.prototype,"unmuteVideoStream");class R_ extends st{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 A_ extends Zr{constructor(e){super({type:Q.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 D_ extends Hi{constructor(e){super(e),this._spriteList=[],this._audioMixer=new Qu({keepAlive:!0})}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=Do(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(s=>s.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 A_(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}addAudioStream(e,t){const n=new R_(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 x_ extends st{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(vt.VideoStreamChange,e))}setAudioStream(e){var t;((t=this._audioStream)==null?void 0:t.id)!==e.id&&(this._audioStream=e,this.emit(vt.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 I_=new ht("streamComposeController");class z_{constructor(e){this._streamManagerController=e,this._composedStream=new x_,this.singleComposer=new C_({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new $t({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new D_({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){I_.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)}unmuteVideoStream(e){this.isEnableMixing&&this.compositionComposer.unmuteVideoStream(e)}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 Na{constructor(e){this._hasBindComposedStreamEvent=!1,this._composedStream=e}bindComposedStreamEvent(){this._hasBindComposedStreamEvent||(this._composedStream.on(vt.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.on(vt.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!0)}unbindComposedStreamEvent(){this._hasBindComposedStreamEvent&&(this._composedStream.off(vt.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.off(vt.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!1)}}const Kt=new ht("PreviewConsumer");class P_ extends Na{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 s=n.srcObject.getVideoTracks()[0],a=n.srcObject.getAudioTracks()[0];s&&s!==i.video&&(this._streamConsumeController.emit(se.CaptureFirstVideoFrame),i.video=s),a&&a!==i.audio&&(this._streamConsumeController.emit(se.CaptureFirstAudioFrame),i.audio=a)}),t.appendChild(n)}startPreview(){if(Kt.log("startPreview"),!this._previewElement){Kt.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(se.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"&&(Kt.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),Kt.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")&&(Kt.log(`remove preview track ${i.label}`),n.removeTrack(i))}),n.getTracks().length===0&&(e.srcObject=null,Kt.log("set srcObject null")))}getPreviewElement(){if(this.isPreviewing)return this._previewElement}get isPreviewing(){return this._isPreviewing}}var Ue={},qi={},$i={exports:{}},Ua;function Ki(){if(Ua)return $i.exports;Ua=1;var r=$i.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")})}),$i.exports}var Ga;function O_(){return Ga||(Ga=1,function(r){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,d,c,u){if(u&&!c)d[u]=e(o[1]);else for(var h=0;h<c.length;h+=1)o[h+1]!=null&&(d[c[h]]=e(o[h+1]))},n=function(o,d,c){var u=o.name&&o.names;o.push&&!d[o.push]?d[o.push]=[]:u&&!d[o.name]&&(d[o.name]={});var h=o.push?{}:u?d[o.name]:d;t(c.match(o.reg),h,o.names,o.name),o.push&&d[o.push].push(h)},i=Ki(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);r.parse=function(o){var d={},c=[],u=d;return o.split(/(\r\n|\r|\n)/).filter(s).forEach(function(h){var l=h[0],f=h.slice(2);l==="m"&&(c.push({rtp:[],fmtp:[]}),u=c[c.length-1]);for(var y=0;y<(i[l]||[]).length;y+=1){var C=i[l][y];if(C.reg.test(f))return n(C,u,f)}}),d.media=c,d};var a=function(o,d){var c=d.split(/=(.+)/,2);return c.length===2?o[c[0]]=e(c[1]):c.length===1&&d.length>1&&(o[c[0]]=void 0),o};r.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},r.parseFmtpConfig=r.parseParams,r.parsePayloads=function(o){return o.toString().split(" ").map(Number)},r.parseRemoteCandidates=function(o){for(var d=[],c=o.split(" ").map(e),u=0;u<c.length;u+=3)d.push({component:c[u],ip:c[u+1],port:c[u+2]});return d},r.parseImageAttributes=function(o){return o.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(a,{})})},r.parseSimulcastStreamList=function(o){return o.split(";").map(function(d){return d.split(",").map(function(c){var u,h=!1;return c[0]!=="~"?u=e(c):(u=e(c.substring(1,c.length)),h=!0),{scid:u,paused:h}})})}}(qi)),qi}var Wi,Ba;function M_(){if(Ba)return Wi;Ba=1;var r=Ki(),e=/%[sdv%]/g,t=function(a){var o=1,d=arguments,c=d.length;return a.replace(e,function(u){if(o>=c)return u;var h=d[o];switch(o+=1,u){case"%%":return"%";case"%s":return String(h);case"%d":return Number(h);case"%v":return""}})},n=function(a,o,d){var c=o.format instanceof Function?o.format(o.push?d:d[o.name]):o.format,u=[a+"="+c];if(o.names)for(var h=0;h<o.names.length;h+=1){var l=o.names[h];o.name?u.push(d[o.name][l]):u.push(d[o.names[h]])}else u.push(d[o.name]);return t.apply(null,u)},i=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return Wi=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(h){h.payloads==null&&(h.payloads="")});var d=o.outerOrder||i,c=o.innerOrder||s,u=[];return d.forEach(function(h){r[h].forEach(function(l){l.name in a&&a[l.name]!=null?u.push(n(h,l,a)):l.push in a&&a[l.push]!=null&&a[l.push].forEach(function(f){u.push(n(h,l,f))})})}),a.media.forEach(function(h){u.push(n("m",r.m[0],h)),c.forEach(function(l){r[l].forEach(function(f){f.name in h&&h[f.name]!=null?u.push(n(l,f,h)):f.push in h&&h[f.push]!=null&&h[f.push].forEach(function(y){u.push(n(l,f,y))})})})}),u.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}(),lo={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&&Nr(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&&!Ua().has(t.report_channel)?(this.logger.warn("your report_channel: "+t.report_channel+" is not exist. report_channel must be one of "+$i().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 "+$i().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 "+$i().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,d=a.options,c=Object.assign(i.initConfig,d);i.emit(x.DEBUGGER_MESSAGE,{type:x.DEBUGGER_MESSAGE_SDK,info:"SDK Load "+a.name+" Plugin",level:"info",time:Date.now(),infoType:"sdk"});var u=new s;return u.apply(i,c),o.push(u),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 "+jr+", 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||!Nr(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 d={};for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&s.indexOf(c)<0&&(d[c]=a[c]);if(a!=null&&typeof Object.getOwnPropertySymbols=="function"){var u=0;for(c=Object.getOwnPropertySymbols(a);u<c.length;u++)s.indexOf(c[u])<0&&(d[c[u]]=a[c[u]])}return d}(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,d=a.params;n.appBridge.onEventV3(s,JSON.stringify(d))}):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 Hr()},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 d=n.configManager.get().user;return s&&(d.tobid=s,d["diss".split("").reverse().join("")]=s),e(me({},d))}},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}(),sn={},zc=[];function Rc(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(zc.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;sn[t]&&sn[t].forEach(function(i){typeof i=="function"&&i(r,n)})}}var an,ho="__rangers_ab_style__";(function(r){r[r.Var=0]="Var",r[r.All=1]="All"})(an||(an={}));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,d=t.ab_cookie_domain,c=t.ab_timeout,u=t.disable_auto_ab,f=qi[t.channel||"sg"]||qi.sg,h=o||Br(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=d||"",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||(!u&&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=Pn(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:an.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 d=s[i];if(d&&Nr(d)){var c=d.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,d.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:an.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,d=a.user,c=this.getABCache(),u=d[this.ab_user_mode]||d.user_unique_id;if(c&&c.uuid&&c.uuid!==u)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:d,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(ho)){var i="body { opacity: 0 !important; }",o=document.head||document.getElementsByTagName("head")[0],a=document.createElement("style");a.id=ho,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(ho))&&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(u){var f=e[u].vid;f&&o.push(f)}),this.versions=this.versions.filter(function(u){return o.includes(u)});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(u){return o.includes(u)});var d=a.val,c=a.vid;d&&c&&this.getVar("$ab_url",d,function(){n.editMode||(d!==window.location.href?setTimeout(function(){if(!n.collect.destroy){var u=""+d;u=u.indexOf("http")===-1?"https://"+u:u,Gi(u).host!==location.host?u=u+"&vid="+c:window.history.replaceState("","",u),window.location.href=u}},100):n.closeOverlayer())})}this.updateVersions()}else this.closeOverlayer();this.callbackMap.forEach(function(u){u.type===an.Var?n.getRealVar(u,""):n.getRealAllVars(u,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(d){d.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(d){console.warn("something error, "+JSON.stringify(d.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:d.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,Nr(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:Oa(),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),Fr(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(),Nr(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:Oa(),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),Fr(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,d=o.url;n.resetStayDuration(a,s,d)}),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,d=o.url;n.setStayParmas(a,s,d)}),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,d=o.errorCode,c=o.response;a==="f_data"&&n.sdkError(s,d,c)}),this.collect.on(e.Types.SDKInnerError,function(o){var a=o.type,s=o.eventData,d=o.errorCode,c=o.msg;n.sdkInnerError(a,s,d,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,d=(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:[d],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,d=[];e.forEach(function(u){u.events.forEach(function(f){d.push(f)})});var c={events:d.map(function(u){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:u.event,sdk_version:s.sdk_version,local_time_ms:u.local_time_ms,tea_event_index:Date.now(),params:u.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,d=a.header,c=[];t.forEach(function(f){f.events.forEach(function(h){c.push(h)})});var u={events:c.map(function(f){return{event:"on_error",params:JSON.stringify({type:e,error_code:n,app_id:d.app_id,app_name:d.app_name||"",error_event:f.event,sdk_version:d.sdk_version,local_time_ms:f.local_time_ms,tea_event_index:Date.now(),params:f.params,header:d,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:[u],timeout:3e4,app_key:"566f58151b0ed37e",forceXhr:!0})},16)}catch{}},r}();function fo(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 po(r){for(var e=r;e&&!fo(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 Ac(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 Hn=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 Hn(r,e);if(Ui(e)){for(var t=!1,n=0;n<e.length;n++)if(Hn(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 u=c.parentElement,f=!1;u;)u.tagName.toLowerCase()==="svg"?(u=null,f=!0):u=u.parentElement;return f}(a)||["HTML","BODY"].includes(a.tagName.toUpperCase()))return!1;var d=a;return d.style.display!=="none"&&(!!fo(d,"container")||!(!function(c){if(c.children.length){var u=c.children;return![].slice.call(u).some(function(f){return f.children.length>0})}return!0}(d)&&!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(d){var c=d.config,u=d.name;t.getPageViewEvent(c,u),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(d){var c=d.getEntries(),u=c[c.length-1],f=u.renderTime||u.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)),Fr(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"}},D_=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 A_(r){for(var e=[];r.parentElement!==null;)e.push(r),r=r.parentElement;var t=[],n=[];return e.forEach(function(i){var o=function(d){if(d===null)return{str:"",index:0};var c=0,u=d.parentElement;if(u)for(var f=u.children,h=0;h<f.length&&f[h]!==d;h++)f[h].nodeName===d.nodeName&&c++;return{str:[d.nodeName.toLowerCase(),fo(d,"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,d=o.element_height,c=a.touch_x,u=a.touch_y,f=A_(e),h=f.element_path,g=f.positions,k=function(I){var U=po(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=po(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(d),i.touch_x=c,i.touch_y=u,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")Hn(I,U)&&(L.attrs=I.getAttribute(U));else if(Ui(U))for(var j=0;j<U.length;j++)Hn(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=po(e);return G.tagName==="A"&&(i.href=G.getAttribute("href")),e.tagName==="IMG"&&(i.src=e.getAttribute("src")),i}var cn=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(Ac(e.target))return null;var n="bav2b_click";switch(t){case"click":return n=e.target.getAttribute("data-applog-click-event")||this.eventName.click,cn(n,e,e.target,this.options,this.ignore);case"change":return me(me({},cn(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 cn(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(Ac(t.target))return null;var n=cn(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=cn(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}(),mo=!1;function O_(r){var e,t,n,i,o=r.event,a=r.editorUrl,s=r.autoTrackInstance;mo||(mo=!0,e=a,t=function(){Rc(o,"editorScriptloadSuccess"),s.destroy()},n=function(){o&&Rc(o,"editorScriptloadError"),mo=!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){zc.push(h)}),o){var s=void 0,d="";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&&(d=h.name)}),d&&(s=d.split("/"))&&s.length)){a="https:/";for(var u=2;u<s.length&&u!==s.length-1;u++)a=a+"/"+s[u];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})},sn[n="tea:openHeatMapCore"]=sn[n]||[],sn[n].push(i)}catch{console.log("openHeatMapCore error")}}var mt,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"})(mt||(mt={}));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=mt.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),d=(o.target,o.isIntersecting,o.intersectionRatio);if(s.intersectionRatio=d,d<=.1&&(o.target.backStatus=!1),e.observeMap.set(a,s),d<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 u=e.observeMap.get(a).intersectionRatio;e.exposureEvent(o,u,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,d,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=Un();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||mt.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,d=window.innerHeight||document.documentElement.clientHeight;return n>=0&&i>=0&&n<=d&&i<=s?(o>s?s:o)*(d-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=mt.RESUME_FORM_PAGE:this.exposureType=mt.LIFECYCLE_SHOW_NEW:(e.hasExposure,e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=mt.RESUME_FORM_PAGE:this.exposureType=mt.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 d=e.hashMap.get(s.oldURL);d&&location.href===d.prev?(e.backStatus=!0,e.exposureType=mt.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 d=s.state;d&&d.current&&e.lastState&&e.lastState.back&&d.current===e.lastState.back?(e.backStatus=!0,e.exposureType=mt.RESUME_FORM_PAGE):e.backStatus=!1}),function(){(function(s,d,c,u){s.addEventListener?s.removeEventListener(d,c,u):s.attachEven&&s.detachEven("on"+d,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 Ic,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,d=0,c=function(u){clearTimeout(a),a=setTimeout(function(){var k=e.scrollTop,z=e.scrollLeft,w=u.target&&u.target.getAttribute("data-scroll-event")||"";g===1||g===2?k===f&&(d=f-i,Math.abs(d)>=n.distance&&n.distance&&n.eventHandle({eventType:"dom",eventName:"scroll",event:w,params:{$direction:g,$offsetY:d,$offsetX:s}},u)):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:d,$offsetX:s}},u)),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(u){console.warn("scroll event error",JSON.stringify(u))}},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 D_(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(d){console.log("handel dom event error "+JSON.stringify(d))}},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"})(Ic||(Ic={}));var xc={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){Ui(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,d=o.errorCode,c=o.response;n.addErrorCount(s,a,d,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 d="log";for(var c in xc)if(xc[c].indexOf(s.event)!==-1){d=c;break}o.addCount(d,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:jr};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()}),Fr(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}(),go=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(lo.hasOwnProperty(n)){var i=lo[n].object,o=""+lo[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;go[t]?(this.process(e,go[t]),console.log("already has "+e+" plugin~")):this.loadPlugin(e,n,function(){i.process(e,go[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,Gr([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 d=e.getPopStateChangeEventData();return e.lastLocation=location.href,e.sendPv(d,"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,Gr([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 d=e.getPopStateChangeEventData();return e.lastLocation=location.href,e.sendPv(d),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 un=new et("default");const _o="VEPUSHER_DEVICE_ID",vo="VEPUSHER_USER_ID",Mc=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(vo,r),r;const e=localStorage.getItem(vo);if(e)return e;const t=Mc(12);return localStorage.setItem(vo,t),r}function J_(r){if(r)return localStorage.setItem(_o,r),r;const e=localStorage.getItem(_o);if(e)return e;const t=Mc(11);return localStorage.setItem(_o,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",...{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",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,un.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.114",...n}};un.config(i),this.markCollectTeaEventReady()},this.isReady=!1,this.queueTeaEvent=[],un.init({app_id:778494,channel:"sg"}),this._showLogInConsole=e}sendTeaEvent(e,t,n=!1){if(e)if(this.isReady)try{const i={...K_(t||{})};un.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 un}}let dn;function Z_({showLogInConsole:r}){dn=new X_({showLogInConsole:r})}function X(r,e,t=!1){dn&&dn.sendTeaEvent(r,e,t)}function Y_(r,e){dn&&dn.configTea(r,e)}const Oc=()=>{X(J.PAGE_VISIBLE_CHANGE,{page_visible:!document.hidden})},Q_=()=>{document.addEventListener("visibilitychange",Oc)},ev=()=>{document.removeEventListener("visibilitychange",Oc)};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 xt{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(gs,"video"),{sampleRate:o}=pr(_s,"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=Ct(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 Ls({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 Ls({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=Dl(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 Ct(this._cameraStreams)[0]||Ct(this._screenStreams)[0]||Ct(this._videoFileStreams)[0]||Ct(this._imageStreams)[0]||Ct(this._customVideoStreams)[0]}getDefaultAudioStream(){return Ct(this._microphoneStreams)[0]||Ct(this._audioFileStreams)[0]||Ct(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 Nt=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 yo{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 Pc=new Nt("SingleComposer");class rv extends yo{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){Pc.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):Pc.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 xt{constructor(e,{width:t,height:n,x:i,y:o,zOrder:a,keepRatio:s,mirrorType:d}){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=d,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,d=i;return o>a?(s=n,d=2*Math.round(n/o/2)):o<a&&(s=2*Math.round(i*o/2),d=i),{width:s,height:d}}_bindVideoTrackSizeChange(){this._stream.on(ms.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!==ds.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 Lc 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,ln=(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 Uc=new Nt("composition-composer");function hn(r,e,t){const n=t.value;return t.value=function(...i){return this._active||Uc.error("composer is not active"),n.apply(this,i)},t}class yr extends yo{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 Lc(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=Aa(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 Lc(i,{frameRate:this._compositionViewConfig.frameRate}),this._composedStream.setVideoStream(this._mixedVideoStream),n.destroy()}}getMixingConfig(){return this._compositionViewConfig}addVideoStream(e,t){if(!e.viewNode){Uc.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()}}ln([hn],yr.prototype,"addVideoStream"),ln([hn],yr.prototype,"updateVideoStream"),ln([hn],yr.prototype,"removeVideoStream"),ln([hn],yr.prototype,"muteVideoStream"),ln([hn],yr.prototype,"unmuteVideoStream");class sv extends xt{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 Tn{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 yo{constructor(e){super(e),this._spriteList=[],this._audioMixer=new Il({keepAlive:!0})}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=Aa(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 xt{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($t.VideoStreamChange,e))}setAudioStream(e){var t;((t=this._audioStream)==null?void 0:t.id)!==e.id&&(this._audioStream=e,this.emit($t.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 Nt("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 Gc{constructor(e){this._hasBindComposedStreamEvent=!1,this._composedStream=e}bindComposedStreamEvent(){this._hasBindComposedStreamEvent||(this._composedStream.on($t.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.on($t.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!0)}unbindComposedStreamEvent(){this._hasBindComposedStreamEvent&&(this._composedStream.off($t.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.off($t.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!1)}}const Sr=new Nt("PreviewConsumer");class hv extends Gc{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={},So={},bo={exports:{}},Nc;function Eo(){if(Nc)return bo.exports;Nc=1;var r=bo.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")})}),bo.exports}var Bc;function fv(){return Bc||(Bc=1,function(r){var e=function(s){return String(Number(s))===s?Number(s):s},t=function(s,d,c,u){if(u&&!c)d[u]=e(s[1]);else for(var f=0;f<c.length;f+=1)s[f+1]!=null&&(d[c[f]]=e(s[f+1]))},n=function(s,d,c){var u=s.name&&s.names;s.push&&!d[s.push]?d[s.push]=[]:u&&!d[s.name]&&(d[s.name]={});var f=s.push?{}:u?d[s.name]:d;t(c.match(s.reg),f,s.names,s.name),s.push&&d[s.push].push(f)},i=Eo(),o=RegExp.prototype.test.bind(/^([a-z])=(.*)/);r.parse=function(s){var d={},c=[],u=d;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:[]}),u=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,u,g)}}),d.media=c,d};var a=function(s,d){var c=d.split(/=(.+)/,2);return c.length===2?s[c[0]]=e(c[1]):c.length===1&&d.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 d=[],c=s.split(" ").map(e),u=0;u<c.length;u+=3)d.push({component:c[u],ip:c[u+1],port:c[u+2]});return d},r.parseImageAttributes=function(s){return s.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(a,{})})},r.parseSimulcastStreamList=function(s){return s.split(";").map(function(d){return d.split(",").map(function(c){var u,f=!1;return c[0]!=="~"?u=e(c):(u=e(c.substring(1,c.length)),f=!0),{scid:u,paused:f}})})}}(So)),So}var wo,Fc;function pv(){if(Fc)return wo;Fc=1;var r=Eo(),e=/%[sdv%]/g,t=function(a){var s=1,d=arguments,c=d.length;return a.replace(e,function(u){if(s>=c)return u;var f=d[s];switch(s+=1,u){case"%%":return"%";case"%s":return String(f);case"%d":return Number(f);case"%v":return""}})},n=function(a,s,d){var c=s.format instanceof Function?s.format(s.push?d:d[s.name]):s.format,u=[a+"="+c];if(s.names)for(var f=0;f<s.names.length;f+=1){var h=s.names[f];s.name?u.push(d[s.name][h]):u.push(d[s.names[f]])}else u.push(d[s.name]);return t.apply(null,u)},i=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];return wo=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 d=s.outerOrder||i,c=s.innerOrder||o,u=[];return d.forEach(function(f){r[f].forEach(function(h){h.name in a&&a[h.name]!=null?u.push(n(f,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(g){u.push(n(f,h,g))})})}),a.media.forEach(function(f){u.push(n("m",r.m[0],f)),c.forEach(function(h){r[h].forEach(function(g){g.name in f&&f[g.name]!=null?u.push(n(h,g,f)):g.push in f&&f[g.push]!=null&&f[g.push].forEach(function(k){u.push(n(h,g,k))})})})}),u.join(`\r
|
|
67
67
|
`)+`\r
|
|
68
|
-
`},Wi}var Fa;function L_(){if(Fa)return Ue;Fa=1;var r=O_(),e=M_(),t=Ki();return Ue.grammar=t,Ue.write=e,Ue.parse=r.parse,Ue.parseParams=r.parseParams,Ue.parseFmtpConfig=r.parseFmtpConfig,Ue.parsePayloads=r.parsePayloads,Ue.parseRemoteCandidates=r.parseRemoteCandidates,Ue.parseImageAttributes=r.parseImageAttributes,Ue.parseSimulcastStreamList=r.parseSimulcastStreamList,Ue}var N_=L_();const Wt=_e(N_);function gn(r){return new Promise(e=>{setTimeout(e,r)})}async function U_(r,e={},t=0){const n=new AbortController;let i=!1;e=Object.assign({},e,{signal:n.signal});const s=[fetch(r,e)];t&&s.push(new Promise((a,o)=>{setTimeout(()=>{i||(o({httpCode:0,message:"Timeout"}),n.abort())},t)}));try{const a=await Promise.race(s);if(i=!0,!a.ok||a.status<200||a.status>=300)throw{httpCode:a.status,message:a.statusText};return a.json()}catch(a){throw i=!0,a}}async function Va(r,e={},t={}){const{timeout:n=0,retryDelay:i=0}=t;let{retryCount:s=0}=t;try{return await U_(r,e,n)}catch(a){if(s--,t.retryCount=s,s<0)throw a;return await gn(i),await Va(r,e,t)}}const Ji=-1;function he(r,e){let t;return e.forEach(n=>{n.type===r&&(t=n)}),t}async function Xi(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:he("media-source",n),codec:he("codec",n),candidatePair:he("candidate-pair",n),remoteCandidate:he("remote-candidate",n),localCandidate:he("local-candidate",n),track:he("track",n),outboundRtp:he("outbound-rtp",n),remoteInboundRtp:he("remote-inbound-rtp",n),transport:he("transport",n)}),i&&(t.video={mediaSource:he("media-source",i),codec:he("codec",i),candidatePair:he("candidate-pair",i),remoteCandidate:he("remote-candidate",i),localCandidate:he("local-candidate",i),track:he("track",i),outboundRtp:he("outbound-rtp",i),remoteInboundRtp:he("remote-inbound-rtp",i),transport:he("transport",i)}),t}async function G_(r,e,t){var u,h,l,f,y,C,v,E,k,g,D,L,R,M,N,U,B,H,Y,W,de,ce,Ee,Ce,we,ye,Le,Ge,Te,_t,It,zt,Nr,Rn,An,Dn,Ur,gt,Gr;const n=await Xi(e,t);await gn(r);const i=await Xi(e,t),{audio:s,video:a}=n,{audio:o,video:d}=i,c={};if(s!=null&&s.codec&&(o!=null&&o.codec)){const De=((u=o.outboundRtp)==null?void 0:u.timestamp)-((h=s.outboundRtp)==null?void 0:h.timestamp),Br=((l=o.outboundRtp)==null?void 0:l.bytesSent)-((f=s.outboundRtp)==null?void 0:f.bytesSent),nt=((y=o.remoteInboundRtp)==null?void 0:y.packetsLost)-((C=s.remoteInboundRtp)==null?void 0:C.packetsLost),Pt=((v=o.outboundRtp)==null?void 0:v.packetsSent)-((E=s.outboundRtp)==null?void 0:E.packetsSent),Fr=(((k=o.mediaSource)==null?void 0:k.totalAudioEnergy)??0)-(((g=s.mediaSource)==null?void 0:g.totalAudioEnergy)??0);c.audio={codec:o.codec.mimeType,channels:o.codec.channels,sendBitrate:Br/De*8e3,packetsSent:(D=o.outboundRtp)==null?void 0:D.packetsSent,nackCount:(L=o.outboundRtp)==null?void 0:L.nackCount,packetsLost:(R=o.remoteInboundRtp)==null?void 0:R.packetsLost,packetsLostPercent:nt/Pt,deltaAudioEnergy:Fr}}if(a!=null&&a.codec&&(d!=null&&d.codec)){const De=((M=d.outboundRtp)==null?void 0:M.timestamp)-((N=a.outboundRtp)==null?void 0:N.timestamp),Br=((U=d.outboundRtp)==null?void 0:U.bytesSent)-((B=a.outboundRtp)==null?void 0:B.bytesSent),nt=((H=d.outboundRtp)==null?void 0:H.framesEncoded)-((Y=a.outboundRtp)==null?void 0:Y.framesEncoded),Pt=((W=d.outboundRtp)==null?void 0:W.totalEncodeTime)-((de=a.outboundRtp)==null?void 0:de.totalEncodeTime),Fr=((ce=d.outboundRtp)==null?void 0:ce.framesSent)-((Ee=a.outboundRtp)==null?void 0:Ee.framesSent),xn=((Ce=d.outboundRtp)==null?void 0:Ce.packetsSent)-((we=a.outboundRtp)==null?void 0:we.packetsSent),Vr=((ye=d.outboundRtp)==null?void 0:ye.totalPacketSendDelay)-((Le=a.outboundRtp)==null?void 0:Le.totalPacketSendDelay),os=((Ge=d.remoteInboundRtp)==null?void 0:Ge.packetsLost)-((Te=a.remoteInboundRtp)==null?void 0:Te.packetsLost);c.video={codec:d.codec.mimeType,sendBitrate:Br/De*8e3,frameWidth:(_t=d.outboundRtp)==null?void 0:_t.frameWidth,frameHeight:(It=d.outboundRtp)==null?void 0:It.frameHeight,framesPerSecond:Math.floor(Fr/De*1e3||0),framesEncoded:(zt=d.outboundRtp)==null?void 0:zt.framesEncoded,framesEncodedPerSecond:nt*1e3/De,keyFramesEncoded:(Nr=d.outboundRtp)==null?void 0:Nr.keyFramesEncoded,framesSent:(Rn=d.outboundRtp)==null?void 0:Rn.frameHeight,frameEncodeAvgTime:Pt*1e3/nt,packetsSent:(An=d.outboundRtp)==null?void 0:An.packetsSent,packetSendDelay:Vr*1e3/xn,nackCount:(Dn=d.outboundRtp)==null?void 0:Dn.nackCount,firCount:(Ur=d.outboundRtp)==null?void 0:Ur.firCount,pliCount:(gt=d.outboundRtp)==null?void 0:gt.pliCount,packetsLost:(Gr=d.remoteInboundRtp)==null?void 0:Gr.packetsLost,packetsLostPercent:os/xn,deltaTime:De}}return{stats:c,originStats:{audio:o,video:d}}}function ae(r,e=Ji){return r??e}function B_(r){var e,t,n,i,s,a,o,d,c,u,h,l,f,y,C,v,E,k,g,D,L,R,M,N,U,B,H,Y,W,de,ce,Ee,Ce,we,ye,Le,Ge,Te,_t,It,zt;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:(s=r.outboundRtp)==null?void 0:s.retransmittedBytesSent,audio_retransmitted_packets_sent:(a=r.outboundRtp)==null?void 0:a.retransmittedPacketsSent,audio_record_sample_rate:(o=r.codec)==null?void 0:o.clockRate,audio_num_channels:(d=r.codec)==null?void 0:d.channels,audio_level:(c=r.mediaSource)!=null&&c.audioLevel?-10*Math.log10(Math.pow((u=r.mediaSource)==null?void 0:u.audioLevel,2)):(h=r.mediaSource)==null?void 0:h.audioLevel,audio_volume:(l=r.mediaSource)!=null&&l.audioLevel?((f=r.mediaSource)==null?void 0:f.audioLevel)*255:(y=r.mediaSource)==null?void 0:y.audioLevel,audio_total_audio_energy:(C=r.mediaSource)==null?void 0:C.totalAudioEnergy,audio_total_input_duration:(v=r.mediaSource)==null?void 0:v.totalSamplesDuration,audio_send_level:(E=r.mediaSource)==null?void 0:E.audioLevel,audio_ice_available_outgoing_bitrate:(k=r.candidatePair)==null?void 0:k.availableOutgoingBitrate,audio_ice_bytes_received:(g=r.candidatePair)==null?void 0:g.bytesReceived,audio_ice_bytes_sent:(D=r.candidatePair)==null?void 0:D.bytesSent,audio_ice_nominated:(L=r.candidatePair)==null?void 0:L.nominated,audio_ice_pair_id:(R=r.candidatePair)==null?void 0:R.id,audio_ice_pair_rtt:(M=r.candidatePair)==null?void 0:M.currentRoundTripTime,audio_ice_pair_state:(N=r.candidatePair)==null?void 0:N.state,audio_ice_pair_writable:(U=r.candidatePair)==null?void 0:U.writable,audio_recv_ping_requests:(B=r.candidatePair)==null?void 0:B.requestsReceived,audio_recv_ping_responses:(H=r.candidatePair)==null?void 0:H.responsesReceived,audio_sent_ping_requests_before_first_response:(Y=r.candidatePair)==null?void 0:Y.requestsSent,audio_sent_ping_requests_total:(((W=r.candidatePair)==null?void 0:W.requestsSent)??0)+(((de=r.candidatePair)==null?void 0:de.consentRequestsSent)??0),audio_sent_ping_responses:(ce=r.candidatePair)==null?void 0:ce.responsesSent,audio_local_candidate_type:(Ee=r.localCandidate)==null?void 0:Ee.candidateType,audio_local_ip:((Ce=r.localCandidate)==null?void 0:Ce.ip)||((we=r.localCandidate)==null?void 0:we.address),audio_local_network_type:(ye=r.localCandidate)==null?void 0:ye.networkType,audio_local_port:(Le=r.localCandidate)==null?void 0:Le.port,audio_local_protocol:(Ge=r.localCandidate)==null?void 0:Ge.protocol,audio_remote_candidate_type:(Te=r.remoteCandidate)==null?void 0:Te.candidateType,audio_remote_ip:((_t=r.remoteCandidate)==null?void 0:_t.ip)||((It=r.remoteCandidate)==null?void 0:It.address),audio_remote_port:(zt=r.remoteCandidate)==null?void 0:zt.port}}function F_(r){var e,t,n,i,s,a,o,d,c,u,h,l,f,y,C,v,E,k,g,D,L,R,M,N,U,B,H,Y,W,de,ce,Ee,Ce,we,ye,Le,Ge;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:(s=r.outboundRtp)==null?void 0:s.qualityLimitationDurations,video_target_bitrate:(a=r.outboundRtp)==null?void 0:a.targetBitrate,video_rtt:(((o=r.remoteInboundRtp)==null?void 0:o.roundTripTime)||0)*1e3,video_jitter:(((d=r.remoteInboundRtp)==null?void 0:d.jitter)||0)*1e3,video_packets_lost:(c=r.remoteInboundRtp)==null?void 0:c.packetsLost,video_fraction_lost:(u=r.remoteInboundRtp)==null?void 0:u.fractionLost,video_ice_available_outgoing_bitrate:(h=r.candidatePair)==null?void 0:h.availableOutgoingBitrate,video_ice_bytes_received:(l=r.candidatePair)==null?void 0:l.bytesReceived,video_ice_bytes_sent:(f=r.candidatePair)==null?void 0:f.bytesSent,video_ice_nominated:(y=r.candidatePair)==null?void 0:y.nominated,video_ice_pair_id:(C=r.candidatePair)==null?void 0:C.id,video_ice_pair_rtt:(v=r.candidatePair)==null?void 0:v.currentRoundTripTime,video_ice_pair_state:(E=r.candidatePair)==null?void 0:E.state,video_ice_pair_writable:(k=r.candidatePair)==null?void 0:k.writable,video_recv_ping_requests:(g=r.candidatePair)==null?void 0:g.requestsReceived,video_recv_ping_responses:(D=r.candidatePair)==null?void 0:D.responsesReceived,video_sent_ping_requests_before_first_response:(L=r.candidatePair)==null?void 0:L.requestsSent,video_sent_ping_requests_total:(((R=r.candidatePair)==null?void 0:R.requestsSent)??0)+(((M=r.candidatePair)==null?void 0:M.consentRequestsSent)??0),video_sent_ping_responses:(N=r.candidatePair)==null?void 0:N.responsesSent,video_local_candidate_type:(U=r.localCandidate)==null?void 0:U.candidateType,video_local_ip:((B=r.localCandidate)==null?void 0:B.ip)||((H=r.localCandidate)==null?void 0:H.address),video_local_network_type:(Y=r.localCandidate)==null?void 0:Y.networkType,video_local_port:(W=r.localCandidate)==null?void 0:W.port,video_local_protocol:(de=r.localCandidate)==null?void 0:de.protocol,video_remote_candidate_type:(ce=r.remoteCandidate)==null?void 0:ce.candidateType,video_remote_ip:((Ee=r.remoteCandidate)==null?void 0:Ee.ip)||((Ce=r.remoteCandidate)==null?void 0:Ce.address),video_remote_port:(we=r.remoteCandidate)==null?void 0:we.port,video_input_frame_rate:(ye=r.mediaSource)==null?void 0:ye.framesPerSecond,video_input_frame_width:(Le=r.mediaSource)==null?void 0:Le.width,video_input_frame_height:(Ge=r.mediaSource)==null?void 0:Ge.height}}function V_(r,e,t){var c,u,h,l,f,y,C,v,E,k,g,D,L,R,M,N,U,B,H,Y,W,de,ce,Ee,Ce,we,ye;const n=F_(e.video??{}),{video_input_frame_width:i,video_input_frame_height:s}=n,a=ae((c=r.video)==null?void 0:c.frameWidth),o=ae((u=r.video)==null?void 0:u.frameHeight),d=a<Number(i)||o<Number(s);return{...n,video_send_k_bitrate:ae((h=r.video)==null?void 0:h.sendBitrate)/1e3,video_send_frame_rate:ae((l=r.video)==null?void 0:l.framesPerSecond),video_encode_avg_time:ae((f=r.video)==null?void 0:f.frameEncodeAvgTime),video_encoder_output_frame_rate:ae((y=r.video)==null?void 0:y.framesEncodedPerSecond),video_encoded_frame_width:ae((C=r.video)==null?void 0:C.frameWidth),video_encoded_frame_height:ae((v=r.video)==null?void 0:v.frameHeight),video_encoded_key_frames:ae((E=r.video)==null?void 0:E.keyFramesEncoded),video_delta_time:ae((k=r.video)==null?void 0:k.deltaTime,2e3),video_packets_sent:ae((g=r.video)==null?void 0:g.packetsSent),video_nack_count:ae((D=r.video)==null?void 0:D.nackCount),video_fir_count:ae((L=r.video)==null?void 0:L.firCount),video_pli_count:ae((R=r.video)==null?void 0:R.pliCount),video_packets_lost:ae((M=r.video)==null?void 0:M.packetsLost),video_packets_lost_percent:(N=r.video)==null?void 0:N.packetsLostPercent,video_codec:(U=r.video)==null?void 0:U.codec,video_duration:(B=r.video)==null?void 0:B.deltaTime,video_frame_rate_compliance:t!=null&&t.idealFrameRate?Math.min(ae((H=r.video)==null?void 0:H.framesPerSecond)/t.idealFrameRate,1)*100:Ji,video_bitrate_compliance:t!=null&&t.idealBitrate?Math.min(ae((Y=r.video)==null?void 0:Y.sendBitrate)/t.idealBitrate,1)*100:Ji,video_resolution_downgrade:d,...B_(e.audio??{}),audio_send_k_bitrate:ae((W=r.audio)==null?void 0:W.sendBitrate)/1e3,audio_send_channels:ae((de=r.audio)==null?void 0:de.channels),audio_packets_sent:ae((ce=r.audio)==null?void 0:ce.packetsSent),audio_packets_lost:ae((Ee=r.audio)==null?void 0:Ee.packetsLost),audio_packets_lost_percent:(Ce=r.audio)==null?void 0:Ce.packetsLostPercent,audio_codec:(we=r.audio)==null?void 0:we.codec,audio_delta_energy:(ye=r.audio)==null?void 0:ye.deltaAudioEnergy}}function j_(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 H_="42001f",q_="42e01f",$_=r=>{var t;if(!Es)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")})},K_=r=>{r.ext&&(ru||Hr)&&(r.ext=r.ext.filter(e=>{var t;return!((t=e.uri)!=null&&t.includes("video-orientation"))}))};function W_(r,e){r==null||r.rtp.forEach(({codec:t,payload:n})=>{if(["vp8","h264"].includes(t.toLocaleLowerCase())){const i=r.fmtp.find(s=>s.payload===n);i?i.config=[...i.config.split(";"),`x-google-min-bitrate=${e*.4}`,`x-google-start-bitrate=${e}`].join(";"):r.fmtp.push({payload:n,config:`x-google-min-bitrate=${e*.4};x-google-start-bitrate=${e}`})}})}function ja(r,e){if(!Array.isArray(r.fmtp)||!Array.isArray(r.rtp))return;const t=r.fmtp.find(a=>a.config&&a.config.includes(H_)),n=r.fmtp.find(a=>a.config&&a.config.includes(q_));if(!t||!n)return;const i=r.rtp.findIndex(a=>a.payload===t.payload),s=r.rtp.findIndex(a=>a.payload===n.payload);if(i!==-1&&s!==-1){if(e==="hardware"){if(s<i){const a=r.rtp[s];r.rtp[s]=r.rtp[i],r.rtp[i]=a}}else if(i<s){const a=r.rtp[i];r.rtp[i]=r.rtp[s],r.rtp[s]=a}}r.payloads=r.rtp.map(a=>a.payload).join(" ")}const ve=new ht("PCConnect");class J_{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 publish(e,t,n){var h;const i=new RTCPeerConnection;this._pc=i,this._bindRTCEvent();const s=e.filter(l=>(l==null?void 0:l.kind)==="audio")[0],a=e.filter(l=>(l==null?void 0:l.kind)==="video")[0];s&&this._ms.addTrack(s),a&&this._ms.addTrack(a),this._audioTransceiver=i.addTransceiver(s||"audio",{direction:"sendonly",sendEncodings:[{maxBitrate:t[0]}],streams:[this._ms]}),ve.log("add track to pc,",s),this._videoTransceiver=i.addTransceiver(a||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),ve.log("add track to pc,",a);const o=await i.createOffer();ve.groupCollapsed("local offer"),ve.log(o.sdp);const d=Wt.parse(o.sdp);d.media.forEach(l=>{l.type==="audio"?$_(l):l.type==="video"&&(K_(l),ja(l,"software"),W_(l,t[1]))}),o.sdp=Wt.write(d),ve.log("local offer modified"),ve.log(o.sdp),await i.setLocalDescription(o);const c=await Va(this._signalUrl,{method:"POST",mode:"cors",body:JSON.stringify({sessionId:""+this._sessionId,version:"1.0-html",localSdp:o,metadata:{platform:"Web"}})},{...this._opts,timeout:n!=null&&n.isReconnect?10*xo:(h=this._opts)==null?void 0:h.timeout});if((c==null?void 0:c.code)!==200)throw{code:c.code,message:c.message};ve.log("remote answer:"),ve.log(c.remoteSdp.sdp);const u=Wt.parse(c.remoteSdp.sdp);if(u.media.forEach(l=>{var f;(f=l.fingerprint)!=null&&f.hash&&(l.fingerprint.hash=l.fingerprint.hash.toUpperCase())}),c.remoteSdp.sdp=Wt.write(u),ve.log("remote answer modified"),ve.log(c.remoteSdp.sdp),ve.groupEnd(),i.connectionState==="closed"){ve.log("PeerConnection is closed, skipping setRemoteDescription");return}j(V.PUSH_SDP_INFO,{offer_sdp:o.sdp,answer_sdp:c.remoteSdp.sdp}),await i.setRemoteDescription(c.remoteSdp)}updateVideoEncodeType(e){var s,a;const t=this._pc,n=(s=t==null?void 0:t.localDescription)==null?void 0:s.sdp,i=(a=t==null?void 0:t.remoteDescription)==null?void 0:a.sdp;if(n&&i){const o=Wt.parse(i);o.media.forEach(d=>{d.type==="video"&&ja(d,e)}),t.setLocalDescription(t.localDescription),t.setRemoteDescription({type:"answer",sdp:Wt.write(o)})}}async updatePublish(e,t){var s,a;let n;t==="video"?n=this._videoTransceiver:n=this._audioTransceiver;const i=(s=n==null?void 0:n.sender)==null?void 0:s.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)),ve.log(`replace ${t} track done! ${i==null?void 0:i.label} -> ${e==null?void 0:e.label}`))}applyBitrate(e,t,n){var a,o,d;const i=t==="video"?(a=this._videoTransceiver)==null?void 0:a.sender:(o=this._audioTransceiver)==null?void 0:o.sender;if(!i)return;const s=i.getParameters();s.encodings=(d=s.encodings)!=null&&d.length?s.encodings:[{}],n?s.encodings[0].minBitrate=e:s.encodings[0].maxBitrate=e,i.setParameters(s),ve.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,ve.log("close pc!")}getStats(){var e,t;return Xi((e=this._audioTransceiver)==null?void 0:e.sender,(t=this._videoTransceiver)==null?void 0:t.sender)}getStatsSnapshoot(e){var t,n;return G_(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",()=>{ve.log("onconnectionstatechange:",e.connectionState),this._onConnectStateChange(e.connectionState)})}}var pt=(r=>(r.OnError="onerror",r.OnConnectClosed="onconnectclosed",r.OnFirstFramePushed="onfirstframepushed",r))(pt||{}),ft=(r=>(r.Video="video",r.Audio="audio",r))(ft||{}),Oe=(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))(Oe||{}),Dt=(r=>(r.Ready="ready",r.Error="error",r.FirstFramePushed="firstframepushed",r.Flvfile="flvfile",r.STATS="stats",r.Close="close",r))(Dt||{}),Zi={exports:{}},Ha;function X_(){return Ha||(Ha=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(d,c,u){this.fn=d,this.context=c,this.once=u||!1}function s(d,c,u,h,l){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new i(u,h||d,l),y=t?t+c:c;return d._events[y]?d._events[y].fn?d._events[y]=[d._events[y],f]:d._events[y].push(f):(d._events[y]=f,d._eventsCount++),d}function a(d,c){--d._eventsCount===0?d._events=new n:delete d._events[c]}function o(){this._events=new n,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,h;if(this._eventsCount===0)return c;for(h in u=this._events)e.call(u,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var l=0,f=h.length,y=new Array(f);l<f;l++)y[l]=h[l].fn;return y},o.prototype.listenerCount=function(c){var u=t?t+c:c,h=this._events[u];return h?h.fn?1:h.length:0},o.prototype.emit=function(c,u,h,l,f,y){var C=t?t+c:c;if(!this._events[C])return!1;var v=this._events[C],E=arguments.length,k,g;if(v.fn){switch(v.once&&this.removeListener(c,v.fn,void 0,!0),E){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,u),!0;case 3:return v.fn.call(v.context,u,h),!0;case 4:return v.fn.call(v.context,u,h,l),!0;case 5:return v.fn.call(v.context,u,h,l,f),!0;case 6:return v.fn.call(v.context,u,h,l,f,y),!0}for(g=1,k=new Array(E-1);g<E;g++)k[g-1]=arguments[g];v.fn.apply(v.context,k)}else{var D=v.length,L;for(g=0;g<D;g++)switch(v[g].once&&this.removeListener(c,v[g].fn,void 0,!0),E){case 1:v[g].fn.call(v[g].context);break;case 2:v[g].fn.call(v[g].context,u);break;case 3:v[g].fn.call(v[g].context,u,h);break;case 4:v[g].fn.call(v[g].context,u,h,l);break;default:if(!k)for(L=1,k=new Array(E-1);L<E;L++)k[L-1]=arguments[L];v[g].fn.apply(v[g].context,k)}}return!0},o.prototype.on=function(c,u,h){return s(this,c,u,h,!1)},o.prototype.once=function(c,u,h){return s(this,c,u,h,!0)},o.prototype.removeListener=function(c,u,h,l){var f=t?t+c:c;if(!this._events[f])return this;if(!u)return a(this,f),this;var y=this._events[f];if(y.fn)y.fn===u&&(!l||y.once)&&(!h||y.context===h)&&a(this,f);else{for(var C=0,v=[],E=y.length;C<E;C++)(y[C].fn!==u||l&&!y[C].once||h&&y[C].context!==h)&&v.push(y[C]);v.length?this._events[f]=v.length===1?v[0]:v:a(this,f)}return this},o.prototype.removeAllListeners=function(c){var u;return c?(u=t?t+c:c,this._events[u]&&a(this,u)):(this._events=new n,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,r.exports=o}(Zi)),Zi.exports}var Z_=X_();const Y_=_e(Z_);var vn=(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))(vn||{});class qa 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 $a(r,e,t){return new qa(r,e,t)}const Zt=class Zt{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 Zt.enable}get _enableLong(){return Zt.enableLong}get long(){return this._enableLong}};Zt.enable=!1,Zt.enableLong=!1;let mt=Zt;const Me=new mt("RTMP_Capture");class Q_{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(Me.log(`replace ${e} track`),e===ft.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){Me.log("no video track to capture");return}if(this.videoTrack.readyState!=="live"){Me.warn("video track not live");return}const e=new MediaStreamTrackProcessor(this.videoTrack);e.track=this.videoTrack;const t=e.readable.getReader();this._videoProcessorReader=t,Me.log("start capture video frame",this.videoTrack);let n;for(;;){n&&clearInterval(n),n=setTimeout(()=>{Me.warn("long time no capture output"),this._bridge._postMockVideoEncodeFlag()},1500);const s=await t.read();if(clearInterval(n),this._videoFirstframeCaptured||(this._videoFirstframeCaptured=!0,Me.log("video first frame captured")),s.done||!s.value){(i=s.value)==null||i.close();break}this._bridge._postVideoFrame(s.value,this.videoTrack.getSettings())}clearInterval(n),this._videoFirstframeCaptured=!1,this._videoProcessorReader=null,Me.log("video track read done!",e.track)}async _startAudioCapture(){if(!this.audioTrack){Me.log("no audio track to capture");return}if(this.audioTrack.readyState!=="live"){Me.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,Me.log("start capture audio frame");;){const n=await t.read();if(this._audioFirstframeCaptured||(this._audioFirstframeCaptured=!0,Me.log("audio first frame captured")),n.done||!n.value)break;this._bridge._postAudioFrame(n.value,this.audioTrack.getSettings())}this._audioFirstframeCaptured=!1,this._audioProcessorReader=null,Me.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 Ka='(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,N,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,N=new Array(C-1);p<C;p++)N[p-1]=arguments[p];d.fn.apply(d.context,N)}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(!N)for(R=1,N=new Array(C-1);R<C;R++)N[R-1]=arguments[R];d[p].fn.apply(d[p].context,N)}}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 x=class x{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 x.enable}get _enableLong(){return x.enableLong}get long(){return this._enableLong}};x.enable=!1,x.enableLong=!1;let E=x;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 L=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){L.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(),L.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),L.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,L.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);L.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 B=(i=>(i[i.AUDIO=8]="AUDIO",i[i.VIDEO=9]="VIDEO",i[i.SCRIPT_DATA=18]="SCRIPT_DATA",i))(B||{});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(B.VIDEO,s);this._core.emit(l.OnPacketed,c)}if(o.hasAudio){const c=this._flv.genSeqTag(B.AUDIO,s);this._core.emit(l.OnPacketed,c)}this._firstFrame=!1,ae.log("first frame encoded & packed")}const r=this._flv.genFrameTag(e==="video"?B.VIDEO:B.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.videoBitrate}`),this._core.emit(l.OnUpstreamFeedback,{videoBitrate:t.videoBitrate,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,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}),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}),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',Wa=typeof self<"u"&&self.Blob&&new Blob([Ka],{type:"text/javascript;charset=utf-8"});function eg(r){let e;try{if(e=Wa&&(self.URL||self.webkitURL).createObjectURL(Wa),!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(Ka),{name:r==null?void 0:r.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}try{mt.enable=location.href.indexOf("rtmpdebug")!==-1,mt.enableLong=location.href.indexOf("rtmpdebug=long")!==-1}catch{}const yn=new mt("Bridge");class Ja extends Y_{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new Q_(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 s,a;let e,t;const n=new Promise((o,d)=>{e=o,t=d}),i=o=>{var d;switch((d=this._worker)==null||d.removeEventListener("message",i),o.data.type){case Dt.Error:t(o.data.data);break;default:this._bindWorkerEvent(),yn.log("rtmp ready!"),e(!0)}};try{this._worker=new eg}catch(o){t($a(vn.RTMP_INIT_FAIL,o.message))}return(s=this._worker)==null||s.postMessage({type:Oe.Init,options:{logEnable:mt.enable,logEnableLong:mt.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 Dt.Error:yn.table(n.data.data),this.emit(pt.OnError,n.data.data);break;case Dt.Flvfile:tg(n.data.buffer);break;case Dt.FirstFramePushed:this.emit(pt.OnFirstFramePushed);break;case Dt.Close:this.emit(pt.OnConnectClosed),this.destroy();break}}),(t=this._worker)==null||t.addEventListener("error",n=>{this.emit(pt.OnError,$a(vn.WORKER_ERROR,n.message))})}addTrack(e){e.kind===ft.Video&&(this._videoMsTrack=e),e.kind===ft.Audio&&(this._audioMsTrack=e),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack)}replaceTrack(e,t){e===ft.Video&&(this._videoMsTrack=t),e===ft.Audio&&(this._audioMsTrack=t),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack),this._capture.restartCapture(e)}async getStats(){var s,a;let e,t;const n=new Promise((o,d)=>{e=o,t=d});this._worker||setTimeout(()=>{t()},0);const i=o=>{var d;switch(o.data.type){case Dt.STATS:e(o.data.data),(d=this._worker)==null||d.removeEventListener("message",i);break}};return(s=this._worker)==null||s.addEventListener("message",i),(a=this._worker)==null||a.postMessage({type:Oe.GetStats}),n}_postVideoFrame(e,t){var n;(n=this._worker)==null||n.postMessage({type:Oe.VideoFrame,frame:e,setting:t},[e])}_postMockVideoEncodeFlag(){var e;(e=this._worker)==null||e.postMessage({type:Oe.MockVideoEncode})}_setAVExist(e,t){var n;(n=this._worker)==null||n.postMessage({type:Oe.AvExist,hasVideo:e,hasAudio:t})}_postAudioFrame(e,t){var n;(n=this._worker)==null||n.postMessage({type:Oe.AudioFrame,frame:e,setting:t},[e])}setEncodeCapacity(e){var t;(t=this._worker)==null||t.postMessage({type:Oe.EncodeConfig,cfg:e})}adjustBitrate(e,t){var n;(n=this._worker)==null||n.postMessage({type:Oe.AdjustBitrate,kind:e,bitrate:t})}publish(e){var t;yn.log("start capture & connect"),this._capture.start(),(t=this._worker)==null||t.postMessage({type:Oe.Publish,url:e})}unpublish(){var e;this._capture.destroy(),(e=this._worker)==null||e.postMessage({type:Oe.UnPublish})}destroy(){var e;yn.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:Oe.Download})}}function tg(r){const e=document.createElement("a");e.href=URL.createObjectURL(new Blob([r])),e.download=Date.now()+".flv",e.click()}const Xa=new ht("RTMPConnect");class rg{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 Ja,this._bindEvents()}get isPushing(){return this._isPushing}get pushUrl(){return this._url}get sessionId(){return 0}_bindEvents(){this._rtmp.on(pt.OnError,e=>{this._isPushing=!1,this._onError(e)}),this._rtmp.on(pt.OnConnectClosed,()=>{this._isPushing=!1,this._onError(new qa(vn.WTP_CONNECT_FAIL,"connect lost"))}),this._rtmp.on(pt.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(ft.Audio,t[0]),t[1]&&this._rtmp.adjustBitrate(ft.Video,t[1]),this._rtmp.publish(this._url)}updatePublish(e,t){Xa.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 gn(e),{stats:await this._rtmp.getStats(),originStats:void 0}}unpublish(){Xa.warn("unpublish"),this._rtmp.unpublish(),this._isPushing=!1}}function Za({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 ng{constructor(e,t=uf){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,j(V.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:Mt.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:Mt.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(s){const a=s.ext||{},{httpCode:o}=a;if(o!==void 0&&String(o).startsWith("4"))this.stop({isSuccess:!1,reason:zn.PushUrlInvalid,failedError:s}),(n=this._onReconnectError)==null||n.call(this,"pushError",s);else{if(!this.isActive())return;this.setStrategyState("executing"),this.execute()}}}},this.executeStrategy=(n=!1)=>{const i=n?0:this._reconnectDelay;this._pushConsumer.emitReconnectStateChange({state:Mt.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,df)},this.state="idle",this._pushConsumer=e,this._maxTimeout=t,this._logger=new ht("ReconnectStrategy")}getNextPushUrl(){const e=this._pushConsumer.pushUrl;return e?Za({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 s=(Date.now()-this._reconnectStartTime)/1e3;n||(e?this._pushConsumer.emitReconnectStateChange({state:Mt.SUCCESS,teaParams:{reconnect_duration:s,session_id:this._pushConsumer.pushSessionId}}):(this._logger.log("Reconnect strategy stopped: ",t),this._pushConsumer.emitReconnectStateChange({state:Mt.FAILED,params:{failedCode:t},teaParams:{reason:t,reconnect_duration:s,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+=s),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:zn.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 Lr={ManualStop:0,ReconnectFailed:1,StartPushError:2,PushError:3},Jt={PushCheck:0,PushError:1},Ya=new ht("PushController");class ig extends Na{constructor(e,{config:t,streamConsumeController:n,streamComposedController:i}){var s,a;if(super(e),this._connect=null,this._connectionState=xe.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=Ft(ms,"audio").bitrate,this._videoBitrate=Ft(fs,"video").bitrate,this.handleReconnectError=(o,d)=>{var c,u;j(V.STOP_PUSH_STREAM,{reason:Lr.ReconnectFailed,error_message:o,session_id:this._pushSessionId,push_mode:this._pushMode,duration:this.pushDuration,reconnect_times:(c=this._reconnectStrategy)==null?void 0:c.getReconnectInfo().totalReconnectCount,reconnect_duration:(u=this._reconnectStrategy)==null?void 0:u.getReconnectInfo().totalReconnectDuration}),this.unpublish()},this.handleAudioStreamChange=o=>{this.updatePush({audioTrack:o.audioTrack})},this.handleVideoStreamChange=o=>{this.updatePush({videoTrack:o.videoTrack})},this._OnRTMPSuccess=()=>{this.setConnectState(xe.CONNECTED)},this._OnRTMPError=o=>{const d=new Bt(ke.PUBLISH_FAILED,`code:${o.code}, message: ${o.message}`);this._streamConsumeController.emit(se.PushError,d),j(V.STOP_PUSH_STREAM,{reason:Lr.PushError,duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode,error_msg:o.message,error_code:o.code}),j(V.START_PUSH_STATUS,{is_success:!1,reason:Jt.PushError,error_message:o.message,session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish()},this._executeReconnect=()=>{var o;(o=this._reconnectStrategy)==null||o.execute(),this.setConnectState(xe.RECONNECTING),this.unpublish({isReconnecting:!0})},this._OnRtcStateChange=o=>{var d;switch(j(V.PUSH_RTC_STATE_CHANGE,{state:o,push_url:this._pushUrl,session_id:this._pushSessionId,push_mode:this._pushMode}),this._streamConsumeController.emit(se.RTCConnectStateChanged,o),o){case"connected":this.setConnectState(xe.CONNECTED);break;case"disconnected":this._reconnectStrategy&&this._executeReconnect();break;case"failed":(d=this._reconnectStrategy)!=null&&d.isActive()?this._executeReconnect():(this.connectionState===xe.CONNECTED?j(V.STOP_PUSH_STREAM,{reason:Lr.PushError,error_message:"peerconnection failed",duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode}):j(V.START_PUSH_STATUS,{is_success:!1,reason:Jt.PushError,error_message:"peerconnection failed",session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish(),this._streamConsumeController.emit(se.PushError,new Bt(ke.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),(s=t==null?void 0:t.reconnectConfig)!=null&&s.enable||!(t!=null&&t.reconnectConfig)){const o=(a=t==null?void 0:t.reconnectConfig)!=null&&a.maxTimeout?t.reconnectConfig.maxTimeout*xo:void 0;this._reconnectStrategy=new ng(this,o),this._reconnectStrategy.onReconnectError=this.handleReconnectError}this._streamComposedController=i}get isPushing(){return this._connectionState===xe.CONNECTED||this._connectionState===xe.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(se.LiveConnectStateChange,e),e){case xe.CONNECTED:(t=this._reconnectStrategy)!=null&&t.isActive()?this._reconnectStrategy.stop({isSuccess:!0}):(this._streamConsumeController.emit(se.PushStart),this.setPushStatsInterval(),j(V.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,o,d;if(t.isReconnect||(this._pushSessionId=Date.now(),j(V.START_PUSH,{push_url:e,session_id:this._pushSessionId})),!e)throw j(V.START_PUSH_STATUS,{is_success:!1,session_id:this._pushSessionId,reason:Jt.PushCheck,push_url:this._pushUrl}),new Error("lack publish url");if(this._connect)return;this.start(),this._pushUrl=Za({pushUrl:e,disableTCC:!0}),this._pushEncodeConfig=t.cfg;const n=this._composedStream.videoTrack,i=this._composedStream.audioTrack;if(this._needCheckAudioTrack&&(!n||!i)){j(V.START_PUSH_STATUS,{is_success:!1,reason:Jt.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}),console.warn("lack videoTrack or audioTrack","videoTrack: ",n==null?void 0:n.id,"audioTrack: ",i==null?void 0:i.id);return}else if(!n&&!i){j(V.START_PUSH_STATUS,{is_success:!1,reason:Jt.PushCheck,push_url:this._pushUrl,error_message:"lack videoTrack and audioTrack",push_mode:this._pushMode,session_id:this._pushSessionId});return}let s;this._pushMode==="rtm"?s=new J_(this._pushUrl,this._pushConfig,this._OnRtcStateChange):s=new rg(e,this._pushConfig,this._OnRTMPError,this._OnRTMPSuccess),this._connect=s;try{!t.isReconnect&&((a=this._reconnectStrategy)!=null&&a.isActive())&&this._reconnectStrategy.stop({quiet:!0}),(o=this._reconnectStrategy)!=null&&o.isActive()||this.setConnectState(xe.CONNECTING),await s.publish([i,n],[this._audioBitrate,this._videoBitrate],{cfg:t.cfg,isReconnect:t.isReconnect}),t.isReconnect||(Ya.log("startPush begin"),this._connectionStartDate=Date.now())}catch(c){const u=new Bt(ke.PUBLISH_FAILED,c.message,c);if(Ya.groupEnd(),(d=this._reconnectStrategy)!=null&&d.isActive())throw this.unpublish({isReconnecting:!0}),u;this._streamConsumeController.emit(se.PushError,u),j(V.STOP_PUSH_STREAM,{reason:Lr.PushError,error_message:u.message,enable_reconnect:!1,push_mode:this._pushMode,session_id:this._pushSessionId,duration:this.pushDuration}),j(V.START_PUSH_STATUS,{is_success:!1,push_url:this._pushUrl,reason:Jt.PushError,error_message:u.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,s;if((t=this._connect)!=null&&t.isPushing){const a=Date.now(),{stats:o,originStats:d}=await this._connect.getStatsSnapshoot(2e3),u=Date.now()-a;Yp(o)?this._prevStats=void 0:this._prevStats=o;const h=this.pushMode==="rtm"?V_(o,d,{idealFrameRate:(n=this._composedStream._videoStream)==null?void 0:n.frameRate,idealBitrate:this._videoBitrate}):j_(o),l=this.pushMode==="rtm"?(i=this._connect)==null?void 0:i.videoSenderTrackStats:{};j(V.PUSH_STATS,{...h,...l,video_draw_frame:this._streamComposedController.getCompositionDrawCountPerSecond(),stats:o,push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:h.video_duration||u,video_duration:h.video_duration||u,is_push:!0},!0)}else await gn(2e3),j(V.PUSH_STATS,{push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:2e3,is_push:!1,is_reconnecting:((s=this._reconnectStrategy)==null?void 0:s.isActive())??!1},!0);this.connectionState!==xe.DISCONNECTED&&(this._statsLoopTimer=window.setTimeout(e,0))};e()}async reconnect(e){if(this.pushMode==="rtm")return this.startPush(e,{isReconnect:!0})}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 Bt(ke.UPDATE_PUBLISH_FAILED,`${n.name}, code:${n.code}`);this._streamConsumeController.emit(se.PushError,i)}}unpublish(e={isReconnecting:!1,isManual:!1}){var t,n,i,s,a;(t=this._connect)==null||t.unpublish(),this._connect=null,e.isManual&&(j(V.STOP_PUSH_STREAM,{reason:Lr.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}),(s=this._reconnectStrategy)==null||s.clearReconnectInfo()),e.isReconnecting||(this._statsLoopTimer&&window.clearTimeout(this._statsLoopTimer),this._prevStats=void 0,this._isReportStart=!1,this._pushEncodeConfig=void 0,this._pushUrl=void 0,this._connectionStartDate=void 0,this._pushSessionId=0,this.setConnectState(xe.DISCONNECTED),(a=this._reconnectStrategy)==null||a.stop({quiet:!0}),this._streamConsumeController.emit(se.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}){j(V.PUSH_RECONNECT_STATUS,{status:e,...t,...n}),this._streamConsumeController.emit(se.ReconnectStateChange,e,t)}}class sg extends st{constructor(e,t){super(),this._previewConsumer=new P_(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new ig(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,{cfg: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()}}const og=()=>typeof window>"u",$e={},Sn=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 Qa(r){const e=r.split(`
|
|
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 s=[/miuibrowser/,/70.*HeyTapBrowser/i];for(const a of s)a.test(n)&&(i=!0);return!i}return!1}const ag=async()=>{let r=await Sn("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Sn("sendonly")),$e.h264encode=Qa(r),$e.vp8encode=r.indexOf("vp8")>-1,$e},cg=async()=>{let r=await Sn("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Sn("recvonly")),$e.h264decode=Qa(r),$e.vp8decode=r.indexOf("vp8")>-1,$e},ug=async()=>{if(typeof $e.h264encode>"u")try{await ag()}catch{return!1}return $e.h264encode||!1},dg=async()=>{if(typeof $e.h264decode>"u")try{await cg()}catch{return!1}return $e.h264decode||!1};class lg{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 hg=new lg;let ec=!0,tc=!0;function bn(r,e,t){const n=r.match(e);return n&&n.length>=t&&parseInt(n[t],10)}function xt(r,e,t){if(!r.RTCPeerConnection)return;const n=r.RTCPeerConnection.prototype,i=n.addEventListener;n.addEventListener=function(a,o){if(a!==e)return i.apply(this,arguments);const d=c=>{const u=t(c);u&&(o.handleEvent?o.handleEvent(u):o(u))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,d),i.apply(this,[a,d])};const s=n.removeEventListener;n.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return s.apply(this,arguments);if(!this._eventMap[e].has(o))return s.apply(this,arguments);const d=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[a,d])},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 pg(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(ec=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function fg(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(tc=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function rc(){if(typeof window=="object"){if(ec)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Yi(r,e){tc&&console.warn(r+" is deprecated, please use "+e+" instead.")}function mg(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=bn(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=bn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=bn(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 nc(r){return Object.prototype.toString.call(r)==="[object Object]"}function ic(r){return nc(r)?Object.keys(r).reduce(function(e,t){const n=nc(r[t]),i=n?ic(r[t]):r[t],s=n&&!Object.keys(i).length;return i===void 0||s?e:Object.assign(e,{[t]:i})},{}):r}function Qi(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?Qi(r,r.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(i=>{Qi(r,r.get(i),t)})}))}function sc(r,e,t){const n=t?"outbound-rtp":"inbound-rtp",i=new Map;if(e===null)return i;const s=[];return r.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&s.push(a)}),s.forEach(a=>{r.forEach(o=>{o.type===n&&o.trackId===a.id&&Qi(r,o,i)})}),i}const oc=rc;function ac(r,e){const t=r&&r.navigator;if(!t.mediaDevices)return;const n=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const d={};return Object.keys(o).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;const u=typeof o[c]=="object"?o[c]:{ideal:o[c]};u.exact!==void 0&&typeof u.exact=="number"&&(u.min=u.max=u.exact);const h=function(l,f){return l?l+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(u.ideal!==void 0){d.optional=d.optional||[];let l={};typeof u.ideal=="number"?(l[h("min",c)]=u.ideal,d.optional.push(l),l={},l[h("max",c)]=u.ideal,d.optional.push(l)):(l[h("",c)]=u.ideal,d.optional.push(l))}u.exact!==void 0&&typeof u.exact!="number"?(d.mandatory=d.mandatory||{},d.mandatory[h("",c)]=u.exact):["min","max"].forEach(l=>{u[l]!==void 0&&(d.mandatory=d.mandatory||{},d.mandatory[h(l,c)]=u[l])})}),o.advanced&&(d.optional=(d.optional||[]).concat(o.advanced)),d},i=function(o,d){if(e.version>=61)return d(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const c=function(u,h,l){h in u&&!(l in u)&&(u[l]=u[h],delete u[h])};o=JSON.parse(JSON.stringify(o)),c(o.audio,"autoGainControl","googAutoGainControl"),c(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=n(o.audio)}if(o&&typeof o.video=="object"){let c=o.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});const u=e.version<66;if(c&&(c.exact==="user"||c.exact==="environment"||c.ideal==="user"||c.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!u)){delete o.video.facingMode;let h;if(c.exact==="environment"||c.ideal==="environment"?h=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(h=["front"]),h)return t.mediaDevices.enumerateDevices().then(l=>{l=l.filter(y=>y.kind==="videoinput");let f=l.find(y=>h.some(C=>y.label.toLowerCase().includes(C)));return!f&&l.length&&h.includes("back")&&(f=l[l.length-1]),f&&(o.video.deviceId=c.exact?{exact:f.deviceId}:{ideal:f.deviceId}),o.video=n(o.video),oc("chrome: "+JSON.stringify(o)),d(o)})}o.video=n(o.video)}return oc("chrome: "+JSON.stringify(o)),d(o)},s=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,d,c){i(o,u=>{t.webkitGetUserMedia(u,d,h=>{c&&c(s(h))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(d){return i(d,c=>o(c).then(u=>{if(c.audio&&!u.getAudioTracks().length||c.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(s(u))))}}}function cc(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function uc(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 s;r.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===i.track.id):s={track:i.track};const a=new Event("track");a.track=i.track,a.receiver=s,a.transceiver={receiver:s},a.streams=[n.stream],this.dispatchEvent(a)}),n.stream.getTracks().forEach(i=>{let s;r.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===i.id):s={track:i};const a=new Event("track");a.track=i,a.receiver=s,a.transceiver={receiver:s},a.streams=[n.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else xt(r,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function dc(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("getSenders"in r.RTCPeerConnection.prototype)&&"createDTMFSender"in r.RTCPeerConnection.prototype){const e=function(i,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=i.createDTMFSender(s):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(o,d){let c=i.apply(this,arguments);return c||(c=e(this,o),this._senders.push(c)),c};const s=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(o){s.apply(this,arguments);const d=this._senders.indexOf(o);d!==-1&&this._senders.splice(d,1)}}const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],t.apply(this,[s]),s.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],n.apply(this,[s]),s.getTracks().forEach(a=>{const o=this._senders.find(d=>d.track===a);o&&this._senders.splice(this._senders.indexOf(o),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 lc(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 s=t.apply(this,[]);return s.forEach(a=>a._pc=this),s});const n=r.RTCPeerConnection.prototype.addTrack;n&&(r.RTCPeerConnection.prototype.addTrack=function(){const s=n.apply(this,arguments);return s._pc=this,s}),r.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(a=>sc(a,s.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(s=>s._pc=this),i}),xt(r,"track",n=>(n.receiver._pc=n.srcElement,n)),r.RTCRtpReceiver.prototype.getStats=function(){const i=this;return this._pc.getStats().then(s=>sc(s,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,s,a;return this.getSenders().forEach(o=>{o.track===n&&(i?a=!0:i=o)}),this.getReceivers().forEach(o=>(o.track===n&&(s?a=!0:s=o),o.track===n)),a||i&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):i?i.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function hc(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,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const d=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(d)===-1&&this._shimmedLocalStreams[o.id].push(d):this._shimmedLocalStreams[o.id]=[o,d],d};const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(c=>{if(this.getSenders().find(h=>h.track===c))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const d=this.getSenders().filter(c=>o.indexOf(c)===-1);this._shimmedLocalStreams[a.id]=[a].concat(d)};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(o=>{const d=this._shimmedLocalStreams[o].indexOf(a);d!==-1&&this._shimmedLocalStreams[o].splice(d,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),i.apply(this,arguments)}}function pc(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return hc(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const u=t.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(h=>this._reverseStreams[h.id])};const n=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(u){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(h=>{if(this.getSenders().find(f=>f.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){const h=new r.MediaStream(u.getTracks());this._streams[u.id]=h,this._reverseStreams[h.id]=u,u=h}n.apply(this,[u])};const i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[u.id]||u]),delete this._reverseStreams[this._streams[u.id]?this._streams[u.id].id:u.id],delete this._streams[u.id]},r.RTCPeerConnection.prototype.addTrack=function(u,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const l=[].slice.call(arguments,1);if(l.length!==1||!l[0].getTracks().find(C=>C===u))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(C=>C.track===u))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const y=this._streams[h.id];if(y)y.addTrack(u),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const C=new r.MediaStream([u]);this._streams[h.id]=C,this._reverseStreams[C.id]=h,this.addStream(C)}return this.getSenders().find(C=>C.track===u)};function s(c,u){let h=u.sdp;return Object.keys(c._reverseStreams||[]).forEach(l=>{const f=c._reverseStreams[l],y=c._streams[f.id];h=h.replace(new RegExp(y.id,"g"),f.id)}),new RTCSessionDescription({type:u.type,sdp:h})}function a(c,u){let h=u.sdp;return Object.keys(c._reverseStreams||[]).forEach(l=>{const f=c._reverseStreams[l],y=c._streams[f.id];h=h.replace(new RegExp(f.id,"g"),y.id)}),new RTCSessionDescription({type:u.type,sdp:h})}["createOffer","createAnswer"].forEach(function(c){const u=r.RTCPeerConnection.prototype[c],h={[c](){const l=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[y=>{const C=s(this,y);l[0].apply(null,[C])},y=>{l[1]&&l[1].apply(null,y)},arguments[2]]):u.apply(this,arguments).then(y=>s(this,y))}};r.RTCPeerConnection.prototype[c]=h[c]});const o=r.RTCPeerConnection.prototype.setLocalDescription;r.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const d=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){const c=d.get.apply(this);return c.type===""?c:s(this,c)}}),r.RTCPeerConnection.prototype.removeTrack=function(u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!u._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(u._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let l;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(C=>u.track===C)&&(l=this._streams[f])}),l&&(l.getTracks().length===1?this.removeStream(this._reverseStreams[l.id]):l.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function es(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 fc(r,e){xt(r,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}const mc=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:fc,shimAddTrackRemoveTrack:pc,shimAddTrackRemoveTrackWithNative:hc,shimGetSendersWithDtmf:dc,shimGetUserMedia:ac,shimMediaStream:cc,shimOnTrack:uc,shimPeerConnection:es,shimSenderReceiverGetStats:lc},Symbol.toStringTag,{value:"Module"}));function _c(r,e){const t=r&&r.navigator,n=r&&r.MediaStreamTrack;if(t.getUserMedia=function(i,s,a){Yi("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(i).then(s,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const i=function(a,o,d){o in a&&!(d in a)&&(a[d]=a[o],delete a[o])},s=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")),s(a)},n&&n.prototype.getSettings){const a=n.prototype.getSettings;n.prototype.getSettings=function(){const o=a.apply(this,arguments);return i(o,"mozAutoGainControl","autoGainControl"),i(o,"mozNoiseSuppression","noiseSuppression"),o}}if(n&&n.prototype.applyConstraints){const a=n.prototype.applyConstraints;n.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),i(o,"autoGainControl","mozAutoGainControl"),i(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function _g(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 gc(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 ts(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 s=r.RTCPeerConnection.prototype[i],a={[i](){return arguments[0]=new(i==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),s.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[s,a,o]=arguments;return n.apply(this,[s||null]).then(d=>{if(e.version<53&&!a)try{d.forEach(c=>{c.type=t[c.type]||c.type})}catch(c){if(c.name!=="TypeError")throw c;d.forEach((u,h)=>{d.set(h,Object.assign({},u,{type:t[u.type]||u.type}))})}return d}).then(a,o)}}function vc(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(s=>s._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 yc(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}),xt(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Sc(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){Yi("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function bc(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function Ec(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 s=e.apply(this,arguments);if(i){const{sender:a}=s,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=n,a.sendEncodings=n,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return s})}function Cc(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 wc(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 Tc(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 kc=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:Ec,shimCreateAnswer:Tc,shimCreateOffer:wc,shimGetDisplayMedia:_g,shimGetParameters:Cc,shimGetUserMedia:_c,shimOnTrack:gc,shimPeerConnection:ts,shimRTCDataChannel:bc,shimReceiverGetStats:yc,shimRemoveStream:Sc,shimSenderGetStats:vc},Symbol.toStringTag,{value:"Module"}));function Rc(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(s=>{this._localStreams?this._localStreams.includes(s)||this._localStreams.push(s):this._localStreams=[s]}),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(s=>{i.includes(s.track)&&this.removeTrack(s)})})}}function Ac(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 s=new Event("addstream");s.stream=i,this.dispatchEvent(s)})})}});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(s=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(s)>=0)return;n._remoteStreams.push(s);const a=new Event("addstream");a.stream=s,n.dispatchEvent(a)})}),e.apply(n,arguments)}}}function Dc(r){if(typeof r!="object"||!r.RTCPeerConnection)return;const e=r.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,i=e.setLocalDescription,s=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(c,u){const h=arguments.length>=2?arguments[2]:arguments[0],l=t.apply(this,[h]);return u?(l.then(c,u),Promise.resolve()):l},e.createAnswer=function(c,u){const h=arguments.length>=2?arguments[2]:arguments[0],l=n.apply(this,[h]);return u?(l.then(c,u),Promise.resolve()):l};let o=function(d,c,u){const h=i.apply(this,[d]);return u?(h.then(c,u),Promise.resolve()):h};e.setLocalDescription=o,o=function(d,c,u){const h=s.apply(this,[d]);return u?(h.then(c,u),Promise.resolve()):h},e.setRemoteDescription=o,o=function(d,c,u){const h=a.apply(this,[d]);return u?(h.then(c,u),Promise.resolve()):h},e.addIceCandidate=o}function xc(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(Ic(i))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,i,s){e.mediaDevices.getUserMedia(n).then(i,s)}).bind(e))}function Ic(r){return r&&r.video!==void 0?Object.assign({},r,{video:ic(r.video)}):r}function zc(r){if(!r.RTCPeerConnection)return;const e=r.RTCPeerConnection;r.RTCPeerConnection=function(n,i){if(n&&n.iceServers){const s=[];for(let a=0;a<n.iceServers.length;a++){let o=n.iceServers[a];o.urls===void 0&&o.url?(Yi("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,s.push(o)):s.push(n.iceServers[a])}n.iceServers=s}return new e(n,i)},r.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(r.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Pc(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 Oc(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 s=this.getTransceivers().find(a=>a.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):n.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Mc(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const Lc=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:Mc,shimCallbacksAPI:Dc,shimConstraints:Ic,shimCreateOfferLegacy:Oc,shimGetUserMedia:xc,shimLocalStreamsAPI:Rc,shimRTCIceServerUrls:zc,shimRemoteStreamsAPI:Ac,shimTrackEventTransceiver:Pc},Symbol.toStringTag,{value:"Module"}));var rs={exports:{}},Nc;function gg(){return Nc||(Nc=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(`
|
|
68
|
+
`},wo}var Vc;function mv(){if(Vc)return ot;Vc=1;var r=fv(),e=pv(),t=Eo();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 br=Oe(gv);function fn(r){return new Promise(e=>{setTimeout(e,r)})}async function _v(r,e={},t=0){const n=new AbortController;let i=!1;e=Object.assign({},e,{signal:n.signal});const o=[fetch(r,e)];t&&o.push(new Promise((a,s)=>{setTimeout(()=>{i||(s({httpCode:0,message:"Timeout"}),n.abort())},t)}));try{const a=await Promise.race(o);if(i=!0,!a.ok||a.status<200||a.status>=300)throw{httpCode:a.status,message:a.statusText};return a.json()}catch(a){throw i=!0,a}}async function jc(r,e={},t={}){const{timeout:n=0,retryDelay:i=0}=t;let{retryCount:o=0}=t;try{return await _v(r,e,n)}catch(a){if(o--,t.retryCount=o,o<0)throw a;return await fn(i),await jc(r,e,t)}}const Co=-1;function De(r,e){let t;return e.forEach(n=>{n.type===r&&(t=n)}),t}async function ko(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:De("media-source",n),codec:De("codec",n),candidatePair:De("candidate-pair",n),remoteCandidate:De("remote-candidate",n),localCandidate:De("local-candidate",n),track:De("track",n),outboundRtp:De("outbound-rtp",n),remoteInboundRtp:De("remote-inbound-rtp",n),transport:De("transport",n)}),i&&(t.video={mediaSource:De("media-source",i),codec:De("codec",i),candidatePair:De("candidate-pair",i),remoteCandidate:De("remote-candidate",i),localCandidate:De("local-candidate",i),track:De("track",i),outboundRtp:De("outbound-rtp",i),remoteInboundRtp:De("remote-inbound-rtp",i),transport:De("transport",i)}),t}async function vv(r,e,t){var u,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,Ae,jt,Ge,Ht,Dt,Xe,Te;const n=await ko(e,t);await fn(r);const i=await ko(e,t),{audio:o,video:a}=n,{audio:s,video:d}=i,c={};if(o!=null&&o.codec&&(s!=null&&s.codec)){const Ie=((u=s.outboundRtp)==null?void 0:u.timestamp)-((f=o.outboundRtp)==null?void 0:f.timestamp),Ne=((h=s.outboundRtp)==null?void 0:h.bytesSent)-((g=o.outboundRtp)==null?void 0:g.bytesSent),Be=((k=s.remoteInboundRtp)==null?void 0:k.packetsLost)-((z=o.remoteInboundRtp)==null?void 0:z.packetsLost),Fe=((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:Ne/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:Be/Fe,deltaAudioEnergy:nt}}if(a!=null&&a.codec&&(d!=null&&d.codec)){const Ie=((U=d.outboundRtp)==null?void 0:U.timestamp)-((L=a.outboundRtp)==null?void 0:L.timestamp),Ne=((j=d.outboundRtp)==null?void 0:j.bytesSent)-(($=a.outboundRtp)==null?void 0:$.bytesSent),Be=((K=d.outboundRtp)==null?void 0:K.framesEncoded)-((Z=a.outboundRtp)==null?void 0:Z.framesEncoded),Fe=((W=d.outboundRtp)==null?void 0:W.totalEncodeTime)-((se=a.outboundRtp)==null?void 0:se.totalEncodeTime),nt=((oe=d.outboundRtp)==null?void 0:oe.framesSent)-((Y=a.outboundRtp)==null?void 0:Y.framesSent),At=((le=d.outboundRtp)==null?void 0:le.packetsSent)-((fe=a.outboundRtp)==null?void 0:fe.packetsSent),ct=((ue=d.outboundRtp)==null?void 0:ue.totalPacketSendDelay)-((be=a.outboundRtp)==null?void 0:be.totalPacketSendDelay),ut=((ye=d.remoteInboundRtp)==null?void 0:ye.packetsLost)-((re=a.remoteInboundRtp)==null?void 0:re.packetsLost);c.video={codec:d.codec.mimeType,sendBitrate:Ne/Ie*8e3,frameWidth:(ke=d.outboundRtp)==null?void 0:ke.frameWidth,frameHeight:(de=d.outboundRtp)==null?void 0:de.frameHeight,framesPerSecond:Math.floor(nt/Ie*1e3||0),framesEncoded:(_e=d.outboundRtp)==null?void 0:_e.framesEncoded,framesEncodedPerSecond:Be*1e3/Ie,keyFramesEncoded:(Ae=d.outboundRtp)==null?void 0:Ae.keyFramesEncoded,framesSent:(jt=d.outboundRtp)==null?void 0:jt.frameHeight,frameEncodeAvgTime:Fe*1e3/Be,packetsSent:(Ge=d.outboundRtp)==null?void 0:Ge.packetsSent,packetSendDelay:ct*1e3/At,nackCount:(Ht=d.outboundRtp)==null?void 0:Ht.nackCount,firCount:(Dt=d.outboundRtp)==null?void 0:Dt.firCount,pliCount:(Xe=d.outboundRtp)==null?void 0:Xe.pliCount,packetsLost:(Te=d.remoteInboundRtp)==null?void 0:Te.packetsLost,packetsLostPercent:ut/At,deltaTime:Ie}}return{stats:c,originStats:{audio:s,video:d}}}function Ce(r,e=Co){return r??e}function yv(r){var e,t,n,i,o,a,s,d,c,u,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:(d=r.codec)==null?void 0:d.channels,audio_level:(c=r.mediaSource)!=null&&c.audioLevel?-10*Math.log10(Math.pow((u=r.mediaSource)==null?void 0:u.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,d,c,u,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:(((d=r.remoteInboundRtp)==null?void 0:d.jitter)||0)*1e3,video_packets_lost:(c=r.remoteInboundRtp)==null?void 0:c.packetsLost,video_fraction_lost:(u=r.remoteInboundRtp)==null?void 0:u.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,u,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((u=r.video)==null?void 0:u.frameHeight),d=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:Co,video_bitrate_compliance:t!=null&&t.idealBitrate?Math.min(Ce((Z=r.video)==null?void 0:Z.sendBitrate)/t.idealBitrate,1)*100:Co,video_resolution_downgrade:d,...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(!Cs)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||Sn)&&(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);i?i.config=[...i.config.split(";"),`x-google-min-bitrate=${e*.4}`,`x-google-start-bitrate=${e}`].join(";"):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(" ")}const Rv=()=>typeof window>"u",gt={},$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
|
+
`);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")),gt.h264encode=$c(r),gt.vp8encode=r.indexOf("vp8")>-1,gt},Av=async()=>{let r=await $n("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await $n("recvonly")),gt.h264decode=$c(r),gt.vp8decode=r.indexOf("vp8")>-1,gt},Iv=async()=>{if(typeof gt.h264encode>"u")try{await Dv()}catch{return!1}return gt.h264encode||!1},xv=async()=>{if(typeof gt.h264decode>"u")try{await Av()}catch{return!1}return gt.h264decode||!1},Le=new Nt("PCConnect"),as=class as{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 publish(e,t,n){var 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]}),Le.log("add track to pc,",o),this._videoTransceiver=i.addTransceiver(a||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),Le.log("add track to pc,",a);const s=await i.createOffer();Le.groupCollapsed("local offer"),Le.log(s.sdp);const d=br.parse(s.sdp);d.media.forEach(h=>{h.type==="audio"?kv(h):h.type==="video"&&(Tv(h),Hc(h,"software"),zv(h,t[1]))}),s.sdp=br.write(d),Le.log("local offer modified"),Le.log(s.sdp),await i.setLocalDescription(s);const c=await jc(this._signalUrl,{method:"POST",mode:"cors",body:JSON.stringify({sessionId:""+this._sessionId,version:"1.0-html",localSdp:s,metadata:{platform:"Web"}})},{...this._opts,timeout:n!=null&&n.isReconnect?10*Ia:(f=this._opts)==null?void 0:f.timeout});if((c==null?void 0:c.code)!==200)throw{code:c.code,message:c.message};Le.log("remote answer:"),Le.log(c.remoteSdp.sdp);const u=br.parse(c.remoteSdp.sdp);if(u.media.forEach(h=>{var g;(g=h.fingerprint)!=null&&g.hash&&(h.fingerprint.hash=h.fingerprint.hash.toUpperCase())}),c.remoteSdp.sdp=br.write(u),Le.log("remote answer modified"),Le.log(c.remoteSdp.sdp),Le.groupEnd(),i.connectionState==="closed"){Le.log("PeerConnection is closed, skipping setRemoteDescription");return}X(J.PUSH_SDP_INFO,{offer_sdp:s.sdp,answer_sdp:c.remoteSdp.sdp}),await i.setRemoteDescription(c.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=br.parse(i);s.media.forEach(d=>{d.type==="video"&&Hc(d,e)}),t.setLocalDescription(t.localDescription),t.setRemoteDescription({type:"answer",sdp:br.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)),Le.log(`replace ${t} track done! ${i==null?void 0:i.label} -> ${e==null?void 0:e.label}`))}applyBitrate(e,t,n){var a,s,d;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=(d=o.encodings)!=null&&d.length?o.encodings:[{}],n?o.encodings[0].minBitrate=e:o.encodings[0].maxBitrate=e,i.setParameters(o),Le.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,Le.log("close pc!")}getStats(){var e,t;return ko((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",()=>{Le.log("onconnectionstatechange:",e.connectionState),this._onConnectStateChange(e.connectionState)})}};as.isSupported=async()=>{try{return Rv()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await xv()&&await Iv()}catch{return!1}};let qn=as;var Bt=(r=>(r.OnError="onerror",r.OnConnectClosed="onconnectclosed",r.OnFirstFramePushed="onfirstframepushed",r))(Bt||{}),Ft=(r=>(r.Video="video",r.Audio="audio",r))(Ft||{}),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||{}),To={exports:{}},qc;function Mv(){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(d,c,u){this.fn=d,this.context=c,this.once=u||!1}function o(d,c,u,f,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var g=new i(u,f||d,h),k=t?t+c:c;return d._events[k]?d._events[k].fn?d._events[k]=[d._events[k],g]:d._events[k].push(g):(d._events[k]=g,d._eventsCount++),d}function a(d,c){--d._eventsCount===0?d._events=new n:delete d._events[c]}function s(){this._events=new n,this._eventsCount=0}s.prototype.eventNames=function(){var c=[],u,f;if(this._eventsCount===0)return c;for(f in u=this._events)e.call(u,f)&&c.push(t?f.slice(1):f);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},s.prototype.listeners=function(c){var u=t?t+c:c,f=this._events[u];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 u=t?t+c:c,f=this._events[u];return f?f.fn?1:f.length:0},s.prototype.emit=function(c,u,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,u),!0;case 3:return w.fn.call(w.context,u,f),!0;case 4:return w.fn.call(w.context,u,f,h),!0;case 5:return w.fn.call(w.context,u,f,h,g),!0;case 6:return w.fn.call(w.context,u,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,u);break;case 3:w[E].fn.call(w[E].context,u,f);break;case 4:w[E].fn.call(w[E].context,u,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,u,f){return o(this,c,u,f,!1)},s.prototype.once=function(c,u,f){return o(this,c,u,f,!0)},s.prototype.removeListener=function(c,u,f,h){var g=t?t+c:c;if(!this._events[g])return this;if(!u)return a(this,g),this;var k=this._events[g];if(k.fn)k.fn===u&&(!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!==u||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 u;return c?(u=t?t+c:c,this._events[u]&&a(this,u)):(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}(To)),To.exports}var Ov=Mv();const Pv=Oe(Ov);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 Er=(Rt=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 Rt.enable}get _enableLong(){return Rt.enableLong}get long(){return this._enableLong}},Rt.enable=!1,Rt.enableLong=!1,Rt);const rt=new Er("RTMP_Capture");class Lv{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===Ft.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 Uv(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{Er.enable=location.href.indexOf("rtmpdebug")!==-1,Er.enableLong=location.href.indexOf("rtmpdebug=long")!==-1}catch{}const Wn=new Er("Bridge");class Zc extends Pv{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new Lv(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,d)=>{e=s,t=d}),i=s=>{var d;switch((d=this._worker)==null||d.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 Uv}catch(s){t(Wc(Kn.RTMP_INIT_FAIL,s.message))}return(o=this._worker)==null||o.postMessage({type:tt.Init,options:{logEnable:Er.enable,logEnableLong:Er.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(Bt.OnError,n.data.data);break;case nr.Flvfile:Gv(n.data.buffer);break;case nr.FirstFramePushed:this.emit(Bt.OnFirstFramePushed);break;case nr.Close:this.emit(Bt.OnConnectClosed),this.destroy();break}}),(t=this._worker)==null||t.addEventListener("error",n=>{this.emit(Bt.OnError,Wc(Kn.WORKER_ERROR,n.message))})}addTrack(e){e.kind===Ft.Video&&(this._videoMsTrack=e),e.kind===Ft.Audio&&(this._audioMsTrack=e),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack)}replaceTrack(e,t){e===Ft.Video&&(this._videoMsTrack=t),e===Ft.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,d)=>{e=s,t=d});this._worker||setTimeout(()=>{t()},0);const i=s=>{var d;switch(s.data.type){case nr.STATS:e(s.data.data),(d=this._worker)==null||d.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 Gv(r){const e=document.createElement("a");e.href=URL.createObjectURL(new Blob([r])),e.download=Date.now()+".flv",e.click()}const Yc=new Nt("RTMPConnect");class Nv{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(Bt.OnError,e=>{this._isPushing=!1,this._onError(e)}),this._rtmp.on(Bt.OnConnectClosed,()=>{this._isPushing=!1,this._onError(new Kc(Kn.WTP_CONNECT_FAIL,"connect lost"))}),this._rtmp.on(Bt.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(Ft.Audio,t[0]),t[1]&&this._rtmp.adjustBitrate(Ft.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 fn(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 Bv=1e3;function Fv(){return!1}class Qc{constructor(){this.maxSize=Bv,this.supported=Fv(),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 Vv{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 jv{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 Hv extends jv{constructor(e){super();const t=new e;this.messenger=new Vv(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 $v(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 Ue=function(){return(Ue=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 zo(r,e,t,n){return new(t||(t=Promise))(function(i,o){function a(c){try{d(n.next(c))}catch(u){o(u)}}function s(c){try{d(n.throw(c))}catch(u){o(u)}}function d(c){c.done?i(c.value):new t(function(u){u(c.value)}).then(a,s)}d((n=n.apply(r,[])).next())})}function Ro(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(d){return function(c){return function(u){if(t)throw new TypeError("Generator is already executing.");for(;a;)try{if(t=1,n&&(i=2&u[0]?n.return:u[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,u[1])).done)return i;switch(n=0,i&&(u=[2&u[0],i.value]),u[0]){case 0:case 1:i=u;break;case 4:return a.label++,{value:u[1],done:!1};case 5:a.label++,n=u[1],u=[0];continue;case 7:u=a.ops.pop(),a.trys.pop();continue;default:if(i=a.trys,!((i=i.length>0&&i[i.length-1])||u[0]!==6&&u[0]!==2)){a=0;continue}if(u[0]===3&&(!i||u[1]>i[0]&&u[1]<i[3])){a.label=u[1];break}if(u[0]===6&&a.label<i[1]){a.label=i[1],i=u;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(u);break}i[2]&&a.ops.pop(),a.trys.pop();continue}u=e.call(r,a)}catch(f){u=[6,f],n=0}finally{t=i=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}([d,c])}}}function qv(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 Do(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(qv(arguments[e]));return r}var ru,Kv=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&&Do(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]"},Wv=(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 d=parseInt(i[s],n);d=1*d^t;var c=String.fromCharCode(d);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},Ao=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 Io(){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 pn=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 d in s)a[d]=s[d]}return a}function i(o){return o.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function o(a){function s(){}function d(u,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,u):encodeURIComponent(String(f)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),u=encodeURIComponent(String(u)).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=u+"="+f+k}}function c(u,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,u===b)break}catch{}}return u?h[u]:h}}return s.set=d,s.get=function(u){return c(u,!1)},s.getJSON=function(u){return c(u,!0)},s.remove=function(u,f){d(u,"",n(f,{expires:-1}))},s.defaults={},s.withConverter=o,s}(function(){})},r.exports=t()}),xo=su(function(r,e){r.exports=function t(n,i,o){function a(c,u){if(!i[c]){if(!n[c]){if(!u&&Io)return Io();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=Io,d=0;d<o.length;d++)a(o[d]);return a}({1:[function(t,n,i){(function(o){var a,s,d=o.MutationObserver||o.WebKitMutationObserver;if(d){var c=0,u=new d(k),f=o.document.createTextNode("");u.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={},d=["REJECTED"],c=["FULFILLED"],u=["PENDING"];function f(b){if(typeof b!="function")throw new TypeError("resolver must be a function");this.state=u,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===d)return this;var E=new this.constructor(a);return this.state!==u?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=d,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 d=Promise;function c(l,p){p&&l.then(function(m){p(null,m)},function(m){p(m)})}function u(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"?d.resolve(g):function(p){return new d(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 d(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 d(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(D){if(D.name!=="ConstraintError")throw D;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 u(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 d.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],D=R.forages,A=0;A<D.length;A++){var M=D[A];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<D.length;H++)D[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 d.resolve()}for(var R=0;R<_.forages.length;R++){var D=_.forages[R];D!==p&&S.push(D._initReady().catch(C))}var A=_.forages.slice(0);return d.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<A.length;N++){var H=A[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 d(function(_,S){m.ready().then(function(){K(m._dbInfo,"readonly",function(C,R){if(C)return S(C);try{var D=R.objectStore(m._dbInfo.storeName).openCursor(),A=1;D.onsuccess=function(){var M=D.result;if(M){var N=M.value;j(N)&&(N=L(N));var H=l(N,M.key,A++);H!==void 0?_(H):M.continue()}else _()},D.onerror=function(){S(D.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 d(function(_,S){m.ready().then(function(){K(m._dbInfo,"readonly",function(C,R){if(C)return S(C);try{var D=R.objectStore(m._dbInfo.storeName).get(l);D.onsuccess=function(){var A=D.result;A===void 0&&(A=null),j(A)&&(A=L(A)),_(A)},D.onerror=function(){S(D.error)}}catch(A){S(A)}})}).catch(S)});return c(v,p),v},setItem:function(l,p,m){var v=this;l=f(l);var _=new d(function(S,C){var R;v.ready().then(function(){return R=v._dbInfo,z.call(p)==="[object Blob]"?w(R.db).then(function(D){return D?p:(A=p,new d(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:A.type})},H.readAsBinaryString(A)}));var A}):p}).then(function(D){K(v._dbInfo,"readwrite",function(A,M){if(A)return C(A);try{var N=M.objectStore(v._dbInfo.storeName);D===null&&(D=void 0);var H=N.put(D,l);M.oncomplete=function(){D===void 0&&(D=null),S(D)},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 d(function(_,S){m.ready().then(function(){K(m._dbInfo,"readwrite",function(C,R){if(C)return S(C);try{var D=R.objectStore(m._dbInfo.storeName).delete(l);R.oncomplete=function(){_()},R.onerror=function(){S(D.error)},R.onabort=function(){try{var A=D.error?D.error:D.transaction.error;S(A)}catch(M){S(M)}}}catch(A){S(A)}})}).catch(S)});return c(v,p),v},clear:function(l){var p=this,m=new d(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 D=R.error?R.error:R.transaction.error;_(D)}catch(A){_(A)}}}catch(D){_(D)}})}).catch(_)});return c(m,l),m},length:function(l){var p=this,m=new d(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(D){_(D)}})}).catch(_)});return c(m,l),m},key:function(l,p){var m=this,v=new d(function(_,S){l<0?_(null):m.ready().then(function(){K(m._dbInfo,"readonly",function(C,R){if(C)return S(C);try{var D=R.objectStore(m._dbInfo.storeName),A=!1,M=(D.openKeyCursor||D.openCursor).call(D);M.onsuccess=function(){var N=M.result;N?l===0||A?_(N.key):(A=!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 d(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),D=(R.openKeyCursor||R.openCursor).call(R),A=[];D.onsuccess=function(){var M=D.result;M?(A.push(M.key),M.continue()):v(A)},D.onerror=function(){_(D.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?d.resolve(_._dbInfo.db):G(l).then(function(R){var D=k[l.name],A=D.forages;D.db=R;for(var M=0;M<A.length;M++)A[M]._dbInfo.db=R;return R});v=l.storeName?C.then(function(R){if(R.objectStoreNames.contains(l.storeName)){var D=R.version+1;b(l);var A=k[l.name],M=A.forages;R.close();for(var N=0;N<M.length;N++){var H=M[N];H._dbInfo.db=null,H._dbInfo.version=D}return new d(function(q,Q){var ve=a.open(l.name,D);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){A.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)||d.resolve()).catch(function(){}),q})}}):C.then(function(R){b(l);var D=k[l.name],A=D.forages;R.close();for(var M=0;M<A.length;M++)A[M]._dbInfo.db=null;return new d(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){D.db=N;for(var H=0;H<A.length;H++)T(A[H]._dbInfo)}).catch(function(N){throw(E(l,N)||d.resolve()).catch(function(){}),N})})}else v=d.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,D=0;l[l.length-1]==="="&&(C--,l[l.length-2]==="="&&C--);var A=new ArrayBuffer(C),M=new Uint8Array(A);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[D++]=m<<2|v>>4,M[D++]=(15&v)<<4|_>>2,M[D++]=(3&_)<<6|63&S;return A}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(D,A){A.rows.length?S(D,R):ye(D,p,function(){D.executeSql(m,v,_,S)},S)},S):S(C,R)},S)}function ke(l,p,m,v){var _=this;l=f(l);var S=new d(function(C,R){_.ready().then(function(){p===void 0&&(p=null);var D=p,A=_._dbInfo;A.serializer.serialize(p,function(M,N){N?R(N):A.db.transaction(function(H){re(H,A,"INSERT OR REPLACE INTO "+A.storeName+" (key, value) VALUES (?, ?)",[l,M],function(){C(D)},function(q,Q){R(Q)})},function(H){if(H.code===H.QUOTA_ERR){if(v>0)return void C(ke.apply(_,[l,D,m,v-1]));R(H)}})})}).catch(R)});return c(S,m),S}function de(l){return new d(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 d(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(D,A){C(A)})},C)});return m.serializer=be,_},_support:typeof openDatabase=="function",iterate:function(l,p){var m=this,v=new d(function(_,S){m.ready().then(function(){var C=m._dbInfo;C.db.transaction(function(R){re(R,C,"SELECT * FROM "+C.storeName,[],function(D,A){for(var M=A.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(D,A){S(A)})})}).catch(S)});return c(v,p),v},getItem:function(l,p){var m=this;l=f(l);var v=new d(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(D,A){var M=A.rows.length?A.rows.item(0).value:null;M&&(M=C.serializer.deserialize(M)),_(M)},function(D,A){S(A)})})}).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 d(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(D,A){S(A)})})}).catch(S)});return c(v,p),v},clear:function(l){var p=this,m=new d(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,D){_(D)})})}).catch(_)});return c(m,l),m},length:function(l){var p=this,m=new d(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,D){var A=D.rows.item(0).c;v(A)},function(R,D){_(D)})})}).catch(_)});return c(m,l),m},key:function(l,p){var m=this,v=new d(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(D,A){var M=A.rows.length?A.rows.item(0).key:null;_(M)},function(D,A){S(A)})})}).catch(S)});return c(v,p),v},keys:function(l){var p=this,m=new d(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,D){for(var A=[],M=0;M<D.rows.length;M++)A.push(D.rows.item(M).key);v(A)},function(R,D){_(D)})})}).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 d(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 d(function(C,R){S.db.transaction(function(D){function A(q){return new d(function(Q,ve){D.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(A(S.storeNames[N]));d.all(M).then(function(){C()}).catch(function(q){R(q)})},function(D){R(D)})})}):d.reject("Invalid arguments"),p),v}};function Ae(l,p){var m=l.name+"/";return l.storeName!==p.storeName&&(m+=l.storeName+"/"),m}function jt(){return!function(){try{return localStorage.setItem("_localforage_support_test",!0),localStorage.removeItem("_localforage_support_test"),!1}catch{return!0}}()||localStorage.length>0}var Ge={_driver:"localStorageWrapper",_initStorage:function(l){var p={};if(l)for(var m in l)p[m]=l[m];return p.keyPrefix=Ae(l,this._defaultConfig),jt()?(this._dbInfo=p,p.serializer=be,d.resolve()):d.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,D=1,A=0;A<R;A++){var M=localStorage.key(A);if(M.indexOf(S)===0){var N=localStorage.getItem(M);if(N&&(N=_.serializer.deserialize(N)),(N=l(N,M.substring(C),D++))!==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 d(function(C,R){var D=v._dbInfo;D.serializer.serialize(p,function(A,M){if(M)R(M);else try{localStorage.setItem(D.keyPrefix+l,A),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 d(function(S){l.storeName?S(Ae(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)}}):d.reject("Invalid arguments"),p),v}},Ht=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(Ht(l[v],p))return!0;v++}return!1},Xe=Array.isArray||function(l){return Object.prototype.toString.call(l)==="[object Array]"},Te={},Ie={},Ne={INDEXEDDB:Z,WEBSQL:_e,LOCALSTORAGE:Ge},Be=[Ne.INDEXEDDB._driver,Ne.WEBSQL._driver,Ne.LOCALSTORAGE._driver],Fe=["dropInstance"],nt=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(Fe),At={description:"",driver:Be.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),Ne)if(Ne.hasOwnProperty(m)){var v=Ne[m],_=v._driver;this[m]=_,Te[_]||this.defineDriver(v)}this._defaultConfig=ut({},At),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 d(function(S,C){try{var R=p._driver,D=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!p._driver)return void C(D);for(var A=nt.concat("_initStorage"),M=0,N=A.length;M<N;M++){var H=A[M];if((!Dt(Fe,H)||p[H])&&typeof p[H]!="function")return void C(D)}(function(){for(var Q=function(cs){return function(){var ii=new Error("Method "+cs+" is not implemented by the current driver"),wd=d.reject(ii);return c(wd,arguments[arguments.length-1]),wd}},ve=0,Ze=Fe.length;ve<Ze;ve++){var ar=Fe[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 u(_,m,v),_},l.prototype.driver=function(){return this._driver||null},l.prototype.getDriver=function(p,m,v){var _=Te[p]?d.resolve(Te[p]):d.reject(new Error("Driver not found."));return u(_,m,v),_},l.prototype.getSerializer=function(p){var m=d.resolve(be);return u(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 u(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(A){return _._extend(A),C(),_._ready=_._initStorage(_._config),_._ready}var D=this._driverSet!==null?this._driverSet.catch(function(){return d.resolve()}):d.resolve();return this._driverSet=D.then(function(){var A=S[0];return _._dbInfo=null,_._ready=null,_.getDriver(A).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=d.reject(ve),_._driverSet}()}}(S)})}).catch(function(){C();var A=new Error("No available storage method found.");return _._driverSet=d.reject(A),_._driverSet}),u(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)}),Jv=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}(),Xv=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}(),Zv=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}(),Yv=function(){function r(e,t){return this.dbStorage=xo.createInstance({driver:[xo.INDEXEDDB,xo.LOCALSTORAGE],name:e,storeName:t}),this.dbStorage}return r.prototype.getItem=function(e){return zo(this,void 0,void 0,function(){var t,n;return Ro(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 Xv,this.session=new Zv,this.cache=new Jv}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 pn.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;pn.set(e,t,{expires:new Date(a),path:"/",domain:o})}catch{}},r.prototype.removeCookie=function(e,t){try{pn.remove(e,{path:"/",domain:t||""})}catch{}},r}(),Qv=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=Ao(window.location.href),s=/Mobile|htc|mini|Android|iP(ad|od|hone)/.test(this.appVersion)?"wap":"web",d=((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(),u=this.os();return{browser:c.browser,browser_version:c.browser_version,platform:s,os_name:u.os_name,os_version:u.os_version,userAgent:t,screen_width:window.screen&&window.screen.width,screen_height:window.screen&&window.screen.height,device_model:this.getDeviceModel(u.os_name),language:n,referrer:i,referrer_host:o,network_type:d,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 d=Ao(e);d.keyword&&(o=d.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 d,c;switch(e){case"Mac OS X":t=s("Mac[ +]OS[ +]X(?:[ /](?:Version )?(\\d+(?:[_\\.]\\d+)+))?",this.userAgent),e="mac";break;case"Android":d=this.userAgent,(c=a(/Android ([\.\_\d]+)/,d))||(c=a(/Android\/([\.\_\d]+)/,d)),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 u=this.userAgent.indexOf("x86_64");t=this.userAgent.substring(u+7,u+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}(),Mo=function(r,e){try{return pn.get(r)}catch{return""}},Oo=function(r,e,t,n){try{var i=n||document.domain,o=+new Date+(t||6048e5);pn.set(r,e,{expires:new Date(o),path:"/",domain:i})}catch{}},ey=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 Mo(e)},r.prototype.setCookie=function(e,t,n,i){Oo(e,t,n,i)},r}(),Po,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 Mo(r)},setCookie:function(r,e,t,n){Oo(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}}()},ty={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 Mo(r)},setCookie:function(r,e,t,n){Oo(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}}()},wr=function(){function r(e,t){this._storage=t&&t==="session"?ty:!e&&cu.isSupportLS?cu:new ey}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}(),Lo={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(Lo))},Uo=function(){return Object.keys(Lo)},du={sg:"1fz22z22z1nz21z4mz4bz4bz21z1ez18z1jz1gz49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz18z1jz1gz24z18z49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",my:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z19z1bz49z1kz27z4az1jz18z20z1iz1mz1dz1dz1gz1az1cz4az1az1mz1k"},ry={va:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",in:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k"},ny={sg:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z21z1ez4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",in:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z24z18z49z23z21z1cz18z21z22z4ez18z4az22z1gz1iz22z1mz1iz24z4az1az1mz1k",ie2:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z1gz1cz4ez4az22z1gz1iz22z1mz1iz25z4az1cz23"},iy={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"}(Po||(Po={})),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=Po,ie=void 0,lu=new Date().getTimezoneOffset(),oy=parseInt(""+-lu/60,10),sy=60*lu,ay=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 Qv(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 wr(!1,"session"),this.localStorage=new wr(!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:oy,tz_offset:sy,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)?Lo[i]:((t=this.initConfig)===null||t===void 0?void 0:t.channel_type)==="tcpy"?ny[i]:((n=this.initConfig)===null||n===void 0?void 0:n.channel_type)==="ttp"?iy[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=Ue(Ue({},t.evtParams||{}),e.evtParams||{});else if(n==="_staging_flag")t.evtParams=Ue(Ue({},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}(),cy=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}(),uy=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}(),dy=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}(),ly=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 Yv(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 zo(this,void 0,void 0,function(){var e;return Ro(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:Ue(Ue({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 zo(this,void 0,void 0,function(){return Ro(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}(),hy=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 wr(!0),this.localStorage=new wr(!1),this.logSetting=new ly,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=Do(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=Do(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"),d=this.configManager.get("user_unique_id_type"),c=[];try{var u=e.filter(function(h){try{Object.keys(s).length&&(h.params=Ue(Ue({},s),h.params)),d&&(h.params.$user_unique_id_type=d);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:u,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 d in o)!this.logSetting.getPredefineParamsList().has(d)&&s.has(d)||(a[d]=o[d]);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 d=!0;if(a.forEach(function(c){c.events.length||(d=!1)}),!d)return;n.collect.emit(B.SubmitBefore,a),n.collect.requestManager.useRequest({url:n.reportUrl,data:a,success:function(c,u,f,h){c&&c.e!==0?(n.collect.emit(B.SubmitError,{type:"f_data",eventData:u,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:u,res:c}),n.collect.emit(B.SubmitSuccess,{eventData:u,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,u,f,h){n.configManager.get("reportErrorCallback")(c,u),n.collect.emit(B.SubmitError,{type:"f_net",eventData:c,errorCode:u,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:u,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}(),Go=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)},fy=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 wr(!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:Go(),user_unique_id:this.configManager.get("user_unique_id")||Go()}):this.remoteWebid()},r.prototype.checkEnv=function(){var e=window.navigator.userAgent;if(e.indexOf("miniProgram")!==-1||e.indexOf("MiniProgram")!==-1){var t=Ao(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=Go();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=Ue(Ue({},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}(),mn=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)})},py=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:mn(),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:mn(),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:mn(),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:mn(),timestamp:Date.now()},this.storage.setSessionItem(this.sessionKey,e))},r}(),at=Uint8Array,Je=Uint16Array,No=Int32Array,Bo=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]),Fo=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 No(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(Bo,2),my=pu.b,Vo=pu.r;my[28]=258,Vo[258]=28;for(var mu=fu(Fo,0),CS=mu.b,gu=mu.r,jo=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,jo[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 d=15-e;for(i=0;i<n;++i)if(r[i])for(var c=i<<4|r[i],u=e-r[i],f=s[r[i]-1]++<<u,h=f|(1<<u)-1;f<=h;++f)a[jo[f]>>d]=c}else for(a=new Je(n),i=0;i<n;++i)r[i]&&(a[i]=jo[s[r[i]-1]++]>>15-r[i]);return a},Vt=new at(288);for(ge=0;ge<144;++ge)Vt[ge]=8;for(ge=144;ge<256;++ge)Vt[ge]=9;for(ge=256;ge<280;++ge)Vt[ge]=7;for(ge=280;ge<288;++ge)Vt[ge]=8;var gn=new at(32);for(ge=0;ge<32;++ge)gn[ge]=5;var gy=or(Vt,9,0);or(Vt,9,1);var _y=or(gn,5,0);or(gn,5,1);var _u=function(r){return(r+7)/8|0},vy=function(r,e,t){return(t==null||t>r.length)&&(t=r.length),new at(r.subarray(e,t))},zt=function(r,e,t){t<<=7&e;var n=e/8|0;r[n]|=t,r[n+1]|=t>>8},_n=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},Ho=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],d=t[1],c=0,u=1,f=2;for(t[0]={s:-1,f:s.f+d.f,l:s,r:d};u!=i-1;)s=t[t[c].f<t[f].f?c++:f++],d=t[c!=u&&t[c].f<t[f].f?c++:f++],t[u++]={s:-1,f:s.f+d.f,l:s,r:d};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=$o(t[u-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}},$o=function(r,e,t){return r.s==-1?Math.max($o(r.l,e,t+1),$o(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(d){t[n++]=d},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}},vn=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,d,c,u){zt(e,u++,t),++i[256];for(var f=Ho(i,15),h=f.t,g=f.l,k=Ho(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=Ho(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=vn(i,Vt)+vn(o,gn)+a,ue=vn(i,h)+vn(o,z)+a+14+3*Z+vn(U,$)+2*U[16]+3*U[17]+7*U[18];if(d>=0&&le<=fe&&le<=ue)return yu(e,u,r.subarray(d,d+c));if(zt(e,u,1+(ue<fe)),u+=2,ue<fe){W=or(h,g,0),se=h,oe=or(z,w,0),Y=z;var be=or($,K,0);for(zt(e,u,E-257),zt(e,u+5,I-1),zt(e,u+10,Z-4),u+=14,L=0;L<Z;++L)zt(e,u+3*L,$[hu[L]]);u+=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];zt(e,u,be[de]),u+=$[de],de>15&&(zt(e,u,ke[L]>>5&127),u+=ke[L]>>12)}}}else W=gy,se=Vt,oe=_y,Y=gn;for(L=0;L<s;++L){var _e=n[L];if(_e>255){_n(e,u,W[(de=_e>>18&31)+257]),u+=se[de+257],de>7&&(zt(e,u,_e>>23&31),u+=Bo[de]);var Ae=31&_e;_n(e,u,oe[Ae]),u+=Y[Ae],Ae>3&&(_n(e,u,_e>>5&8191),u+=Fo[Ae])}else _n(e,u,W[_e]),u+=se[_e]}return _n(e,u,W[256]),u+se[256]},yy=new No([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),bu=new at(0),Sy=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}(),by=function(){var r=-1;return{p:function(e){for(var t=r,n=0;n<e.length;++n)t=Sy[255&t^e[n]]^t>>>8;r=t},d:function(){return~r}}},Ey=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,d,c,u,f,h){var g=h.z||s.length,k=new at(u+g+5*(1+Math.ceil(g/7e3))+f),z=k.subarray(u,k.length-f),w=h.l,b=7&(h.r||0);if(d){b&&(z[0]=h.r>>3);for(var T=yy[d-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 No(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,Ae=0,jt=O,Ge=ye-re&32767;if(ke>2&&be==$(Y-Ge))for(var Ht=Math.min(E,ke)-1,Dt=Math.min(32767,Y),Xe=Math.min(258,ke);Ge<=Dt&&--jt&&ye!=re;){if(s[Y+_e]==s[Y+_e-Ge]){for(var Te=0;Te<Xe&&s[Y+Te]==s[Y+Te-Ge];++Te);if(Te>_e){if(_e=Te,Ae=Ge,Te>Ht)break;var Ie=Math.min(Ge,Te-2),Ne=0;for(de=0;de<Ie;++de){var Be=Y-Ge+de&32767,Fe=Be-I[Be]&32767;Fe>Ne&&(Ne=Fe,re=Be)}}}Ge+=(ye=re)-(re=I[ye])&32767}if(Ae){K[le++]=268435456|Vo[_e]<<18|gu[Ae];var nt=31&Vo[_e],At=31&gu[Ae];oe+=Bo[nt]+Fo[At],++Z[257+nt],++W[At],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 vy(k,0,u+_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)},qo=function(r,e,t){for(;t;++e)r[e]=t,t>>>=8},wy=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&&qo(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)}},Cy=function(r){return 10+(r.filename?r.filename.length+1:0)};function Eu(r,e){e||(e={});var t=by(),n=r.length;t.p(r);var i=Ey(r,e,Cy(e),8),o=i.length;return wy(i,e),qo(i,o-8,t.d()),qo(i,o-4,n),i}var ky=(typeof TextEncoder<"u"&&new TextEncoder,typeof TextDecoder<"u"&&new TextDecoder);try{ky.decode(bu,{stream:!0})}catch{}var Ty=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,d=e.zip,c=e.timeout,u=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()},u),w=JSON.stringify(i);this.env==="row"&&d&&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,d=e.timeout,c=e.withCredentials,u=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"),u&&h.setRequestHeader("X-MCS-AppKey",""+u),Object.keys(this.customHeader).length)for(var z in this.customHeader)h.setRequestHeader(z,this.customHeader[z]);c&&(h.withCredentials=!0),d&&(h.timeout=d,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}(),zy=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 d=n.touches?n.touches[0].clientX:n.clientX,c=n.touches?n.touches[0].clientY:n.clientY,u=d-t.offsetX,f=c-t.offsetY,h=window.innerWidth-t.element.offsetWidth,g=window.innerHeight-t.element.offsetHeight;u=Math.max(0,Math.min(u,h)),f=Math.max(0,Math.min(f,g)),t.element.style.transform=`translate(
|
|
70
|
+
`+(u-t.initialX)+`px,
|
|
71
|
+
`+(f-t.initialY)+`px
|
|
72
|
+
)`})}},this.onEnd=function(){if(t.isDragging){t.isDragging=!1;var n=new DOMMatrix(getComputedStyle(t.element).transform),i=t.initialX+n.m41,o=t.initialY+n.m42;t.element.style.left=i+"px",t.element.style.top=o+"px",t.element.style.transform="none",t.initialX=i,t.initialY=o,document.removeEventListener("mousemove",t.onMove),document.removeEventListener("mouseup",t.onEnd),document.removeEventListener("touchmove",t.onMove),document.removeEventListener("touchend",t.onEnd),setTimeout(function(){t.clickAllowed=!0},50)}},this.element=e,this.isDragging=!1,this.animationFrameId=null,this.lastX=0,this.lastY=0,this.initialX=0,this.initialY=0,this.offsetX=0,this.offsetY=0,this.clickAllowed=!0,this.dragThreshold=1,this.initPosition(),this.bindEvents(),this.bindClickHandler()}return r.prototype.initPosition=function(){var e=this.element.getBoundingClientRect();this.element.style.position="fixed",this.element.style.left=e.left+"px",this.element.style.top=e.top+"px",this.element.style.transform="translate(0, 0)"},r.prototype.bindEvents=function(){this.element.addEventListener("mousedown",this.onStart.bind(this)),this.element.addEventListener("touchstart",this.onStart.bind(this))},r.prototype.onStart=function(e){e.preventDefault(),this.initialX=e.clientX||e.touches[0].clientX,this.initialY=e.clientY||e.touches[0].clientY;var t=e.touches?e.touches[0].clientX:e.clientX,n=e.touches?e.touches[0].clientY:e.clientY,i=this.element.getBoundingClientRect();this.initialX=i.left,this.initialY=i.top,this.offsetX=t-this.initialX,this.offsetY=n-this.initialY,this.clickAllowed=!0,this.isDragging=!0,document.addEventListener("mousemove",this.onMove),document.addEventListener("mouseup",this.onEnd),document.addEventListener("touchmove",this.onMove),document.addEventListener("touchend",this.onEnd)},r.prototype.bindClickHandler=function(){var e=this;this.element.addEventListener("click",function(t){if(!e.clickAllowed)return t.stopImmediatePropagation(),void t.preventDefault();window&&window.postMessage({type:"devtool:web:open-draw"},location.origin)})},r}(),Ry=function(){function r(e,t){if(this.devToolReady=!1,this.sendAlready=!1,t.enable_debug&&e.configManager.get("browser")!=="Microsoft Internet Explorer"){this.collect=e,this.config=t,this.app_id=t.app_id;var n=e.adapters.storage;this.cacheStorgae=new n(!1),this.devToolOrigin=window.location.origin,this.currentInstance=t.current_instance||"",this.loadUrl=t.devtool_url||"https://sf16-website-login.neutral.ttwstatic.com/obj/tiktok_web_login_static/log-sdk/collect/devtool/debug-web.v2.0.0.js",this.filterEvent=new Set(["__bav_page","__bav_beat","__bav_page_statistics","__bav_click","__bav_page_exposure","bav2b_page","bav2b_beat","bav2b_page_statistics","bav2b_click","bav2b_page_exposure","_be_active","predefine_pageview","__profile_set","__profile_set_once","__profile_increment","__profile_unset","__profile_append","predefine_page_alive","predefine_page_close","abtest_exposure"]),this.load()}}return r.prototype.loadScript=function(e){try{var t=document.createElement("script");t.src=e,t.onerror=function(){console.log("load DevTool render fail")},t.onload=function(){console.log("load DevTool render success")},document.getElementsByTagName("body")[0].appendChild(t)}catch(n){console.log("devTool load fail, "+n.message)}},r.prototype.parseUrl=function(){var e={};try{var t=window.location.href.split("?")[1].split("&");t.length&&t.forEach(function(n){var i=n.split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])})}catch{}return e},r.prototype.load=function(){try{var e=this.parseUrl();if(e.open_devtool_web&&e.app_id){if(parseInt(e.app_id)!==this.app_id||e.current_instance&&e.current_instance!==this.currentInstance)return}else if(!this.getStorage())return;this.loadBaseInfo(),this.loadHook(),this.setStorage(),this.addLintener(),this.loadDebuggerModule(),this.loadDevTool()}catch(t){console.log("debug fail, "+t.message)}},r.prototype.getStorage=function(){var e=this.cacheStorgae.getItem("__applog_open_devtool_web");return e&&parseInt(e)===this.app_id},r.prototype.setStorage=function(){this.cacheStorgae.setItem("__applog_open_devtool_web",this.app_id)},r.prototype.loadDevTool=function(){this.loadScript(this.loadUrl)},r.prototype.loadBaseInfo=function(){if(this.log=[],this.event=[],this.info=[{title:"BaseInfo",key:"base",type:1,content:[{name:"app_id",desc:"APPID",value:this.config.app_id},{name:"channel",desc:"CHANNEL",value:this.config.channel},{name:"domain",desc:"Domain",value:this.collect.configManager.getDomain()},{name:"sdk_version",desc:"SDK Version",value:"5.3.14_oversea"},{name:"sdk_type",desc:"SDK Import Type",value:"npm"}]},{title:"UserInfo",key:"user",type:2,content:[{name:"uuid",desc:"UserUniqueId",value:this.collect.configManager.get("user").user_unique_id||""},{name:"web_id",desc:"WEB_ID",value:this.collect.configManager.get("user").web_id||""}]},{title:"CommonInfo",type:2,key:"common",content:[{name:"browser",desc:"Browser",value:this.collect.configManager.get("browser")},{name:"browser_version",desc:"Browser Version",value:this.collect.configManager.get("browser_version")},{name:"platform",desc:"Platform",value:this.collect.configManager.get("platform")},{name:"device_model",desc:"Devide Model",value:this.collect.configManager.get("device_model")},{name:"os_name",desc:"Os Name",value:this.collect.configManager.get("os_name")},{name:"os_version",desc:"Os Version",value:this.collect.configManager.get("os_version")},{name:"resolution",desc:"Screen Resolution",value:this.collect.configManager.get("resolution")},{name:"referrer",desc:"Referrer",value:this.collect.configManager.get("referrer")},{name:"custom",desc:"Custom Info",value:JSON.stringify(this.collect.configManager.get("custom"))}]},{title:"Config Info",key:"config",type:3,content:[{name:"autotrack",desc:"AutoTrackEvent",value:!!this.config.autotrack},{name:"stay",desc:"StayDuration",value:!!this.config.enable_stay_duration}]},{title:"A/B Config Info",key:"ab",type:4,content:[{name:"ab",desc:"A/BTester",value:!!this.config.enable_ab_test}]}],this.config.enable_ab_test){var e=this.getInfo("ab"),t=[{name:"ab",desc:"A/BTester",value:!!this.config.enable_ab_test},{name:"vid",desc:"A/B VID",value:this.collect.configManager.getAbVersion()},{name:"ab_domain",desc:"Domain",value:this.config.ab_channel_domain||Jn(ry[this.config.channel])},{name:"all_values",desc:"A/B ALL Values",value:this.collect.configManager.getAbCache()}];e.content=t,this.setInfo("ab",e)}},r.prototype.getInfo=function(e){var t=null;return this.info.forEach(function(n){n.key===e&&(t=n)}),t},r.prototype.setInfo=function(e,t){var n=!1;this.info.forEach(function(i){i.key===e&&(n=!0,i=t)}),n||this.info.push(t)},r.prototype.getSecondInfo=function(e,t){var n=this.getInfo(e),i=null;return n.content.forEach(function(o){o.name===t&&(i=o)}),i},r.prototype.setSecondInfo=function(e,t,n){var i=this.getInfo(e),o=!1;if(i.content.forEach(function(s){s.name===t&&(s.value=n,o=!0)}),!o){var a={name:t,value:n,desc:t.toLocaleUpperCase()};i.content.push(a)}this.setInfo(e,i)},r.prototype.loadHook=function(){var e=this;this.collect.on(P.DEBUGGER_MESSAGE,function(t){switch(t.type){case P.DEBUGGER_MESSAGE_SDK:var n={time:t.time,type:t.logType||"sdk",infoType:t.infoType||"sdk",level:t.level,name:t.info,show:!0,levelShow:!0,needDesc:!!t.data};if(t.data&&(n.desc={content:JSON.stringify(t.data)}),e.updateLog(n),t.secType&&t.secType==="AB")e.setSecondInfo("ab","vid",e.collect.configManager.getAbVersion()),e.setSecondInfo("ab","all_values",e.collect.configManager.getAbCache());else if(t.secType==="USER")e.setSecondInfo("user",t.common==="user_unique_id"?"uuid":t.common,e.collect.configManager.get(t.common));else if(t.secType==="HEADER"){var i=e.collect.configManager.get(t.common);e.setSecondInfo("common",t.common,t.common==="custom"?JSON.stringify(i):i)}return void e.updateInfo();case P.DEBUGGER_MESSAGE_EVENT:if(t.data&&t.data.length){var o=t.data[0],a=o.events;if(!a.length)return;a.forEach(function(s){s.checkShow=!0,s.searchShow=!0,s.focusShow=!0,s.status=t.status,s.type=e.filterEvent.has(s.event)?"sdk":"cus",s.verifyType=t.verifyType?"verify":"no",s.info="",t.status==="fail"&&(s.info={message:"code: "+t.code+", msg: "+(t.msg||t.failType)})}),e.updateEvent(o)}return}})},r.prototype.addLintener=function(){var e=this;window.addEventListener("message",function(t){if(e.devToolOrigin===t.origin){if(t&&t.data&&t.data.type==="devtool:web:ready"){if(e.devToolOrigin=t.origin,e.devToolReady=!0,e.sendAlready)return;e.sendData("devtool:web:init",{info:e.info,log:e.log,event:e.event,sdk_type:"5.3.14_oversea".includes("tob")?"tob":"inner",appId:e.app_id}),e.sendAlready=!0}t&&t.data&&t.data.type==="devtool:web:ssid"&&e.collect.getToken(function(n){e.setSecondInfo("user","sid",n.tobid),e.updateInfo()})}})},r.prototype.sendData=function(e,t){try{var n={type:e,payload:t};window&&window.postMessage(n,this.devToolOrigin)}catch{}},r.prototype.updateInfo=function(){this.devToolReady&&this.sendData("devtool:web:info",this.info)},r.prototype.updateLog=function(e){this.devToolReady?this.sendData("devtool:web:log",e):this.log.push(e)},r.prototype.updateEvent=function(e){this.devToolReady?this.sendData("devtool:web:event",e):this.event.push(e)},r.prototype.loadDebuggerModule=function(){var e=`#debugger-applog-web {
|
|
73
|
+
position: fixed;
|
|
74
|
+
width: 45px;
|
|
75
|
+
height: 45px;
|
|
76
|
+
background-image: url(`+Jn("1fz22z22z1nz21z4mz4bz4bz21z1dz4dz4iz49z25z1cz19z21z1gz22z1cz49z1jz1mz1ez1gz1lz4az1lz1cz23z22z20z18z1jz4az22z22z25z21z22z18z22z1gz1az4az1az1mz1kz4bz1mz19z1hz4bz22z1gz1iz22z1mz1iz16z25z1cz19z16z1jz1mz1ez1gz1lz16z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz1bz1cz24z22z1mz1mz1jz4bz18z1nz1nz1jz1mz1ez4az1nz1lz1e")+`);
|
|
77
|
+
bottom: 5%;
|
|
78
|
+
right: 10%;
|
|
79
|
+
cursor: pointer;
|
|
80
|
+
z-index:100;
|
|
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 zy(a)},r}(),Ko={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"],Cr=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 Kv,this.remotePlugin=new Map,this.logger=new cy(e),this.Types=B,this.adapters.storage=wr}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 "+Uo().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 "+Uo().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 "+Uo().join(",")+", use us_east instead, please check!!!",infoType:"sdk"})),this.spider=new uy,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 dy(this,e.enable_native),this.configManager=new ay(this,e),this.requestManager=new Ty(this,e),this.bridgeReport=this.appBridge.bridgeInject(),this.debugger=new Ry(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 hy,this.tokenManager=new fy,this.sessionManager=new py,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,d=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,d),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=Ue({},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 d={};for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&s.indexOf(c)<0&&(d[c]=a[c]);if(a!=null&&typeof Object.getOwnPropertySymbols=="function"){var u=0;for(c=Object.getOwnPropertySymbols(a);u<c.length;u++)s.indexOf(c[u])<0&&(d[c[u]]=a[c[u]])}return d}(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,d=a.params;n.appBridge.onEventV3(s,JSON.stringify(d))}):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=Wv();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=Ue(Ue({},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 mn()},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 d=n.configManager.get().user;return s&&(d.tobid=s,d["diss".split("").reverse().join("")]=s),e(Ue({},d))}},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}(),Ay=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(d){d.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(d){console.warn("something error, "+JSON.stringify(d.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:d.message})}})},r}(),Iy=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}(),xy=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,d=o.errorCode,c=o.response;a==="f_data"&&n.sdkError(s,d,c)}),this.collect.on(e.Types.SDKInnerError,function(o){var a=o.type,s=o.eventData,d=o.errorCode,c=o.msg;n.sdkInnerError(a,s,d,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,d=(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:[d],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,d=[];e.forEach(function(u){u.events.forEach(function(f){d.push(f)})});var c={events:d.map(function(u){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:u.event,sdk_version:s.sdk_version,local_time_ms:u.local_time_ms,tea_event_index:Date.now(),params:u.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,d=a.header,c=[];t.forEach(function(f){f.events.forEach(function(h){c.push(h)})});var u={events:c.map(function(f){return{event:"on_error",params:JSON.stringify({type:e,error_code:n,app_id:d.app_id,app_name:d.app_name||"",error_event:f.event,sdk_version:d.sdk_version,local_time_ms:f.local_time_ms,tea_event_index:Date.now(),params:f.params,header:d,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:[u],timeout:3e4,app_key:"566f58151b0ed37e"})},16)}catch{}},r}(),Wo=typeof window<"u"?(window.LogPluginObject||(window.LogPluginObject={}),window.LogPluginObject):null,My=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(Ko.hasOwnProperty(n)){var i=Ko[n].object,o=""+Ko[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;Wo[t]?(this.process(e,Wo[t]),console.log("already has "+e+" plugin~")):this.loadPlugin(e,n,function(){i.process(e,Wo[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}();Cr.usePlugin(My,"extend"),Cr.usePlugin(Ay,"et"),Cr.usePlugin(Iy,"heartbeat"),Cr.usePlugin(xy,"monitor"),new Cr("default");var Oy=Cr;class kr{constructor({userId:e}){this.collector=new Oy("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 kr.instance||(kr.instance=new kr({userId:e})),kr.instance}event(e,t){this.collector.event(e,t||{})}}class Py extends Hv{constructor({userId:e}){super($v),this.logger=kr.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 Ly=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=Ly*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 Jo=Cu("audio_encoder_support","3d");function Uy(){return wu(["EncodedAudioChunk","AudioEncoder","AudioData"])}function Gy(r){const e=Jo.get(),t=`${r}_support`;return e&&e[t]?e[t]:null}function Ny(r,e){const t=Jo.get()||{},n=`${r}_support`;t[n]=e,Jo.set(t)}async function By(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=Gy(r);if(e)return console.log(`Audio encoder ${r} support result from cache:`,e),e;const t=await By(r);return Ny(r,t),t}function Fy(){return Tu(Zn[He.OPUS])}function Vy(){return Tu(Zn[He.AAC])}const Xo=Cu("video_encoder_support","3d");function Zo(){return wu(["EncodedVideoChunk","VideoEncoder","VideoFrame"])}function zu(r){const e=Xo.get(),t=`${r}_support`;return e&&e[t]?e[t]:null}function Yo(r,e){const t=Xo.get()||{},n=`${r}_support`;t[n]=e,Xo.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 jy(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,d=480,c=new OffscreenCanvas(s,d),u=c.getContext("2d");u&&(u.fillStyle="#FF0000",u.fillRect(0,0,s,d));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 Hy(r){if(!Zo())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 Yo(r,t),t}async function $y(r,e=3e3){if(!Zo())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 Yo(r,n),n;const i=await jy(r,e);return Yo(r,i),i}function qy(){return Hy(Zn[He.H264])}function Ky(){return $y(Zn[He.H265])}function Wy(){return Uy().supported}function Jy(){return Zo().supported}async function Xy(r){if(!Wy())return{supported:!1,info:"AudioEncoder API not supported"};try{switch(r){case"aac":return await Vy();case"opus":return await Fy();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 Zy(r){if(!Jy())return{supported:!1,info:"VideoEncoder API not supported"};try{switch(r){case"h264":return await qy();case"h265":return await Ky();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 Yy(r,e=!1){const t=["aac"],n=["h264"],i={audioCodecs:{},videoCodecs:{}};for(const f of t)i.audioCodecs[f]=await Xy(f);for(const f of n)i.videoCodecs[f]=await Zy(f);const o=[],a=[],s=[],d=[];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):d.push(f)});const u={supported:a.length===0&&d.length===0,supportedAudio:o,supportedVideo:s,unsupportedAudio:a,unsupportedVideo:d};return e&&(u.details=i),u}async function Qy(){return(await Yy()).supported}class Du{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 Py({userId:Kt.instance.userId??""});const a=()=>{this.engine.online()};window.addEventListener("online",a),this._clearOnline=()=>{window.removeEventListener("online",a)}}static async isSupported(){return await Qy()&&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 fn(e);const{video:t,audio:n,upspeed:i}=await this.engine.getStats();return{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}}}publish(e,t,n){const i={url:this.url,maxReconnectCount:10,autoReconnect:!1,bitrate:{},cfg:Object.assign({gopSize:90},n||{}),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 Au({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 eS{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 Nt("ReconnectStrategy")}getNextPushUrl(){const e=this._pushConsumer.pushUrl;return e?Au({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 yn={ManualStop:0,ReconnectFailed:1,StartPushError:2,PushError:3},Tr={PushCheck:0,PushError:1},Iu=new Nt("PushController");class tS extends Gc{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(_s,"audio").bitrate,this._videoBitrate=pr(gs,"video").bitrate,this.handleReconnectError=(s,d)=>{var c,u;X(J.STOP_PUSH_STREAM,{reason:yn.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:(u=this._reconnectStrategy)==null?void 0:u.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 d=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,d),X(J.STOP_PUSH_STREAM,{reason:yn.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:Tr.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 d;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":(d=this._reconnectStrategy)!=null&&d.isActive()?this._executeReconnect():(this.connectionState===$e.CONNECTED?X(J.STOP_PUSH_STREAM,{reason:yn.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:Tr.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*Ia:void 0;this._reconnectStrategy=new eS(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,d;if(t.isReconnect||(this._pushSessionId=Date.now(),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:Tr.PushCheck,push_url:this._pushUrl}),new Error("lack publish url");if(this._connect)return;this.start(),this._pushUrl=Au({pushUrl:e,disableTCC:!0}),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:Tr.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:Tr.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(e,this._pushConfig,this._OnRtcStateChange);else if(this._pushMode==="webTransport")o=new Nv(e,this._pushConfig,this._OnRTMPError,this._OnRTMPSuccess);else if(this._pushMode==="mediaEngine")o=new Du(e,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}),t.isReconnect||(Iu.log("startPush begin"),this._connectionStartDate=Date.now())}catch(c){const u=new fr(qe.PUBLISH_FAILED,c.message,c);if(Iu.groupEnd(),(d=this._reconnectStrategy)!=null&&d.isActive())throw this.unpublish({isReconnecting:!0}),u;this._streamConsumeController.emit(Ee.PushError,u),X(J.STOP_PUSH_STREAM,{reason:yn.PushError,error_message:u.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:Tr.PushError,error_message:u.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:d,originStats:c}=await this._connect.getStatsSnapshoot(2e3),f=Date.now()-s;!Im(d)&&((n=this._connect)!=null&&n.isPushing)&&this.connectionState===$e.CONNECTED?this._prevStats=d:this._prevStats=void 0;const h=this.pushMode==="rtm"?bv(d,c,{idealFrameRate:(i=this._composedStream._videoStream)==null?void 0:i.frameRate,idealBitrate:this._videoBitrate}):Ev(d),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:d,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 fn(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});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:yn.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._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 rS extends xt{constructor(e,t){super(),this._previewConsumer=new hv(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new tS(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,{cfg: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 nS{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 iS=new nS;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 d=c=>{const u=t(c);u&&(s.handleEvent?s.handleEvent(u):s(u))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(s,d),i.apply(this,[a,d])};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 d=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,d])},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 oS(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 sS(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 Qo(r,e){Mu&&console.warn(r+" is deprecated, please use "+e+" instead.")}function aS(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 es(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?es(r,r.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(i=>{es(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&&es(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 d={};return Object.keys(s).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;const u=typeof s[c]=="object"?s[c]:{ideal:s[c]};u.exact!==void 0&&typeof u.exact=="number"&&(u.min=u.max=u.exact);const f=function(h,g){return h?h+g.charAt(0).toUpperCase()+g.slice(1):g==="deviceId"?"sourceId":g};if(u.ideal!==void 0){d.optional=d.optional||[];let h={};typeof u.ideal=="number"?(h[f("min",c)]=u.ideal,d.optional.push(h),h={},h[f("max",c)]=u.ideal,d.optional.push(h)):(h[f("",c)]=u.ideal,d.optional.push(h))}u.exact!==void 0&&typeof u.exact!="number"?(d.mandatory=d.mandatory||{},d.mandatory[f("",c)]=u.exact):["min","max"].forEach(h=>{u[h]!==void 0&&(d.mandatory=d.mandatory||{},d.mandatory[f(h,c)]=u[h])})}),s.advanced&&(d.optional=(d.optional||[]).concat(s.advanced)),d},i=function(s,d){if(e.version>=61)return d(s);if(s=JSON.parse(JSON.stringify(s)),s&&typeof s.audio=="object"){const c=function(u,f,h){f in u&&!(h in u)&&(u[h]=u[f],delete u[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 u=e.version<66;if(c&&(c.exact==="user"||c.exact==="environment"||c.ideal==="user"||c.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!u)){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)),d(s)})}s.video=n(s.video)}return Gu("chrome: "+JSON.stringify(s)),d(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,d,c){i(s,u=>{t.webkitGetUserMedia(u,d,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(d){return i(d,c=>s(c).then(u=>{if(c.audio&&!u.getAudioTracks().length||c.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(f=>{f.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(o(u))))}}}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,d){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 d=this._senders.indexOf(s);d!==-1&&this._senders.splice(d,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(d=>d.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 d=e.apply(this,arguments);return this._shimmedLocalStreams[s.id]?this._shimmedLocalStreams[s.id].indexOf(d)===-1&&this._shimmedLocalStreams[s.id].push(d):this._shimmedLocalStreams[s.id]=[s,d],d};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 d=this.getSenders().filter(c=>s.indexOf(c)===-1);this._shimmedLocalStreams[a.id]=[a].concat(d)};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 d=this._shimmedLocalStreams[s].indexOf(a);d!==-1&&this._shimmedLocalStreams[s].splice(d,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 u=t.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(f=>this._reverseStreams[f.id])};const n=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(u){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(f=>{if(this.getSenders().find(g=>g.track===f))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){const f=new r.MediaStream(u.getTracks());this._streams[u.id]=f,this._reverseStreams[f.id]=u,u=f}n.apply(this,[u])};const i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[u.id]||u]),delete this._reverseStreams[this._streams[u.id]?this._streams[u.id].id:u.id],delete this._streams[u.id]},r.RTCPeerConnection.prototype.addTrack=function(u,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===u))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===u))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(u),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const z=new r.MediaStream([u]);this._streams[f.id]=z,this._reverseStreams[z.id]=f,this.addStream(z)}return this.getSenders().find(z=>z.track===u)};function o(c,u){let f=u.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:u.type,sdp:f})}function a(c,u){let f=u.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:u.type,sdp:f})}["createOffer","createAnswer"].forEach(function(c){const u=r.RTCPeerConnection.prototype[c],f={[c](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[k=>{const z=o(this,k);h[0].apply(null,[z])},k=>{h[1]&&h[1].apply(null,k)},arguments[2]]):u.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 d=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){const c=d.get.apply(this);return c.type===""?c:o(this,c)}}),r.RTCPeerConnection.prototype.removeTrack=function(u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!u._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(u._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=>u.track===z)&&(h=this._streams[g])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function ts(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:ts,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){Qo("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,d){s in a&&!(d in a)&&(a[d]=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 cS(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 rs(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(d=>{if(e.version<53&&!a)try{d.forEach(c=>{c.type=t[c.type]||c.type})}catch(c){if(c.name!=="TypeError")throw c;d.forEach((u,f)=>{d.set(f,Object.assign({},u,{type:t[u.type]||u.type}))})}return d}).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){Qo("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:cS,shimGetParameters:td,shimGetUserMedia:Wu,shimOnTrack:Ju,shimPeerConnection:rs,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,u){const f=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[f]);return u?(h.then(c,u),Promise.resolve()):h},e.createAnswer=function(c,u){const f=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[f]);return u?(h.then(c,u),Promise.resolve()):h};let s=function(d,c,u){const f=i.apply(this,[d]);return u?(f.then(c,u),Promise.resolve()):f};e.setLocalDescription=s,s=function(d,c,u){const f=o.apply(this,[d]);return u?(f.then(c,u),Promise.resolve()):f},e.setRemoteDescription=s,s=function(d,c,u){const f=a.apply(this,[d]);return u?(f.then(c,u),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?(Qo("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 ns={exports:{}},md;function uS(){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(`
|
|
70
83
|
`).map(n=>n.trim())},e.splitSections=function(t){return t.split(`
|
|
71
|
-
m=`).map((i,
|
|
72
|
-
`)},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
|
|
84
|
+
m=`).map((i,o)=>(o>0?"m="+i:i).trim()+`\r
|
|
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
|
|
73
86
|
`},e.parseExtmap=function(t){const n=t.substring(9).split(" ");return{id:parseInt(n[0],10),direction:n[0].indexOf("/")>0?n[0].split("/")[1]:"sendrecv",uri:n[1],attributes:n.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r
|
|
74
|
-
`},e.parseFmtp=function(t){const n={};let i;const
|
|
75
|
-
`}return n},e.parseRtcpFb=function(t){const n=t.substring(t.indexOf(" ")+1).split(" ");return{type:n.shift(),parameter:n.join(" ")}},e.writeRtcpFb=function(t){let n="",i=t.payloadType;return t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(
|
|
76
|
-
`}),n},e.parseSsrcMedia=function(t){const n=t.indexOf(" "),i={ssrc:parseInt(t.substring(7,n),10)},
|
|
77
|
-
`;return t.fingerprints.forEach(
|
|
87
|
+
`},e.parseFmtp=function(t){const n={};let i;const o=t.substring(t.indexOf(" ")+1).split(";");for(let a=0;a<o.length;a++)i=o[a].trim().split("="),n[i[0].trim()]=i[1];return n},e.writeFmtp=function(t){let n="",i=t.payloadType;if(t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const o=[];Object.keys(t.parameters).forEach(a=>{t.parameters[a]!==void 0?o.push(a+"="+t.parameters[a]):o.push(a)}),n+="a=fmtp:"+i+" "+o.join(";")+`\r
|
|
88
|
+
`}return n},e.parseRtcpFb=function(t){const n=t.substring(t.indexOf(" ")+1).split(" ");return{type:n.shift(),parameter:n.join(" ")}},e.writeRtcpFb=function(t){let n="",i=t.payloadType;return t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(o=>{n+="a=rtcp-fb:"+i+" "+o.type+(o.parameter&&o.parameter.length?" "+o.parameter:"")+`\r
|
|
89
|
+
`}),n},e.parseSsrcMedia=function(t){const n=t.indexOf(" "),i={ssrc:parseInt(t.substring(7,n),10)},o=t.indexOf(":",n);return o>-1?(i.attribute=t.substring(n+1,o),i.value=t.substring(o+1)):i.attribute=t.substring(n+1),i},e.parseSsrcGroup=function(t){const n=t.substring(13).split(" ");return{semantics:n.shift(),ssrcs:n.map(i=>parseInt(i,10))}},e.getMid=function(t){const n=e.matchPrefix(t,"a=mid:")[0];if(n)return n.substring(6)},e.parseFingerprint=function(t){const n=t.substring(14).split(" ");return{algorithm:n[0].toLowerCase(),value:n[1].toUpperCase()}},e.getDtlsParameters=function(t,n){return{role:"auto",fingerprints:e.matchPrefix(t+n,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,n){let i="a=setup:"+n+`\r
|
|
90
|
+
`;return t.fingerprints.forEach(o=>{i+="a=fingerprint:"+o.algorithm+" "+o.value+`\r
|
|
78
91
|
`}),i},e.parseCryptoLine=function(t){const n=t.substring(9).split(" ");return{tag:parseInt(n[0],10),cryptoSuite:n[1],keyParams:n[2],sessionParams:n.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r
|
|
79
|
-
`},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const n=t.substring(7).split("|");return{keyMethod:"inline",keySalt:n[0],lifeTime:n[1],mkiValue:n[2]?n[2].split(":")[0]:void 0,mkiLength:n[2]?n[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,n){return e.matchPrefix(t+n,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,n){const i=e.matchPrefix(t+n,"a=ice-ufrag:")[0],
|
|
92
|
+
`},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const n=t.substring(7).split("|");return{keyMethod:"inline",keySalt:n[0],lifeTime:n[1],mkiValue:n[2]?n[2].split(":")[0]:void 0,mkiLength:n[2]?n[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,n){return e.matchPrefix(t+n,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,n){const i=e.matchPrefix(t+n,"a=ice-ufrag:")[0],o=e.matchPrefix(t+n,"a=ice-pwd:")[0];return i&&o?{usernameFragment:i.substring(12),password:o.substring(10)}:null},e.writeIceParameters=function(t){let n="a=ice-ufrag:"+t.usernameFragment+`\r
|
|
80
93
|
a=ice-pwd:`+t.password+`\r
|
|
81
94
|
`;return t.iceLite&&(n+=`a=ice-lite\r
|
|
82
|
-
`),n},e.parseRtpParameters=function(t){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},
|
|
95
|
+
`),n},e.parseRtpParameters=function(t){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},o=e.splitLines(t)[0].split(" ");n.profile=o[2];for(let s=3;s<o.length;s++){const d=o[s],c=e.matchPrefix(t,"a=rtpmap:"+d+" ")[0];if(c){const u=e.parseRtpMap(c),f=e.matchPrefix(t,"a=fmtp:"+d+" ");switch(u.parameters=f.length?e.parseFmtp(f[0]):{},u.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+d+" ").map(e.parseRtcpFb),n.codecs.push(u),u.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(u.name.toUpperCase());break}}}e.matchPrefix(t,"a=extmap:").forEach(s=>{n.headerExtensions.push(e.parseExtmap(s))});const a=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return n.codecs.forEach(s=>{a.forEach(d=>{s.rtcpFeedback.find(u=>u.type===d.type&&u.parameter===d.parameter)||s.rtcpFeedback.push(d)})}),n},e.writeRtpDescription=function(t,n){let i="";i+="m="+t+" ",i+=n.codecs.length>0?"9":"0",i+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=n.codecs.map(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r
|
|
83
96
|
`,i+=`c=IN IP4 0.0.0.0\r
|
|
84
97
|
`,i+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
|
85
|
-
`,n.codecs.forEach(a=>{i+=e.writeRtpMap(a),i+=e.writeFmtp(a),i+=e.writeRtcpFb(a)});let
|
|
86
|
-
`),n.headerExtensions&&n.headerExtensions.forEach(a=>{i+=e.writeExtmap(a)}),i},e.parseRtpEncodingParameters=function(t){const n=[],i=e.parseRtpParameters(t),
|
|
98
|
+
`,n.codecs.forEach(a=>{i+=e.writeRtpMap(a),i+=e.writeFmtp(a),i+=e.writeRtcpFb(a)});let o=0;return n.codecs.forEach(a=>{a.maxptime>o&&(o=a.maxptime)}),o>0&&(i+="a=maxptime:"+o+`\r
|
|
99
|
+
`),n.headerExtensions&&n.headerExtensions.forEach(a=>{i+=e.writeExtmap(a)}),i},e.parseRtpEncodingParameters=function(t){const n=[],i=e.parseRtpParameters(t),o=i.fecMechanisms.indexOf("RED")!==-1,a=i.fecMechanisms.indexOf("ULPFEC")!==-1,s=e.matchPrefix(t,"a=ssrc:").map(h=>e.parseSsrcMedia(h)).filter(h=>h.attribute==="cname"),d=s.length>0&&s[0].ssrc;let c;const u=e.matchPrefix(t,"a=ssrc-group:FID").map(h=>h.substring(17).split(" ").map(k=>parseInt(k,10)));u.length>0&&u[0].length>1&&u[0][0]===d&&(c=u[0][1]),i.codecs.forEach(h=>{if(h.name.toUpperCase()==="RTX"&&h.parameters.apt){let g={ssrc:d,codecPayloadType:parseInt(h.parameters.apt,10)};d&&c&&(g.rtx={ssrc:c}),n.push(g),o&&(g=JSON.parse(JSON.stringify(g)),g.fec={ssrc:d,mechanism:a?"red+ulpfec":"red"},n.push(g))}}),n.length===0&&d&&n.push({ssrc:d});let f=e.matchPrefix(t,"b=");return f.length&&(f[0].indexOf("b=TIAS:")===0?f=parseInt(f[0].substring(7),10):f[0].indexOf("b=AS:")===0?f=parseInt(f[0].substring(5),10)*1e3*.95-50*40*8:f=void 0,n.forEach(h=>{h.maxBitrate=f})),n},e.parseRtcpParameters=function(t){const n={},i=e.matchPrefix(t,"a=ssrc:").map(s=>e.parseSsrcMedia(s)).filter(s=>s.attribute==="cname")[0];i&&(n.cname=i.value,n.ssrc=i.ssrc);const o=e.matchPrefix(t,"a=rtcp-rsize");n.reducedSize=o.length>0,n.compound=o.length===0;const a=e.matchPrefix(t,"a=rtcp-mux");return n.mux=a.length>0,n},e.writeRtcpParameters=function(t){let n="";return t.reducedSize&&(n+=`a=rtcp-rsize\r
|
|
87
100
|
`),t.mux&&(n+=`a=rtcp-mux\r
|
|
88
101
|
`),t.ssrc!==void 0&&t.cname&&(n+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
|
|
89
|
-
`),n},e.parseMsid=function(t){let n;const i=e.matchPrefix(t,"a=msid:");if(i.length===1)return n=i[0].substring(7).split(" "),{stream:n[0],track:n[1]};const
|
|
102
|
+
`),n},e.parseMsid=function(t){let n;const i=e.matchPrefix(t,"a=msid:");if(i.length===1)return n=i[0].substring(7).split(" "),{stream:n[0],track:n[1]};const o=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(o.length>0)return n=o[0].value.split(" "),{stream:n[0],track:n[1]}},e.parseSctpDescription=function(t){const n=e.parseMLine(t),i=e.matchPrefix(t,"a=max-message-size:");let o;i.length>0&&(o=parseInt(i[0].substring(19),10)),isNaN(o)&&(o=65536);const a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:n.fmt,maxMessageSize:o};const s=e.matchPrefix(t,"a=sctpmap:");if(s.length>0){const d=s[0].substring(10).split(" ");return{port:parseInt(d[0],10),protocol:d[1],maxMessageSize:o}}},e.writeSctpDescription=function(t,n){let i=[];return t.protocol!=="DTLS/SCTP"?i=["m="+t.kind+" 9 "+t.protocol+" "+n.protocol+`\r
|
|
90
103
|
`,`c=IN IP4 0.0.0.0\r
|
|
91
104
|
`,"a=sctp-port:"+n.port+`\r
|
|
92
105
|
`]:i=["m="+t.kind+" 9 "+t.protocol+" "+n.port+`\r
|
|
93
106
|
`,`c=IN IP4 0.0.0.0\r
|
|
94
107
|
`,"a=sctpmap:"+n.port+" "+n.protocol+` 65535\r
|
|
95
108
|
`],n.maxMessageSize!==void 0&&i.push("a=max-message-size:"+n.maxMessageSize+`\r
|
|
96
|
-
`),i.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,n,i){let
|
|
97
|
-
o=`+(i||"thisisadapterortc")+" "+
|
|
109
|
+
`),i.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,n,i){let o;const a=n!==void 0?n:2;return t?o=t:o=e.generateSessionId(),`v=0\r
|
|
110
|
+
o=`+(i||"thisisadapterortc")+" "+o+" "+a+` IN IP4 127.0.0.1\r
|
|
98
111
|
s=-\r
|
|
99
112
|
t=0 0\r
|
|
100
|
-
`},e.getDirection=function(t,n){const i=e.splitLines(t);for(let
|
|
101
|
-
a=extmap-allow-mixed`)!==-1){const
|
|
113
|
+
`},e.getDirection=function(t,n){const i=e.splitLines(t);for(let o=0;o<i.length;o++)switch(i[o]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[o].substring(2)}return n?e.getDirection(n):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const i=e.splitLines(t)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},e.parseOLine=function(t){const i=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const n=e.splitLines(t);for(let i=0;i<n.length;i++)if(n[i].length<2||n[i].charAt(1)!=="=")return!1;return!0},r.exports=e}(ns)),ns.exports}var gd=uS();const zr=Oe(gd),dS=it({__proto__:null,default:zr},[gd]);function Qn(r){if(!r.RTCIceCandidate||r.RTCIceCandidate&&"foundation"in r.RTCIceCandidate.prototype)return;const e=r.RTCIceCandidate;r.RTCIceCandidate=function(n){if(typeof n=="object"&&n.candidate&&n.candidate.indexOf("a=")===0&&(n=JSON.parse(JSON.stringify(n)),n.candidate=n.candidate.substring(2)),n.candidate&&n.candidate.length){const i=new e(n),o=zr.parseCandidate(n.candidate);for(const a in o)a in i||Object.defineProperty(i,a,{value:o[a]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new e(n)},r.RTCIceCandidate.prototype=e.prototype,sr(r,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new r.RTCIceCandidate(t.candidate),writable:"false"}),t))}function is(r){!r.RTCIceCandidate||r.RTCIceCandidate&&"relayProtocol"in r.RTCIceCandidate.prototype||sr(r,"icecandidate",e=>{if(e.candidate){const t=zr.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function ei(r,e){if(!r.RTCPeerConnection)return;"sctp"in r.RTCPeerConnection.prototype||Object.defineProperty(r.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(s){if(!s||!s.sdp)return!1;const d=zr.splitSections(s.sdp);return d.shift(),d.some(c=>{const u=zr.parseMLine(c);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},n=function(s){const d=s.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(d===null||d.length<2)return-1;const c=parseInt(d[1],10);return c!==c?-1:c},i=function(s){let d=65536;return e.browser==="firefox"&&(e.version<57?s===-1?d=16384:d=2147483637:e.version<60?d=e.version===57?65535:65536:d=2147483637),d},o=function(s,d){let c=65536;e.browser==="firefox"&&e.version===57&&(c=65535);const u=zr.matchPrefix(s.sdp,"a=max-message-size:");return u.length>0?c=parseInt(u[0].substring(19),10):e.browser==="firefox"&&d!==-1&&(c=2147483637),c},a=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:d}=this.getConfiguration();d==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const d=n(arguments[0]),c=i(d),u=o(arguments[0],d);let f;c===0&&u===0?f=Number.POSITIVE_INFINITY:c===0||u===0?f=Math.max(c,u):f=Math.min(c,u);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return f}}),this._sctp=h}return a.apply(this,arguments)}}function ti(r){if(!(r.RTCPeerConnection&&"createDataChannel"in r.RTCPeerConnection.prototype))return;function e(n,i){const o=n.send;n.send=function(){const s=arguments[0],d=s.length||s.size||s.byteLength;if(n.readyState==="open"&&i.sctp&&d>i.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+i.sctp.maxMessageSize+" bytes)");return o.apply(n,arguments)}}const t=r.RTCPeerConnection.prototype.createDataChannel;r.RTCPeerConnection.prototype.createDataChannel=function(){const i=t.apply(this,arguments);return e(i,this),i},sr(r,"datachannel",n=>(e(n.channel,n.target),n))}function os(r){if(!r.RTCPeerConnection||"connectionState"in r.RTCPeerConnection.prototype)return;const e=r.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=i=>{const o=i.target;if(o._lastConnectionState!==o.connectionState){o._lastConnectionState=o.connectionState;const a=new Event("connectionstatechange",i);o.dispatchEvent(a)}return i},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function ss(r,e){if(!r.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const t=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(i){if(i&&i.sdp&&i.sdp.indexOf(`
|
|
114
|
+
a=extmap-allow-mixed`)!==-1){const o=i.sdp.split(`
|
|
102
115
|
`).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
|
|
103
|
-
`);r.RTCSessionDescription&&i instanceof r.RTCSessionDescription?arguments[0]=new r.RTCSessionDescription({type:i.type,sdp:s}):i.sdp=s}return t.apply(this,arguments)}}function Tn(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;const t=r.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(r.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function kn(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;const t=r.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(r.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return t.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?t.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}const yg=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:ss,shimAddIceCandidateNullOrEmpty:Tn,shimConnectionState:is,shimMaxMessageSize:Cn,shimParameterlessSetLocalDescription:kn,shimRTCIceCandidate:En,shimRTCIceCandidateRelayProtocol:ns,shimSendThrowTypeError:wn},Symbol.toStringTag,{value:"Module"}));function Sg({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=rc,n=mg(r),i={browserDetails:n,commonShim:yg,extractVersion:bn,disableLog:pg,disableWarnings:fg,sdp:vg};switch(n.browser){case"chrome":if(!mc||!es||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),i;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),i;t("adapter.js shimming chrome."),i.browserShim=mc,Tn(r,n),kn(r),ac(r,n),cc(r),es(r,n),uc(r),pc(r,n),dc(r),lc(r),fc(r,n),En(r),ns(r),is(r),Cn(r,n),wn(r),ss(r,n);break;case"firefox":if(!kc||!ts||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),i;t("adapter.js shimming firefox."),i.browserShim=kc,Tn(r,n),kn(r),_c(r,n),ts(r,n),gc(r),Sc(r),vc(r),yc(r),bc(r),Ec(r),Cc(r),wc(r),Tc(r),En(r),is(r),Cn(r,n),wn(r);break;case"safari":if(!Lc||!e.shimSafari)return t("Safari shim is not included in this adapter release."),i;t("adapter.js shimming safari."),i.browserShim=Lc,Tn(r,n),kn(r),zc(r),Oc(r),Dc(r),Rc(r),Ac(r),Pc(r),xc(r),Mc(r),En(r),ns(r),Cn(r,n),wn(r),ss(r,n);break;default:t("Unsupported browser!");break}return i}Sg({window:typeof window>"u"?void 0:window});function bg(){const r={hardware_concurrency:navigator.hardwareConcurrency};navigator.deviceMemory&&(r.device_memory=navigator.deviceMemory+"GB");try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(t){const n=t.getExtension("WEBGL_debug_renderer_info");n&&(r.gpu_vendor=t.getParameter(n.UNMASKED_VENDOR_WEBGL),r.gpu_renderer=t.getParameter(n.UNMASKED_RENDERER_WEBGL)),r.webgl_version=t.getParameter(t.VERSION),r.webgl_shading_language_version=t.getParameter(t.SHADING_LANGUAGE_VERSION),r.webgl_vendor=t.getParameter(t.VENDOR),r.webgl_renderer=t.getParameter(t.RENDERER)}}catch{}return r}class Eg extends st{static async isSupported(e){if(e==="webTransport")return Promise.resolve(Ja.isSupported());try{return og()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await dg()&&await ug()}catch{return!1}}constructor(e){var t,n,i,s,a,o,d,c,u,h;if(super(),this._options=e??{},this._streamManagerController=new E_(this),this._streamComposeController=new z_(this._streamManagerController),this._streamConsumeController=new sg(this._streamComposeController,e),this._streamConsumeController.setPushConfig(e),this._observer=hg,this._bindEvent(),!(e!=null&&e.loggerConfig)||(t=e==null?void 0:e.loggerConfig)!=null&&t.enable){v_({showLogInConsole:((n=e==null?void 0:e.loggerConfig)==null?void 0:n.showInConsole)??!1});const l=m_((i=e==null?void 0:e.loggerConfig)==null?void 0:i.userId),f=__((s=e==null?void 0:e.loggerConfig)==null?void 0:s.deviceId);y_({user_unique_id:l,device_id:f,account_id:((a=e==null?void 0:e.loggerConfig)==null?void 0:a.accountId)??0,customer_app_name:((o=e==null?void 0:e.loggerConfig)==null?void 0:o.appName)??"unknown",customer_app_id:((d=e==null?void 0:e.loggerConfig)==null?void 0:d.appId)??0},{user_id:l,device_id:f,account_id:((c=e==null?void 0:e.loggerConfig)==null?void 0:c.accountId)??0,customer_app_name:((u=e==null?void 0:e.loggerConfig)==null?void 0:u.appName)??"unknown",customer_app_id:((h=e==null?void 0:e.loggerConfig)==null?void 0:h.appId)??0}),j(V.PUSHER_INIT,{options:e,...bg()}),S_()}}async getDevicesList(e){return this._streamManagerController.getDevicesList(e)}async getCameras(){return this._streamManagerController.getCameras()}async getMicrophones(){return this._streamManagerController.getMicrophones()}async startCamera(e){return this._streamManagerController.startCameraCapture(e)}stopCamera(e){this._streamManagerController.stopCapture({streamId:e,type:Q.Camera})}async startMicrophone(e){return await this._streamManagerController.startMicrophoneCapture(e)}stopMicrophone(e){this._streamManagerController.stopCapture({streamId:e,type:Q.Microphone})}async startVideoFileCapture(e){return e?await this._streamManagerController.startVideoFileCapture(e):void 0}stopVideoFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Q.VideoFile})}async startScreenCapture(e=!1){return await this._streamManagerController.startScreenCapture(e)}stopScreenCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Q.Screen})}async startAudioFileCapture(e){return e?await this._streamManagerController.startAudioFileCapture(e):void 0}stopAudioFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Q.AudioFile})}async startImageCapture(e){return e?await this._streamManagerController.startImageCapture(e):void 0}stopImageCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Q.Image})}startCustomVideoCapture(e){return e?this._streamManagerController.startCustomVideoCapture(e):void 0}stopCustomVideoCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Q.CustomVideo})}startCustomAudioCapture(e){return e?this._streamManagerController.startCustomAudioCapture(e):void 0}stopCustomAudioCapture(e){this._streamManagerController.stopCapture({streamId:e,type:Q.CustomAudio})}async startVolumeDetect(e){var t;e?await this._streamManagerController.startVolumeDetect(e):await((t=this._streamComposeController.getComposedStream().audioStream)==null?void 0:t.startVolumeDetect())}stopVolumeDetect(e){var t;e?this._streamManagerController.stopVolumeDetect(e):(t=this._streamComposeController.getComposedStream().audioStream)==null||t.stopVolumeDetect()}getVolume(e){var t;return e?this._streamManagerController.getVolume(e):((t=this._streamComposeController.getComposedStream().audioStream)==null?void 0:t.volume)??0}enableMixing(e){if(j(V.SWITCH_ENABLE_MIXING,{enable:e,is_pushing:this.isPushing()}),this.isPushing())throw new Error("can not change mixing while pushing");this._streamComposeController.enableMixing(e)}setMixingConfig(e){j(V.SET_MIXING_CONFIG,e),this._streamComposeController.setMixingConfig(e)}getMixingConfig(){return this._streamComposeController.getMixingConfig()}setRenderView(e){return this._streamConsumeController.setRenderView(e)}startPreview(){return this._streamConsumeController.startPreview()}stopPreview(){return this._streamConsumeController.stopPreview()}async startPush(e){try{await this._streamComposeController.resumeMixer()}catch(t){if(j(V.PUSH_AUDIO_CONTEXT_START_FAILED,{error:t}),this._options.checkAudio)throw new Bt(ke.AUDIO_RESUME_FAILED,(t==null?void 0:t.message)??"audio resume failed");console.warn("audioContext cannot resume automatically")}return this._streamConsumeController.startPush(e)}addVideoStream(e){j(V.ADD_VIDEO_STREAM,{number:ue(e)?e.length:1,config:e}),ue(e)?e.forEach(t=>{this._streamComposeController.addVideoStream(t)}):this._streamComposeController.addVideoStream(e)}removeVideoStream(e){j(V.DELETE_VIDEO_STREAM,{stream_id:e}),this._streamComposeController.removeVideoStream(e)}updateVideoStream(e){j(V.UPDATE_VIDEO_STREAM,{number:ue(e)?e.length:1,config:e}),ue(e)?this._streamComposeController.updateVideoStream(e):this._streamComposeController.updateVideoStream([e])}muteVideoStream(e){j(V.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.muteVideoStream(e)}unmuteVideoStream(e){j(V.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.unmuteVideoStream(e)}addAudioStream(e){j(V.ADD_AUDIO_STREAM,{number:ue(e)?e.length:1,config:e}),ue(e)?e.map(t=>this._streamComposeController.addAudioStream(t)):this._streamComposeController.addAudioStream(e)}removeAudioStream(e){j(V.DELETE_AUDIO_STREAM,{stream_id:e}),this._streamComposeController.removeAudioStream(e)}updateAudioStream(e){j(V.UPDATE_AUDIO_STREAM,{number:ue(e)?e.length:1,config:e}),ue(e)?this._streamComposeController.updateAudioStream(e):this._streamComposeController.updateAudioStream([e])}muteAudioStream(e){j(V.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.muteAudioStream(e)}unmuteAudioStream(e){j(V.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.unmuteAudioStream(e)}setProperty(e,t){switch(j(V.SET_PROPERTY_CALL,{key:e,value:t}),e){case"setVideoResolution":this._streamManagerController.setVideoResolution(t);break;case"setVideoFps":this._streamManagerController.setVideoFps(t);break;case"setAudioSampleRate":this._streamManagerController.setAudioSampleRate(t);break;case"setPushMode":this._streamConsumeController.setPushMode(t);break;case"setVideoBitrate":this._streamConsumeController.setBitrate(t,"video");break;case"setAudioBitrate":this._streamConsumeController.setBitrate(t,"audio");break;case"setVolumeDetectScriptUrl":Xr.instance.volumeDetectScriptUrl=t;break;case"setMixerWorkerScriptUrl":this._streamComposeController.setMixerWorkerScript(t);break;case"updatePushUrl":this._streamConsumeController.updatePushUrl(t);break;case"setVideoKBitrate":this._streamConsumeController.setBitrate(Number(t)*1e3,"video");break;case"setAudioKBitrate":this._streamConsumeController.setBitrate(Number(t)*1e3,"audio");break}}setVideoQuality(e){if(j(V.SET_VIDEO_QUALITY,{quality:e}),this._streamConsumeController.pushMode==="webTransport"&&["120p","180p","240p"].indexOf(e)!==-1)throw new Error("quality not allowed lower than 360p on rtmp mode");const{width:t,height:n,frameRate:i,bitrate:s}=Ft(e,"video");this._streamManagerController.setVideoResolution({width:t,height:n}),this._streamManagerController.setVideoFps(i),this._streamComposeController.setVideoQuality({width:t,height:n,frameRate:i}),this._streamConsumeController.setBitrate(s,"video")}setAudioQuality(e){j(V.SET_AUDIO_QUALITY,{quality:e});const{sampleRate:t,bitrate:n}=Ft(e,"audio");this._streamManagerController.setAudioSampleRate(t),this._streamConsumeController.setBitrate(n,"audio")}getMediaStream(e){return this._streamManagerController.getStreamById(e).mediaStream}getStream(e){return this._streamManagerController.getStreamById(e)}stopPush(){return this._streamConsumeController.stopPush()}isPushing(){return this._streamConsumeController.isPushing()}getStats(){return this._streamConsumeController.getStats()}getPreviewElement(){return this._streamConsumeController.getPreviewElement()}getVideoStreamRenderConfig(e){return this._streamComposeController.getVideoStreamRenderConfig(e)}_bindEvent(){this._streamManagerController.on(Be.Error,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(Be.Interrupted,e=>{this.observer.onCaptureInterrupted(e.id)}),this._streamConsumeController.on(se.PushStart,()=>{this.observer.onPushStart()}),this._streamConsumeController.on(se.PushStop,()=>{this.observer.onPushStop()}),this._streamConsumeController.on(se.RTCConnectStateChanged,e=>{this.observer.onPushStatusUpdate(hs[e],e)}),this._streamConsumeController.on(se.PushError,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(Be.DeviceStopCapture,e=>{this.observer.onStopCapture(e.id)}),this._streamConsumeController.on(se.CaptureFirstAudioFrame,()=>{this.observer.onCaptureFirstAudioFrame()}),this._streamConsumeController.on(se.CaptureFirstVideoFrame,()=>{this.observer.onCaptureFirstVideoFrame()}),this._streamConsumeController.on(se.ReconnectStateChange,(e,t)=>{this.observer.onReconnectStateChange(e,t)}),this._streamConsumeController.on(se.LiveConnectStateChange,e=>{this.observer.onLiveConnectStateChange(e)}),Ju(e=>{e.deviceInfo.kind==="videoinput"?this.observer.onCameraChanged(e.deviceInfo):e.deviceInfo.kind==="audioinput"&&this.observer.onMicrophoneChanged(e.deviceInfo)})}async destroy(){await this._streamConsumeController.destroy(),this._streamManagerController.destroy(),b_()}get observer(){return this._observer}get isEnableMixing(){return this._streamComposeController.isEnableMixing}get pushMode(){return this._streamConsumeController.pushMode}}return Eg});
|
|
116
|
+
`);r.RTCSessionDescription&&i instanceof r.RTCSessionDescription?arguments[0]=new r.RTCSessionDescription({type:i.type,sdp:o}):i.sdp=o}return t.apply(this,arguments)}}function ri(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;const t=r.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(r.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ni(r,e){if(!(r.RTCPeerConnection&&r.RTCPeerConnection.prototype))return;const t=r.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(r.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return t.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?t.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}const lS=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:ss,shimAddIceCandidateNullOrEmpty:ri,shimConnectionState:os,shimMaxMessageSize:ei,shimParameterlessSetLocalDescription:ni,shimRTCIceCandidate:Qn,shimRTCIceCandidateRelayProtocol:is,shimSendThrowTypeError:ti},Symbol.toStringTag,{value:"Module"}));function hS({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=Ou,n=aS(r),i={browserDetails:n,commonShim:lS,extractVersion:Yn,disableLog:oS,disableWarnings:sS,sdp:dS};switch(n.browser){case"chrome":if(!Ku||!ts||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),i;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),i;t("adapter.js shimming chrome."),i.browserShim=Ku,ri(r,n),ni(r),Nu(r,n),Bu(r),ts(r,n),Fu(r),$u(r,n),Vu(r),ju(r),qu(r,n),Qn(r),is(r),os(r),ei(r,n),ti(r),ss(r,n);break;case"firefox":if(!id||!rs||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),i;t("adapter.js shimming firefox."),i.browserShim=id,ri(r,n),ni(r),Wu(r,n),rs(r,n),Ju(r),Yu(r),Xu(r),Zu(r),Qu(r),ed(r),td(r),rd(r),nd(r),Qn(r),os(r),ei(r,n),ti(r);break;case"safari":if(!pd||!e.shimSafari)return t("Safari shim is not included in this adapter release."),i;t("adapter.js shimming safari."),i.browserShim=pd,ri(r,n),ni(r),dd(r),hd(r),ad(r),od(r),sd(r),ld(r),cd(r),fd(r),Qn(r),is(r),ei(r,n),ti(r),ss(r,n);break;default:t("Unsupported browser!");break}return i}hS({window:typeof window>"u"?void 0:window});function fS(){const r={hardware_concurrency:navigator.hardwareConcurrency};navigator.deviceMemory&&(r.device_memory=navigator.deviceMemory+"GB");try{const e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(t){const n=t.getExtension("WEBGL_debug_renderer_info");n&&(r.gpu_vendor=t.getParameter(n.UNMASKED_VENDOR_WEBGL),r.gpu_renderer=t.getParameter(n.UNMASKED_RENDERER_WEBGL)),r.webgl_version=t.getParameter(t.VERSION),r.webgl_shading_language_version=t.getParameter(t.SHADING_LANGUAGE_VERSION),r.webgl_vendor=t.getParameter(t.VENDOR),r.webgl_renderer=t.getParameter(t.RENDERER)}}catch{}return r}class pS extends xt{static async isSupported(e){if(e==="mediaEngine")return Du.isSupported();if(e==="webTransport")return Promise.resolve(Zc.isSupported());if(e==="rtm")return qn.isSupported()}constructor(e){var t,n,i,o,a,s,d,c,u,f;if(super(),this._options=e??{},this._streamManagerController=new tv(this),this._streamComposeController=new lv(this._streamManagerController),this._streamConsumeController=new rS(this._streamComposeController,e),this._streamConsumeController.setPushConfig(e),this._observer=iS,this._bindEvent(),!(e!=null&&e.loggerConfig)||(t=e==null?void 0:e.loggerConfig)!=null&&t.enable){Z_({showLogInConsole:((n=e==null?void 0:e.loggerConfig)==null?void 0:n.showInConsole)??!1});const h=W_((i=e==null?void 0:e.loggerConfig)==null?void 0:i.userId),g=J_((o=e==null?void 0:e.loggerConfig)==null?void 0:o.deviceId);Kt.instance.userId=h,Kt.instance.deviceId=g,Y_({user_unique_id:h,device_id:g,account_id:((a=e==null?void 0:e.loggerConfig)==null?void 0:a.accountId)??0,customer_app_name:((s=e==null?void 0:e.loggerConfig)==null?void 0:s.appName)??"unknown",customer_app_id:((d=e==null?void 0:e.loggerConfig)==null?void 0:d.appId)??0},{user_id:h,device_id:g,account_id:((c=e==null?void 0:e.loggerConfig)==null?void 0:c.accountId)??0,customer_app_name:((u=e==null?void 0:e.loggerConfig)==null?void 0:u.appName)??"unknown",customer_app_id:((f=e==null?void 0:e.loggerConfig)==null?void 0:f.appId)??0}),X(J.PUSHER_INIT,{options:e,...fS()}),Q_()}}async getDevicesList(e){return this._streamManagerController.getDevicesList(e)}async getCameras(){return this._streamManagerController.getCameras()}async getMicrophones(){return this._streamManagerController.getMicrophones()}async startCamera(e){return this._streamManagerController.startCameraCapture(e)}stopCamera(e){this._streamManagerController.stopCapture({streamId:e,type:ae.Camera})}async startMicrophone(e){return await this._streamManagerController.startMicrophoneCapture(e)}stopMicrophone(e){this._streamManagerController.stopCapture({streamId:e,type:ae.Microphone})}async startVideoFileCapture(e){return e?await this._streamManagerController.startVideoFileCapture(e):void 0}stopVideoFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:ae.VideoFile})}async startScreenCapture(e=!1){return await this._streamManagerController.startScreenCapture(e)}stopScreenCapture(e){this._streamManagerController.stopCapture({streamId:e,type:ae.Screen})}async startAudioFileCapture(e){return e?await this._streamManagerController.startAudioFileCapture(e):void 0}stopAudioFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:ae.AudioFile})}async startImageCapture(e){return e?await this._streamManagerController.startImageCapture(e):void 0}stopImageCapture(e){this._streamManagerController.stopCapture({streamId:e,type:ae.Image})}startCustomVideoCapture(e){return e?this._streamManagerController.startCustomVideoCapture(e):void 0}stopCustomVideoCapture(e){this._streamManagerController.stopCapture({streamId:e,type:ae.CustomVideo})}startCustomAudioCapture(e){return e?this._streamManagerController.startCustomAudioCapture(e):void 0}stopCustomAudioCapture(e){this._streamManagerController.stopCapture({streamId:e,type:ae.CustomAudio})}async startVolumeDetect(e){var t;e?await this._streamManagerController.startVolumeDetect(e):await((t=this._streamComposeController.getComposedStream().audioStream)==null?void 0:t.startVolumeDetect())}stopVolumeDetect(e){var t;e?this._streamManagerController.stopVolumeDetect(e):(t=this._streamComposeController.getComposedStream().audioStream)==null||t.stopVolumeDetect()}getVolume(e){var t;return e?this._streamManagerController.getVolume(e):((t=this._streamComposeController.getComposedStream().audioStream)==null?void 0:t.volume)??0}enableMixing(e){if(X(J.SWITCH_ENABLE_MIXING,{enable:e,is_pushing:this.isPushing()}),this.isPushing())throw new Error("can not change mixing while pushing");this._streamComposeController.enableMixing(e)}setMixingConfig(e){X(J.SET_MIXING_CONFIG,e),this._streamComposeController.setMixingConfig(e)}getMixingConfig(){return this._streamComposeController.getMixingConfig()}setRenderView(e){return this._streamConsumeController.setRenderView(e)}startPreview(){return this._streamConsumeController.startPreview()}stopPreview(){return this._streamConsumeController.stopPreview()}async startPush(e){try{await this._streamComposeController.resumeMixer()}catch(t){if(X(J.PUSH_AUDIO_CONTEXT_START_FAILED,{error:t}),this._options.checkAudio)throw new fr(qe.AUDIO_RESUME_FAILED,(t==null?void 0:t.message)??"audio resume failed");console.warn("audioContext cannot resume automatically")}return this._streamConsumeController.startPush(e)}addVideoStream(e){X(J.ADD_VIDEO_STREAM,{number:ze(e)?e.length:1,config:e}),ze(e)?e.forEach(t=>{this._streamComposeController.addVideoStream(t)}):this._streamComposeController.addVideoStream(e)}removeVideoStream(e){X(J.DELETE_VIDEO_STREAM,{stream_id:e}),this._streamComposeController.removeVideoStream(e)}updateVideoStream(e){X(J.UPDATE_VIDEO_STREAM,{number:ze(e)?e.length:1,config:e}),ze(e)?this._streamComposeController.updateVideoStream(e):this._streamComposeController.updateVideoStream([e])}muteVideoStream(e){X(J.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.muteVideoStream(e)}unmuteVideoStream(e){X(J.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.unmuteVideoStream(e)}addAudioStream(e){X(J.ADD_AUDIO_STREAM,{number:ze(e)?e.length:1,config:e}),ze(e)?e.map(t=>this._streamComposeController.addAudioStream(t)):this._streamComposeController.addAudioStream(e)}removeAudioStream(e){X(J.DELETE_AUDIO_STREAM,{stream_id:e}),this._streamComposeController.removeAudioStream(e)}updateAudioStream(e){X(J.UPDATE_AUDIO_STREAM,{number:ze(e)?e.length:1,config:e}),ze(e)?this._streamComposeController.updateAudioStream(e):this._streamComposeController.updateAudioStream([e])}muteAudioStream(e){X(J.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.muteAudioStream(e)}unmuteAudioStream(e){X(J.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.unmuteAudioStream(e)}setProperty(e,t){switch(X(J.SET_PROPERTY_CALL,{key:e,value:t}),e){case"setVideoResolution":this._streamManagerController.setVideoResolution(t);break;case"setVideoFps":this._streamManagerController.setVideoFps(t);break;case"setAudioSampleRate":this._streamManagerController.setAudioSampleRate(t);break;case"setPushMode":this._streamConsumeController.setPushMode(t);break;case"setVideoBitrate":this._streamConsumeController.setBitrate(t,"video");break;case"setAudioBitrate":this._streamConsumeController.setBitrate(t,"audio");break;case"setVolumeDetectScriptUrl":Kt.instance.volumeDetectScriptUrl=t;break;case"setMixerWorkerScriptUrl":this._streamComposeController.setMixerWorkerScript(t);break;case"updatePushUrl":this._streamConsumeController.updatePushUrl(t);break;case"setVideoKBitrate":this._streamConsumeController.setBitrate(Number(t)*1e3,"video");break;case"setAudioKBitrate":this._streamConsumeController.setBitrate(Number(t)*1e3,"audio");break}}setVideoQuality(e){if(X(J.SET_VIDEO_QUALITY,{quality:e}),this._streamConsumeController.pushMode==="webTransport"&&["120p","180p","240p"].indexOf(e)!==-1)throw new Error("quality not allowed lower than 360p on rtmp mode");const{width:t,height:n,frameRate:i,bitrate:o}=pr(e,"video");this._streamManagerController.setVideoResolution({width:t,height:n}),this._streamManagerController.setVideoFps(i),this._streamComposeController.setVideoQuality({width:t,height:n,frameRate:i}),this._streamConsumeController.setBitrate(o,"video")}setAudioQuality(e){X(J.SET_AUDIO_QUALITY,{quality:e});const{sampleRate:t,bitrate:n}=pr(e,"audio");this._streamManagerController.setAudioSampleRate(t),this._streamConsumeController.setBitrate(n,"audio")}getMediaStream(e){return this._streamManagerController.getStreamById(e).mediaStream}getStream(e){return this._streamManagerController.getStreamById(e)}stopPush(){return this._streamConsumeController.stopPush()}isPushing(){return this._streamConsumeController.isPushing()}getStats(){return this._streamConsumeController.getStats()}getPreviewElement(){return this._streamConsumeController.getPreviewElement()}getVideoStreamRenderConfig(e){return this._streamComposeController.getVideoStreamRenderConfig(e)}_bindEvent(){this._streamManagerController.on(dt.Error,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(dt.Interrupted,e=>{this.observer.onCaptureInterrupted(e.id)}),this._streamConsumeController.on(Ee.PushStart,()=>{this.observer.onPushStart()}),this._streamConsumeController.on(Ee.PushStop,()=>{this.observer.onPushStop()}),this._streamConsumeController.on(Ee.RTCConnectStateChanged,e=>{console.log("RTCConnectStateChanged",e),this.observer.onPushStatusUpdate(ps[e],e)}),this._streamConsumeController.on(Ee.PushError,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(dt.DeviceStopCapture,e=>{this.observer.onStopCapture(e.id)}),this._streamConsumeController.on(Ee.CaptureFirstAudioFrame,()=>{this.observer.onCaptureFirstAudioFrame()}),this._streamConsumeController.on(Ee.CaptureFirstVideoFrame,()=>{this.observer.onCaptureFirstVideoFrame()}),this._streamConsumeController.on(Ee.ReconnectStateChange,(e,t)=>{this.observer.onReconnectStateChange(e,t)}),this._streamConsumeController.on(Ee.LiveConnectStateChange,e=>{this.observer.onLiveConnectStateChange(e)}),zl(e=>{e.deviceInfo.kind==="videoinput"?this.observer.onCameraChanged(e.deviceInfo):e.deviceInfo.kind==="audioinput"&&this.observer.onMicrophoneChanged(e.deviceInfo)})}async destroy(){await this._streamConsumeController.destroy(),this._streamManagerController.destroy(),ev()}get observer(){return this._observer}get isEnableMixing(){return this._streamComposeController.isEnableMixing}get pushMode(){return this._streamConsumeController.pushMode}}return pS});
|