@volcengine/vepusher 2.0.4-rc.2 → 2.0.4-rc.4
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 +343 -7
- package/dist/index.es.js +7697 -2582
- package/dist/index.umd.js +35 -25
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function($,D){typeof exports=="object"&&typeof module<"u"?module.exports=D():typeof define=="function"&&define.amd?define(D):($=typeof globalThis<"u"?globalThis:$||self,$["ve-pusher"]=D())})(this,function(){"use strict";var lh=Object.defineProperty;var mh=($,D,Z)=>D in $?lh($,D,{enumerable:!0,configurable:!0,writable:!0,value:Z}):$[D]=Z;var m=($,D,Z)=>mh($,typeof D!="symbol"?D+"":D,Z);var bs,ks,Ps,xs,Rs,As;function $(r,e){for(var t=0;t<e.length;t++){const i=e[t];if(typeof i!="string"&&!Array.isArray(i)){for(const s in i)if(s!=="default"&&!(s in r)){const n=Object.getOwnPropertyDescriptor(i,s);n&&Object.defineProperty(r,s,n.get?n:{enumerable:!0,get:()=>i[s]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}function D(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Z={exports:{}},tr;function tn(){return tr||(tr=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(u,d,c){this.fn=u,this.context=d,this.once=c||!1}function n(u,d,c,h,p){if(typeof c!="function")throw new TypeError("The listener must be a function");var l=new s(c,h||u,p),f=t?t+d:d;return u._events[f]?u._events[f].fn?u._events[f]=[u._events[f],l]:u._events[f].push(l):(u._events[f]=l,u._eventsCount++),u}function a(u,d){--u._eventsCount===0?u._events=new i:delete u._events[d]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],c,h;if(this._eventsCount===0)return d;for(h in c=this._events)e.call(c,h)&&d.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(c)):d},o.prototype.listeners=function(d){var c=t?t+d:d,h=this._events[c];if(!h)return[];if(h.fn)return[h.fn];for(var p=0,l=h.length,f=new Array(l);p<l;p++)f[p]=h[p].fn;return f},o.prototype.listenerCount=function(d){var c=t?t+d:d,h=this._events[c];return h?h.fn?1:h.length:0},o.prototype.emit=function(d,c,h,p,l,f){var g=t?t+d:d;if(!this._events[g])return!1;var _=this._events[g],T=arguments.length,b,v;if(_.fn){switch(_.once&&this.removeListener(d,_.fn,void 0,!0),T){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,c),!0;case 3:return _.fn.call(_.context,c,h),!0;case 4:return _.fn.call(_.context,c,h,p),!0;case 5:return _.fn.call(_.context,c,h,p,l),!0;case 6:return _.fn.call(_.context,c,h,p,l,f),!0}for(v=1,b=new Array(T-1);v<T;v++)b[v-1]=arguments[v];_.fn.apply(_.context,b)}else{var j=_.length,R;for(v=0;v<j;v++)switch(_[v].once&&this.removeListener(d,_[v].fn,void 0,!0),T){case 1:_[v].fn.call(_[v].context);break;case 2:_[v].fn.call(_[v].context,c);break;case 3:_[v].fn.call(_[v].context,c,h);break;case 4:_[v].fn.call(_[v].context,c,h,p);break;default:if(!b)for(R=1,b=new Array(T-1);R<T;R++)b[R-1]=arguments[R];_[v].fn.apply(_[v].context,b)}}return!0},o.prototype.on=function(d,c,h){return n(this,d,c,h,!1)},o.prototype.once=function(d,c,h){return n(this,d,c,h,!0)},o.prototype.removeListener=function(d,c,h,p){var l=t?t+d:d;if(!this._events[l])return this;if(!c)return a(this,l),this;var f=this._events[l];if(f.fn)f.fn===c&&(!p||f.once)&&(!h||f.context===h)&&a(this,l);else{for(var g=0,_=[],T=f.length;g<T;g++)(f[g].fn!==c||p&&!f[g].once||h&&f[g].context!==h)&&_.push(f[g]);_.length?this._events[l]=_.length===1?_[0]:_:a(this,l)}return this},o.prototype.removeAllListeners=function(d){var c;return d?(c=t?t+d:d,this._events[c]&&a(this,c)):(this._events=new i,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}(Z)),Z.exports}var rn=tn();const Q=D(rn);var rr=(r=>(r.LeftToRight="LeftToRight",r.UpToDown="UpToDown",r.All="All",r.None="None",r))(rr||{}),S=(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))(S||{}),z=(r=>(r.DeviceCaptured="deviceCaptured",r.DeviceStopCapture="deviceStopCapture",r.Error="error",r.Interrupted="interrupted",r))(z||{}),A=(r=>(r.PushStart="pushStart",r.PushStop="pushStop",r.PushError="pushError",r.RTCConnectStateChanged="rtcConnectStateChanged",r.CaptureFirstVideoFrame="capturefirstvideoframe",r.CaptureFirstAudioFrame="capturefirstaudioframe",r.NotAllowedAutoPlay="notallowedautoplay",r))(A||{}),ir=(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))(ir||{}),sr=(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))(sr||{}),nr=(r=>(r.STANDARD="48000x40",r.HIGH="48000x128",r))(nr||{}),ne=(r=>(r.VideoStreamChange="videoStreamChange",r.AudioStreamChange="audioStreamChange",r))(ne||{}),or=(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))(or||{}),it=(r=>(r.SizeChange="sizeChange",r))(it||{}),st=(r=>(r.Portrait="portrait",r.Landscape="landscape",r))(st||{});const ar="720p-1",cr="STANDARD";var y=(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))(y||{}),E=(r=>(r.AUDIO="audio",r.VIDEO="video",r))(E||{}),I=(r=>(r.ENDED="ended",r.MUTE="mute",r.UNMUTE="unmute",r.PLAY_FAILED="play-failed",r.SIZE_CHANGE="size-change",r))(I||{});const O=[];for(let r=0;r<256;++r)O.push((r+256).toString(16).slice(1));function sn(r,e=0){return(O[r[e+0]]+O[r[e+1]]+O[r[e+2]]+O[r[e+3]]+"-"+O[r[e+4]]+O[r[e+5]]+"-"+O[r[e+6]]+O[r[e+7]]+"-"+O[r[e+8]]+O[r[e+9]]+"-"+O[r[e+10]]+O[r[e+11]]+O[r[e+12]]+O[r[e+13]]+O[r[e+14]]+O[r[e+15]]).toLowerCase()}let nt;const nn=new Uint8Array(16);function on(){if(!nt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");nt=crypto.getRandomValues.bind(crypto)}return nt(nn)}const dr={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function oe(r,e,t){var s;if(dr.randomUUID&&!r)return dr.randomUUID();r=r||{};const i=r.random??((s=r.rng)==null?void 0:s.call(r))??on();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=i[6]&15|64,i[8]=i[8]&63|128,sn(i)}class ur{constructor(){m(this,"id",oe());m(this,"_nextNode");m(this,"_track");m(this,"_destNode")}gain(e){if(this._nextNode instanceof hr)return this._nextNode.g=e,this._nextNode;const t=new hr(this,{g:e});return this._nextNode=t,t}connect(e,t){if(!this.available())return;let{_node:i}=this;i||(i=this.createNode(e)),this._node=i,this.previousNode&&this.previousNode.connect(e,i),t&&i.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 hr extends ur{constructor(t,i){super();m(this,"previousNode");m(this,"_node");m(this,"_g");this.previousNode=t,this._g=i.g}createNode(t){return new GainNode(t,{gain:this._g})}set g(t){this._g=t,this._node&&(this._node.gain.value=t)}}class an extends ur{constructor(t){super();m(this,"previousNode",null);m(this,"source");this.source=t}available(){return this.source.available()}destroy(){super.destroy()}}class cn extends an{constructor(){super(...arguments);m(this,"_node")}createNode(t){if(this._node)return this._node;let i;if(this.source instanceof yr){const s=this.source.element();i=new MediaElementAudioSourceNode(t,{mediaElement:s}),s.muted=!1}else{const s=this.source.track();i=new MediaStreamAudioSourceNode(t,{mediaStream:new MediaStream([s])})}return i}}class C extends Error{constructor(t,i,s){super(i);m(this,"code");m(this,"message");m(this,"error");this.code=t,this.message=i,this.error=s,Object.setPrototypeOf(this,C.prototype)}toString(){return`VeCapture Error: ${this.code} ${this.message}`}}const pr={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"}},lr="__debug__",dn="[VE-CAPTURE]";function un(){if(typeof location>"u"||typeof localStorage>"u")return!1;let r=!1;return location.href.includes(lr)&&(r=!0),localStorage.getItem(lr)&&(r=!0),r}let L=class{constructor(e){m(this,"moduleName");this.moduleName=e}print(e,t,...i){const s=hn();un()&&console.log(`${s}-${dn}%c[${pr[e].text}]%c[${this.moduleName}][${t}]`,`background-color:${pr[e].color};`,"background-color:rgba(0, 0, 0, 0)",...i)}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 i=this;return function(...n){i.info(`${t}-invoke`,...n);try{const a=e(...n);return typeof(a==null?void 0:a.then)=="function"?a.then(o=>(i.success(`${t}-result`,o),o)).catch(o=>{throw i.error(`${t}-result`,o),o}):(i.success(`${t}-result`,a),a)}catch(a){i.error(`[${t}-result`,a)}}}};function hn(){const r=new Date;return`${r.toTimeString().split(" ")[0]}:${r.getMilliseconds().toString().padStart(3,"0")}`}function ot(r,e){const t=document.createElement(r);return e.id&&(t.id=e.id),e.classList&&e.classList.forEach(i=>{t.classList.add(i)}),e.style&&Object.assign(t.style,e.style),e.attributes&&Object.entries(e.attributes).forEach(([i,s])=>{i==="muted"&&(t instanceof HTMLVideoElement||t instanceof HTMLAudioElement)?t.muted=!0:t.setAttribute(i,s)}),t}function mr({width:r,height:e}){const t=document.createElement("canvas"),i=t.getContext("2d");if(!i)throw new C(y.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:i,canvas:t}}class at{constructor(e){m(this,"target");m(this,"_eventDict",new Map);this.target=e}on(e,t){let i=this._eventDict.get(e);i||(i=[t]),this._eventDict.set(e,i),this.target.addEventListener(e,t)}off(e,t){let i=this._eventDict.get(e);i&&(i=i.filter(s=>s!==t),this._eventDict.set(e,i),this.target.removeEventListener(e,t))}once(e,t){const i=s=>{t(s),this.off(e,i)};this.on(e,i)}clear(e){const t=this._eventDict.get(e);t&&t.forEach(i=>{this.target.removeEventListener(e,i)})}clearAll(){for(const e of this._eventDict.keys())this.clear(e)}}const x=()=>typeof window>"u";function P(){return navigator.userAgent.toLowerCase()}function ct(r=P()){let e="none";return x()||(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 fr=ct()==="firefox",Le=ct()==="safari";ct(),!x()&&/crios/i.test(P()),!x()&&/edg\//i.test(P()),!x()&&/edgA/i.test(P()),!x()&&/edgios/i.test(P()),!x()&&/dingtalk/i.test(P()),!x()&&/opr\//.test(P()),!x()&&/(iphone|ipod)/i.exec(P()),!x()&&(/(ipad)/i.exec(P())||/macintosh/i.test(P())&&"ontouchend"in document),!x()&&/macintosh/i.test(P()),!x()&&/micromessenger/i.test(P()),!x()&&P().includes("mobile"),!x()&&/sm-\w+/i.test(P());const pn=!x()&&!!/(iphone|ipad|ipod)/i.exec(P());!x()&&/android/i.test(P()),!x()&&/windows/i.test(P()),!x()&&/openharmony/i.test(P());let _r="0";const ln=!x()&&((bs=P().match(/version\/(\d+)/i))==null?void 0:bs[1]);Le&&ln&&(_r=(ks=navigator.userAgent.match(/version\/(\d+\.\d+)/i))==null?void 0:ks[1]),!x()&&((Ps=P().match(/firefox\/(\d+)/i))==null||Ps[1]);const dt=_r;!x()&&((Rs=(xs=P().match(/ ([\d_]+) like mac os x/i))==null?void 0:xs[1])==null||Rs.split("_").map(r=>parseInt(r))),!x()&&((As=P().match(/chrome\/(\d+)/i))==null||As[1]);function mn(){var r;return!!((r=navigator==null?void 0:navigator.permissions)!=null&&r.query)}function ut(){return!!(navigator!=null&&navigator.mediaDevices)}function fn(){var r;return ut()&&!!((r=navigator==null?void 0:navigator.mediaDevices)!=null&&r.getUserMedia)}function _n(){return!!Promise.withResolvers}function gn(){return!(Le&&dt==="16.1")}function vn(){return!(Le&&dt&&["16.1","16.2","16.3"].includes(dt))}function Cn(){return!fr}function yn(){return typeof CanvasCaptureMediaStreamTrack<"u"}function Sn(r){return typeof r.requestFrame=="function"}function Tn(){return!!ut()&&typeof navigator.mediaDevices.ondevicechange<"u"&&typeof navigator.mediaDevices.addEventListener=="function"}const q={permissionQuery:mn,mediaDevices:ut,settingResolutionInGetDisplayMedia:gn,promiseWithResolvers:_n,getUserMedia:fn,isolateEnumerateDevices:Cn,supportIdealParamsInGetDisplayMedia:vn,canvasCaptureMediaStreamTrack:yn,requestFrameOnMediaStream:Sn,ondevicechange:Tn};function En(){if(q.promiseWithResolvers())return Promise.withResolvers();let r,e;const t=new Promise((i,s)=>{r=i,e=s});if(!r||!e)throw Error("resolver and rejector working unexpected");return{promise:t,resolve:r,reject:e}}function gr(r={}){const{timeout:e,message:t}={timeout:0,message:new C(y.UNEXPECTED_ERROR,"unexpected timeout"),...r},{promise:i,resolve:s,reject:n}=En();if(e<=0)return{promise:i,resolve:s,reject:n};const a=setTimeout(()=>{n(t)},e);return{promise:i,resolve:u=>{clearTimeout(a),s(u)},reject:n}}const bn={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"metadata",muted:"",crossOrigin:"anonymous"},kn={playsinline:"","webkit-playsinline":"",preload:"metadata",muted:"",crossOrigin:"anonymous"};class Ee{constructor(e,t=[]){m(this,"id",oe());m(this,"_referenceTracks",[]);m(this,"_element");m(this,"_volumeMode",0);m(this,"_readyLock");m(this,"_releaseReadyLock");m(this,"_throwReadyLock");m(this,"_stream");let i;if(e instanceof MediaStreamTrack){const o=new MediaStream([e]);i=Pn(o),this._stream=o}else if(e.url)i=xn(e);else throw new C(y.UNEXPECTED_TYPE,`got ${typeof e}, expected: MediaStreamTrack or constraints for creating element`);const{promise:s,resolve:n,reject:a}=gr({timeout:2e3,message:new C(y.PLAY_FAILED,"load media timeout")});this._readyLock=s,this._releaseReadyLock=n,this._throwReadyLock=a,this._element=new at(i),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===E.AUDIO){this._upgradeVolumeMode(1e-4);const i=t.getAudioTracks();if(i.length<1)throw new C(y.UNEXPECTED_TYPE,"got empty list of audio tracks");return i[0]}if(e===E.VIDEO){const i=t.getVideoTracks();if(i.length<1)throw new C(y.UNEXPECTED_TYPE,"got empty list of video tracks");return i[0]}throw new C(y.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 C(y.PLAY_FAILED,"play element failed",e)}}_bindPlayerEvent(e){e.on("loadedmetadata",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new C(y.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 Pn(r){let e="audio";r.getVideoTracks().length>0&&(e="video");const t=vr(e==="video"?E.VIDEO:E.AUDIO);return t.srcObject=r,t}function xn(r){const{url:e,kind:t,loop:i}=r,s=vr(t);return s.src=e,s.loop=i,s}function vr(r){if(r===E.VIDEO)return ot(E.VIDEO,{style:{width:"100%",height:"100%"},attributes:bn});if(r===E.AUDIO)return ot(E.AUDIO,{style:{display:"none"},attributes:kn});throw new C(y.UNEXPECTED_TYPE,`got ${r}, expected: audio, video`)}class ht extends Q{emit(e,...t){const i=this.listenerCount(e);return Promise.resolve().then(()=>{super.emit(e,...t)}),!!i}on(e,t,i){const s=(...n)=>{try{return t(...n)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.on(e,s,i)}once(e,t,i){const s=(...n)=>{try{return t(...n)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.once(e,s,i)}}function pt(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 C(y.UNEXPECTED_TYPE,"unexpected constraints type")}const lt=1e3;class Cr{constructor(e){m(this,"id",oe());m(this,"_context");m(this,"_canvas");m(this,"_image");m(this,"_config");m(this,"_readyLock");m(this,"_releaseReadyLock");m(this,"_throwReadyLock");m(this,"_loopTimer");m(this,"_referenceTracks",[]);m(this,"_stream");const t=pt(e.width),i=pt(e.height),s=pt(e.frameRate);this._config={width:t,height:i,frameRate:s};const{context:n,canvas:a}=mr({width:t,height:i});this._context=n,this._canvas=a;const o=Rn({url:e.url,width:t,height:i});this._image=new at(o);const{promise:u,resolve:d,reject:c}=gr({timeout:2e3,message:new C(y.PLAY_FAILED,"load image timeout")});this._readyLock=u,this._releaseReadyLock=d,this._throwReadyLock=c,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 i=t.getVideoTracks();if(i.length<1)throw new C(y.UNEXPECTED_TYPE,"got empty list of video tracks");return i[0]}element(){return this._image.target}isReady(){return this._readyLock}_bindImageEvent(e){e.on("load",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new C(y.PLAY_FAILED,"HTMLMediaElement got error when loading file"))})}async _paint(){const{width:e,height:t,frameRate:i}=this._config;this._context.drawImage(this._image.target,0,0,e,t),this._loopTimer&&clearTimeout(this._loopTimer),this._loopTimer=setTimeout(this._paint.bind(this),lt/i)}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 Rn({url:r,height:e,width:t}){const i=ot("img",{style:{width:`${t}px`,height:`${e}px`},attributes:{crossOrigin:"anonymous"}});return i.src=r,i}class mt extends ht{constructor(t){super();m(this,"id",oe());m(this,"_track");m(this,"_element");t instanceof MediaStreamTrack?(this._track=new at(t),this._bindTrackEvent(this._track)):t instanceof Ee?(this._element=t,t.addReferenceTrack(this)):t instanceof Cr&&(this._element=t)}_bindTrackEvent(t){t.on("ended",this._handleTrackEnded.bind(this)),t.on("mute",()=>{this.emit(I.MUTE)}),t.on("unmute",()=>{this.emit(I.UNMUTE)})}_handleTrackEnded(){this.emit(I.ENDED),this.destroy()}handlePlayFailed(){this.emit(I.PLAY_FAILED)}track(){if(this.logger.info("track"),!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not available when creating MediaStreamTrack");if(this._track)return this._track.target;if(!this._element)throw new C(y.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 C(y.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element)return this._element.element();if(!this._track)throw new C(y.UNEXPECTED_TYPE,"got this._track falsy");const t=new Ee(this._track.target,[this]);this._element=t;const i=t.element();return this.logger.success("element",i),i}available(){return!!(this._track||this._element)}destroy(){var t,i,s;(t=this._track)==null||t.clearAll(),(i=this._track)==null||i.target.stop(),this._track&&delete this._track,(s=this._element)==null||s.removeReference(this),delete this._element}}class Fe extends mt{constructor(){super(...arguments);m(this,"kind",E.AUDIO);m(this,"_node")}node(){if(this.logger.info("node",this.id),!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");if(this._node)return this._node;const t=new cn(this);return this._node=t,t}element(){if(this.logger.info("element",this.id),!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element){const i=this._element.element(!0);if(!(i instanceof HTMLMediaElement))throw new C(y.UNEXPECTED_TYPE,"source should be HTMLMediaElement");return i}if(!this._track)throw new C(y.UNEXPECTED_TYPE,"got this._track falsy");const t=new Ee(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 An extends Fe{constructor(){super(...arguments);m(this,"logger",new L("MicrophoneAudioTrack"))}}class wn extends Fe{constructor(){super(...arguments);m(this,"logger",new L("ScreenAudioTrack"))}}class yr extends Fe{constructor(){super(...arguments);m(this,"logger",new L("MediaAudioTrack"))}handlePlayFailed(){this.emit(I.PLAY_FAILED)}async play(){if(this._element){if(!(this._element instanceof Ee))throw new C(y.UNEXPECTED_TYPE,"element is not TrackMediaElement");return this._element._playElement()}}}class On extends Fe{constructor(){super(...arguments);m(this,"logger",new L("CustomAudioTrack"))}}let Dn=1;const ft=new L("PromiseQueue");class In{constructor(e){m(this,"lockingPromise",Promise.resolve());m(this,"locks",0);m(this,"name","");m(this,"lockId");m(this,"closeReason");this.lockId=Dn++,e&&(this.name=e),ft.info(`lock-${this.name}-${this.lockId}`,"is created.")}get isLocked(){return this.locks>0}lock(){this.locks+=1,ft.info(`lock-${this.name}-${this.lockId}`,`locked, current queue ${this.locks}.`);let e;const t=new Promise(s=>{e=()=>{this.locks-=1,ft.info(`lock-${this.name}-${this.lockId}`,`unlocked, current queue ${this.locks}.`),s()}}),i=this.lockingPromise.then(()=>e);return this.lockingPromise=this.lockingPromise.then(()=>t),i}}const Mn=300,Ln=3e3,G=new L("Devices");class Fn extends ht{constructor(){super();m(this,"_deviceMap",{audioinput:[],audiooutput:[],videoinput:[]});m(this,"_permissions",{[E.AUDIO]:!1,[E.VIDEO]:!1});m(this,"_changedQueue",new In("device changed queue"));this._init()}async _init(){this._initDeviceChanged(),await this._initPermissionChanged();const t=br(this._permissions);t.length>0&&this._refreshDevices(t)}_initDeviceChanged(){if(G.info("_initDeviceChanged","invoked"),!q.ondevicechange()){G.error("_initDeviceChanged","no supported, use timer instead"),setInterval(()=>{this._handleDeviceChanged()},Ln);return}q.ondevicechange()&&navigator.mediaDevices.addEventListener("devicechange",()=>{G.info("devicechange"),setTimeout(()=>{this._handleDeviceChanged()},Mn)})}async _initPermissionChanged(){if(!q.permissionQuery()){G.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",()=>{G.info("_initPermissionChanged","update permission for audio"),this._permissions.audio=t.state==="granted"})}catch(t){G.error("_initPermissionChanged",t)}try{const t=await navigator.permissions.query({name:"camera"});this._permissions.video=t.state==="granted",t.addEventListener("change",()=>{G.info("_initPermissionChanged","update permission for video"),this._permissions.video=t.state==="granted"})}catch(t){G.error("_initPermissionChanged",t)}}async _refreshDevices(t){if(!q.mediaDevices())throw new C(y.NOT_SUPPORTED,"mediaDevices is not supported");if(t.length===0)throw new C(y.UNEXPECTED_TYPE,"kinds expect to containt values");let i;if(!q.isolateEnumerateDevices()){const a={};t.forEach(o=>{a[o]=!0}),i=await navigator.mediaDevices.getUserMedia(a)}let s=await navigator.mediaDevices.enumerateDevices();i&&Sr(i),s=s.filter(({deviceId:a})=>!!a);const n={audioinput:[],audiooutput:[],videoinput:[]};s.forEach(a=>{const{kind:o}=a;n[o].push(a)}),this._deviceMap=n}async _acquireUserPermission(t){let i=!1;if(t.forEach(s=>{i=i||!this._permissions[s]}),!i)return{grant:!0};if(!q.getUserMedia())return{grant:!1,reason:new C(y.NOT_SUPPORTED,"getUserMedia is not supported")};try{const s={};t.forEach(a=>{s[a]=!0});const n=await navigator.mediaDevices.getUserMedia(s);return n?(s.audio&&(this._permissions[E.AUDIO]=!0),s.video&&(this._permissions[E.VIDEO]=!0),Sr(n),{grant:!0}):{grant:!1,reason:new C(y.UNEXPECTED_TYPE,"get stream falsy")}}catch(s){return{grant:!1,reason:new C(y.CAPTURE_FAILED,"acquire user permission failed",s)}}}async _handleDeviceChanged(){G.info("_handleDeviceChanged",this._deviceMap,this._permissions);const t=await this._changedQueue.lock();try{const i=Er(this._deviceMap);let s=[];const n=br(this._permissions);n.length===0?G.warn("_handleDeviceChanged","no permission, use empty list"):(await this._refreshDevices(n),s=Er(this._deviceMap)),s.forEach(a=>{i.findIndex(u=>Tr(u,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"active"})}),i.forEach(a=>{s.findIndex(u=>Tr(u,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"inactive"})})}finally{t()}}async enumerateDevices(t){const i=[];t.forEach(o=>{if(o==="audioinput"||o==="audiooutput")i.push(E.AUDIO);else if(o==="videoinput")i.push(E.VIDEO);else throw new C(y.UNEXPECTED_TYPE,"kind in kinds should be enum MediaDeviceKind")});const{grant:s,reason:n}=await this._acquireUserPermission(i);if(!s)throw n;await this._refreshDevices(i);const a=[];return t.forEach(o=>{a.push(...this._deviceMap[o])}),a}async enableDevices(t){return this._acquireUserPermission(t)}}function Sr(r){r.getTracks().forEach(e=>e.stop())}function Tr(r,e){return r.deviceId===e.deviceId}function Er(r){return Array.from([...r.audioinput.values(),...r.videoinput.values(),...r.audiooutput.values()])}function br(r){const e=[];return r.audio&&e.push(E.AUDIO),r.video&&e.push(E.VIDEO),e}const _t=new Fn,gt={LeftToRight:"LeftToRight",UpToDown:"UpToDown",All:"All"};class vt{constructor(){m(this,"id",oe())}position(e,t){return new Nn(this,{x:e,y:t})}scale(e){return new kr(this,{s:e})}mirror(e){return new kr(this,{mirrorType:e})}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}}class Nn extends vt{constructor(t,i){super();m(this,"previousNode");m(this,"_x");m(this,"_y");this.previousNode=t,this._x=i.x,this._y=i.y}paint(t){t.translate(this._x,this._y)}}class kr extends vt{constructor(t,i){super();m(this,"previousNode");m(this,"_scaleParams",[1,1]);if(this.previousNode=t,i.mirrorType)switch(i.mirrorType){case gt.LeftToRight:this._scaleParams=[-1,1];break;case gt.UpToDown:this._scaleParams=[1,-1];break;case gt.All:this._scaleParams=[-1,-1];break;default:this._scaleParams=[1,1];break}else i.s&&(this._scaleParams=[i.s,i.s])}paint(t){t.scale(this._scaleParams[0],this._scaleParams[1])}}class Vn extends vt{constructor(t){super();m(this,"previousNode",null);m(this,"_source");this._source=t}available(){return this._source.available()}}class Ne extends Vn{constructor(t,i){super(t);m(this,"_targetWidth");m(this,"_targetHeight");const{width:s,height:n}=i??{};this._targetWidth=s??this._source.width(),this._targetHeight=n??this._source.height()}size(t,i){return new Ne(this._source,{width:t,height:i})}paint(t){const i=this._targetWidth,s=this._targetHeight;t.drawImage(this._source.element(),-i/2,-s/2,i,s)}}class Un extends mt{constructor(){super(...arguments);m(this,"logger",new L("PictureTrack"));m(this,"kind",E.VIDEO)}element(){const t=super.element();if(!(t instanceof HTMLImageElement))throw new C(y.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 C(y.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");const t=new Ne(this);return this.logger.info("node",t),t}destroy(){this.logger.warn("destroy"),super.destroy()}}const $n=500;class Ve extends mt{constructor(){super(...arguments);m(this,"kind",E.VIDEO);m(this,"sizeChangeTimer");m(this,"watchSizeChangeOnce",()=>{const t=this.width(),i=this.height();this.sizeChangeTimer=setTimeout(()=>{const s=this.width(),n=this.height();(i!==n||t!==s)&&this.emit(I.SIZE_CHANGE,{width:s,height:n})},$n)})}element(){const t=super.element();if(!(t instanceof HTMLVideoElement))throw new C(y.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return t}node(){if(!this.available())throw new C(y.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");return new Ne(this)}destroy(){clearTimeout(this.sizeChangeTimer),super.destroy()}}class Bn extends Ve{constructor(t){super(t);m(this,"logger",new L("CameraVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class jn extends Ve{constructor(t){super(t);m(this,"logger",new L("ScreenVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class zn extends Ve{constructor(){super(...arguments);m(this,"logger",new L("MediaVideoTrack"))}height(){const{videoHeight:t}=this.element();return t??0}width(){const{videoWidth:t}=this.element();return t??0}}class Gn extends Ve{constructor(){super(...arguments);m(this,"logger",new L("CustomVideoTrack"))}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}function Pr(r,e){let t;if(e!=null&&e.frameRate&&typeof e.frameRate=="number"&&(t=e.frameRate),t)try{r.applyConstraints({...e,frameRate:{min:t,ideal:t}})}catch{}}const W=new L("Capture");async function Hn(r){return _t.enumerateDevices(r)}async function qn(r){_t.removeAllListeners("onDeviceStateChanged"),_t.on("onDeviceStateChanged",r)}async function Wn(r){let e;try{const i={video:r??!0};typeof i.video=="object"&&i.video.facingMode&&delete i.video.deviceId,e=await navigator.mediaDevices.getUserMedia(i)}catch(i){throw new C(y.CAPTURE_FAILED,"got error when capturing camera",i)}const t=e.getVideoTracks()[0];if(r!=null&&r.frameRate&&Pr(t,r),!t)throw new C(y.UNEXPECTED_TYPE,"got falsy in track");return new Bn(t)}async function Xn(r,e){const{video:t,audio:i}=r;let s=t===!0?{}:t;e!=null&&e.displaySurface&&(s.displaySurface=e.displaySurface,delete e.displaySurface),q.settingResolutionInGetDisplayMedia()||(s=!0),!q.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 n;try{n=await navigator.mediaDevices.getDisplayMedia({video:s,audio:i,...e})}catch(d){throw new C(y.CAPTURE_FAILED,"got error when capture screen",d)}const a=n.getVideoTracks()[0],o=n.getAudioTracks()[0];if(!a)throw new C(y.UNEXPECTED_TYPE,"got falsy in videoTrack");typeof s!="boolean"&&typeof s.frameRate=="number"&&Pr(a,s);const u=[];return u.push(new jn(a)),o&&u.push(new wn(o)),u}async function Kn(r){const{url:e,audio:t,video:i,loop:s}=r,n=new Ee({url:e,kind:i?E.VIDEO:E.AUDIO,loop:s}),a=[];return t&&a.push(new yr(n)),i&&a.push(new zn(n)),await n.isReady(),a}async function Jn(r){const e=new Cr(r);return await e.isReady(),new Un(e)}async function Yn(r){let e;try{const i={audio:r??!0};e=await navigator.mediaDevices.getUserMedia(i)}catch(i){throw new C(y.CAPTURE_FAILED,"got error when capturing microphone",i)}const t=e.getAudioTracks()[0];if(!t)throw new C(y.UNEXPECTED_TYPE,"got falsy in track");return new An(t)}function Zn(r){if(!r||r.kind!=="video")throw new C(y.UNEXPECTED_TYPE,"error custom video track type");return new Gn(r)}function Qn(r){if(!r||r.kind!=="audio")throw new C(y.UNEXPECTED_TYPE,"error custom audio track type");return new On(r)}const eo=W.invoke(Hn,"enumerateInputDevices"),to=W.invoke(Wn,"createCameraTrack"),ro=W.invoke(Jn,"createPictureTrack"),xr=W.invoke(Kn,"createMediaTracks"),io=W.invoke(Yn,"createMicrophoneTrack"),so=W.invoke(Xn,"createScreenTracks"),no=W.invoke(qn,"onDeviceChanged"),oo=W.invoke(Zn,"createCustomVideoTrack"),ao=W.invoke(Qn,"createCustomAudioTrack");var Ct=(r=>(r.PAUSING="pausing",r))(Ct||{});const co={sampleRate:48e3,keepAlive:!0},Rr=new Map,be=new L("Mixer");class uo extends ht{constructor(t){super();m(this,"id",oe());m(this,"_context");m(this,"_config");m(this,"_nodeList",[]);m(this,"_destNode");m(this,"_bufferNode");m(this,"_track");be.info("ctor",t),this._config={...co,...t},this._context=ho(this._config),this._bindContextEvent(this._context)}mix(t){be.info("mix",t),yt(this._context);for(const i of this._nodeList)t.includes(i)||i.destroy();this._nodeList=t,this._connect(t,this._destNode),this._nodeList.length===0&&this._appendSlience(this._context,this._destNode)}resume(){return be.info("resume"),this._context.resume()}_connect(t,i){for(const s of t)s.connect(this._context,i)}_appendSlience(t,i){if(!i||this._bufferNode)return;const{sampleRate:s}=t,n=new AudioBuffer({length:100,sampleRate:s}),a=new AudioBufferSourceNode(t,{buffer:n,loop:!0});a.connect(i),this._bufferNode=a}_bindContextEvent(t){t.addEventListener("statechange",this._handleContextStateChange.bind(this))}_handleContextStateChange(){const t=this._context;(t.state==="suspended"||t.state==="interrupted")&&(be.info("_emit_",Ct.PAUSING),this.emit(Ct.PAUSING))}track(){if(be.info("track"),yt(this._context),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 i=t.stream.getAudioTracks()[0];return this._destNode=t,this._track=i,i}}function ho(r){const{sampleRate:e,keepAlive:t}=r;let i=Rr.get(e);return(!i||i.state==="closed")&&(i=new AudioContext({sampleRate:e}),Rr.set(e,i)),t&&(i.onstatechange=()=>{yt(i)}),i}function yt(r){if(r.state==="suspended"||r.state==="interrupted")return r.resume()}const po=r=>(e,t)=>(r.set(e,t),t),Ar=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,wr=536870912,Or=wr*2,lo=(r,e)=>t=>{const i=e.get(t);let s=i===void 0?t.size:i<Or?i+1:0;if(!t.has(s))return r(t,s);if(t.size<wr){for(;t.has(s);)s=Math.floor(Math.random()*Or);return r(t,s)}if(t.size>Ar)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;t.has(s);)s=Math.floor(Math.random()*Ar);return r(t,s)},Dr=new WeakMap,mo=po(Dr),ee=lo(mo,Dr),fo=r=>r.method!==void 0&&r.method==="call",_o=r=>typeof r.id=="number"&&typeof r.result=="boolean",Ir=((r,e)=>{let t=null;return()=>{if(t!==null)return t;const i=new Blob([e],{type:"application/javascript; charset=utf-8"}),s=URL.createObjectURL(i);return t=r(s),setTimeout(()=>URL.revokeObjectURL(s)),t}})(r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),i=new Map,s=new Worker(r);return s.addEventListener("message",({data:d})=>{if(fo(d)){const{params:{timerId:c,timerType:h}}=d;if(h==="interval"){const p=e.get(c);if(typeof p===void 0)throw new Error("The timer is in an undefined state.");if(typeof p=="number"){const l=i.get(p);if(l===void 0||l.timerId!==c||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&p()}else if(h==="timeout"){const p=t.get(c);if(typeof p===void 0)throw new Error("The timer is in an undefined state.");if(typeof p=="number"){const l=i.get(p);if(l===void 0||l.timerId!==c||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&(p(),t.delete(c))}}else if(_o(d)){const{id:c}=d,h=i.get(c);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:p,timerType:l}=h;i.delete(c),l==="interval"?e.delete(p):t.delete(p)}else{const{error:{message:c}}=d;throw new Error(c)}}),{clearInterval:d=>{if(typeof e.get(d)=="function"){const c=ee(i);i.set(c,{timerId:d,timerType:"interval"}),e.set(d,c),s.postMessage({id:c,method:"clear",params:{timerId:d,timerType:"interval"}})}},clearTimeout:d=>{if(typeof t.get(d)=="function"){const c=ee(i);i.set(c,{timerId:d,timerType:"timeout"}),t.set(d,c),s.postMessage({id:c,method:"clear",params:{timerId:d,timerType:"timeout"}})}},setInterval:(d,c=0,...h)=>{const p=ee(e);return e.set(p,()=>{d(...h),typeof e.get(p)=="function"&&s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}})}),s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}}),p},setTimeout:(d,c=0,...h)=>{const p=ee(t);return t.set(p,()=>d(...h)),s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"timeout"}}),p}}},`(()=>{"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})}}))})();`),go=r=>Ir().clearTimeout(r),vo=(...r)=>Ir().setTimeout(...r),Co=r=>r.method!==void 0&&r.method==="call",yo=r=>typeof r.id=="number"&&typeof r.result=="boolean",So=r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),i=new Map,s=new Worker(r,{credentials:"omit"});return s.addEventListener("message",({data:d})=>{if(Co(d)){const{params:{timerId:c,timerType:h}}=d;if(h==="interval"){const p=e.get(c);if(typeof p===void 0)throw new Error("The timer is in an undefined state.");if(typeof p=="number"){const l=i.get(p);if(l===void 0||l.timerId!==c||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&p()}else if(h==="timeout"){const p=t.get(c);if(typeof p===void 0)throw new Error("The timer is in an undefined state.");if(typeof p=="number"){const l=i.get(p);if(l===void 0||l.timerId!==c||l.timerType!==h)throw new Error("The timer is in an undefined state.")}else typeof p=="function"&&(p(),t.delete(c))}}else if(yo(d)){const{id:c}=d,h=i.get(c);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:p,timerType:l}=h;i.delete(c),l==="interval"?e.delete(p):t.delete(p)}else{const{error:{message:c}}=d;throw new Error(c)}}),{clearInterval:d=>{if(typeof e.get(d)=="function"){const c=ee(i);i.set(c,{timerId:d,timerType:"interval"}),e.set(d,c),s.postMessage({id:c,method:"clear",params:{timerId:d,timerType:"interval"}})}},clearTimeout:d=>{if(typeof t.get(d)=="function"){const c=ee(i);i.set(c,{timerId:d,timerType:"timeout"}),t.set(d,c),s.postMessage({id:c,method:"clear",params:{timerId:d,timerType:"timeout"}})}},setInterval:(d,c=0,...h)=>{const p=ee(e);return e.set(p,()=>{d(...h),typeof e.get(p)=="function"&&s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}})}),s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"interval"}}),p},setTimeout:(d,c=0,...h)=>{const p=ee(t);return t.set(p,()=>d(...h)),s.postMessage({id:null,method:"set",params:{delay:c,now:performance.timeOrigin+performance.now(),timerId:p,timerType:"timeout"}}),p}}},To={width:640,height:480,frameRate:30,backgroundColor:"#000000"},Ue=new L("View");class Eo{constructor(e){m(this,"id",oe());m(this,"_context");m(this,"_canvas");m(this,"_config");m(this,"_nodeList",[]);m(this,"_track");m(this,"_stopped",!0);m(this,"_nextTime",Date.now());m(this,"_workerTimeoutId");m(this,"_raqId");m(this,"_workerTimerScriptUrl");m(this,"_customSetTimeout");m(this,"_customClearTimeout");m(this,"_loopTimer");m(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)},lt/this._config.frameRate),this._raqId=requestAnimationFrame(this._paintLoop)});Ue.info("ctor",e),this._config={...To,...e};const{context:t,canvas:i}=mr(this._config);this._context=t,this._canvas=i,this._customSetTimeout=vo,this._customClearTimeout=go}setWorkerTimerScriptUrl(e){if(this._workerTimerScriptUrl=e,this._workerTimerScriptUrl){const t=So(this._workerTimerScriptUrl);this._customSetTimeout=(...i)=>t.setTimeout(...i),this._customClearTimeout=i=>t.clearTimeout(i)}}_shouldDraw(e){if(e<this._nextTime)return!1;for(;e>this._nextTime;)this._nextTime+=lt/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=[]){Ue.info("draw",e),this._nodeList=e}_drawOnCanvas(){if(this._shouldDraw(Date.now())){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)}}}}_drawBackground(){const{backgroundColor:e,width:t,height:i}=this._config;this._context.clearRect(0,0,t,i),e&&(this._context.fillStyle=e,this._context.fillRect(0,0,t,i))}track(){if(Ue.info("track"),this._track)return this._track;this._stopped=!1,this._paintLoop();const{frameRate:e}=this._config,t=this._canvas.captureStream(e);return this._track=t.getVideoTracks()[0],this._track}updateFps(){if(this._track){const{frameRate:e}=this._config,t=this._canvas.captureStream(e);return this._track=t.getVideoTracks()[0],this._track}else return this.track()}element(){return Ue.info("element"),this._paintLoop(),this._canvas}stop(){this._stopped=!0}}function bo(){return Math.random().toString(36).slice(-8)}const ko=`
|
|
1
|
+
(function(ge,Y){typeof exports=="object"&&typeof module<"u"?module.exports=Y():typeof define=="function"&&define.amd?define(Y):(ge=typeof globalThis<"u"?globalThis:ge||self,ge.vePusher=Y())})(this,function(){"use strict";var P_=Object.defineProperty;var L_=(ge,Y,Ne)=>Y in ge?P_(ge,Y,{enumerable:!0,configurable:!0,writable:!0,value:Ne}):ge[Y]=Ne;var b=(ge,Y,Ne)=>L_(ge,typeof Y!="symbol"?Y+"":Y,Ne);var Ya,Qa,ec,tc,rc,ic;function ge(r,e){for(var t=0;t<e.length;t++){const i=e[t];if(typeof i!="string"&&!Array.isArray(i)){for(const n in i)if(n!=="default"&&!(n in r)){const s=Object.getOwnPropertyDescriptor(i,n);s&&Object.defineProperty(r,n,s.get?s:{enumerable:!0,get:()=>i[n]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}function Y(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Ne={exports:{}},wn;function _c(){return wn||(wn=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function n(h,c,u){this.fn=h,this.context=c,this.once=u||!1}function s(h,c,u,l,d){if(typeof u!="function")throw new TypeError("The listener must be a function");var p=new n(u,l||h,d),f=t?t+c:c;return h._events[f]?h._events[f].fn?h._events[f]=[h._events[f],p]:h._events[f].push(p):(h._events[f]=p,h._eventsCount++),h}function a(h,c){--h._eventsCount===0?h._events=new i:delete h._events[c]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,l;if(this._eventsCount===0)return c;for(l in u=this._events)e.call(u,l)&&c.push(t?l.slice(1):l);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,l=this._events[u];if(!l)return[];if(l.fn)return[l.fn];for(var d=0,p=l.length,f=new Array(p);d<p;d++)f[d]=l[d].fn;return f},o.prototype.listenerCount=function(c){var u=t?t+c:c,l=this._events[u];return l?l.fn?1:l.length:0},o.prototype.emit=function(c,u,l,d,p,f){var v=t?t+c:c;if(!this._events[v])return!1;var m=this._events[v],E=arguments.length,y,_;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),E){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,u),!0;case 3:return m.fn.call(m.context,u,l),!0;case 4:return m.fn.call(m.context,u,l,d),!0;case 5:return m.fn.call(m.context,u,l,d,p),!0;case 6:return m.fn.call(m.context,u,l,d,p,f),!0}for(_=1,y=new Array(E-1);_<E;_++)y[_-1]=arguments[_];m.fn.apply(m.context,y)}else{var C=m.length,z;for(_=0;_<C;_++)switch(m[_].once&&this.removeListener(c,m[_].fn,void 0,!0),E){case 1:m[_].fn.call(m[_].context);break;case 2:m[_].fn.call(m[_].context,u);break;case 3:m[_].fn.call(m[_].context,u,l);break;case 4:m[_].fn.call(m[_].context,u,l,d);break;default:if(!y)for(z=1,y=new Array(E-1);z<E;z++)y[z-1]=arguments[z];m[_].fn.apply(m[_].context,y)}}return!0},o.prototype.on=function(c,u,l){return s(this,c,u,l,!1)},o.prototype.once=function(c,u,l){return s(this,c,u,l,!0)},o.prototype.removeListener=function(c,u,l,d){var p=t?t+c:c;if(!this._events[p])return this;if(!u)return a(this,p),this;var f=this._events[p];if(f.fn)f.fn===u&&(!d||f.once)&&(!l||f.context===l)&&a(this,p);else{for(var v=0,m=[],E=f.length;v<E;v++)(f[v].fn!==u||d&&!f[v].once||l&&f[v].context!==l)&&m.push(f[v]);m.length?this._events[p]=m.length===1?m[0]:m:a(this,p)}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 i,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}(Ne)),Ne.exports}var gc=_c();const Ge=Y(gc);var Tn=(r=>(r.LeftToRight="LeftToRight",r.UpToDown="UpToDown",r.All="All",r.None="None",r))(Tn||{}),N=(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))(N||{}),ye=(r=>(r.DeviceCaptured="deviceCaptured",r.DeviceStopCapture="deviceStopCapture",r.Error="error",r.Interrupted="interrupted",r))(ye||{}),j=(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))(j||{}),zn=(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))(zn||{}),kn=(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))(kn||{}),An=(r=>(r.STANDARD="48000x40",r.HIGH="48000x128",r))(An||{}),Ye=(r=>(r.VideoStreamChange="videoStreamChange",r.AudioStreamChange="audioStreamChange",r))(Ye||{}),Rn=(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))(Rn||{});const Dn={SizeChange:"sizeChange"};var Xr=(r=>(r.Portrait="portrait",r.Landscape="landscape",r))(Xr||{});const xn="720p-1",On="STANDARD";var de=(r=>(r[r.DISCONNECTED=0]="DISCONNECTED",r[r.CONNECTING=1]="CONNECTING",r[r.CONNECTED=2]="CONNECTED",r[r.RECONNECTING=3]="RECONNECTING",r))(de||{}),dt=(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))(dt||{}),Yr=(r=>(r[r.PushUrlInvalid=1001]="PushUrlInvalid",r[r.ReconnectTimeout=1002]="ReconnectTimeout",r))(Yr||{}),I=(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))(I||{}),B=(r=>(r.AUDIO="audio",r.VIDEO="video",r))(B||{}),Q=(r=>(r.ENDED="ended",r.MUTE="mute",r.UNMUTE="unmute",r.PLAY_FAILED="play-failed",r.SIZE_CHANGE="size-change",r))(Q||{});const Z=[];for(let r=0;r<256;++r)Z.push((r+256).toString(16).slice(1));function vc(r,e=0){return(Z[r[e+0]]+Z[r[e+1]]+Z[r[e+2]]+Z[r[e+3]]+"-"+Z[r[e+4]]+Z[r[e+5]]+"-"+Z[r[e+6]]+Z[r[e+7]]+"-"+Z[r[e+8]]+Z[r[e+9]]+"-"+Z[r[e+10]]+Z[r[e+11]]+Z[r[e+12]]+Z[r[e+13]]+Z[r[e+14]]+Z[r[e+15]]).toLowerCase()}let Qr;const yc=new Uint8Array(16);function bc(){if(!Qr){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Qr=crypto.getRandomValues.bind(crypto)}return Qr(yc)}const Mn={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Qe(r,e,t){var n;if(Mn.randomUUID&&!r)return Mn.randomUUID();r=r||{};const i=r.random??((n=r.rng)==null?void 0:n.call(r))??bc();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=i[6]&15|64,i[8]=i[8]&63|128,vc(i)}class In{constructor(){b(this,"id",Qe());b(this,"_nextNode");b(this,"_track");b(this,"_destNode")}gain(e){if(this._nextNode instanceof Pn)return this._nextNode.g=e,this._nextNode;const t=new Pn(this,{g:e});return this._nextNode=t,t}connect(e,t){if(!this.available())return;let{_node:i}=this;i||(i=this.createNode(e)),this._node=i,this.previousNode&&this.previousNode.connect(e,i),t&&i.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 Pn extends In{constructor(t,i){super();b(this,"previousNode");b(this,"_node");b(this,"_g");this.previousNode=t,this._g=i.g}createNode(t){return new GainNode(t,{gain:this._g})}set g(t){this._g=t,this._node&&(this._node.gain.value=t)}}class Sc extends In{constructor(t){super();b(this,"previousNode",null);b(this,"source");this.source=t}available(){return this.source.available()}destroy(){super.destroy()}}class Ec extends Sc{constructor(){super(...arguments);b(this,"_node")}createNode(t){if(this._node)return this._node;let i;if(this.source instanceof Hn){const n=this.source.element();i=new MediaElementAudioSourceNode(t,{mediaElement:n}),n.muted=!1}else{const n=this.source.track();i=new MediaStreamAudioSourceNode(t,{mediaStream:new MediaStream([n])})}return i}}class M extends Error{constructor(t,i,n){super(i);b(this,"code");b(this,"message");b(this,"error");this.code=t,this.message=i,this.error=n,Object.setPrototypeOf(this,M.prototype)}toString(){return`VeCapture Error: ${this.code} ${this.message}`}}const Ln={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"}},Un="__debug__",Cc="[VE-CAPTURE]";function wc(){if(typeof location>"u"||typeof localStorage>"u")return!1;let r=!1;return location.href.includes(Un)&&(r=!0),localStorage.getItem(Un)&&(r=!0),r}let ne=class{constructor(e){b(this,"moduleName");this.moduleName=e}print(e,t,...i){const n=Tc();wc()&&console.log(`${n}-${Cc}%c[${Ln[e].text}]%c[${this.moduleName}][${t}]`,`background-color:${Ln[e].color};`,"background-color:rgba(0, 0, 0, 0)",...i)}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 i=this;return function(...s){i.info(`${t}-invoke`,...s);try{const a=e(...s);return typeof(a==null?void 0:a.then)=="function"?a.then(o=>(i.success(`${t}-result`,o),o)).catch(o=>{throw i.error(`${t}-result`,o),o}):(i.success(`${t}-result`,a),a)}catch(a){i.error(`[${t}-result`,a)}}}};function Tc(){const r=new Date;return`${r.toTimeString().split(" ")[0]}:${r.getMilliseconds().toString().padStart(3,"0")}`}function ei(r,e){const t=document.createElement(r);return e.id&&(t.id=e.id),e.classList&&e.classList.forEach(i=>{t.classList.add(i)}),e.style&&Object.assign(t.style,e.style),e.attributes&&Object.entries(e.attributes).forEach(([i,n])=>{i==="muted"&&(t instanceof HTMLVideoElement||t instanceof HTMLAudioElement)?t.muted=!0:t.setAttribute(i,n)}),t}function Nn({width:r,height:e}){const t=document.createElement("canvas"),i=t.getContext("2d");if(!i)throw new M(I.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:i,canvas:t}}class ti{constructor(e){b(this,"target");b(this,"_eventDict",new Map);this.target=e}on(e,t){let i=this._eventDict.get(e);i||(i=[t]),this._eventDict.set(e,i),this.target.addEventListener(e,t)}off(e,t){let i=this._eventDict.get(e);i&&(i=i.filter(n=>n!==t),this._eventDict.set(e,i),this.target.removeEventListener(e,t))}once(e,t){const i=n=>{t(n),this.off(e,i)};this.on(e,i)}clear(e){const t=this._eventDict.get(e);t&&t.forEach(i=>{this.target.removeEventListener(e,i)})}clearAll(){for(const e of this._eventDict.keys())this.clear(e)}}const H=()=>typeof window>"u";function F(){return navigator.userAgent.toLowerCase()}function ri(r=F()){let e="none";return H()||(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 Gn=ri()==="firefox",dr=ri()==="safari";ri(),!H()&&/crios/i.test(F()),!H()&&/edg\//i.test(F()),!H()&&/edgA/i.test(F()),!H()&&/edgios/i.test(F()),!H()&&/dingtalk/i.test(F()),!H()&&/opr\//.test(F()),!H()&&/(iphone|ipod)/i.exec(F()),!H()&&(/(ipad)/i.exec(F())||/macintosh/i.test(F())&&"ontouchend"in document),!H()&&/macintosh/i.test(F()),!H()&&/micromessenger/i.test(F()),!H()&&F().includes("mobile"),!H()&&/sm-\w+/i.test(F());const zc=!H()&&!!/(iphone|ipad|ipod)/i.exec(F());!H()&&/android/i.test(F()),!H()&&/windows/i.test(F()),!H()&&/openharmony/i.test(F());let Bn="0";const kc=!H()&&((Ya=F().match(/version\/(\d+)/i))==null?void 0:Ya[1]);dr&&kc&&(Bn=(Qa=navigator.userAgent.match(/version\/(\d+\.\d+)/i))==null?void 0:Qa[1]),!H()&&((ec=F().match(/firefox\/(\d+)/i))==null||ec[1]);const ii=Bn;!H()&&((rc=(tc=F().match(/ ([\d_]+) like mac os x/i))==null?void 0:tc[1])==null||rc.split("_").map(r=>parseInt(r))),!H()&&((ic=F().match(/chrome\/(\d+)/i))==null||ic[1]);function Ac(){var r;return!!((r=navigator==null?void 0:navigator.permissions)!=null&&r.query)}function ni(){return!!(navigator!=null&&navigator.mediaDevices)}function Rc(){var r;return ni()&&!!((r=navigator==null?void 0:navigator.mediaDevices)!=null&&r.getUserMedia)}function Dc(){return!!Promise.withResolvers}function xc(){return!(dr&&ii==="16.1")}function Oc(){return!(dr&&ii&&["16.1","16.2","16.3"].includes(ii))}function Mc(){return!Gn}function Ic(){return typeof CanvasCaptureMediaStreamTrack<"u"}function Pc(r){return typeof r.requestFrame=="function"}function Lc(){return!!ni()&&typeof navigator.mediaDevices.ondevicechange<"u"&&typeof navigator.mediaDevices.addEventListener=="function"}const ze={permissionQuery:Ac,mediaDevices:ni,settingResolutionInGetDisplayMedia:xc,promiseWithResolvers:Dc,getUserMedia:Rc,isolateEnumerateDevices:Mc,supportIdealParamsInGetDisplayMedia:Oc,canvasCaptureMediaStreamTrack:Ic,requestFrameOnMediaStream:Pc,ondevicechange:Lc};function Uc(){if(ze.promiseWithResolvers())return Promise.withResolvers();let r,e;const t=new Promise((i,n)=>{r=i,e=n});if(!r||!e)throw Error("resolver and rejector working unexpected");return{promise:t,resolve:r,reject:e}}function Vn(r={}){const{timeout:e,message:t}={timeout:0,message:new M(I.UNEXPECTED_ERROR,"unexpected timeout"),...r},{promise:i,resolve:n,reject:s}=Uc();if(e<=0)return{promise:i,resolve:n,reject:s};const a=setTimeout(()=>{s(t)},e);return{promise:i,resolve:h=>{clearTimeout(a),n(h)},reject:s}}const Nc={playsinline:"","webkit-playsinline":"","x5-playsinline":"","x5-video-player-type":"h5","x-webkit-airplay":"allow",preload:"metadata",muted:"",crossOrigin:"anonymous"},Gc={playsinline:"","webkit-playsinline":"",preload:"metadata",muted:"",crossOrigin:"anonymous"};class Rt{constructor(e,t=[]){b(this,"id",Qe());b(this,"_referenceTracks",[]);b(this,"_element");b(this,"_volumeMode",0);b(this,"_readyLock");b(this,"_releaseReadyLock");b(this,"_throwReadyLock");b(this,"_stream");let i;if(e instanceof MediaStreamTrack){const o=new MediaStream([e]);i=Bc(o),this._stream=o}else if(e.url)i=Vc(e);else throw new M(I.UNEXPECTED_TYPE,`got ${typeof e}, expected: MediaStreamTrack or constraints for creating element`);const{promise:n,resolve:s,reject:a}=Vn({timeout:2e3,message:new M(I.PLAY_FAILED,"load media timeout")});this._readyLock=n,this._releaseReadyLock=s,this._throwReadyLock=a,this._element=new ti(i),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===B.AUDIO){this._upgradeVolumeMode(1e-4);const i=t.getAudioTracks();if(i.length<1)throw new M(I.UNEXPECTED_TYPE,"got empty list of audio tracks");return i[0]}if(e===B.VIDEO){const i=t.getVideoTracks();if(i.length<1)throw new M(I.UNEXPECTED_TYPE,"got empty list of video tracks");return i[0]}throw new M(I.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 M(I.PLAY_FAILED,"play element failed",e)}}_bindPlayerEvent(e){e.on("loadedmetadata",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new M(I.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 Bc(r){let e="audio";r.getVideoTracks().length>0&&(e="video");const t=Fn(e==="video"?B.VIDEO:B.AUDIO);return t.srcObject=r,t}function Vc(r){const{url:e,kind:t,loop:i}=r,n=Fn(t);return n.src=e,n.loop=i,n}function Fn(r){if(r===B.VIDEO)return ei(B.VIDEO,{style:{width:"100%",height:"100%"},attributes:Nc});if(r===B.AUDIO)return ei(B.AUDIO,{style:{display:"none"},attributes:Gc});throw new M(I.UNEXPECTED_TYPE,`got ${r}, expected: audio, video`)}class si extends Ge{emit(e,...t){const i=this.listenerCount(e);return Promise.resolve().then(()=>{super.emit(e,...t)}),!!i}on(e,t,i){const n=(...s)=>{try{return t(...s)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.on(e,n,i)}once(e,t,i){const n=(...s)=>{try{return t(...s)}catch(a){console.error(`[SafeEventEmitter] event listener threw an error when handling [${e}] event: `,a)}};return super.once(e,n,i)}}function oi(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 M(I.UNEXPECTED_TYPE,"unexpected constraints type")}const ai=1e3;class jn{constructor(e){b(this,"id",Qe());b(this,"_context");b(this,"_canvas");b(this,"_image");b(this,"_config");b(this,"_readyLock");b(this,"_releaseReadyLock");b(this,"_throwReadyLock");b(this,"_loopTimer");b(this,"_referenceTracks",[]);b(this,"_stream");const t=oi(e.width),i=oi(e.height),n=oi(e.frameRate);this._config={width:t,height:i,frameRate:n};const{context:s,canvas:a}=Nn({width:t,height:i});this._context=s,this._canvas=a;const o=Fc({url:e.url,width:t,height:i});this._image=new ti(o);const{promise:h,resolve:c,reject:u}=Vn({timeout:2e3,message:new M(I.PLAY_FAILED,"load image timeout")});this._readyLock=h,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 i=t.getVideoTracks();if(i.length<1)throw new M(I.UNEXPECTED_TYPE,"got empty list of video tracks");return i[0]}element(){return this._image.target}isReady(){return this._readyLock}_bindImageEvent(e){e.on("load",()=>{this._releaseReadyLock()}),e.on("error",()=>{this._throwReadyLock(new M(I.PLAY_FAILED,"HTMLMediaElement got error when loading file"))})}async _paint(){const{width:e,height:t,frameRate:i}=this._config;this._context.drawImage(this._image.target,0,0,e,t),this._loopTimer&&clearTimeout(this._loopTimer),this._loopTimer=setTimeout(this._paint.bind(this),ai/i)}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 Fc({url:r,height:e,width:t}){const i=ei("img",{style:{width:`${t}px`,height:`${e}px`},attributes:{crossOrigin:"anonymous"}});return i.src=r,i}class ci extends si{constructor(t){super();b(this,"id",Qe());b(this,"_track");b(this,"_element");t instanceof MediaStreamTrack?(this._track=new ti(t),this._bindTrackEvent(this._track)):t instanceof Rt?(this._element=t,t.addReferenceTrack(this)):t instanceof jn&&(this._element=t)}_bindTrackEvent(t){t.on("ended",this._handleTrackEnded.bind(this)),t.on("mute",()=>{this.emit(Q.MUTE)}),t.on("unmute",()=>{this.emit(Q.UNMUTE)})}_handleTrackEnded(){this.emit(Q.ENDED),this.destroy()}handlePlayFailed(){this.emit(Q.PLAY_FAILED)}track(){if(this.logger.info("track"),!this.available())throw new M(I.TRACK_NOT_AVAILABLE,"track is not available when creating MediaStreamTrack");if(this._track)return this._track.target;if(!this._element)throw new M(I.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 M(I.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element)return this._element.element();if(!this._track)throw new M(I.UNEXPECTED_TYPE,"got this._track falsy");const t=new Rt(this._track.target,[this]);this._element=t;const i=t.element();return this.logger.success("element",i),i}available(){return!!(this._track||this._element)}destroy(){var t,i,n;(t=this._track)==null||t.clearAll(),(i=this._track)==null||i.target.stop(),this._track&&delete this._track,(n=this._element)==null||n.removeReference(this),delete this._element}}class lr extends ci{constructor(){super(...arguments);b(this,"kind",B.AUDIO);b(this,"_node")}node(){if(this.logger.info("node",this.id),!this.available())throw new M(I.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");if(this._node)return this._node;const t=new Ec(this);return this._node=t,t}element(){if(this.logger.info("element",this.id),!this.available())throw new M(I.TRACK_NOT_AVAILABLE,"track is not available when creating HTMLMediaElement");if(this._element){const i=this._element.element(!0);if(!(i instanceof HTMLMediaElement))throw new M(I.UNEXPECTED_TYPE,"source should be HTMLMediaElement");return i}if(!this._track)throw new M(I.UNEXPECTED_TYPE,"got this._track falsy");const t=new Rt(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 jc extends lr{constructor(){super(...arguments);b(this,"logger",new ne("MicrophoneAudioTrack"))}}class Hc extends lr{constructor(){super(...arguments);b(this,"logger",new ne("ScreenAudioTrack"))}}class Hn extends lr{constructor(){super(...arguments);b(this,"logger",new ne("MediaAudioTrack"))}handlePlayFailed(){this.emit(Q.PLAY_FAILED)}async play(){if(this._element){if(!(this._element instanceof Rt))throw new M(I.UNEXPECTED_TYPE,"element is not TrackMediaElement");return this._element._playElement()}}}class $c extends lr{constructor(){super(...arguments);b(this,"logger",new ne("CustomAudioTrack"))}}let Kc=1;const ui=new ne("PromiseQueue");class qc{constructor(e){b(this,"lockingPromise",Promise.resolve());b(this,"locks",0);b(this,"name","");b(this,"lockId");b(this,"closeReason");this.lockId=Kc++,e&&(this.name=e),ui.info(`lock-${this.name}-${this.lockId}`,"is created.")}get isLocked(){return this.locks>0}lock(){this.locks+=1,ui.info(`lock-${this.name}-${this.lockId}`,`locked, current queue ${this.locks}.`);let e;const t=new Promise(n=>{e=()=>{this.locks-=1,ui.info(`lock-${this.name}-${this.lockId}`,`unlocked, current queue ${this.locks}.`),n()}}),i=this.lockingPromise.then(()=>e);return this.lockingPromise=this.lockingPromise.then(()=>t),i}}const Wc=300,Jc=3e3,be=new ne("Devices");class Zc extends si{constructor(){super();b(this,"_deviceMap",{audioinput:[],audiooutput:[],videoinput:[]});b(this,"_permissions",{[B.AUDIO]:!1,[B.VIDEO]:!1});b(this,"_changedQueue",new qc("device changed queue"));this._init()}async _init(){this._initDeviceChanged(),await this._initPermissionChanged();const t=Wn(this._permissions);t.length>0&&this._refreshDevices(t)}_initDeviceChanged(){if(be.info("_initDeviceChanged","invoked"),!ze.ondevicechange()){be.error("_initDeviceChanged","no supported, use timer instead"),setInterval(()=>{this._handleDeviceChanged()},Jc);return}ze.ondevicechange()&&navigator.mediaDevices.addEventListener("devicechange",()=>{be.info("devicechange"),setTimeout(()=>{this._handleDeviceChanged()},Wc)})}async _initPermissionChanged(){if(!ze.permissionQuery()){be.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",()=>{be.info("_initPermissionChanged","update permission for audio"),this._permissions.audio=t.state==="granted"})}catch(t){be.error("_initPermissionChanged",t)}try{const t=await navigator.permissions.query({name:"camera"});this._permissions.video=t.state==="granted",t.addEventListener("change",()=>{be.info("_initPermissionChanged","update permission for video"),this._permissions.video=t.state==="granted"})}catch(t){be.error("_initPermissionChanged",t)}}async _refreshDevices(t){if(!ze.mediaDevices())throw new M(I.NOT_SUPPORTED,"mediaDevices is not supported");if(t.length===0)throw new M(I.UNEXPECTED_TYPE,"kinds expect to containt values");let i;if(!ze.isolateEnumerateDevices()){const a={};t.forEach(o=>{a[o]=!0}),i=await navigator.mediaDevices.getUserMedia(a)}let n=await navigator.mediaDevices.enumerateDevices();i&&$n(i),n=n.filter(({deviceId:a})=>!!a);const s={audioinput:[],audiooutput:[],videoinput:[]};n.forEach(a=>{const{kind:o}=a;s[o].push(a)}),this._deviceMap=s}async _acquireUserPermission(t){let i=!1;if(t.forEach(n=>{i=i||!this._permissions[n]}),!i)return{grant:!0};if(!ze.getUserMedia())return{grant:!1,reason:new M(I.NOT_SUPPORTED,"getUserMedia is not supported")};try{const n={};t.forEach(a=>{n[a]=!0});const s=await navigator.mediaDevices.getUserMedia(n);return s?(n.audio&&(this._permissions[B.AUDIO]=!0),n.video&&(this._permissions[B.VIDEO]=!0),$n(s),{grant:!0}):{grant:!1,reason:new M(I.UNEXPECTED_TYPE,"get stream falsy")}}catch(n){return{grant:!1,reason:new M(I.CAPTURE_FAILED,"acquire user permission failed",n)}}}async _handleDeviceChanged(){be.info("_handleDeviceChanged",this._deviceMap,this._permissions);const t=await this._changedQueue.lock();try{const i=qn(this._deviceMap);let n=[];const s=Wn(this._permissions);s.length===0?be.warn("_handleDeviceChanged","no permission, use empty list"):(await this._refreshDevices(s),n=qn(this._deviceMap)),n.forEach(a=>{i.findIndex(h=>Kn(h,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"active"})}),i.forEach(a=>{n.findIndex(h=>Kn(h,a))!==-1||this.emit("onDeviceStateChanged",{deviceInfo:a,deviceState:"inactive"})})}finally{t()}}async enumerateDevices(t){const i=[];t.forEach(o=>{if(o==="audioinput"||o==="audiooutput")i.push(B.AUDIO);else if(o==="videoinput")i.push(B.VIDEO);else throw new M(I.UNEXPECTED_TYPE,"kind in kinds should be enum MediaDeviceKind")});const{grant:n,reason:s}=await this._acquireUserPermission(i);if(!n)throw s;await this._refreshDevices(i);const a=[];return t.forEach(o=>{a.push(...this._deviceMap[o])}),a}async enableDevices(t){return this._acquireUserPermission(t)}}function $n(r){r.getTracks().forEach(e=>e.stop())}function Kn(r,e){return r.deviceId===e.deviceId}function qn(r){return Array.from([...r.audioinput.values(),...r.videoinput.values(),...r.audiooutput.values()])}function Wn(r){const e=[];return r.audio&&e.push(B.AUDIO),r.video&&e.push(B.VIDEO),e}const hi=new Zc,di={LeftToRight:"LeftToRight",UpToDown:"UpToDown",All:"All"};class li{constructor(){b(this,"id",Qe())}position(e,t){return new Xc(this,{x:e,y:t})}scale(e){return new Jn(this,{s:e})}mirror(e){return new Jn(this,{mirrorType:e})}available(){var e;return((e=this.previousNode)==null?void 0:e.available())??!1}}class Xc extends li{constructor(t,i){super();b(this,"previousNode");b(this,"_x");b(this,"_y");this.previousNode=t,this._x=i.x,this._y=i.y}paint(t){t.translate(this._x,this._y)}}class Jn extends li{constructor(t,i){super();b(this,"previousNode");b(this,"_scaleParams",[1,1]);if(this.previousNode=t,i.mirrorType)switch(i.mirrorType){case di.LeftToRight:this._scaleParams=[-1,1];break;case di.UpToDown:this._scaleParams=[1,-1];break;case di.All:this._scaleParams=[-1,-1];break;default:this._scaleParams=[1,1];break}else i.s&&(this._scaleParams=[i.s,i.s])}paint(t){t.scale(this._scaleParams[0],this._scaleParams[1])}}class Yc extends li{constructor(t){super();b(this,"previousNode",null);b(this,"_source");this._source=t}available(){return this._source.available()}}class pr extends Yc{constructor(t,i){super(t);b(this,"_targetWidth");b(this,"_targetHeight");const{width:n,height:s}=i??{};this._targetWidth=n??this._source.width(),this._targetHeight=s??this._source.height()}size(t,i){return new pr(this._source,{width:t,height:i})}paint(t){const i=this._targetWidth,n=this._targetHeight;t.drawImage(this._source.element(),-i/2,-n/2,i,n)}}class Qc extends ci{constructor(){super(...arguments);b(this,"logger",new ne("PictureTrack"));b(this,"kind",B.VIDEO)}element(){const t=super.element();if(!(t instanceof HTMLImageElement))throw new M(I.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 M(I.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");const t=new pr(this);return this.logger.info("node",t),t}destroy(){this.logger.warn("destroy"),super.destroy()}}const eu=500;class fr extends ci{constructor(){super(...arguments);b(this,"kind",B.VIDEO);b(this,"sizeChangeTimer");b(this,"watchSizeChangeOnce",()=>{const t=this.width(),i=this.height();this.sizeChangeTimer=setTimeout(()=>{const n=this.width(),s=this.height();(i!==s||t!==n)&&this.emit(Q.SIZE_CHANGE,{width:n,height:s})},eu)})}element(){const t=super.element();if(!(t instanceof HTMLVideoElement))throw new M(I.UNEXPECTED_TYPE,"source should be HTMLVideoElement");return t}node(){if(!this.available())throw new M(I.TRACK_NOT_AVAILABLE,"track is not avaiable when creating node");return new pr(this)}destroy(){clearTimeout(this.sizeChangeTimer),super.destroy()}}class tu extends fr{constructor(t){super(t);b(this,"logger",new ne("CameraVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class ru extends fr{constructor(t){super(t);b(this,"logger",new ne("ScreenVideoTrack"));this.watchSizeChangeOnce()}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}class iu extends fr{constructor(){super(...arguments);b(this,"logger",new ne("MediaVideoTrack"))}height(){const{videoHeight:t}=this.element();return t??0}width(){const{videoWidth:t}=this.element();return t??0}}class nu extends fr{constructor(){super(...arguments);b(this,"logger",new ne("CustomVideoTrack"))}height(){const{height:t}=this.track().getSettings();return t??0}width(){const{width:t}=this.track().getSettings();return t??0}}async function Zn(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(i){console.warn("[VePusher Error]: frameRate limit failed",i)}}const ke=new ne("Capture");async function su(r){return hi.enumerateDevices(r)}async function ou(r){hi.removeAllListeners("onDeviceStateChanged"),hi.on("onDeviceStateChanged",r)}async function au(r,e){let t;try{const n={video:r??!0};typeof n.video=="object"&&n.video.facingMode&&delete n.video.deviceId,t=await navigator.mediaDevices.getUserMedia(n)}catch(n){throw new M(I.CAPTURE_FAILED,"got error when capturing camera",n)}const i=t.getVideoTracks()[0];if(r!=null&&r.frameRate&&e&&Zn(i,r),!i)throw new M(I.UNEXPECTED_TYPE,"got falsy in track");return new tu(i)}async function cu(r,e,t){const{video:i,audio:n}=r;let s=i===!0?{}:i;e!=null&&e.displaySurface&&(s.displaySurface=e.displaySurface,delete e.displaySurface),ze.settingResolutionInGetDisplayMedia()||(s=!0),!ze.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:n,...e})}catch(u){throw new M(I.CAPTURE_FAILED,"got error when capture screen",u)}const o=a.getVideoTracks()[0],h=a.getAudioTracks()[0];if(!o)throw new M(I.UNEXPECTED_TYPE,"got falsy in videoTrack");typeof s!="boolean"&&typeof s.frameRate=="number"&&t&&Zn(o,s);const c=[];return c.push(new ru(o)),h&&c.push(new Hc(h)),c}async function uu(r){const{url:e,audio:t,video:i,loop:n}=r,s=new Rt({url:e,kind:i?B.VIDEO:B.AUDIO,loop:n}),a=[];return t&&a.push(new Hn(s)),i&&a.push(new iu(s)),await s.isReady(),a}async function hu(r){const e=new jn(r);return await e.isReady(),new Qc(e)}async function du(r){let e;try{const i={audio:r??!0};e=await navigator.mediaDevices.getUserMedia(i)}catch(i){throw new M(I.CAPTURE_FAILED,"got error when capturing microphone",i)}const t=e.getAudioTracks()[0];if(!t)throw new M(I.UNEXPECTED_TYPE,"got falsy in track");return new jc(t)}function lu(r){if(!r||r.kind!=="video")throw new M(I.UNEXPECTED_TYPE,"error custom video track type");return new nu(r)}function pu(r){if(!r||r.kind!=="audio")throw new M(I.UNEXPECTED_TYPE,"error custom audio track type");return new $c(r)}const fu=ke.invoke(su,"enumerateInputDevices"),mu=ke.invoke(au,"createCameraTrack"),_u=ke.invoke(hu,"createPictureTrack"),Xn=ke.invoke(uu,"createMediaTracks"),gu=ke.invoke(du,"createMicrophoneTrack"),vu=ke.invoke(cu,"createScreenTracks"),yu=ke.invoke(ou,"onDeviceChanged"),bu=ke.invoke(lu,"createCustomVideoTrack"),Su=ke.invoke(pu,"createCustomAudioTrack");var pi=(r=>(r.PAUSING="pausing",r))(pi||{});const Eu={sampleRate:48e3,keepAlive:!0},Yn=new Map,Dt=new ne("Mixer");class Cu extends si{constructor(t){super();b(this,"id",Qe());b(this,"_context");b(this,"_config");b(this,"_nodeList",[]);b(this,"_destNode");b(this,"_bufferNode");b(this,"_track");b(this,"unlockAudioContext",()=>{if(this._context.state!=="suspended")return;const t=document.body,i=["touchstart","touchend","mousedown","keydown"],n=()=>{i.forEach(a=>{t.removeEventListener(a,s)})},s=()=>{xt(this._context).then(n)};i.forEach(a=>{t.addEventListener(a,s,!1)})});Dt.info("ctor",t),this._config={...Eu,...t},this._context=wu(this._config),this._bindContextEvent(this._context)}mix(t){Dt.info("mix",t),xt(this._context);for(const i of this._nodeList)t.includes(i)||i.destroy();this._nodeList=t,this._connect(t,this._destNode),this._nodeList.length===0&&this._appendSlience(this._context,this._destNode)}resume(){return Dt.info("resume"),xt(this._context)}_connect(t,i){for(const n of t)n.connect(this._context,i)}_appendSlience(t,i){if(!i||this._bufferNode)return;const{sampleRate:n}=t,s=new AudioBuffer({length:100,sampleRate:n}),a=new AudioBufferSourceNode(t,{buffer:s,loop:!0});a.connect(i),this._bufferNode=a}_bindContextEvent(t){t.addEventListener("statechange",this._handleContextStateChange.bind(this))}_handleContextStateChange(){const t=this._context;(t.state==="suspended"||t.state==="interrupted")&&(Dt.info("_emit_",pi.PAUSING),this.emit(pi.PAUSING))}track(){if(Dt.info("track"),xt(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 i=t.stream.getAudioTracks()[0];return this._destNode=t,this._track=i,i}}function wu(r){const{sampleRate:e,keepAlive:t}=r;let i=Yn.get(e);return(!i||i.state==="closed")&&(i=new AudioContext({sampleRate:e}),Yn.set(e,i)),t&&(i.onstatechange=()=>{xt(i)}),i}function xt(r){return r.state==="suspended"||r.state==="interrupted"?r.resume():Promise.resolve()}const Tu=r=>(e,t)=>(r.set(e,t),t),Qn=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,es=536870912,ts=es*2,zu=(r,e)=>t=>{const i=e.get(t);let n=i===void 0?t.size:i<ts?i+1:0;if(!t.has(n))return r(t,n);if(t.size<es){for(;t.has(n);)n=Math.floor(Math.random()*ts);return r(t,n)}if(t.size>Qn)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;t.has(n);)n=Math.floor(Math.random()*Qn);return r(t,n)},rs=new WeakMap,ku=Tu(rs),Be=zu(ku,rs),Au=r=>r.method!==void 0&&r.method==="call",Ru=r=>typeof r.id=="number"&&typeof r.result=="boolean",is=((r,e)=>{let t=null;return()=>{if(t!==null)return t;const i=new Blob([e],{type:"application/javascript; charset=utf-8"}),n=URL.createObjectURL(i);return t=r(n),setTimeout(()=>URL.revokeObjectURL(n)),t}})(r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),i=new Map,n=new Worker(r);return n.addEventListener("message",({data:c})=>{if(Au(c)){const{params:{timerId:u,timerType:l}}=c;if(l==="interval"){const d=e.get(u);if(typeof d===void 0)throw new Error("The timer is in an undefined state.");if(typeof d=="number"){const p=i.get(d);if(p===void 0||p.timerId!==u||p.timerType!==l)throw new Error("The timer is in an undefined state.")}else typeof d=="function"&&d()}else if(l==="timeout"){const d=t.get(u);if(typeof d===void 0)throw new Error("The timer is in an undefined state.");if(typeof d=="number"){const p=i.get(d);if(p===void 0||p.timerId!==u||p.timerType!==l)throw new Error("The timer is in an undefined state.")}else typeof d=="function"&&(d(),t.delete(u))}}else if(Ru(c)){const{id:u}=c,l=i.get(u);if(l===void 0)throw new Error("The timer is in an undefined state.");const{timerId:d,timerType:p}=l;i.delete(u),p==="interval"?e.delete(d):t.delete(d)}else{const{error:{message:u}}=c;throw new Error(u)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const u=Be(i);i.set(u,{timerId:c,timerType:"interval"}),e.set(c,u),n.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"interval"}})}},clearTimeout:c=>{if(typeof t.get(c)=="function"){const u=Be(i);i.set(u,{timerId:c,timerType:"timeout"}),t.set(c,u),n.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"timeout"}})}},setInterval:(c,u=0,...l)=>{const d=Be(e);return e.set(d,()=>{c(...l),typeof e.get(d)=="function"&&n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:d,timerType:"interval"}})}),n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:d,timerType:"interval"}}),d},setTimeout:(c,u=0,...l)=>{const d=Be(t);return t.set(d,()=>c(...l)),n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:d,timerType:"timeout"}}),d}}},`(()=>{"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})}}))})();`),Du=r=>is().clearTimeout(r),xu=(...r)=>is().setTimeout(...r),Ou=r=>r.method!==void 0&&r.method==="call",Mu=r=>typeof r.id=="number"&&typeof r.result=="boolean",Iu=r=>{const e=new Map([[0,()=>{}]]),t=new Map([[0,()=>{}]]),i=new Map,n=new Worker(r,{credentials:"omit"});return n.addEventListener("message",({data:c})=>{if(Ou(c)){const{params:{timerId:u,timerType:l}}=c;if(l==="interval"){const d=e.get(u);if(typeof d===void 0)throw new Error("The timer is in an undefined state.");if(typeof d=="number"){const p=i.get(d);if(p===void 0||p.timerId!==u||p.timerType!==l)throw new Error("The timer is in an undefined state.")}else typeof d=="function"&&d()}else if(l==="timeout"){const d=t.get(u);if(typeof d===void 0)throw new Error("The timer is in an undefined state.");if(typeof d=="number"){const p=i.get(d);if(p===void 0||p.timerId!==u||p.timerType!==l)throw new Error("The timer is in an undefined state.")}else typeof d=="function"&&(d(),t.delete(u))}}else if(Mu(c)){const{id:u}=c,l=i.get(u);if(l===void 0)throw new Error("The timer is in an undefined state.");const{timerId:d,timerType:p}=l;i.delete(u),p==="interval"?e.delete(d):t.delete(d)}else{const{error:{message:u}}=c;throw new Error(u)}}),{clearInterval:c=>{if(typeof e.get(c)=="function"){const u=Be(i);i.set(u,{timerId:c,timerType:"interval"}),e.set(c,u),n.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"interval"}})}},clearTimeout:c=>{if(typeof t.get(c)=="function"){const u=Be(i);i.set(u,{timerId:c,timerType:"timeout"}),t.set(c,u),n.postMessage({id:u,method:"clear",params:{timerId:c,timerType:"timeout"}})}},setInterval:(c,u=0,...l)=>{const d=Be(e);return e.set(d,()=>{c(...l),typeof e.get(d)=="function"&&n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:d,timerType:"interval"}})}),n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:d,timerType:"interval"}}),d},setTimeout:(c,u=0,...l)=>{const d=Be(t);return t.set(d,()=>c(...l)),n.postMessage({id:null,method:"set",params:{delay:u,now:performance.timeOrigin+performance.now(),timerId:d,timerType:"timeout"}}),d}}},Pu={width:640,height:480,frameRate:30,backgroundColor:"#000000"},mr=new ne("View");class Lu{constructor(e){b(this,"id",Qe());b(this,"_context");b(this,"_canvas");b(this,"_config");b(this,"_nodeList",[]);b(this,"_track");b(this,"_stopped",!0);b(this,"_nextTime",Date.now());b(this,"_workerTimeoutId");b(this,"_raqId");b(this,"_workerTimerScriptUrl");b(this,"_customSetTimeout");b(this,"_customClearTimeout");b(this,"_loopTimer");b(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)},ai/this._config.frameRate),this._raqId=requestAnimationFrame(this._paintLoop)});mr.info("ctor",e),this._config={...Pu,...e};const{context:t,canvas:i}=Nn(this._config);this._context=t,this._canvas=i,this._customSetTimeout=xu,this._customClearTimeout=Du}setWorkerTimerScriptUrl(e){if(this._workerTimerScriptUrl=e,this._workerTimerScriptUrl){const t=Iu(this._workerTimerScriptUrl);this._customSetTimeout=(...i)=>t.setTimeout(...i),this._customClearTimeout=i=>t.clearTimeout(i)}}_shouldDraw(e){if(e<this._nextTime)return!1;for(;e>this._nextTime;)this._nextTime+=ai/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=[]){mr.info("draw",e),this._nodeList=e}_drawOnCanvas(){if(this._shouldDraw(Date.now())){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)}}}}_drawBackground(){const{backgroundColor:e,width:t,height:i}=this._config;this._context.clearRect(0,0,t,i),e&&(this._context.fillStyle=e,this._context.fillRect(0,0,t,i))}track(){if(mr.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,i=this._canvas.captureStream(t);return this._track=i.getVideoTracks()[0],e.stop(),this._track}else return this.track()}element(){return mr.info("element"),this._paintLoop(),this._canvas}stop(){this._stopped=!0}}function Uu(){return Math.random().toString(36).slice(-8)}const Nu=`
|
|
2
2
|
const SMOOTHING_FACTOR = 0.8;
|
|
3
3
|
const MINIMUM_VALUE = 0.00001;
|
|
4
4
|
|
|
@@ -53,41 +53,51 @@ registerProcessor('vumeter', class extends AudioWorkletProcessor {
|
|
|
53
53
|
return true;
|
|
54
54
|
}
|
|
55
55
|
});
|
|
56
|
-
`,Po=URL.createObjectURL(new Blob([ko],{type:"application/javascript"}));class xo{constructor(){this._audioCtx=null,this._volume=0}get volume(){return this._volume}async start(e,t){if(this._audioCtx)return;const i=new AudioContext;await i.audioWorklet.addModule(t||Po);const s=new MediaStream;s.addTrack(e);const n=i.createMediaStreamSource(s),a=new AudioWorkletNode(i,"vumeter");a.port.onmessage=o=>{const u=o.data.volume||0;this._volume=Math.min(u*100/2,10)},n.connect(a).connect(i.destination),this._audioCtx=i}stop(){var e;(e=this._audioCtx)==null||e.close(),this._audioCtx=null}}class $e{constructor(){this._volumeDetectScriptUrl=void 0}static get instance(){return this._instance||(this._instance=new $e),this._instance}get volumeDetectScriptUrl(){return this._volumeDetectScriptUrl}set volumeDetectScriptUrl(e){this._volumeDetectScriptUrl=e}}class Mr extends Q{constructor(e){super(),this._width=0,this._height=0,this._mediaStream=null,this._nextStream=null,this._trackMap={},this.type=e.type,this.id=bo(),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[S.Camera,S.Screen,S.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 xo),await this._volumeDetector.start(this.audioTrack,$e.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 le extends Mr{get isVideoStream(){return!0}get isAudioStream(){return!1}bindTrackSizeChangeEvent(e){e.on(I.SIZE_CHANGE,({width:t,height:i})=>{this._width=t,this._height=i,this.emit(it.SizeChange,{width:t,height:i})})}}class Be extends Mr{get isVideoStream(){return!1}get isAudioStream(){return!0}}class Ro extends le{constructor(e){super({type:S.Camera,stream:e}),this._trackMap.video=e.track(),this._width=e.width(),this._height=e.height(),this.bindTrackSizeChangeEvent(e)}get source(){return this._source}get viewNode(){return this.source.node()}get mixerNode(){return null}bindTrackEnd(e){this.source.on(I.ENDED,e)}destroy(){this.source.destroy()}}var Lr=typeof global=="object"&&global&&global.Object===Object&&global,Ao=typeof self=="object"&&self&&self.Object===Object&&self,X=Lr||Ao||Function("return this")(),te=X.Symbol,Fr=Object.prototype,wo=Fr.hasOwnProperty,Oo=Fr.toString,ke=te?te.toStringTag:void 0;function Do(r){var e=wo.call(r,ke),t=r[ke];try{r[ke]=void 0;var i=!0}catch{}var s=Oo.call(r);return i&&(e?r[ke]=t:delete r[ke]),s}var Io=Object.prototype,Mo=Io.toString;function Lo(r){return Mo.call(r)}var Fo="[object Null]",No="[object Undefined]",Nr=te?te.toStringTag:void 0;function me(r){return r==null?r===void 0?No:Fo:Nr&&Nr in Object(r)?Do(r):Lo(r)}function fe(r){return r!=null&&typeof r=="object"}var Vo="[object Symbol]";function je(r){return typeof r=="symbol"||fe(r)&&me(r)==Vo}function Vr(r,e){for(var t=-1,i=r==null?0:r.length,s=Array(i);++t<i;)s[t]=e(r[t],t,r);return s}var F=Array.isArray,Ur=te?te.prototype:void 0,$r=Ur?Ur.toString:void 0;function Br(r){if(typeof r=="string")return r;if(F(r))return Vr(r,Br)+"";if(je(r))return $r?$r.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var Uo=/\s/;function $o(r){for(var e=r.length;e--&&Uo.test(r.charAt(e)););return e}var Bo=/^\s+/;function jo(r){return r&&r.slice(0,$o(r)+1).replace(Bo,"")}function Pe(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var jr=NaN,zo=/^[-+]0x[0-9a-f]+$/i,Go=/^0b[01]+$/i,Ho=/^0o[0-7]+$/i,qo=parseInt;function Wo(r){if(typeof r=="number")return r;if(je(r))return jr;if(Pe(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Pe(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=jo(r);var t=Go.test(r);return t||Ho.test(r)?qo(r.slice(2),t?2:8):zo.test(r)?jr:+r}var Xo=1/0,Ko=17976931348623157e292;function Jo(r){if(!r)return r===0?r:0;if(r=Wo(r),r===Xo||r===-1/0){var e=r<0?-1:1;return e*Ko}return r===r?r:0}function Yo(r){var e=Jo(r),t=e%1;return e===e?t?e-t:e:0}function Zo(r){return r}var Qo="[object AsyncFunction]",ea="[object Function]",ta="[object GeneratorFunction]",ra="[object Proxy]";function zr(r){if(!Pe(r))return!1;var e=me(r);return e==ea||e==ta||e==Qo||e==ra}var St=X["__core-js_shared__"],Gr=function(){var r=/[^.]+$/.exec(St&&St.keys&&St.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function ia(r){return!!Gr&&Gr in r}var sa=Function.prototype,na=sa.toString;function ae(r){if(r!=null){try{return na.call(r)}catch{}try{return r+""}catch{}}return""}var oa=/[\\^$.*+?()[\]{}|]/g,aa=/^\[object .+?Constructor\]$/,ca=Function.prototype,da=Object.prototype,ua=ca.toString,ha=da.hasOwnProperty,pa=RegExp("^"+ua.call(ha).replace(oa,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function la(r){if(!Pe(r)||ia(r))return!1;var e=zr(r)?pa:aa;return e.test(ae(r))}function ma(r,e){return r==null?void 0:r[e]}function _e(r,e){var t=ma(r,e);return la(t)?t:void 0}var Tt=_e(X,"WeakMap");function fa(r,e,t,i){for(var s=r.length,n=t+-1;++n<s;)if(e(r[n],n,r))return n;return-1}var _a=9007199254740991,ga=/^(?:0|[1-9]\d*)$/;function Hr(r,e){var t=typeof r;return e=e??_a,!!e&&(t=="number"||t!="symbol"&&ga.test(r))&&r>-1&&r%1==0&&r<e}function qr(r,e){return r===e||r!==r&&e!==e}var va=9007199254740991;function Et(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=va}function bt(r){return r!=null&&Et(r.length)&&!zr(r)}var Ca=Object.prototype;function ya(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Ca;return r===t}function Sa(r,e){for(var t=-1,i=Array(r);++t<r;)i[t]=e(t);return i}var Ta="[object Arguments]";function Wr(r){return fe(r)&&me(r)==Ta}var Xr=Object.prototype,Ea=Xr.hasOwnProperty,ba=Xr.propertyIsEnumerable,Kr=Wr(function(){return arguments}())?Wr:function(r){return fe(r)&&Ea.call(r,"callee")&&!ba.call(r,"callee")};function ka(){return!1}var Jr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Yr=Jr&&typeof module=="object"&&module&&!module.nodeType&&module,Pa=Yr&&Yr.exports===Jr,Zr=Pa?X.Buffer:void 0,xa=Zr?Zr.isBuffer:void 0,kt=xa||ka,Ra="[object Arguments]",Aa="[object Array]",wa="[object Boolean]",Oa="[object Date]",Da="[object Error]",Ia="[object Function]",Ma="[object Map]",La="[object Number]",Fa="[object Object]",Na="[object RegExp]",Va="[object Set]",Ua="[object String]",$a="[object WeakMap]",Ba="[object ArrayBuffer]",ja="[object DataView]",za="[object Float32Array]",Ga="[object Float64Array]",Ha="[object Int8Array]",qa="[object Int16Array]",Wa="[object Int32Array]",Xa="[object Uint8Array]",Ka="[object Uint8ClampedArray]",Ja="[object Uint16Array]",Ya="[object Uint32Array]",k={};k[za]=k[Ga]=k[Ha]=k[qa]=k[Wa]=k[Xa]=k[Ka]=k[Ja]=k[Ya]=!0,k[Ra]=k[Aa]=k[Ba]=k[wa]=k[ja]=k[Oa]=k[Da]=k[Ia]=k[Ma]=k[La]=k[Fa]=k[Na]=k[Va]=k[Ua]=k[$a]=!1;function Za(r){return fe(r)&&Et(r.length)&&!!k[me(r)]}function Qa(r){return function(e){return r(e)}}var Qr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,xe=Qr&&typeof module=="object"&&module&&!module.nodeType&&module,ec=xe&&xe.exports===Qr,Pt=ec&&Lr.process,ei=function(){try{var r=xe&&xe.require&&xe.require("util").types;return r||Pt&&Pt.binding&&Pt.binding("util")}catch{}}(),ti=ei&&ei.isTypedArray,ri=ti?Qa(ti):Za,tc=Object.prototype,rc=tc.hasOwnProperty;function ic(r,e){var t=F(r),i=!t&&Kr(r),s=!t&&!i&&kt(r),n=!t&&!i&&!s&&ri(r),a=t||i||s||n,o=a?Sa(r.length,String):[],u=o.length;for(var d in r)rc.call(r,d)&&!(a&&(d=="length"||s&&(d=="offset"||d=="parent")||n&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||Hr(d,u)))&&o.push(d);return o}function sc(r,e){return function(t){return r(e(t))}}var nc=sc(Object.keys,Object),oc=Object.prototype,ac=oc.hasOwnProperty;function cc(r){if(!ya(r))return nc(r);var e=[];for(var t in Object(r))ac.call(r,t)&&t!="constructor"&&e.push(t);return e}function Re(r){return bt(r)?ic(r):cc(r)}var dc=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,uc=/^\w*$/;function xt(r,e){if(F(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||je(r)?!0:uc.test(r)||!dc.test(r)||e!=null&&r in Object(e)}var Ae=_e(Object,"create");function hc(){this.__data__=Ae?Ae(null):{},this.size=0}function pc(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var lc="__lodash_hash_undefined__",mc=Object.prototype,fc=mc.hasOwnProperty;function _c(r){var e=this.__data__;if(Ae){var t=e[r];return t===lc?void 0:t}return fc.call(e,r)?e[r]:void 0}var gc=Object.prototype,vc=gc.hasOwnProperty;function Cc(r){var e=this.__data__;return Ae?e[r]!==void 0:vc.call(e,r)}var yc="__lodash_hash_undefined__";function Sc(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=Ae&&e===void 0?yc:e,this}function ce(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}ce.prototype.clear=hc,ce.prototype.delete=pc,ce.prototype.get=_c,ce.prototype.has=Cc,ce.prototype.set=Sc;function Tc(){this.__data__=[],this.size=0}function ze(r,e){for(var t=r.length;t--;)if(qr(r[t][0],e))return t;return-1}var Ec=Array.prototype,bc=Ec.splice;function kc(r){var e=this.__data__,t=ze(e,r);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():bc.call(e,t,1),--this.size,!0}function Pc(r){var e=this.__data__,t=ze(e,r);return t<0?void 0:e[t][1]}function xc(r){return ze(this.__data__,r)>-1}function Rc(r,e){var t=this.__data__,i=ze(t,r);return i<0?(++this.size,t.push([r,e])):t[i][1]=e,this}function K(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}K.prototype.clear=Tc,K.prototype.delete=kc,K.prototype.get=Pc,K.prototype.has=xc,K.prototype.set=Rc;var we=_e(X,"Map");function Ac(){this.size=0,this.__data__={hash:new ce,map:new(we||K),string:new ce}}function wc(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Ge(r,e){var t=r.__data__;return wc(e)?t[typeof e=="string"?"string":"hash"]:t.map}function Oc(r){var e=Ge(this,r).delete(r);return this.size-=e?1:0,e}function Dc(r){return Ge(this,r).get(r)}function Ic(r){return Ge(this,r).has(r)}function Mc(r,e){var t=Ge(this,r),i=t.size;return t.set(r,e),this.size+=t.size==i?0:1,this}function J(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}J.prototype.clear=Ac,J.prototype.delete=Oc,J.prototype.get=Dc,J.prototype.has=Ic,J.prototype.set=Mc;var Lc="Expected a function";function Rt(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(Lc);var t=function(){var i=arguments,s=e?e.apply(this,i):i[0],n=t.cache;if(n.has(s))return n.get(s);var a=r.apply(this,i);return t.cache=n.set(s,a)||n,a};return t.cache=new(Rt.Cache||J),t}Rt.Cache=J;var Fc=500;function Nc(r){var e=Rt(r,function(i){return t.size===Fc&&t.clear(),i}),t=e.cache;return e}var Vc=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Uc=/\\(\\)?/g,$c=Nc(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(Vc,function(t,i,s,n){e.push(s?n.replace(Uc,"$1"):i||t)}),e});function Bc(r){return r==null?"":Br(r)}function ii(r,e){return F(r)?r:xt(r,e)?[r]:$c(Bc(r))}function He(r){if(typeof r=="string"||je(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function si(r,e){e=ii(e,r);for(var t=0,i=e.length;r!=null&&t<i;)r=r[He(e[t++])];return t&&t==i?r:void 0}function jc(r,e,t){var i=r==null?void 0:si(r,e);return i===void 0?t:i}function zc(r,e){for(var t=-1,i=e.length,s=r.length;++t<i;)r[s+t]=e[t];return r}function Gc(){this.__data__=new K,this.size=0}function Hc(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function qc(r){return this.__data__.get(r)}function Wc(r){return this.__data__.has(r)}var Xc=200;function Kc(r,e){var t=this.__data__;if(t instanceof K){var i=t.__data__;if(!we||i.length<Xc-1)return i.push([r,e]),this.size=++t.size,this;t=this.__data__=new J(i)}return t.set(r,e),this.size=t.size,this}function Y(r){var e=this.__data__=new K(r);this.size=e.size}Y.prototype.clear=Gc,Y.prototype.delete=Hc,Y.prototype.get=qc,Y.prototype.has=Wc,Y.prototype.set=Kc;function ni(r,e){for(var t=-1,i=r==null?0:r.length,s=0,n=[];++t<i;){var a=r[t];e(a,t,r)&&(n[s++]=a)}return n}function Jc(){return[]}var Yc=Object.prototype,Zc=Yc.propertyIsEnumerable,oi=Object.getOwnPropertySymbols,Qc=oi?function(r){return r==null?[]:(r=Object(r),ni(oi(r),function(e){return Zc.call(r,e)}))}:Jc;function ed(r,e,t){var i=e(r);return F(r)?i:zc(i,t(r))}function ai(r){return ed(r,Re,Qc)}var At=_e(X,"DataView"),wt=_e(X,"Promise"),Ot=_e(X,"Set"),ci="[object Map]",td="[object Object]",di="[object Promise]",ui="[object Set]",hi="[object WeakMap]",pi="[object DataView]",rd=ae(At),id=ae(we),sd=ae(wt),nd=ae(Ot),od=ae(Tt),re=me;(At&&re(new At(new ArrayBuffer(1)))!=pi||we&&re(new we)!=ci||wt&&re(wt.resolve())!=di||Ot&&re(new Ot)!=ui||Tt&&re(new Tt)!=hi)&&(re=function(r){var e=me(r),t=e==td?r.constructor:void 0,i=t?ae(t):"";if(i)switch(i){case rd:return pi;case id:return ci;case sd:return di;case nd:return ui;case od:return hi}return e});var li=X.Uint8Array,ad="__lodash_hash_undefined__";function cd(r){return this.__data__.set(r,ad),this}function dd(r){return this.__data__.has(r)}function qe(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new J;++e<t;)this.add(r[e])}qe.prototype.add=qe.prototype.push=cd,qe.prototype.has=dd;function ud(r,e){for(var t=-1,i=r==null?0:r.length;++t<i;)if(e(r[t],t,r))return!0;return!1}function hd(r,e){return r.has(e)}var pd=1,ld=2;function mi(r,e,t,i,s,n){var a=t&pd,o=r.length,u=e.length;if(o!=u&&!(a&&u>o))return!1;var d=n.get(r),c=n.get(e);if(d&&c)return d==e&&c==r;var h=-1,p=!0,l=t&ld?new qe:void 0;for(n.set(r,e),n.set(e,r);++h<o;){var f=r[h],g=e[h];if(i)var _=a?i(g,f,h,e,r,n):i(f,g,h,r,e,n);if(_!==void 0){if(_)continue;p=!1;break}if(l){if(!ud(e,function(T,b){if(!hd(l,b)&&(f===T||s(f,T,t,i,n)))return l.push(b)})){p=!1;break}}else if(!(f===g||s(f,g,t,i,n))){p=!1;break}}return n.delete(r),n.delete(e),p}function md(r){var e=-1,t=Array(r.size);return r.forEach(function(i,s){t[++e]=[s,i]}),t}function fd(r){var e=-1,t=Array(r.size);return r.forEach(function(i){t[++e]=i}),t}var _d=1,gd=2,vd="[object Boolean]",Cd="[object Date]",yd="[object Error]",Sd="[object Map]",Td="[object Number]",Ed="[object RegExp]",bd="[object Set]",kd="[object String]",Pd="[object Symbol]",xd="[object ArrayBuffer]",Rd="[object DataView]",fi=te?te.prototype:void 0,Dt=fi?fi.valueOf:void 0;function Ad(r,e,t,i,s,n,a){switch(t){case Rd:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case xd:return!(r.byteLength!=e.byteLength||!n(new li(r),new li(e)));case vd:case Cd:case Td:return qr(+r,+e);case yd:return r.name==e.name&&r.message==e.message;case Ed:case kd:return r==e+"";case Sd:var o=md;case bd:var u=i&_d;if(o||(o=fd),r.size!=e.size&&!u)return!1;var d=a.get(r);if(d)return d==e;i|=gd,a.set(r,e);var c=mi(o(r),o(e),i,s,n,a);return a.delete(r),c;case Pd:if(Dt)return Dt.call(r)==Dt.call(e)}return!1}var wd=1,Od=Object.prototype,Dd=Od.hasOwnProperty;function Id(r,e,t,i,s,n){var a=t&wd,o=ai(r),u=o.length,d=ai(e),c=d.length;if(u!=c&&!a)return!1;for(var h=u;h--;){var p=o[h];if(!(a?p in e:Dd.call(e,p)))return!1}var l=n.get(r),f=n.get(e);if(l&&f)return l==e&&f==r;var g=!0;n.set(r,e),n.set(e,r);for(var _=a;++h<u;){p=o[h];var T=r[p],b=e[p];if(i)var v=a?i(b,T,p,e,r,n):i(T,b,p,r,e,n);if(!(v===void 0?T===b||s(T,b,t,i,n):v)){g=!1;break}_||(_=p=="constructor")}if(g&&!_){var j=r.constructor,R=e.constructor;j!=R&&"constructor"in r&&"constructor"in e&&!(typeof j=="function"&&j instanceof j&&typeof R=="function"&&R instanceof R)&&(g=!1)}return n.delete(r),n.delete(e),g}var Md=1,_i="[object Arguments]",gi="[object Array]",We="[object Object]",Ld=Object.prototype,vi=Ld.hasOwnProperty;function Fd(r,e,t,i,s,n){var a=F(r),o=F(e),u=a?gi:re(r),d=o?gi:re(e);u=u==_i?We:u,d=d==_i?We:d;var c=u==We,h=d==We,p=u==d;if(p&&kt(r)){if(!kt(e))return!1;a=!0,c=!1}if(p&&!c)return n||(n=new Y),a||ri(r)?mi(r,e,t,i,s,n):Ad(r,e,u,t,i,s,n);if(!(t&Md)){var l=c&&vi.call(r,"__wrapped__"),f=h&&vi.call(e,"__wrapped__");if(l||f){var g=l?r.value():r,_=f?e.value():e;return n||(n=new Y),s(g,_,t,i,n)}}return p?(n||(n=new Y),Id(r,e,t,i,s,n)):!1}function It(r,e,t,i,s){return r===e?!0:r==null||e==null||!fe(r)&&!fe(e)?r!==r&&e!==e:Fd(r,e,t,i,It,s)}var Nd=1,Vd=2;function Ud(r,e,t,i){var s=t.length,n=s;if(r==null)return!n;for(r=Object(r);s--;){var a=t[s];if(a[2]?a[1]!==r[a[0]]:!(a[0]in r))return!1}for(;++s<n;){a=t[s];var o=a[0],u=r[o],d=a[1];if(a[2]){if(u===void 0&&!(o in r))return!1}else{var c=new Y,h;if(!(h===void 0?It(d,u,Nd|Vd,i,c):h))return!1}}return!0}function Ci(r){return r===r&&!Pe(r)}function $d(r){for(var e=Re(r),t=e.length;t--;){var i=e[t],s=r[i];e[t]=[i,s,Ci(s)]}return e}function yi(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function Bd(r){var e=$d(r);return e.length==1&&e[0][2]?yi(e[0][0],e[0][1]):function(t){return t===r||Ud(t,r,e)}}function jd(r,e){return r!=null&&e in Object(r)}function zd(r,e,t){e=ii(e,r);for(var i=-1,s=e.length,n=!1;++i<s;){var a=He(e[i]);if(!(n=r!=null&&t(r,a)))break;r=r[a]}return n||++i!=s?n:(s=r==null?0:r.length,!!s&&Et(s)&&Hr(a,s)&&(F(r)||Kr(r)))}function Gd(r,e){return r!=null&&zd(r,e,jd)}var Hd=1,qd=2;function Wd(r,e){return xt(r)&&Ci(e)?yi(He(r),e):function(t){var i=jc(t,r);return i===void 0&&i===e?Gd(t,r):It(e,i,Hd|qd)}}function Xd(r){return function(e){return e==null?void 0:e[r]}}function Kd(r){return function(e){return si(e,r)}}function Jd(r){return xt(r)?Xd(He(r)):Kd(r)}function Mt(r){return typeof r=="function"?r:r==null?Zo:typeof r=="object"?F(r)?Wd(r[0],r[1]):Bd(r):Jd(r)}function Yd(r){return function(e,t,i){for(var s=-1,n=Object(e),a=i(e),o=a.length;o--;){var u=a[++s];if(t(n[u],u,n)===!1)break}return e}}var Zd=Yd();function Qd(r,e){return r&&Zd(r,e,Re)}function eu(r,e){return function(t,i){if(t==null)return t;if(!bt(t))return r(t,i);for(var s=t.length,n=-1,a=Object(t);++n<s&&i(a[n],n,a)!==!1;);return t}}var tu=eu(Qd);function ru(r,e){var t=[];return tu(r,function(i,s,n){e(i,s,n)&&t.push(i)}),t}function Si(r,e){var t=F(r)?ni:ru;return t(r,Mt(e))}function iu(r){return function(e,t,i){var s=Object(e);if(!bt(e)){var n=Mt(t);e=Re(e),t=function(o){return n(s[o],o,s)}}var a=r(e,t,i);return a>-1?s[n?e[a]:a]:void 0}}var su=Math.max;function nu(r,e,t){var i=r==null?0:r.length;if(!i)return-1;var s=t==null?0:Yo(t);return s<0&&(s=su(i+s,0)),fa(r,Mt(e),s)}var Oe=iu(nu);function ou(r,e){return Vr(e,function(t){return r[t]})}function ge(r){return r==null?[]:ou(r,Re(r))}function au(r){return r==null}class cu extends Be{constructor(e){super({type:S.Microphone,stream:e}),this._trackMap.audio=e.track()}get source(){return this._source}get mixerNode(){return this.source.node()}bindTrackEnd(e){this.source.on(I.ENDED,e)}destroy(){this.source.destroy()}}class du extends le{constructor(e){super({type:S.VideoFile,stream:e});const t=Oe(e,s=>s.kind===E.VIDEO),i=Oe(e,s=>s.kind===E.AUDIO);this._videoStream=t,this._audioStream=i,this._trackMap.video=t==null?void 0:t.track(),this._trackMap.audio=i==null?void 0:i.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(I.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 uu extends le{constructor(e){super({type:S.Screen,stream:e});const t=Oe(e,s=>s.kind===E.VIDEO),i=Oe(e,s=>s.kind===E.AUDIO);this._videoStream=t,this._audioStream=i,this._trackMap.video=t==null?void 0:t.track(),this._trackMap.audio=i==null?void 0:i.track(),t&&(this._height=t==null?void 0:t.height(),this._width=t==null?void 0:t.width(),this.bindTrackSizeChangeEvent(t))}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(I.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 hu extends Be{constructor(e){super({type:S.AudioFile,stream:e});const t=Oe(e,i=>i.kind===E.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(I.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}class pu extends le{constructor(e){super({type:S.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(I.ENDED,e)}destroy(){this.source.destroy()}}class lu extends le{constructor(e){super({type:S.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(I.ENDED,e)}destroy(){this.source.destroy()}}class mu extends Be{constructor(e){super({type:S.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(I.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}const fu=["user","environment"];var N=(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))(N||{});class De extends Error{constructor(e,t,i){super(),this.code=e,this.message=t,i&&(this.ext=i)}}function ve(r,e,t){const i=st.Landscape;if(e==="video"){const u=(i===st.Landscape?ir:sr)[r],[d,c,h,p]=u.split("x").map(l=>Number(l));return{width:d,height:c,frameRate:h,bitrate:p*1e3}}const s=nr[r],[n,a]=s.split("x").map(o=>Number(o));return{sampleRate:n,bitrate:a*1e3}}class _u extends Q{constructor(){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:e,height:t,frameRate:i}=ve(ar,"video"),{sampleRate:s}=ve(cr,"audio");this._videoConstraints={width:e,height:t,frameRate:i},this._audioConstraints={sampleRate:s,enableAutoGainControl:!0,enableNoiseSuppression:!0,enableEchoCancellation:!0}}_notifyCaptured(e){this.emit(z.DeviceCaptured,e)}_notifyStopCapture(e){this.emit(z.DeviceStopCapture,e)}_bindStreamEvent(e){e.bindTrackEnd(()=>{this.emit(z.Interrupted,e),this.stopCapture({streamId:e.id,type:e.type})})}_handleError(e,t){const i=new De(t,e.message);this.emit(z.Error,i)}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){return eo(e?[e]:["audioinput","videoinput"])}async getMicrophones(){return this.getDevicesList("audioinput")}async getCameras(){return this.getDevicesList("videoinput")}stopCapture({streamId:e,type:t}){let i;switch(t){case S.Camera:i="_cameraStreams";break;case S.Screen:i="_screenStreams";break;case S.VideoFile:i="_videoFileStreams";break;case S.Microphone:i="_microphoneStreams";break;case S.AudioFile:i="_audioFileStreams";break;case S.Image:i="_imageStreams";break;case S.CustomVideo:i="_customVideoStreams";break;case S.CustomAudio:i="_customAudioStreams";break}if(i){let s=[];if(e){const n=this[i][e];s.push(n)}else s=ge(this[i]);s.forEach(n=>{this._notifyStopCapture(n),n.destroy(),delete this[i][n.id]})}}async startCameraCapture(e){let t={};fu.includes(e)?t={facingMode:e}:t={deviceId:e};try{const i=await to({...t,...this._videoConstraints}),s=new Ro(i);return this._cameraStreams[s.id]=s,this._notifyCaptured(s),this._bindStreamEvent(s),s.id}catch(i){throw this._handleError(i,N.OPEN_CAMERA_FAILED),i}}async startMicrophoneCapture(e){try{const t=await io({...this._audioConstraints,deviceId:e}),i=new cu(t);return this._microphoneStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,N.OPEN_MICROPHONE_FAILED),t}}async startScreenCapture(e){try{const t=await so({audio:e,video:this._videoConstraints}),i=new uu(t);return this._screenStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,N.OPEN_SCREEN_FAILED),t}}async startVideoFileCapture(e){try{const t=await xr({url:e,video:!0,audio:!0,loop:!0}),i=new du(t);return this._videoFileStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,N.VIDEO_FILE_CAPTURE_FAILED),t}}async startAudioFileCapture(e){try{const t=await xr({url:e,video:!1,audio:!0,loop:!0}),i=new hu(t);return this._audioFileStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,N.AUDIO_FILE_CAPTURE_FAILED),t}}async startImageCapture(e){try{const t=await ro({url:e,width:0,height:0,frameRate:30}),i=new pu(t);return this._imageStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}catch(t){throw this._handleError(t,N.IMAGE_FILE_CAPTURE_FAILED),t}}startCustomVideoCapture(e){const t=oo(e);if(t){const i=new lu(t);return this._customVideoStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}}startCustomAudioCapture(e){const t=ao(e);if(t){const i=new mu(t);return this._customAudioStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}}async startVolumeDetect(e){const t=this.getStreamById(e);if(t)try{await t.startVolumeDetect()}catch(i){this._handleError(i,N.VOLUME_DETECT_FAILED)}}stopVolumeDetect(e){const t=this.getStreamById(e);t&&t.stopVolumeDetect()}getDefaultVideoStream(){return ge(this._cameraStreams)[0]||ge(this._screenStreams)[0]||ge(this._videoFileStreams)[0]}getDefaultAudioStream(){return ge(this._microphoneStreams)[0]||ge(this._audioFileStreams)[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(S).forEach(e=>{this.stopCapture({type:e})})}}let de=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 Lt{constructor({streamManagerController:e,composedStream:t,streamComposeController:i}){this._streamManagerController=e,this._composedStream=t,this._streamComposeController=i,this._active=!1,this.bindStreamManagerControllerEvent()}bindStreamManagerControllerEvent(){this._streamManagerController.on(z.DeviceCaptured,e=>{this._active&&this.onStreamCapture(e)}),this._streamManagerController.on(z.DeviceStopCapture,e=>{this._active&&this.onStreamStopCapture(e)})}getComposedStream(){return this._composedStream}enable(){this._active=!0}disable(){this._active=!1}}const Ti=new de("SingleComposer");class gu extends Lt{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:i}){var s,n;if(this._active)try{await((n=(s=this._composedStream.videoStream)==null?void 0:s.videoTrack)==null?void 0:n.applyConstraints({width:{min:e,ideal:e},height:{min:t,ideal:t},frameRate:{min:i,ideal:i}}))}catch(a){Ti.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(i=>{this._streamComposeController.removeAudioStream(i.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 i=this._streamManagerController.getDefaultVideoStream();i?this._handleVideoStreamCapture(i):Ti.error("all video stream stop capture")}}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class vu extends Q{constructor(e,{width:t,height:i,x:s,y:n,zOrder:a,keepRatio:o,mirrorType:u}){super(),this._rect={x:0,y:0,width:0,height:0,zOrder:0},this._isHidden=!1,this._paintSize={width:0,height:0},this._rect.width=t??e.width,this._rect.height=i??e.height,this._rect.x=s??0,this._rect.y=n??0,this._rect.zOrder=a??0,this._rect.sourceHeight=e.height,this._rect.sourceWidth=e.width,this._rect.keepRatio=o??!1,this._rect.mirrorType=u,this._stream=e,this._bindVideoTrackSizeChange()}_getPaintSize({elementWidth:e,elementHeight:t}){const i=this._rect.width,s=this._rect.height;if(i===0&&s===0)return{width:0,height:0};if(i===0)return{height:s,width:e*(s/t)};if(s===0)return{width:i,height:t*(i/e)};const n=e/t,a=i/s;let o=i,u=s;return n>a?(o=i,u=2*Math.round(i/n/2)):n<a&&(o=2*Math.round(s*n/2),u=s),{width:o,height:u}}_bindVideoTrackSizeChange(){this._stream.on(it.SizeChange,({width:e,height:t})=>{this.setBaseProps("sourceWidth",e),this.setBaseProps("sourceHeight",t)})}getViewNode(){var s;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=(s=this._stream.viewNode)==null?void 0:s.size(e.width,e.height);let i;return this._rect.mirrorType!==void 0&&this._rect.mirrorType!==rr.None?i=t==null?void 0:t.mirror(this._rect.mirrorType):i=t,i=i==null?void 0:i.position(this._rect.x,this._rect.y),i}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 i=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}i&&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 Ei extends le{constructor(e){super({type:S.MixVideo,stream:e}),this._trackMap.video=e}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 Cu=Object.defineProperty,yu=Object.getOwnPropertyDescriptor,Ie=(r,e,t,i)=>{for(var s=yu(e,t),n=r.length-1,a;n>=0;n--)(a=r[n])&&(s=a(e,t,s)||s);return s&&Cu(e,t,s),s};const bi=new de("composition-composer");function Me(r,e,t){const i=t.value;return t.value=function(...s){return this._active||bi.error("composer is not active"),i.apply(this,s)},t}class Ce extends Lt{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new Eo}onStreamCapture(e){}onStreamStopCapture(e){e&&e.isVideoStream&&this.removeVideoStream(e.id)}enable(){super.enable();const e=this._videoMixer.track();this._mixedVideoStream?this._mixedVideoStream.replaceVideoTrack(e):this._mixedVideoStream=new Ei(e),this._composedStream.setVideoStream(this._mixedVideoStream)}disable(){super.disable(),this._videoMixer.stop()}_updateSpriteToMixer(){const e=Si(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,i)=>t.zOrder-i.zOrder),e.on("propsChange",t=>{au(t.zOrder)||(this._sprites=this._sprites.sort((i,s)=>i.zOrder-s.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 i=this._videoMixer.updateFps();this._mixedVideoStream?this._mixedVideoStream.replaceVideoTrack(i):this._mixedVideoStream=new Ei(i),this._composedStream.setVideoStream(this._mixedVideoStream)}}addVideoStream(e,t){if(!e.viewNode){bi.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const i=new vu(e,t);this._addSprite(i)}_updateSingleVideoStream(e){const t=e.streamId;if(!t)return;const i=this._sprites.find(s=>s.stream.id===t);i&&(i.height=e.height,i.width=e.width,i.x=e.x,i.y=e.y,i.zOrder=e.zOrder,i.keepRatio=e.keepRatio??!1,i.mirrorType=e.mirrorType)}updateVideoStream(e){e.forEach(t=>{this._updateSingleVideoStream(t)}),this._updateSpriteToMixer()}removeVideoStream(e){if(!e)return;const t=this._sprites.find(i=>i.stream.id===e);t&&this._removeSprite(t)}muteVideoStream(e){if(e){const t=this._sprites.find(i=>i.stream.id===e);t&&t.hide()}else this._sprites.forEach(t=>{t.hide()});this._updateSpriteToMixer()}unmuteVideoStream(e){if(e){const t=this._sprites.find(i=>i.stream.id===e);t&&t.show()}else this._sprites.forEach(t=>{t.show()});this._updateSpriteToMixer()}setMixerWorkerScript(e){this._videoMixer.setWorkerTimerScriptUrl(e)}}Ie([Me],Ce.prototype,"addVideoStream"),Ie([Me],Ce.prototype,"updateVideoStream"),Ie([Me],Ce.prototype,"removeVideoStream"),Ie([Me],Ce.prototype,"muteVideoStream"),Ie([Me],Ce.prototype,"unmuteVideoStream");class Su extends Q{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 Tu extends Be{constructor(e){super({type:S.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 Eu extends Lt{constructor(e){super(e),this._spriteList=[],this._audioMixer=new uo}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=Si(this._spriteList.map(t=>t.isMute?null:t.getMixerNode()));this._audioMixer.mix(e)}_updateSingleAudioStream(e){const{streamId:t,volume:i}=e,s=this._spriteList.find(n=>n.stream.id===t);s?i!==void 0&&(s.volume=i):console.error("can not find stream"+t)}enable(){super.enable();const e=this._audioMixer.track(),t=new Tu(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}addAudioStream(e,t){const i=new Su(e,t);this._spriteList.push(i),this._updateSpriteToMixer()}removeAudioStream(e){const t=this._spriteList.find(i=>i.stream.id===e);t&&(this._spriteList=this._spriteList.filter(i=>i!==t),this._updateSpriteToMixer())}updateAudioStream(e){e.forEach(t=>{this._updateSingleAudioStream(t)}),this._updateSpriteToMixer()}muteAudioStream(e){if(e){const t=this._spriteList.find(i=>i.stream.id===e);t&&t.mute()}else this._spriteList.forEach(t=>{t.mute()});this._updateSpriteToMixer()}unmuteAudioStream(e){if(e){const t=this._spriteList.find(i=>i.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 bu extends Q{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(ne.VideoStreamChange,e))}setAudioStream(e){var t;((t=this._audioStream)==null?void 0:t.id)!==e.id&&(this._audioStream=e,this.emit(ne.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 ku=new de("streamComposeController");class Pu{constructor(e){this._streamManagerController=e,this._composedStream=new bu,this.singleComposer=new gu({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new Ce({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new Eu({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:i}){this.singleComposer.setVideoQuality({width:e,height:t,frameRate:i}),this.compositionComposer.setMixingConfig({width:e,height:t,frameRate:i})}setMixingConfig(e){this.compositionComposer.setMixingConfig(e)}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){ku.error("can not find video stream"+e.streamId);return}this.compositionComposer.addVideoStream(t,e)}updateVideoStream(e){this.compositionComposer.updateVideoStream(e);const t=e.map(i=>({streamId:i.streamId,volume:i.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)}}class ki{constructor(e){this._hasBindComposedStreamEvent=!1,this._composedStream=e}bindComposedStreamEvent(){this._hasBindComposedStreamEvent||(this._composedStream.on(ne.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.on(ne.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!0)}unbindComposedStreamEvent(){this._hasBindComposedStreamEvent&&(this._composedStream.off(ne.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.off(ne.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!1)}}const ye=new de("PreviewConsumer");class xu extends ki{constructor(e,{streamConsumeController:t}){super(e),this._isPreviewing=!1,this._previewElement=null,this.handleAudioStreamChange=i=>{this.startPreview()},this.handleVideoStreamChange=i=>{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 i=document.createElement("video");i.style.width="100%",i.style.height="100%",i.autoplay=!0,i.playsInline=!0,i.setAttribute("webkit-playsinline",""),i.setAttribute("x5-playsinline",""),this._previewElement=i;const s={video:null,audio:null};i.addEventListener("loadeddata",()=>{const n=i.srcObject.getVideoTracks()[0],a=i.srcObject.getAudioTracks()[0];n&&n!==s.video&&(this._streamConsumeController.emit(A.CaptureFirstVideoFrame),s.video=n),a&&a!==s.audio&&(this._streamConsumeController.emit(A.CaptureFirstAudioFrame),s.audio=a)}),t.appendChild(i)}startPreview(){if(ye.log("startPreview"),!this._previewElement){ye.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(i=>{this._streamConsumeController.emit(A.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 i=e.srcObject||new MediaStream;i.getTracks().find(s=>s.id===t.id)||(t.kind==="audio"&&i.getTracks().forEach(s=>{s.kind==="audio"&&(ye.log(`remove preview track, ${s.label}, readyState=${s.readyState}`),i.removeTrack(s))}),t.kind==="video"&&i.getTracks().forEach(s=>{s.kind==="video"&&(i.removeTrack(s),ye.log(`remove preview track, ${s.label}, readyState=${s.readyState}`))}),i.addTrack(t),e.srcObject?e.load():e.srcObject=i)}_removeTrack(e,t){if(!e)return;const i=e.srcObject;i&&(i.getTracks().forEach(s=>{(s.id===(t==null?void 0:t.id)||s.readyState==="ended")&&(ye.log(`remove preview track ${s.label}`),i.removeTrack(s))}),i.getTracks().length===0&&(e.srcObject=null,ye.log("set srcObject null")))}getPreviewElement(){if(this.isPreviewing)return this._previewElement}get isPreviewing(){return this._isPreviewing}}var B={},Ft={},Nt={exports:{}},Pi;function Vt(){if(Pi)return Nt.exports;Pi=1;var r=Nt.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(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),Nt.exports}var xi;function Ru(){return xi||(xi=1,function(r){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,u,d,c){if(c&&!d)u[c]=e(o[1]);else for(var h=0;h<d.length;h+=1)o[h+1]!=null&&(u[d[h]]=e(o[h+1]))},i=function(o,u,d){var c=o.name&&o.names;o.push&&!u[o.push]?u[o.push]=[]:c&&!u[o.name]&&(u[o.name]={});var h=o.push?{}:c?u[o.name]:u;t(d.match(o.reg),h,o.names,o.name),o.push&&u[o.push].push(h)},s=Vt(),n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);r.parse=function(o){var u={},d=[],c=u;return o.split(/(\r\n|\r|\n)/).filter(n).forEach(function(h){var p=h[0],l=h.slice(2);p==="m"&&(d.push({rtp:[],fmtp:[]}),c=d[d.length-1]);for(var f=0;f<(s[p]||[]).length;f+=1){var g=s[p][f];if(g.reg.test(l))return i(g,c,l)}}),u.media=d,u};var a=function(o,u){var d=u.split(/=(.+)/,2);return d.length===2?o[d[0]]=e(d[1]):d.length===1&&u.length>1&&(o[d[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 u=[],d=o.split(" ").map(e),c=0;c<d.length;c+=3)u.push({component:d[c],ip:d[c+1],port:d[c+2]});return u},r.parseImageAttributes=function(o){return o.split(" ").map(function(u){return u.substring(1,u.length-1).split(",").reduce(a,{})})},r.parseSimulcastStreamList=function(o){return o.split(";").map(function(u){return u.split(",").map(function(d){var c,h=!1;return d[0]!=="~"?c=e(d):(c=e(d.substring(1,d.length)),h=!0),{scid:c,paused:h}})})}}(Ft)),Ft}var Ut,Ri;function Au(){if(Ri)return Ut;Ri=1;var r=Vt(),e=/%[sdv%]/g,t=function(a){var o=1,u=arguments,d=u.length;return a.replace(e,function(c){if(o>=d)return c;var h=u[o];switch(o+=1,c){case"%%":return"%";case"%s":return String(h);case"%d":return Number(h);case"%v":return""}})},i=function(a,o,u){var d=o.format instanceof Function?o.format(o.push?u:u[o.name]):o.format,c=[a+"="+d];if(o.names)for(var h=0;h<o.names.length;h+=1){var p=o.names[h];o.name?c.push(u[o.name][p]):c.push(u[o.names[h]])}else c.push(u[o.name]);return t.apply(null,c)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],n=["i","c","b","a"];return Ut=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 u=o.outerOrder||s,d=o.innerOrder||n,c=[];return u.forEach(function(h){r[h].forEach(function(p){p.name in a&&a[p.name]!=null?c.push(i(h,p,a)):p.push in a&&a[p.push]!=null&&a[p.push].forEach(function(l){c.push(i(h,p,l))})})}),a.media.forEach(function(h){c.push(i("m",r.m[0],h)),d.forEach(function(p){r[p].forEach(function(l){l.name in h&&h[l.name]!=null?c.push(i(p,l,h)):l.push in h&&h[l.push]!=null&&h[l.push].forEach(function(f){c.push(i(p,l,f))})})})}),c.join(`\r
|
|
56
|
+
`,Gu=URL.createObjectURL(new Blob([Nu],{type:"application/javascript"}));class Bu{constructor(){this._audioCtx=null,this._volume=0}get volume(){return this._volume}async start(e,t){if(this._audioCtx)return;const i=new AudioContext;await i.audioWorklet.addModule(t||Gu);const n=new MediaStream;n.addTrack(e);const s=i.createMediaStreamSource(n),a=new AudioWorkletNode(i,"vumeter");a.port.onmessage=o=>{const h=o.data.volume||0;this._volume=Math.min(h*100/2,10)},s.connect(a).connect(i.destination),this._audioCtx=i}stop(){var e;(e=this._audioCtx)==null||e.close(),this._audioCtx=null}}class _r{constructor(){this._volumeDetectScriptUrl=void 0}static get instance(){return this._instance||(this._instance=new _r),this._instance}get volumeDetectScriptUrl(){return this._volumeDetectScriptUrl}set volumeDetectScriptUrl(e){this._volumeDetectScriptUrl=e}}class ns extends Ge{constructor(e){super(),this._width=0,this._height=0,this._mediaStream=null,this._nextStream=null,this._trackMap={},this.type=e.type,this.id=Uu(),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[N.Camera,N.Screen,N.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 Bu),await this._volumeDetector.start(this.audioTrack,_r.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 ns{get isVideoStream(){return!0}get isAudioStream(){return!1}bindTrackSizeChangeEvent(e){e.on(Q.SIZE_CHANGE,({width:t,height:i})=>{this._width=t,this._height=i,this.emit(Dn.SizeChange,{width:t,height:i})})}}class gr extends ns{get isVideoStream(){return!1}get isAudioStream(){return!0}}class Vu extends lt{constructor(e){super({type:N.Camera,stream:e}),this._trackMap.video=e.track(),this._width=e.width(),this._height=e.height(),this.bindTrackSizeChangeEvent(e)}get source(){return this._source}get viewNode(){return this.source.node()}get mixerNode(){return null}bindTrackEnd(e){this.source.on(Q.ENDED,e)}destroy(){this.source.destroy()}}var ss=typeof global=="object"&&global&&global.Object===Object&&global,Fu=typeof self=="object"&&self&&self.Object===Object&&self,Ae=ss||Fu||Function("return this")(),Ve=Ae.Symbol,os=Object.prototype,ju=os.hasOwnProperty,Hu=os.toString,Ot=Ve?Ve.toStringTag:void 0;function $u(r){var e=ju.call(r,Ot),t=r[Ot];try{r[Ot]=void 0;var i=!0}catch{}var n=Hu.call(r);return i&&(e?r[Ot]=t:delete r[Ot]),n}var Ku=Object.prototype,qu=Ku.toString;function Wu(r){return qu.call(r)}var Ju="[object Null]",Zu="[object Undefined]",as=Ve?Ve.toStringTag:void 0;function pt(r){return r==null?r===void 0?Zu:Ju:as&&as in Object(r)?$u(r):Wu(r)}function ft(r){return r!=null&&typeof r=="object"}var Xu="[object Symbol]";function vr(r){return typeof r=="symbol"||ft(r)&&pt(r)==Xu}function cs(r,e){for(var t=-1,i=r==null?0:r.length,n=Array(i);++t<i;)n[t]=e(r[t],t,r);return n}var $=Array.isArray,us=Ve?Ve.prototype:void 0,hs=us?us.toString:void 0;function ds(r){if(typeof r=="string")return r;if($(r))return cs(r,ds)+"";if(vr(r))return hs?hs.call(r):"";var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}var Yu=/\s/;function Qu(r){for(var e=r.length;e--&&Yu.test(r.charAt(e)););return e}var eh=/^\s+/;function th(r){return r&&r.slice(0,Qu(r)+1).replace(eh,"")}function Mt(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var ls=NaN,rh=/^[-+]0x[0-9a-f]+$/i,ih=/^0b[01]+$/i,nh=/^0o[0-7]+$/i,sh=parseInt;function oh(r){if(typeof r=="number")return r;if(vr(r))return ls;if(Mt(r)){var e=typeof r.valueOf=="function"?r.valueOf():r;r=Mt(e)?e+"":e}if(typeof r!="string")return r===0?r:+r;r=th(r);var t=ih.test(r);return t||nh.test(r)?sh(r.slice(2),t?2:8):rh.test(r)?ls:+r}var ah=1/0,ch=17976931348623157e292;function uh(r){if(!r)return r===0?r:0;if(r=oh(r),r===ah||r===-1/0){var e=r<0?-1:1;return e*ch}return r===r?r:0}function hh(r){var e=uh(r),t=e%1;return e===e?t?e-t:e:0}function dh(r){return r}var lh="[object AsyncFunction]",ph="[object Function]",fh="[object GeneratorFunction]",mh="[object Proxy]";function ps(r){if(!Mt(r))return!1;var e=pt(r);return e==ph||e==fh||e==lh||e==mh}var fi=Ae["__core-js_shared__"],fs=function(){var r=/[^.]+$/.exec(fi&&fi.keys&&fi.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function _h(r){return!!fs&&fs in r}var gh=Function.prototype,vh=gh.toString;function et(r){if(r!=null){try{return vh.call(r)}catch{}try{return r+""}catch{}}return""}var yh=/[\\^$.*+?()[\]{}|]/g,bh=/^\[object .+?Constructor\]$/,Sh=Function.prototype,Eh=Object.prototype,Ch=Sh.toString,wh=Eh.hasOwnProperty,Th=RegExp("^"+Ch.call(wh).replace(yh,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function zh(r){if(!Mt(r)||_h(r))return!1;var e=ps(r)?Th:bh;return e.test(et(r))}function kh(r,e){return r==null?void 0:r[e]}function mt(r,e){var t=kh(r,e);return zh(t)?t:void 0}var mi=mt(Ae,"WeakMap");function Ah(r,e,t,i){for(var n=r.length,s=t+-1;++s<n;)if(e(r[s],s,r))return s;return-1}var Rh=9007199254740991,Dh=/^(?:0|[1-9]\d*)$/;function ms(r,e){var t=typeof r;return e=e??Rh,!!e&&(t=="number"||t!="symbol"&&Dh.test(r))&&r>-1&&r%1==0&&r<e}function _s(r,e){return r===e||r!==r&&e!==e}var xh=9007199254740991;function _i(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=xh}function yr(r){return r!=null&&_i(r.length)&&!ps(r)}var Oh=Object.prototype;function gs(r){var e=r&&r.constructor,t=typeof e=="function"&&e.prototype||Oh;return r===t}function Mh(r,e){for(var t=-1,i=Array(r);++t<r;)i[t]=e(t);return i}var Ih="[object Arguments]";function vs(r){return ft(r)&&pt(r)==Ih}var ys=Object.prototype,Ph=ys.hasOwnProperty,Lh=ys.propertyIsEnumerable,gi=vs(function(){return arguments}())?vs:function(r){return ft(r)&&Ph.call(r,"callee")&&!Lh.call(r,"callee")};function Uh(){return!1}var bs=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ss=bs&&typeof module=="object"&&module&&!module.nodeType&&module,Nh=Ss&&Ss.exports===bs,Es=Nh?Ae.Buffer:void 0,Gh=Es?Es.isBuffer:void 0,br=Gh||Uh,Bh="[object Arguments]",Vh="[object Array]",Fh="[object Boolean]",jh="[object Date]",Hh="[object Error]",$h="[object Function]",Kh="[object Map]",qh="[object Number]",Wh="[object Object]",Jh="[object RegExp]",Zh="[object Set]",Xh="[object String]",Yh="[object WeakMap]",Qh="[object ArrayBuffer]",ed="[object DataView]",td="[object Float32Array]",rd="[object Float64Array]",id="[object Int8Array]",nd="[object Int16Array]",sd="[object Int32Array]",od="[object Uint8Array]",ad="[object Uint8ClampedArray]",cd="[object Uint16Array]",ud="[object Uint32Array]",V={};V[td]=V[rd]=V[id]=V[nd]=V[sd]=V[od]=V[ad]=V[cd]=V[ud]=!0,V[Bh]=V[Vh]=V[Qh]=V[Fh]=V[ed]=V[jh]=V[Hh]=V[$h]=V[Kh]=V[qh]=V[Wh]=V[Jh]=V[Zh]=V[Xh]=V[Yh]=!1;function hd(r){return ft(r)&&_i(r.length)&&!!V[pt(r)]}function dd(r){return function(e){return r(e)}}var Cs=typeof exports=="object"&&exports&&!exports.nodeType&&exports,It=Cs&&typeof module=="object"&&module&&!module.nodeType&&module,ld=It&&It.exports===Cs,vi=ld&&ss.process,ws=function(){try{var r=It&&It.require&&It.require("util").types;return r||vi&&vi.binding&&vi.binding("util")}catch{}}(),Ts=ws&&ws.isTypedArray,yi=Ts?dd(Ts):hd,pd=Object.prototype,fd=pd.hasOwnProperty;function md(r,e){var t=$(r),i=!t&&gi(r),n=!t&&!i&&br(r),s=!t&&!i&&!n&&yi(r),a=t||i||n||s,o=a?Mh(r.length,String):[],h=o.length;for(var c in r)fd.call(r,c)&&!(a&&(c=="length"||n&&(c=="offset"||c=="parent")||s&&(c=="buffer"||c=="byteLength"||c=="byteOffset")||ms(c,h)))&&o.push(c);return o}function _d(r,e){return function(t){return r(e(t))}}var gd=_d(Object.keys,Object),vd=Object.prototype,yd=vd.hasOwnProperty;function zs(r){if(!gs(r))return gd(r);var e=[];for(var t in Object(r))yd.call(r,t)&&t!="constructor"&&e.push(t);return e}function Pt(r){return yr(r)?md(r):zs(r)}var bd=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Sd=/^\w*$/;function bi(r,e){if($(r))return!1;var t=typeof r;return t=="number"||t=="symbol"||t=="boolean"||r==null||vr(r)?!0:Sd.test(r)||!bd.test(r)||e!=null&&r in Object(e)}var Lt=mt(Object,"create");function Ed(){this.__data__=Lt?Lt(null):{},this.size=0}function Cd(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var wd="__lodash_hash_undefined__",Td=Object.prototype,zd=Td.hasOwnProperty;function kd(r){var e=this.__data__;if(Lt){var t=e[r];return t===wd?void 0:t}return zd.call(e,r)?e[r]:void 0}var Ad=Object.prototype,Rd=Ad.hasOwnProperty;function Dd(r){var e=this.__data__;return Lt?e[r]!==void 0:Rd.call(e,r)}var xd="__lodash_hash_undefined__";function Od(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=Lt&&e===void 0?xd:e,this}function tt(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}tt.prototype.clear=Ed,tt.prototype.delete=Cd,tt.prototype.get=kd,tt.prototype.has=Dd,tt.prototype.set=Od;function Md(){this.__data__=[],this.size=0}function Sr(r,e){for(var t=r.length;t--;)if(_s(r[t][0],e))return t;return-1}var Id=Array.prototype,Pd=Id.splice;function Ld(r){var e=this.__data__,t=Sr(e,r);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():Pd.call(e,t,1),--this.size,!0}function Ud(r){var e=this.__data__,t=Sr(e,r);return t<0?void 0:e[t][1]}function Nd(r){return Sr(this.__data__,r)>-1}function Gd(r,e){var t=this.__data__,i=Sr(t,r);return i<0?(++this.size,t.push([r,e])):t[i][1]=e,this}function Re(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}Re.prototype.clear=Md,Re.prototype.delete=Ld,Re.prototype.get=Ud,Re.prototype.has=Nd,Re.prototype.set=Gd;var Ut=mt(Ae,"Map");function Bd(){this.size=0,this.__data__={hash:new tt,map:new(Ut||Re),string:new tt}}function Vd(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}function Er(r,e){var t=r.__data__;return Vd(e)?t[typeof e=="string"?"string":"hash"]:t.map}function Fd(r){var e=Er(this,r).delete(r);return this.size-=e?1:0,e}function jd(r){return Er(this,r).get(r)}function Hd(r){return Er(this,r).has(r)}function $d(r,e){var t=Er(this,r),i=t.size;return t.set(r,e),this.size+=t.size==i?0:1,this}function De(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}De.prototype.clear=Bd,De.prototype.delete=Fd,De.prototype.get=jd,De.prototype.has=Hd,De.prototype.set=$d;var Kd="Expected a function";function Si(r,e){if(typeof r!="function"||e!=null&&typeof e!="function")throw new TypeError(Kd);var t=function(){var i=arguments,n=e?e.apply(this,i):i[0],s=t.cache;if(s.has(n))return s.get(n);var a=r.apply(this,i);return t.cache=s.set(n,a)||s,a};return t.cache=new(Si.Cache||De),t}Si.Cache=De;var qd=500;function Wd(r){var e=Si(r,function(i){return t.size===qd&&t.clear(),i}),t=e.cache;return e}var Jd=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Zd=/\\(\\)?/g,Xd=Wd(function(r){var e=[];return r.charCodeAt(0)===46&&e.push(""),r.replace(Jd,function(t,i,n,s){e.push(n?s.replace(Zd,"$1"):i||t)}),e});function Yd(r){return r==null?"":ds(r)}function ks(r,e){return $(r)?r:bi(r,e)?[r]:Xd(Yd(r))}function Cr(r){if(typeof r=="string"||vr(r))return r;var e=r+"";return e=="0"&&1/r==-1/0?"-0":e}function As(r,e){e=ks(e,r);for(var t=0,i=e.length;r!=null&&t<i;)r=r[Cr(e[t++])];return t&&t==i?r:void 0}function Qd(r,e,t){var i=r==null?void 0:As(r,e);return i===void 0?t:i}function el(r,e){for(var t=-1,i=e.length,n=r.length;++t<i;)r[n+t]=e[t];return r}function tl(){this.__data__=new Re,this.size=0}function rl(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}function il(r){return this.__data__.get(r)}function nl(r){return this.__data__.has(r)}var sl=200;function ol(r,e){var t=this.__data__;if(t instanceof Re){var i=t.__data__;if(!Ut||i.length<sl-1)return i.push([r,e]),this.size=++t.size,this;t=this.__data__=new De(i)}return t.set(r,e),this.size=t.size,this}function xe(r){var e=this.__data__=new Re(r);this.size=e.size}xe.prototype.clear=tl,xe.prototype.delete=rl,xe.prototype.get=il,xe.prototype.has=nl,xe.prototype.set=ol;function Rs(r,e){for(var t=-1,i=r==null?0:r.length,n=0,s=[];++t<i;){var a=r[t];e(a,t,r)&&(s[n++]=a)}return s}function al(){return[]}var cl=Object.prototype,ul=cl.propertyIsEnumerable,Ds=Object.getOwnPropertySymbols,hl=Ds?function(r){return r==null?[]:(r=Object(r),Rs(Ds(r),function(e){return ul.call(r,e)}))}:al;function dl(r,e,t){var i=e(r);return $(r)?i:el(i,t(r))}function xs(r){return dl(r,Pt,hl)}var Ei=mt(Ae,"DataView"),Ci=mt(Ae,"Promise"),wi=mt(Ae,"Set"),Os="[object Map]",ll="[object Object]",Ms="[object Promise]",Is="[object Set]",Ps="[object WeakMap]",Ls="[object DataView]",pl=et(Ei),fl=et(Ut),ml=et(Ci),_l=et(wi),gl=et(mi),Oe=pt;(Ei&&Oe(new Ei(new ArrayBuffer(1)))!=Ls||Ut&&Oe(new Ut)!=Os||Ci&&Oe(Ci.resolve())!=Ms||wi&&Oe(new wi)!=Is||mi&&Oe(new mi)!=Ps)&&(Oe=function(r){var e=pt(r),t=e==ll?r.constructor:void 0,i=t?et(t):"";if(i)switch(i){case pl:return Ls;case fl:return Os;case ml:return Ms;case _l:return Is;case gl:return Ps}return e});var Us=Ae.Uint8Array,vl="__lodash_hash_undefined__";function yl(r){return this.__data__.set(r,vl),this}function bl(r){return this.__data__.has(r)}function wr(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new De;++e<t;)this.add(r[e])}wr.prototype.add=wr.prototype.push=yl,wr.prototype.has=bl;function Sl(r,e){for(var t=-1,i=r==null?0:r.length;++t<i;)if(e(r[t],t,r))return!0;return!1}function El(r,e){return r.has(e)}var Cl=1,wl=2;function Ns(r,e,t,i,n,s){var a=t&Cl,o=r.length,h=e.length;if(o!=h&&!(a&&h>o))return!1;var c=s.get(r),u=s.get(e);if(c&&u)return c==e&&u==r;var l=-1,d=!0,p=t&wl?new wr:void 0;for(s.set(r,e),s.set(e,r);++l<o;){var f=r[l],v=e[l];if(i)var m=a?i(v,f,l,e,r,s):i(f,v,l,r,e,s);if(m!==void 0){if(m)continue;d=!1;break}if(p){if(!Sl(e,function(E,y){if(!El(p,y)&&(f===E||n(f,E,t,i,s)))return p.push(y)})){d=!1;break}}else if(!(f===v||n(f,v,t,i,s))){d=!1;break}}return s.delete(r),s.delete(e),d}function Tl(r){var e=-1,t=Array(r.size);return r.forEach(function(i,n){t[++e]=[n,i]}),t}function zl(r){var e=-1,t=Array(r.size);return r.forEach(function(i){t[++e]=i}),t}var kl=1,Al=2,Rl="[object Boolean]",Dl="[object Date]",xl="[object Error]",Ol="[object Map]",Ml="[object Number]",Il="[object RegExp]",Pl="[object Set]",Ll="[object String]",Ul="[object Symbol]",Nl="[object ArrayBuffer]",Gl="[object DataView]",Gs=Ve?Ve.prototype:void 0,Ti=Gs?Gs.valueOf:void 0;function Bl(r,e,t,i,n,s,a){switch(t){case Gl:if(r.byteLength!=e.byteLength||r.byteOffset!=e.byteOffset)return!1;r=r.buffer,e=e.buffer;case Nl:return!(r.byteLength!=e.byteLength||!s(new Us(r),new Us(e)));case Rl:case Dl:case Ml:return _s(+r,+e);case xl:return r.name==e.name&&r.message==e.message;case Il:case Ll:return r==e+"";case Ol:var o=Tl;case Pl:var h=i&kl;if(o||(o=zl),r.size!=e.size&&!h)return!1;var c=a.get(r);if(c)return c==e;i|=Al,a.set(r,e);var u=Ns(o(r),o(e),i,n,s,a);return a.delete(r),u;case Ul:if(Ti)return Ti.call(r)==Ti.call(e)}return!1}var Vl=1,Fl=Object.prototype,jl=Fl.hasOwnProperty;function Hl(r,e,t,i,n,s){var a=t&Vl,o=xs(r),h=o.length,c=xs(e),u=c.length;if(h!=u&&!a)return!1;for(var l=h;l--;){var d=o[l];if(!(a?d in e:jl.call(e,d)))return!1}var p=s.get(r),f=s.get(e);if(p&&f)return p==e&&f==r;var v=!0;s.set(r,e),s.set(e,r);for(var m=a;++l<h;){d=o[l];var E=r[d],y=e[d];if(i)var _=a?i(y,E,d,e,r,s):i(E,y,d,r,e,s);if(!(_===void 0?E===y||n(E,y,t,i,s):_)){v=!1;break}m||(m=d=="constructor")}if(v&&!m){var C=r.constructor,z=e.constructor;C!=z&&"constructor"in r&&"constructor"in e&&!(typeof C=="function"&&C instanceof C&&typeof z=="function"&&z instanceof z)&&(v=!1)}return s.delete(r),s.delete(e),v}var $l=1,Bs="[object Arguments]",Vs="[object Array]",Tr="[object Object]",Kl=Object.prototype,Fs=Kl.hasOwnProperty;function ql(r,e,t,i,n,s){var a=$(r),o=$(e),h=a?Vs:Oe(r),c=o?Vs:Oe(e);h=h==Bs?Tr:h,c=c==Bs?Tr:c;var u=h==Tr,l=c==Tr,d=h==c;if(d&&br(r)){if(!br(e))return!1;a=!0,u=!1}if(d&&!u)return s||(s=new xe),a||yi(r)?Ns(r,e,t,i,n,s):Bl(r,e,h,t,i,n,s);if(!(t&$l)){var p=u&&Fs.call(r,"__wrapped__"),f=l&&Fs.call(e,"__wrapped__");if(p||f){var v=p?r.value():r,m=f?e.value():e;return s||(s=new xe),n(v,m,t,i,s)}}return d?(s||(s=new xe),Hl(r,e,t,i,n,s)):!1}function zi(r,e,t,i,n){return r===e?!0:r==null||e==null||!ft(r)&&!ft(e)?r!==r&&e!==e:ql(r,e,t,i,zi,n)}var Wl=1,Jl=2;function Zl(r,e,t,i){var n=t.length,s=n;if(r==null)return!s;for(r=Object(r);n--;){var a=t[n];if(a[2]?a[1]!==r[a[0]]:!(a[0]in r))return!1}for(;++n<s;){a=t[n];var o=a[0],h=r[o],c=a[1];if(a[2]){if(h===void 0&&!(o in r))return!1}else{var u=new xe,l;if(!(l===void 0?zi(c,h,Wl|Jl,i,u):l))return!1}}return!0}function js(r){return r===r&&!Mt(r)}function Xl(r){for(var e=Pt(r),t=e.length;t--;){var i=e[t],n=r[i];e[t]=[i,n,js(n)]}return e}function Hs(r,e){return function(t){return t==null?!1:t[r]===e&&(e!==void 0||r in Object(t))}}function Yl(r){var e=Xl(r);return e.length==1&&e[0][2]?Hs(e[0][0],e[0][1]):function(t){return t===r||Zl(t,r,e)}}function Ql(r,e){return r!=null&&e in Object(r)}function ep(r,e,t){e=ks(e,r);for(var i=-1,n=e.length,s=!1;++i<n;){var a=Cr(e[i]);if(!(s=r!=null&&t(r,a)))break;r=r[a]}return s||++i!=n?s:(n=r==null?0:r.length,!!n&&_i(n)&&ms(a,n)&&($(r)||gi(r)))}function tp(r,e){return r!=null&&ep(r,e,Ql)}var rp=1,ip=2;function np(r,e){return bi(r)&&js(e)?Hs(Cr(r),e):function(t){var i=Qd(t,r);return i===void 0&&i===e?tp(t,r):zi(e,i,rp|ip)}}function sp(r){return function(e){return e==null?void 0:e[r]}}function op(r){return function(e){return As(e,r)}}function ap(r){return bi(r)?sp(Cr(r)):op(r)}function ki(r){return typeof r=="function"?r:r==null?dh:typeof r=="object"?$(r)?np(r[0],r[1]):Yl(r):ap(r)}function cp(r){return function(e,t,i){for(var n=-1,s=Object(e),a=i(e),o=a.length;o--;){var h=a[++n];if(t(s[h],h,s)===!1)break}return e}}var up=cp();function hp(r,e){return r&&up(r,e,Pt)}function dp(r,e){return function(t,i){if(t==null)return t;if(!yr(t))return r(t,i);for(var n=t.length,s=-1,a=Object(t);++s<n&&i(a[s],s,a)!==!1;);return t}}var lp=dp(hp);function pp(r,e){var t=[];return lp(r,function(i,n,s){e(i,n,s)&&t.push(i)}),t}function $s(r,e){var t=$(r)?Rs:pp;return t(r,ki(e))}function fp(r){return function(e,t,i){var n=Object(e);if(!yr(e)){var s=ki(t);e=Pt(e),t=function(o){return s(n[o],o,n)}}var a=r(e,t,i);return a>-1?n[s?e[a]:a]:void 0}}var mp=Math.max;function _p(r,e,t){var i=r==null?0:r.length;if(!i)return-1;var n=t==null?0:hh(t);return n<0&&(n=mp(i+n,0)),Ah(r,ki(e),n)}var Nt=fp(_p);function gp(r,e){return cs(e,function(t){return r[t]})}function Me(r){return r==null?[]:gp(r,Pt(r))}var vp="[object Map]",yp="[object Set]",bp=Object.prototype,Sp=bp.hasOwnProperty;function Ep(r){if(r==null)return!0;if(yr(r)&&($(r)||typeof r=="string"||typeof r.splice=="function"||br(r)||yi(r)||gi(r)))return!r.length;var e=Oe(r);if(e==vp||e==yp)return!r.size;if(gs(r))return!zs(r).length;for(var t in r)if(Sp.call(r,t))return!1;return!0}function Cp(r){return r==null}class wp extends gr{constructor(e){super({type:N.Microphone,stream:e}),this._trackMap.audio=e.track()}get source(){return this._source}get mixerNode(){return this.source.node()}bindTrackEnd(e){this.source.on(Q.ENDED,e)}destroy(){this.source.destroy()}}class Tp extends lt{constructor(e){super({type:N.VideoFile,stream:e});const t=Nt(e,n=>n.kind===B.VIDEO),i=Nt(e,n=>n.kind===B.AUDIO);this._videoStream=t,this._audioStream=i,this._trackMap.video=t==null?void 0:t.track(),this._trackMap.audio=i==null?void 0:i.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(Q.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 zp extends lt{constructor(e){super({type:N.Screen,stream:e});const t=Nt(e,n=>n.kind===B.VIDEO),i=Nt(e,n=>n.kind===B.AUDIO);this._videoStream=t,this._audioStream=i,this._trackMap.video=t==null?void 0:t.track(),this._trackMap.audio=i==null?void 0:i.track(),t&&(this._height=t==null?void 0:t.height(),this._width=t==null?void 0:t.width(),this.bindTrackSizeChangeEvent(t))}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(Q.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 kp extends gr{constructor(e){super({type:N.AudioFile,stream:e});const t=Nt(e,i=>i.kind===B.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(Q.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}class Ap extends lt{constructor(e){super({type:N.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(Q.ENDED,e)}destroy(){this.source.destroy()}}class Rp extends lt{constructor(e){super({type:N.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(Q.ENDED,e)}destroy(){this.source.destroy()}}class Dp extends gr{constructor(e){super({type:N.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(Q.ENDED,e)}destroy(){var e;(e=this._audioStream)==null||e.destroy()}}const xp=["user","environment"],Op=18e4,Mp=1e4,Ks=1e3;var oe=(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))(oe||{});class _t extends Error{constructor(e,t,i){super(),this.code=e,this.message=t,i&&(this.ext=i)}}function gt(r,e,t){const i=Xr.Landscape;if(e==="video"){const h=(i===Xr.Landscape?zn:kn)[r],[c,u,l,d]=h.split("x").map(p=>Number(p));return{width:c,height:u,frameRate:l,bitrate:d*1e3}}const n=An[r],[s,a]=n.split("x").map(o=>Number(o));return{sampleRate:s,bitrate:a*1e3}}var U=function(){return(U=Object.assign||function(r){for(var e,t=1,i=arguments.length;t<i;t++)for(var n in e=arguments[t])Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}).apply(this,arguments)};function Ip(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var i,n,s=t.call(r),a=[];try{for(;(e===void 0||e-- >0)&&!(i=s.next()).done;)a.push(i.value)}catch(o){n={error:o}}finally{try{i&&!i.done&&(t=s.return)&&t.call(s)}finally{if(n)throw n.error}}return a}function rt(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(Ip(arguments[e]));return r}var qs,Pp=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 i=this;e&&t&&typeof t=="function"&&this.on(e,function n(s){t(s),i.off(e,n)})},r.prototype.off=function(e,t){if(e&&this._hooks[e]&&this._hooks[e].length)if(t){var i=this._hooks[e].indexOf(t);i!==-1&&this._hooks[e].splice(i,1)}else this._hooks[e]=[]},r.prototype.emit=function(e,t,i){if(i){if(!e)return;this._cache.indexOf(i)!==-1?this._emit(e,t):(this._hooksCache.hasOwnProperty(i)||(this._hooksCache[i]={}),this._hooksCache[i].hasOwnProperty(e)||(this._hooksCache[i][e]=[]),this._hooksCache[i][e].push(t))}else this._emit(e,t)},r.prototype._emit=function(e,t){e&&this._hooks[e]&&this._hooks[e].length&&rt(this._hooks[e]).forEach(function(i){try{i(t)}catch{}})},r.prototype.set=function(e){e&&this._cache.indexOf(e)===-1&&this._cache.push(e)},r}(),Gt=function(r){return r!=null&&Object.prototype.toString.call(r)=="[object Object]"},zr=function(r){return Array.isArray(r)},Lp=(qs=+Date.now()+Number((""+Math.random()).slice(2,8)),function(){return qs+=1}),K=function(r){return function(e,t,i){if(typeof e=="string"&&typeof i=="number"){var n,s=[];i=i<=25?i:i%25;var a=String.fromCharCode(i+97);n=e.split(a);for(var o=0;o<n.length;o++){var h=parseInt(n[o],i);h=1*h^t;var c=String.fromCharCode(h);s.push(c)}return s.join("")}}(r,64,25)},Ws=function(){return!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)},Ai=function(r){Ws()?window.addEventListener("pagehide",r,!1):window.addEventListener("beforeunload",r,!1)},Up=function(r,e,t){var i=document.createElement("script");i.src=r,i.onerror=function(){t(r)},i.onload=function(){e()},document.getElementsByTagName("head")[0].appendChild(i)},Js=function(){var r=0;return["hidden","msHidden","webkitHidden"].forEach(function(e){document[e]!==void 0&&(r=1)}),r},Np=function(r,e){r===void 0&&(r=function(){}),e===void 0&&(e=1e3);var t,i=Date.now()+e;return t=window.setTimeout(function n(){var s=Date.now()-i;r(),i+=e,t=window.setTimeout(n,Math.max(0,e-s))},e),function(){window.clearTimeout(t)}},Ri=function(r){var e=document.createElement("a");return e.href=r,e},kr=function(r){var e={};try{var t=Ri(r).search;if(!t)return e;(t=t.slice(1)).split("&").forEach(function(i){var n,s,a=i.split("=");a.length&&(n=a[0],s=a[1]);try{e[n]=decodeURIComponent(s===void 0?"":s)}catch{e[n]=s}})}catch{}return e},Zs=function(r){for(var e=0,t=0,i=(r+="").length,n=0;n<i;n++)((e=31*e+r.charCodeAt(t++))>0x7fffffffffff||e<-0x800000000000)&&(e&=0xffffffffffff);return e<0&&(e+=0x7ffffffffffff),e},Di,xi=(function(r,e){var t;t=function(){function i(){for(var s=0,a={};s<arguments.length;s++){var o=arguments[s];for(var h in o)a[h]=o[h]}return a}function n(s){return s.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function s(a){function o(){}function h(u,l,d){if(typeof document<"u"){typeof(d=i({path:"/"},o.defaults,d)).expires=="number"&&(d.expires=new Date(1*new Date+864e5*d.expires)),d.expires=d.expires?d.expires.toUTCString():"";try{var p=JSON.stringify(l);/^[\{\[]/.test(p)&&(l=p)}catch{}l=a.write?a.write(l,u):encodeURIComponent(String(l)).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 f="";for(var v in d)d[v]&&(f+="; "+v,d[v]!==!0&&(f+="="+d[v].split(";")[0]));return document.cookie=u+"="+l+f}}function c(u,l){if(typeof document<"u"){for(var d={},p=document.cookie?document.cookie.split("; "):[],f=0;f<p.length;f++){var v=p[f].split("="),m=v.slice(1).join("=");l||m.charAt(0)!=='"'||(m=m.slice(1,-1));try{var E=n(v[0]);if(m=(a.read||a)(m,E)||n(m),l)try{m=JSON.parse(m)}catch{}if(d[E]=m,u===E)break}catch{}}return u?d[u]:d}}return o.set=h,o.get=function(u){return c(u,!1)},o.getJSON=function(u){return c(u,!0)},o.remove=function(u,l){h(u,"",i(l,{expires:-1}))},o.defaults={},o.withConverter=s,o}(function(){})},r.exports=t()}(Di={exports:{}},Di.exports),Di.exports),Oi=function(r,e){try{return r?xi.get(r):xi.get()}catch{return""}},Mi=function(r,e,t,i){try{var n=i||document.domain,s=+new Date+(t||6048e5);xi.set(r,e,{expires:new Date(s),path:"/",domain:n})}catch{}},Gp=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 Oi(e)},r.prototype.setCookie=function(e,t,i,n){Mi(e,t,i,n)},r}(),Ii,g,Xs={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 Oi(r)},setCookie:function(r,e,t,i){Mi(r,e,t,i)},isSupportLS:function(){try{return localStorage.setItem("_ranger-test-key","hi"),localStorage.getItem("_ranger-test-key"),localStorage.removeItem("_ranger-test-key"),!0}catch{return!1}}()},Bp={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 Oi(r)},setCookie:function(r,e,t,i){Mi(r,e,t,i)},isSupportSession:function(){try{return sessionStorage.setItem("_ranger-test-key","hi"),sessionStorage.getItem("_ranger-test-key"),sessionStorage.removeItem("_ranger-test-key"),!0}catch{return!1}}()},Ie=function(){function r(e,t){this._storage=t&&t==="session"?Bp:!e&&Xs.isSupportLS?Xs:new Gp}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,i,n){this._storage.setCookie(e,t,i,n)},r.prototype.removeItem=function(e){this._storage.removeItem(e)},r}(),Vp=function(){function r(e,t,i){this.appid=e,this.domain=t,this.userAgent=window.navigator.userAgent,this.appVersion=window.navigator.appVersion,this.cookie_expire=i}return r.prototype.init=function(){var e,t=window.navigator.userAgent,i=window.navigator.language,n=document.referrer,s=n?Ri(n).hostname:"",a=kr(window.location.href),o=/Mobile|htc|mini|Android|iP(ad|od|hone)/.test(this.appVersion)?"wap":"web",h=((e=window.navigator.connection)===null||e===void 0?void 0:e.effectiveType)||"";this.utm=function(l,d,p,f){var v=new Ie(!1),m=new Ie(!1,"session"),E=l?"_tea_utm_cache_"+l:"_tea_utm_cache",y=l?"_$utm_from_url_"+l:"_$utm_from_url",_={},C=["tr_shareuser","tr_admaster","tr_param1","tr_param2","tr_param3","tr_param4","$utm_from_url"],z={ad_id:Number(d.ad_id)||void 0,campaign_id:Number(d.campaign_id)||void 0,creative_id:Number(d.creative_id)||void 0,utm_source:d.utm_source,utm_medium:d.utm_medium,utm_campaign:d.utm_campaign,utm_term:d.utm_term,utm_content:d.utm_content,tr_shareuser:d.tr_shareuser,tr_admaster:d.tr_admaster,tr_param1:d.tr_param1,tr_param2:d.tr_param2,tr_param3:d.tr_param3,tr_param4:d.tr_param4};try{var w=!1;for(var O in z)z[O]&&(C.indexOf(O)!==-1?(_.hasOwnProperty("tracer_data")||(_.tracer_data={}),_.tracer_data[O]=z[O]):_[O]=z[O],w=!0);if(w)m.setItem(y,"1"),v.setCookie(E,JSON.stringify(_),f,p);else{var k=v.getCookie(E,p);k&&(_=JSON.parse(k))}m.getItem(y)&&(_.hasOwnProperty("tracer_data")||(_.tracer_data={}),_.tracer_data.$utm_from_url=1)}catch{return z}return _}(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:i,referrer:n,referrer_host:s,network_type:h,utm:this.utm,latest_data:this.last(n,s)}},r.prototype.last=function(e,t){var i="",n="",s="",a=location.hostname,o=!1;if(e&&t&&a!==t){i=e,n=t,o=!0;var h=kr(e);h.keyword&&(s=h.keyword)}return{$latest_referrer:i,$latest_referrer_host:n,$latest_search_keyword:s,isLast:o}},r.prototype.browser=function(){var e,t,i="",n=""+parseFloat(this.appVersion),s=this.userAgent;return s.indexOf("Edge")!==-1||s.indexOf("Edg")!==-1?(i="Microsoft Edge",s.indexOf("Edge")!==-1?(e=s.indexOf("Edge"),n=s.substring(e+5)):(e=s.indexOf("Edg"),n=s.substring(e+4))):(e=s.indexOf("MSIE"))!==-1?(i="Microsoft Internet Explorer",n=s.substring(e+5)):(e=s.indexOf("MetaSr"))!==-1?(i="sougoubrowser",n=s.substring(e+7,e+10)):s.indexOf("MQQBrowser")!==-1||s.indexOf("QQBrowser")!==-1?(i="qqbrowser",s.indexOf("MQQBrowser")!==-1?(e=s.indexOf("MQQBrowser"),n=s.substring(e+11,e+15)):s.indexOf("QQBrowser")!==-1&&(e=s.indexOf("QQBrowser"),n=s.substring(e+10,e+25))):s.indexOf("Chrome")!==-1?(e=s.indexOf("MicroMessenger"))!==-1?(i="weixin",n=s.substring(e+15,e+20)):(e=s.indexOf("360"))!==-1?(i="360browser",n=s.substring(s.indexOf("Chrome")+7)):s.indexOf("baidubrowser")!==-1||s.indexOf("BIDUBrowser")!==-1?(s.indexOf("baidubrowser")!==-1?(e=s.indexOf("baidubrowser"),n=s.substring(e+13,e+16)):s.indexOf("BIDUBrowser")!==-1&&(e=s.indexOf("BIDUBrowser"),n=s.substring(e+12,e+15)),i="baidubrowser"):(e=s.indexOf("xiaomi"))!==-1?s.indexOf("openlanguagexiaomi")!==-1?(i="openlanguage xiaomi",n=s.substring(e+7,e+13)):(i="xiaomi",n=s.substring(e-7,e-1)):(e=s.indexOf("TTWebView"))!==-1?(i="TTWebView",n=s.substring(e+10,e+23)):((e=s.indexOf("Chrome"))!==-1||(e=s.indexOf("Chrome"))!==-1)&&(i="Chrome",n=s.substring(e+7)):s.indexOf("Safari")!==-1?(e=s.indexOf("QQ"))!==-1?(i="qqbrowser",n=s.substring(e+10,e+16)):(e=s.indexOf("Safari"))!==-1&&(i="Safari",n=s.substring(e+7),(e=s.indexOf("Version"))!==-1&&(n=s.substring(e+8))):(e=s.indexOf("Firefox"))!==-1?(i="Firefox",n=s.substring(e+8)):(e=s.indexOf("MicroMessenger"))!==-1?(i="weixin",n=s.substring(e+15,e+20)):(e=s.indexOf("QQ"))!==-1&&(i="qqbrowser",n=s.substring(e+3,e+8)),(t=n.indexOf(";"))!==-1&&(n=n.substring(0,t)),(t=n.indexOf(" "))!==-1&&(n=n.substring(0,t)),(t=n.indexOf(")"))!==-1&&(n=n.substring(0,t)),{browser:i,browser_version:n}},r.prototype.os=function(){for(var e="",t="",i=[{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:"Windows",r:/(Windows|Windows NT)/},{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:"OpenHarmony",r:/Harmony/},{s:"Linux",r:/(Linux|X11)/},{s:"Sun OS",r:/SunOS/}],n=0;n<i.length;n++){var s=i[n];if(s.r.test(this.userAgent)){(e=s.s)==="Mac OS X"&&this.isNewIpad()&&(e="iOS");break}}var a=function(l,d){var p=l.exec(d);return p&&p[1]?p[1]:""},o=function(l,d){var p=RegExp("(?:^|[^A-Z0-9-_]|[^A-Z0-9-]_|sprd-)(?:"+l+")","i").exec(d);return p?p.slice(1)[0]:""};/Windows/.test(e)&&(t=a(/Windows (.*)/,e),e="windows");var h,c;switch(e){case"Mac OS X":t=o("Mac[ +]OS[ +]X(?:[ /](?:Version )?(\\d+(?:[_\\.]\\d+)+))?",this.userAgent),e="mac";break;case"Android":h=this.userAgent,(c=a(/Android ([\.\_\d]+)/,h))||(c=a(/Android\/([\.\_\d]+)/,h)),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);break;case"OpenHarmony":t=function(l){var d=a(/OpenHarmony\s*([\d\.]+)/,l);return d||(d=a(/OpenHarmony\s*([\d\.]+)/,l)),d}(this.userAgent),e="OpenHarmony"}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 i=navigator.userAgent.replace("Mozilla/5.0 (",""),n=i.indexOf(";");t=n===-1?"":i.slice(0,n)}}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}(),Ys={cn:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az1gz22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz22z1mz19z1jz1mz1ez4az22z1mz19z21z1lz21z21z1bz1iz4az1az1mz1k"},Fp={cn:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z4az28z1gz1hz1gz1cz18z1nz1gz4az1az1mz1k",sg:"1fz22z22z1nz21z4mz4bz4bz21z1ez18z1jz1gz49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",va:"1fz22z22z1nz21z4mz4bz4bz1kz18z1jz1gz24z18z49z1kz1az21z4az19z27z22z1cz1mz24z1cz20z21z1cz18z4az1az1mz1k",my:"1fz22z22z1nz21z4mz4bz4bz1kz1az21z49z19z1bz49z1kz27z4az1jz18z20z1iz1mz1dz1dz1gz1az1cz4az1az1mz1k"},Fe="5.3.4",jp=(K("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z1cz1bz1gz22z1mz20z49z20z18z1lz1ez1cz20z21z4az1hz21"),K("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z18z19z49z1az1mz20z1cz4az1hz21"),K("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz24z1gz21z23z18z1jz49z18z19z49z1jz1mz18z1bz1cz20z4az1hz21"),K("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz1fz1cz18z22z1kz18z1nz49z1az1mz20z1c")),Hp=(K("1fz22z22z1nz21z4mz4bz4bz1jz1dz4fz49z1bz18z22z18z4az24z1mz1jz1az1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz1bz18z22z18z49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz22z1cz21z22z1cz20z49z1cz24z1cz1lz22z49z1gz1lz21z1nz1cz1az22z1mz20"),["1fz22z22z1nz21z4mz4bz4bz1bz18z22z18z4az19z27z22z1cz1bz18z1lz1az1cz4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z1cz23z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz22z1cz18z4az22z1gz1iz22z1mz1iz49z23z21z22z21z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z21z1ez4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22","1fz22z22z1nz21z4mz4bz4bz1gz1mz49z24z18z4az22z1gz1iz22z1mz1iz49z20z1mz25z4az1lz1cz22"].map(function(r){return K(r)})),Pi=function(){function r(e,t){this.collector=e,this.config=t,this.eventNameWhiteList=["__bav_page","__bav_beat","__bav_page_statistics","__bav_click","__bav_page_exposure","__bav_slide"],this.paramsNameWhiteList=["$inactive","$inline","$target_uuid_list","$source_uuid","$is_spider","$source_id","$is_first_time","_staging_flag"],this.regStr=new RegExp("^[a-zA-Z0-9][a-z0-9A-Z_.-]{1,255}$")}return r.prototype.checkVerify=function(e){var t=this;if(!e||!e.length)return!1;var i=e[0];if(!i)return!1;var n=i.events,s=i.header;if(!n||!n.length)return!1;var a=!0;return n.forEach(function(o){if(!o)return a=!1,void(o.checkEvent="事件异常");t.checkEventName(o.event)||(a=!1,o.checkEvent="事件名不能以 $ or __开头"),t.checkEventParams(o.params)||(a=!1,o.checkParams="属性名不能以 $ or __开头")}),this.checkEventParams(s)||(a=!1),a},r.prototype.checkEventName=function(e){return!!e&&this.calculate(e,"event")},r.prototype.checkEventParams=function(e){var t=e;if(typeof e=="string"&&(t=JSON.parse(t)),!Object.keys(t).length)return!0;for(var i in t)return!!this.calculate(i,"params")&&(!(typeof t[i]=="string"&&t[i].length>1024)||(console.warn("params: "+i+" can not over 1024 byte, please check;"),!1));return!0},r.prototype.calculate=function(e,t){return(t==="event"?this.eventNameWhiteList:this.paramsNameWhiteList).indexOf(e)!==-1||!new RegExp("^\\$").test(e)&&!new RegExp("^__").test(e)||(console.warn((t==="event"?"event":"params")+" name: "+e+" can not start with $ or __, pleace check;"),!1)},r}();(function(r){r.Init="init",r.Config="config",r.Start="start",r.Ready="ready",r.UnReady="un-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-device-id",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.SetSessionId="set-session-id",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.CustomHeader="custom-request-header",r.SDKInnerError="sdk-inner-error",r.SDKRunTimeError="sdk-run-time-error",r.LogSetting="log-setting",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.DestoryInstance="destory-instance",r.VisualCollectReady="visual-collect-ready",r.VisualApiReady="visual-api-ready",r.VisualApiUpdate="visual-api-update"})(Ii||(Ii={})),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"}(g||(g={}));var S=Ii,L=void 0,Qs=new Date().getTimezoneOffset(),$p=parseInt(""+-Qs/60,10),Kp=60*Qs,qp=7776e6,Wp=function(){function r(e,t){var i=this;this.is_first_time=!0,this.configPersist=!1,this.initConfig=t,this.collect=e;var n=new Vp(t.app_id,t.cookie_domain||"",t.cookie_expire||qp).init();this.eventCheck=new Pi(e,t);var s="__tea_cache_first_"+t.app_id;this.configKey="__tea_cache_config_"+t.app_id,this.sessionStorage=new Ie(!1,"session"),this.localStorage=new Ie(!1,"local"),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:L,user_type:L,user_id:L,user_is_auth:L,user_is_login:L,device_id:L,web_id:L,ip_addr_id:L,user_unique_id_type:L},header:{app_id:L,app_name:L,app_install_id:L,install_id:L,app_package:L,app_channel:L,app_version:L,ab_version:L,os_name:n.os_name,os_version:n.os_version,device_model:n.device_model,ab_client:L,traffic_type:L,client_ip:L,device_brand:L,os_api:L,access:L,language:n.language,region:L,app_language:L,app_region:L,creative_id:n.utm.creative_id,ad_id:n.utm.ad_id,campaign_id:n.utm.campaign_id,log_type:L,rnd:L,platform:n.platform,sdk_version:Fe,sdk_lib:"js",province:L,city:L,timezone:$p,tz_offset:Kp,tz_name:L,sim_region:L,carrier:L,resolution:n.screen_width+"x"+n.screen_height,browser:n.browser,browser_version:n.browser_version,referrer:n.referrer,referrer_host:n.referrer_host,width:n.screen_width,height:n.screen_height,screen_width:n.screen_width,screen_height:n.screen_height,utm_term:n.utm.utm_term,utm_content:n.utm.utm_content,utm_source:n.utm.utm_source,utm_medium:n.utm.utm_medium,utm_campaign:n.utm.utm_campaign,tracer_data:JSON.stringify(n.utm.tracer_data),custom:n.network_type?{network_type:n.network_type}:{},wechat_unionid:L,wechat_openid:L}},this.ab_version="",this.evtParams={},this.reportErrorCallback=function(){},this.isLast=!1,this.setCustom(n),this.initDomain(),this.initABData(),this.collect.on("route-change",function(o){i.changeReferInfo(o.config)})}return r.prototype.initDomain=function(){var e=this.initConfig.channel_domain;if(e)this.domain=e;else{var t=this.initConfig.channel;this.domain=K(Fp[t])}},r.prototype.setDomain=function(e){this.domain=e},r.prototype.getDomain=function(){return this.domain},r.prototype.initABData=function(){var e="__tea_sdk_ab_version_"+this.initConfig.app_id,t=null;if(this.initConfig.ab_cross){var i=this.localStorage.getCookie(e,this.initConfig.ab_cookie_domain);t=i?JSON.parse(i):null}else t=this.localStorage.getItem(e);this.setAbCache(t)},r.prototype.setAbCache=function(e){this.ab_cache=e},r.prototype.getAbCache=function(){return this.ab_cache},r.prototype.setAbVersion=function(e){this.ab_version=e},r.prototype.getAbVersion=function(){return this.ab_version},r.prototype.clearAbCache=function(){this.ab_version="",this.ab_cache={}},r.prototype.getUrl=function(e){var t="";switch(e){case"event":t="/list";break;case"webid":t="/webid";break;case"tobid":t="/tobid"}var i="";return this.initConfig.caller&&(i="?sdk_version="+Fe+"&sdk_name=web&app_id="+this.initConfig.app_id+"&caller="+this.initConfig.caller),""+this.getDomain()+t+i},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.changeReferInfo=function(e){var t=e;this.envInfo.header.referrer=t.referrer;var i="";try{i=new URL(t.referrer).host}catch{}this.envInfo.header.referrer_host=i||this.envInfo.header.referrer_host},r.prototype.set=function(e){var t=this;Object.keys(e).forEach(function(i){e[i]!==void 0&&e[i]!==null||t.delete(i);try{t.eventCheck.calculate(i,"config")}catch{}if(i==="traffic_type"&&t.isLast&&(t.envInfo.header.custom.$latest_traffic_source_type=e[i]),i==="evtParams")t.evtParams=U(U({},t.evtParams||{}),e.evtParams||{});else if(i==="_staging_flag")t.evtParams=U(U({},t.evtParams||{}),{_staging_flag:e._staging_flag});else if(i==="reportErrorCallback"&&typeof e[i]=="function")t.reportErrorCallback=e[i];else{var n="",s="";if(i.indexOf(".")>-1){var a=i.split(".");n=a[0],s=a[1]}n?n==="user"||n==="header"?t.envInfo[n][s]=e[i]:(t.envInfo.header.custom[s]=e[i],t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 添加了Custom",level:"info",time:Date.now(),infoType:"sdk",secType:"HEADER",common:"custom"})):Object.hasOwnProperty.call(t.envInfo.user,i)?(["user_type","ip_addr_id"].indexOf(i)>-1?t.envInfo.user[i]=e[i]?Number(e[i]):e[i]:["user_id","web_id","user_unique_id","user_unique_id_type"].indexOf(i)>-1?t.envInfo.user[i]=e[i]?String(e[i]):e[i]:["user_is_auth","user_is_login"].indexOf(i)>-1?t.envInfo.user[i]=!!e[i]:i==="device_id"&&(t.envInfo.user[i]=e[i]),t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 修改了公共参数",level:"info",time:Date.now(),infoType:"sdk",secType:"USER",common:i})):Object.hasOwnProperty.call(t.envInfo.header,i)?(t.envInfo.header[i]=e[i],t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 修改了公共参数",level:"info",time:Date.now(),infoType:"sdk",secType:"HEADER",common:i})):(t.envInfo.header.custom[i]=e[i],t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 添加了Custom",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(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:t.message})}},r.prototype.setStore=function(e){try{if(!this.configPersist)return;var t=this.storage.getItem(this.configKey)||{};if(t&&Object.keys(e).length){var i=Object.assign(e,t);this.storage.setItem(this.configKey,i)}}catch(n){console.log("setStore error"),this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:n.message})}},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(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:t.message}),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(i){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:i.message}),console.log("delete error")}},r}(),Jp=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;","[AppLog WEB SDK] [instance: "+this.name+"] "+e)},r.prototype.warn=function(e){this.isLog&&console.warn("[AppLog WEB SDK] [instance: "+this.name+"] "+e)},r.prototype.error=function(e){this.isLog&&console.error("[AppLog WEB SDK] [instance: "+this.name+"] "+e)},r.prototype.throw=function(e){throw this.error(this.name),new Error(e)},r}(),Zp=function(){function r(){this.spiderBot=["Baiduspider","googlebot","360Spider","haosouspider","YoudaoBot","Sogou News Spider","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 i=!1;return this.spiderBot.forEach(function(n){t.indexOf(n)!==-1&&(i=!0)}),i},r}(),Xp=function(){function r(t,i){this.collect=t,this.native=i}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(i,n){try{t.bridgeInject()?AppLogBridge.hasStarted(function(s){console.log("AppLogBridge is started? : "+s),s?i(!0):n(!1)}):n(!1)}catch(s){console.log("AppLogBridge, error:"+JSON.stringify(s.stack)),n(!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 i=this;try{Object.keys(t).forEach(function(n){n==="user_unique_id"?i.setUserUniqueId(t[n]):t[n]?i.addHeaderInfo(n,t[n]):i.removeHeaderInfo(n)})}catch{console.error("setConfig error")}},e.setUserUniqueId=function(t){try{AppLogBridge.setUserUniqueId(t)}catch{console.error("setUserUniqueId error")}},e.addHeaderInfo=function(t,i){try{AppLogBridge.addHeaderInfo(t,i)}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,i){try{AppLogBridge.onEventV3(t,i),this.collect.emit(DebuggerMesssge.DEBUGGER_MESSAGE,{type:DebuggerMesssge.DEBUGGER_MESSAGE_EVENT,info:"bridge埋点上报",time:Date.now(),data:[{events:[{event:t,params:i}]}],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}(),vt=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)})},Yp=function(){function r(){}return r.prototype.apply=function(e,t){var i=this;this.collect=e,this.storage=new Ie(!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(S.SessionReset,function(n){i.resetSessionId(n)}),this.collect.on(S.SessionResetTime,function(){i.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:vt(),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:vt(),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||vt(),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:vt(),timestamp:Date.now()},this.storage.setItem(this.sessionKey,e))},r}(),Qp=function(){function r(){this.eventLimit=50,this.enable_ttwebid=!1,this.eventCache=[],this.beconEventCache=[]}return r.prototype.apply=function(e,t){var i=this;this.collect=e,this.config=t,this.configManager=e.configManager,this.eventCheck=new Pi(e,t),this.cacheStorgae=new Ie(!0),this.localStorage=new Ie(!1),this.maxReport=t.max_report||10,this.reportTime=t.reportTime||t.report_time||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.pageId=vt(),this.collect.on(S.Ready,function(){i.reportAll(!1)}),this.collect.on(S.ConfigDomain,function(){i.reportUrl=i.configManager.getUrl("event")}),this.collect.on(S.Event,function(s){i.event(s)}),this.collect.on(S.BeconEvent,function(s){i.beconEvent(s)}),this.collect.on(S.CleanEvents,function(){i.reportAll(!1)});var n=this.linster();this.collect.on(S.DestoryInstance,function(){n&&n()})},r.prototype.linster=function(){var e=this,t=function(){e.reportAll(!0)};window.addEventListener("unload",t,!1),Ai(t);var i=function(){document.visibilityState==="hidden"&&e.reportAll(!0)};return document.addEventListener("visibilitychange",i,!1),function(){window.removeEventListener("unload",t),window.removeEventListener("pagehide",t,!1),window.removeEventListener("beforeunload",t,!1),document.removeEventListener("visibilitychange",i,!1)}},r.prototype.reportAll=function(e){this.report(e),this.reportBecon()},r.prototype.event=function(e){var t=this;try{if(this.collect.destroy||this.collect.sdkStop)return;if(this.config.enable_ios_sendbeacon&&Ws())return void this.beconEvent(e);var i=this.cacheStorgae.getItem(this.eventKey)||[],n=e;this.config.batch_event&&(n=this.batchEvent(e));var s=rt(n,i);if(this.cacheStorgae.setItem(this.eventKey,s),this.reportTimeout&&clearTimeout(this.reportTimeout),s.length>=this.maxReport)this.report(!1);else{var a=this.reportTime;this.reportTimeout=setTimeout(function(){t.report(!1),t.reportTimeout=null},a)}}catch(o){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 发生了异常",level:"error",time:Date.now(),data:o.message,infoType:"sdk"})}},r.prototype.beconEvent=function(e){if(!this.collect.destroy&&!this.collect.sdkStop){var t=rt(e,this.cacheStorgae.getItem(this.beconKey)||[]);this.cacheStorgae.setItem(this.beconKey,t),this.collect.tokenManager.getReady()&&this.collect.sdkReady&&(this.cacheStorgae.removeItem(this.beconKey),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)||[];e&&e.length&&(this.cacheStorgae.removeItem(this.beconKey),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.config.batch_event?this.send([t],e):this.sliceEvent(t,e))}},r.prototype.batchEvent=function(e){var t=[];if(e.length>this.eventLimit)for(var i=0;i<e.length;i+=this.eventLimit){var n;n=e.slice(i,i+this.eventLimit);var s=this.merge(n);t.push(s)}else t=s=this.merge(e);return t},r.prototype.sliceEvent=function(e,t){if(e.length>this.eventLimit)for(var i=0;i<e.length;i+=this.eventLimit){var n;n=e.slice(i,i+this.eventLimit);var s=this.split(this.merge(n));this.send(s,t)}else s=this.split(this.merge(e)),this.send(s,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 i=this,n=this.configManager.get(),s=n.header,a=n.user;this.config.enable_pageid&&(s.custom.page_id=this.pageId),s.custom=JSON.stringify(s.custom);var o=this.configManager.get("evtParams"),h=this.configManager.get("user_unique_id_type"),c=[];try{var u=e.filter(function(d){try{Object.keys(o).length&&!t&&(d.params=U(U({},o),d.params)),h&&(d.params.$user_unique_id_type=h);var p=i.configManager.getAbCache(),f=a[i.config.ab_user_mode]||a.user_unique_id;return p&&p.uuid&&p.uuid===f&&i.configManager.getAbVersion()&&(d.ab_sdk_version=i.configManager.getAbVersion()),d.session_id=i.collect.sessionManager.getSessionId(),d.params=JSON.stringify(d.params),d}catch(v){return console.warn("filter merge event: "+(d&&d.event)+" error, pls check",v&&v.message),i.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 处理Event数据异常",level:"error",time:Date.now(),data:v.message,infoType:"sdk"}),!1}}),l=JSON.parse(JSON.stringify({events:u,user:a,header:s}));l.local_time=Math.floor(Date.now()/1e3),l.user_unique_type=this.config.enable_ttwebid?this.config.user_unique_type:void 0,l.verbose=1,c.push(l)}catch(d){console.warn("event merge error, pls check",d&&d.message)}return c},r.prototype.split=function(e){return e=e.map(function(t){var i=[];return i.push(t),i})},r.prototype.blockEvent=function(e){try{var t=this.blockList;if(this.config.enable_logsetting){var i=this.blockList,n=this.logSetting.getSettingData("blocklist_events").block_event;t=i.concat(n.filter(function(s){return i.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?!0:!t.length)||!!this.whiteList.includes(e)}catch{return!0}},r.prototype.customAllowFilter=function(e,t){try{if(t||!this.config.enable_logsetting||!this.config.enable_logsetting_header_custom)return JSON.stringify(e);var i=this.logSetting.getSettingData().header_custom_allow,n={};if(i&&i.length&&Object.keys(e).length){var s=new Set(i);for(var a in e)s.has(a)&&(n[a]=e[a])}return JSON.stringify(n)}catch(o){return this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行customAllowFilter发生了异常",level:"error",time:Date.now(),data:o.message,infoType:"sdk"}),JSON.stringify(e)}},r.prototype.paramsAllowFilter=function(e,t){try{if(t||!this.config.enable_logsetting||!this.config.enable_logsetting_params)return JSON.stringify(e.params);var i=this.logSetting.getSettingData().params_block,n=e.event,s=e.params,a={};if(i&&i[n]&&i[n].length){var o=new Set(i[n]);for(var h in s)!this.logSetting.getPredefineParamsList().has(h)&&o.has(h)||(a[h]=s[h]);return JSON.stringify(a)}return JSON.stringify(e.params)}catch(c){return this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行paramsAllowFilter发生了异常",level:"error",time:Date.now(),data:c.message,infoType:"sdk"}),JSON.stringify(e.params)}},r.prototype.send=function(e,t){var i=this;e.length&&(this.config.disable_track_event||e.forEach(function(n){try{var s=JSON.parse(JSON.stringify(n));i.config.filter&&((s=i.config.filter(s))||console.warn("filter must return data !!")),i.collect.eventFilter&&s&&((s=i.collect.eventFilter(s))||console.warn("filterEvent api must return data !!"));var a=s||n,o=JSON.parse(JSON.stringify(a));if(i.eventCheck.checkVerify(o),!a.length)return;var h=!0;if(a.forEach(function(c){c.events.length||(h=!1)}),!h)return;i.collect.emit(S.SubmitBefore,a),i.collect.requestManager.useRequest({url:i.reportUrl,data:a,success:function(c,u){c&&c.e!==0?(i.collect.emit(S.SubmitError,{type:"f_data",eventData:u,errorCode:c.e,response:c}),i.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"埋点上报失败",time:Date.now(),data:o,code:c.e,msg:c.m||"",failType:"数据异常失败",status:"fail"})):(i.collect.emit(S.SubmitScuess,{eventData:u,res:c}),i.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"埋点上报成功",time:Date.now(),data:o,code:200,status:"success"}))},fail:function(c,u){i.configManager.get("reportErrorCallback")(c,u),i.collect.emit(S.SubmitError,{type:"f_net",eventData:c,errorCode:u}),i.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"埋点上报网络异常",time:Date.now(),data:o,code:u,failType:"网络异常失败",status:"fail"})},timeout:i.timeout,useBeacon:t,withCredentials:i.enable_ttwebid,zip:!0}),i.collect.emit(S.SubmitAfter,a)}catch(c){console.warn("something error, "+JSON.stringify(c.stack)),i.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK发送埋点发生了异常",level:"error",time:Date.now(),data:c.message,infoType:"sdk"})}}))},r}(),Bt=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)},ef=function(){function r(){this.cacheToken={},this.enableCookie=!1,this.enable_ttwebid=!1,this.enableCustomWebid=!1}return r.prototype.apply=function(e,t){var i=this;this.collect=e,this.config=t,this.configManager=this.collect.configManager,this.storage=new Ie(!1),this.tokenKey="__tea_cache_tokens_"+t.app_id,this.enable_ttwebid=t.enable_ttwebid,this.enableCustomWebid=t.enable_custom_webid,this.collect.on(S.ConfigUuid,function(n){i.setUuid(n)}),this.collect.on(S.ConfigWebId,function(n){i.setWebId(n)}),this.collect.on(S.ConfigDiD,function(n){i.setDeviceId(n)}),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;if(this.enableCookie){var t=this.storage.getCookie(this.tokenKey,this.cookieDomain);this.cacheToken=t&&typeof t=="string"?JSON.parse(t):{}}else 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(S.CustomWebId,function(){e.tokenReady=!0,e.collect.emit(S.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:Bt(),user_unique_id:this.configManager.get("user_unique_id")||Bt()}):this.remoteWebid()},r.prototype.checkEnv=function(){var e=window.navigator.userAgent;if(e.indexOf("miniProgram")!==-1||e.indexOf("MiniProgram")!==-1){var t=kr(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"),i={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(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 发起WebID请求",logType:"fetch",level:"info",time:Date.now(),data:i,infoType:"sdk"}),this.collect.requestManager.useRequest({url:t,data:i,success:function(n){var s;if(n&&n.e===0)s=n.web_id,e.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"WebID请求成功",logType:"fetch",level:"info",time:Date.now(),data:n,infoType:"sdk"});else{var a=Bt();s=a,e.collect.configManager.set({localWebId:a}),e.collect.emit(S.TokenError),e.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"WebID请求返回值异常,采用本地生成",logType:"fetch",level:"warn",time:Date.now(),data:n,infoType:"sdk"}),e.collect.logger.warn("appid: "+e.config.app_id+" get webid error, use local webid~")}e.complete({web_id:e.configManager.get("web_id")||s,user_unique_id:e.configManager.get("user_unique_id")||s})},fail:function(){var n=Bt();e.complete({web_id:e.configManager.get("web_id")||n,user_unique_id:e.configManager.get("user_unique_id")||n}),e.collect.configManager.set({localWebId:n}),e.collect.emit(S.TokenError),e.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"WebID请求网络异常,采用本地生成",logType:"fetch",level:"error",time:Date.now(),data:{localWebId:n},infoType:"sdk"}),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,i=e.user_unique_id,n=e.device_id;if(e.timestamp=Date.now(),this.collect.configManager.set({web_id:t,user_unique_id:i}),this.config.enable_device_id){var s=this.configManager.get("device_id")||n||t;this.collect.configManager.set({device_id:s}),e=U(U({},e),{device_id:s})}else e!=null&&e.device_id&&delete e.device_id;this.setStorage(e),this.tokenReady=!0,this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 完成用户信息设置",logType:"info",level:"info",time:Date.now(),data:{web_id:t,user_unique_id:i},infoType:"sdk"}),this.collect.emit(S.TokenComplete)},r.prototype.completeTtWid=function(e){var t=e.user_unique_id||"",i=this.configManager.get("user_unique_id");(i||t)&&this.configManager.set({user_unique_id:i||t}),this.setStorage(e),this.tokenReady=!0,this.collect.emit(S.TokenComplete)},r.prototype.setUuid=function(e){if(e&&["null","undefined","Null","None"].indexOf(e)===-1){var t=String(e),i=this.configManager.get("user_unique_id"),n=this.cacheToken&&this.cacheToken.user_unique_id;if(t===i&&t===n)return;this.configManager.set({user_unique_id:t}),this.cacheToken?this.cacheToken.user_unique_id=t:(this.cacheToken={},this.cacheToken.user_unique_id=t),this.cacheToken.timestamp=Date.now(),this.setStorage(this.cacheToken),this.collect.emit(S.TokenChange,"uuid"),this.collect.emit(S.SessionReset)}else this.clearUuid()},r.prototype.clearUuid=function(){this.config.enable_ttwebid||this.configManager.get("web_id")&&this.configManager.get("user_unique_id")!==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(S.TokenReset,"uuid"))},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"),i=this.configManager.get("user_unique_id");i&&i!==t||(this.configManager.set({user_unique_id:e}),this.collect.emit(S.TokenChange,"uuid")),t!==e&&(this.configManager.set({web_id:e}),this.collect.emit(S.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.enableCookie||this.enable_ttwebid?(this.storage.setCookie(this.tokenKey,e,this.expiresTime,this.cookieDomain),this.enable_ttwebid&&(delete e.web_id,this.storage.setItem(this.tokenKey,e))):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 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(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 发起GetToken请求",logType:"fetch",level:"info",time:Date.now(),data:i,infoType:"sdk"}),e.collect.requestManager.useRequest({url:e.configManager.getUrl("tobid"),data:i,success:function(n){n&&n.e===0?(t(n.tobid),e.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"GetToken请求成功",logType:"fetch",level:"info",time:Date.now(),data:n,infoType:"sdk"})):(t(""),e.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"GetToken请求失败",logType:"fetch",level:"error",time:Date.now(),data:n,infoType:"sdk"}))},fail:function(){t(""),e.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"GetToken请求失败",logType:"fetch",level:"error",time:Date.now(),infoType:"sdk"})},time:3e4,withCredentials:e.enable_ttwebid})})},r}();function yt(r){for(var e=r.length;--e>=0;)r[e]=0}var Li=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]),Ar=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]),tf=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),eo=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Pe=new Array(576);yt(Pe);var Vt=new Array(60);yt(Vt);var Ft=new Array(512);yt(Ft);var jt=new Array(256);yt(jt);var Ui=new Array(29);yt(Ui);var to,ro,io,Rr=new Array(30);function Ni(r,e,t,i,n){this.static_tree=r,this.extra_bits=e,this.extra_base=t,this.elems=i,this.max_length=n,this.has_stree=r&&r.length}function Gi(r,e){this.dyn_tree=r,this.max_code=0,this.stat_desc=e}yt(Rr);var no=function(r){return r<256?Ft[r]:Ft[256+(r>>>7)]},Ht=function(r,e){r.pending_buf[r.pending++]=255&e,r.pending_buf[r.pending++]=e>>>8&255},se=function(r,e,t){r.bi_valid>16-t?(r.bi_buf|=e<<r.bi_valid&65535,Ht(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)},Se=function(r,e,t){se(r,t[2*e],t[2*e+1])},so=function(r,e){var t=0;do t|=1&r,r>>>=1,t<<=1;while(--e>0);return t>>>1},oo=function(r,e,t){var i,n,s=new Array(16),a=0;for(i=1;i<=15;i++)a=a+t[i-1]<<1,s[i]=a;for(n=0;n<=e;n++){var o=r[2*n+1];o!==0&&(r[2*n]=so(s[o]++,o))}},ao=function(r){var 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},co=function(r){r.bi_valid>8?Ht(r,r.bi_buf):r.bi_valid>0&&(r.pending_buf[r.pending++]=r.bi_buf),r.bi_buf=0,r.bi_valid=0},uo=function(r,e,t,i){var n=2*e,s=2*t;return r[n]<r[s]||r[n]===r[s]&&i[e]<=i[t]},Bi=function(r,e,t){for(var i=r.heap[t],n=t<<1;n<=r.heap_len&&(n<r.heap_len&&uo(e,r.heap[n+1],r.heap[n],r.depth)&&n++,!uo(e,i,r.heap[n],r.depth));)r.heap[t]=r.heap[n],t=n,n<<=1;r.heap[t]=i},ho=function(r,e,t){var i,n,s,a,o=0;if(r.sym_next!==0)do i=255&r.pending_buf[r.sym_buf+o++],i+=(255&r.pending_buf[r.sym_buf+o++])<<8,n=r.pending_buf[r.sym_buf+o++],i===0?Se(r,n,e):(s=jt[n],Se(r,s+256+1,e),(a=Li[s])!==0&&(n-=Ui[s],se(r,n,a)),s=no(--i),Se(r,s,t),(a=Ar[s])!==0&&(i-=Rr[s],se(r,i,a)));while(o<r.sym_next);Se(r,256,e)},Vi=function(r,e){var t,i,n,s=e.dyn_tree,a=e.stat_desc.static_tree,o=e.stat_desc.has_stree,h=e.stat_desc.elems,c=-1;for(r.heap_len=0,r.heap_max=573,t=0;t<h;t++)s[2*t]!==0?(r.heap[++r.heap_len]=c=t,r.depth[t]=0):s[2*t+1]=0;for(;r.heap_len<2;)s[2*(n=r.heap[++r.heap_len]=c<2?++c:0)]=1,r.depth[n]=0,r.opt_len--,o&&(r.static_len-=a[2*n+1]);for(e.max_code=c,t=r.heap_len>>1;t>=1;t--)Bi(r,s,t);n=h;do t=r.heap[1],r.heap[1]=r.heap[r.heap_len--],Bi(r,s,1),i=r.heap[1],r.heap[--r.heap_max]=t,r.heap[--r.heap_max]=i,s[2*n]=s[2*t]+s[2*i],r.depth[n]=(r.depth[t]>=r.depth[i]?r.depth[t]:r.depth[i])+1,s[2*t+1]=s[2*i+1]=n,r.heap[1]=n++,Bi(r,s,1);while(r.heap_len>=2);r.heap[--r.heap_max]=r.heap[1],function(u,l){var d,p,f,v,m,E,y=l.dyn_tree,_=l.max_code,C=l.stat_desc.static_tree,z=l.stat_desc.has_stree,w=l.stat_desc.extra_bits,O=l.stat_desc.extra_base,k=l.stat_desc.max_length,T=0;for(v=0;v<=15;v++)u.bl_count[v]=0;for(y[2*u.heap[u.heap_max]+1]=0,d=u.heap_max+1;d<573;d++)(v=y[2*y[2*(p=u.heap[d])+1]+1]+1)>k&&(v=k,T++),y[2*p+1]=v,p>_||(u.bl_count[v]++,m=0,p>=O&&(m=w[p-O]),E=y[2*p],u.opt_len+=E*(v+m),z&&(u.static_len+=E*(C[2*p+1]+m)));if(T!==0){do{for(v=k-1;u.bl_count[v]===0;)v--;u.bl_count[v]--,u.bl_count[v+1]+=2,u.bl_count[k]--,T-=2}while(T>0);for(v=k;v!==0;v--)for(p=u.bl_count[v];p!==0;)(f=u.heap[--d])>_||(y[2*f+1]!==v&&(u.opt_len+=(v-y[2*f+1])*y[2*f],y[2*f+1]=v),p--)}}(r,e),oo(s,c,r.bl_count)},lo=function(r,e,t){var i,n,s=-1,a=e[1],o=0,h=7,c=4;for(a===0&&(h=138,c=3),e[2*(t+1)+1]=65535,i=0;i<=t;i++)n=a,a=e[2*(i+1)+1],++o<h&&n===a||(o<c?r.bl_tree[2*n]+=o:n!==0?(n!==s&&r.bl_tree[2*n]++,r.bl_tree[32]++):o<=10?r.bl_tree[34]++:r.bl_tree[36]++,o=0,s=n,a===0?(h=138,c=3):n===a?(h=6,c=3):(h=7,c=4))},po=function(r,e,t){var i,n,s=-1,a=e[1],o=0,h=7,c=4;for(a===0&&(h=138,c=3),i=0;i<=t;i++)if(n=a,a=e[2*(i+1)+1],!(++o<h&&n===a)){if(o<c)do Se(r,n,r.bl_tree);while(--o!=0);else n!==0?(n!==s&&(Se(r,n,r.bl_tree),o--),Se(r,16,r.bl_tree),se(r,o-3,2)):o<=10?(Se(r,17,r.bl_tree),se(r,o-3,3)):(Se(r,18,r.bl_tree),se(r,o-11,7));o=0,s=n,a===0?(h=138,c=3):n===a?(h=6,c=3):(h=7,c=4)}},fo=!1,mo=function(r,e,t,i){se(r,0+(i?1:0),3),co(r),Ht(r,t),Ht(r,~t),t&&r.pending_buf.set(r.window.subarray(e,e+t),r.pending),r.pending+=t},$t={_tr_init:function(r){fo||(function(){var e,t,i,n,s,a=new Array(16);for(i=0,n=0;n<28;n++)for(Ui[n]=i,e=0;e<1<<Li[n];e++)jt[i++]=n;for(jt[i-1]=n,s=0,n=0;n<16;n++)for(Rr[n]=s,e=0;e<1<<Ar[n];e++)Ft[s++]=n;for(s>>=7;n<30;n++)for(Rr[n]=s<<7,e=0;e<1<<Ar[n]-7;e++)Ft[256+s++]=n;for(t=0;t<=15;t++)a[t]=0;for(e=0;e<=143;)Pe[2*e+1]=8,e++,a[8]++;for(;e<=255;)Pe[2*e+1]=9,e++,a[9]++;for(;e<=279;)Pe[2*e+1]=7,e++,a[7]++;for(;e<=287;)Pe[2*e+1]=8,e++,a[8]++;for(oo(Pe,287,a),e=0;e<30;e++)Vt[2*e+1]=5,Vt[2*e]=so(e,5);to=new Ni(Pe,Li,257,286,15),ro=new Ni(Vt,Ar,0,30,15),io=new Ni(new Array(0),tf,0,19,7)}(),fo=!0),r.l_desc=new Gi(r.dyn_ltree,to),r.d_desc=new Gi(r.dyn_dtree,ro),r.bl_desc=new Gi(r.bl_tree,io),r.bi_buf=0,r.bi_valid=0,ao(r)},_tr_stored_block:mo,_tr_flush_block:function(r,e,t,i){var n,s,a=0;r.level>0?(r.strm.data_type===2&&(r.strm.data_type=function(o){var h,c=4093624447;for(h=0;h<=31;h++,c>>>=1)if(1&c&&o.dyn_ltree[2*h]!==0)return 0;if(o.dyn_ltree[18]!==0||o.dyn_ltree[20]!==0||o.dyn_ltree[26]!==0)return 1;for(h=32;h<256;h++)if(o.dyn_ltree[2*h]!==0)return 1;return 0}(r)),Vi(r,r.l_desc),Vi(r,r.d_desc),a=function(o){var h;for(lo(o,o.dyn_ltree,o.l_desc.max_code),lo(o,o.dyn_dtree,o.d_desc.max_code),Vi(o,o.bl_desc),h=18;h>=3&&o.bl_tree[2*eo[h]+1]===0;h--);return o.opt_len+=3*(h+1)+5+5+4,h}(r),n=r.opt_len+3+7>>>3,(s=r.static_len+3+7>>>3)<=n&&(n=s)):n=s=t+5,t+4<=n&&e!==-1?mo(r,e,t,i):r.strategy===4||s===n?(se(r,2+(i?1:0),3),ho(r,Pe,Vt)):(se(r,4+(i?1:0),3),function(o,h,c,u){var l;for(se(o,h-257,5),se(o,c-1,5),se(o,u-4,4),l=0;l<u;l++)se(o,o.bl_tree[2*eo[l]+1],3);po(o,o.dyn_ltree,h-1),po(o,o.dyn_dtree,c-1)}(r,r.l_desc.max_code+1,r.d_desc.max_code+1,a+1),ho(r,r.dyn_ltree,r.dyn_dtree)),ao(r),i&&co(r)},_tr_tally:function(r,e,t){return 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*(jt[t]+256+1)]++,r.dyn_dtree[2*no(e)]++),r.sym_next===r.sym_end},_tr_align:function(r){se(r,2,3),Se(r,256,Pe),function(e){e.bi_valid===16?(Ht(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)}},Kt=function(r,e,t,i){for(var n=65535&r|0,s=r>>>16&65535|0,a=0;t!==0;){t-=a=t>2e3?2e3:t;do s=s+(n=n+e[i++]|0)|0;while(--a);n%=65521,s%=65521}return n|s<<16|0},rf=new Uint32Array(function(){for(var r,e=[],t=0;t<256;t++){r=t;for(var i=0;i<8;i++)r=1&r?3988292384^r>>>1:r>>>1;e[t]=r}return e}()),q=function(r,e,t,i){var n=rf,s=i+t;r^=-1;for(var a=i;a<s;a++)r=r>>>8^n[255&(r^e[a])];return-1^r},it={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"},x={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},nf=$t._tr_init,Fi=$t._tr_stored_block,sf=$t._tr_flush_block,je=$t._tr_tally,of=$t._tr_align,He=x.Z_NO_FLUSH,af=x.Z_PARTIAL_FLUSH,cf=x.Z_FULL_FLUSH,le=x.Z_FINISH,_o=x.Z_BLOCK,X=x.Z_OK,go=x.Z_STREAM_END,Ee=x.Z_STREAM_ERROR,uf=x.Z_DATA_ERROR,ji=x.Z_BUF_ERROR,hf=x.Z_DEFAULT_COMPRESSION,df=x.Z_FILTERED,Dr=x.Z_HUFFMAN_ONLY,lf=x.Z_RLE,pf=x.Z_FIXED,ff=x.Z_DEFAULT_STRATEGY,mf=x.Z_UNKNOWN,xr=x.Z_DEFLATED,Hi=286,_f=30,gf=19,vf=2*Hi+1,yf=15,nt=function(r,e){return r.msg=it[e],e},vo=function(r){return 2*r-(r>4?9:0)},$e=function(r){for(var e=r.length;--e>=0;)r[e]=0},bf=function(r){var e,t,i,n=r.w_size;i=e=r.hash_size;do t=r.head[--i],r.head[i]=t>=n?t-n:0;while(--e);i=e=n;do t=r.prev[--i],r.prev[i]=t>=n?t-n:0;while(--e)},Ke=function(r,e,t){return(e<<r.hash_shift^t)&r.hash_mask},ae=function(r){var e=r.state,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))},ce=function(r,e){sf(r,r.block_start>=0?r.block_start:-1,r.strstart-r.block_start,e),r.block_start=r.strstart,ae(r.strm)},G=function(r,e){r.pending_buf[r.pending++]=e},qt=function(r,e){r.pending_buf[r.pending++]=e>>>8&255,r.pending_buf[r.pending++]=255&e},$i=function(r,e,t,i){var n=r.avail_in;return n>i&&(n=i),n===0?0:(r.avail_in-=n,e.set(r.input.subarray(r.next_in,r.next_in+n),t),r.state.wrap===1?r.adler=Kt(r.adler,e,n,t):r.state.wrap===2&&(r.adler=q(r.adler,e,n,t)),r.next_in+=n,r.total_in+=n,n)},yo=function(r,e){var t,i,n=r.max_chain_length,s=r.strstart,a=r.prev_length,o=r.nice_match,h=r.strstart>r.w_size-262?r.strstart-(r.w_size-262):0,c=r.window,u=r.w_mask,l=r.prev,d=r.strstart+258,p=c[s+a-1],f=c[s+a];r.prev_length>=r.good_match&&(n>>=2),o>r.lookahead&&(o=r.lookahead);do if(c[(t=e)+a]===f&&c[t+a-1]===p&&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<d);if(i=258-(d-s),s=d-258,i>a){if(r.match_start=e,a=i,i>=o)break;p=c[s+a-1],f=c[s+a]}}while((e=l[e&u])>h&&--n!=0);return a<=r.lookahead?a:r.lookahead},bt=function(r){var e,t,i,n=r.w_size;do{if(t=r.window_size-r.lookahead-r.strstart,r.strstart>=n+(n-262)&&(r.window.set(r.window.subarray(n,n+n-t),0),r.match_start-=n,r.strstart-=n,r.block_start-=n,r.insert>r.strstart&&(r.insert=r.strstart),bf(r),t+=n),r.strm.avail_in===0)break;if(e=$i(r.strm,r.window,r.strstart+r.lookahead,t),r.lookahead+=e,r.lookahead+r.insert>=3)for(i=r.strstart-r.insert,r.ins_h=r.window[i],r.ins_h=Ke(r,r.ins_h,r.window[i+1]);r.insert&&(r.ins_h=Ke(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)},bo=function(r,e){var t,i,n,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,n=r.bi_valid+42>>3,r.strm.avail_out<n||(n=r.strm.avail_out-n,t>(i=r.strstart-r.block_start)+r.strm.avail_in&&(t=i+r.strm.avail_in),t>n&&(t=n),t<s&&(t===0&&e!==le||e===He||t!==i+r.strm.avail_in)))break;a=e===le&&t===i+r.strm.avail_in?1:0,Fi(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,ae(r.strm),i&&(i>t&&(i=t),r.strm.output.set(r.window.subarray(r.block_start,r.block_start+i),r.strm.next_out),r.strm.next_out+=i,r.strm.avail_out-=i,r.strm.total_out+=i,r.block_start+=i,t-=i),t&&($i(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>=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!==He&&e!==le&&r.strm.avail_in===0&&r.strstart===r.block_start?2:(n=r.window_size-r.strstart,r.strm.avail_in>n&&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++,n+=r.w_size,r.insert>r.strstart&&(r.insert=r.strstart)),n>r.strm.avail_in&&(n=r.strm.avail_in),n&&($i(r.strm,r.window,r.strstart,n),r.strstart+=n,r.insert+=n>r.w_size-r.insert?r.w_size-r.insert:n),r.high_water<r.strstart&&(r.high_water=r.strstart),n=r.bi_valid+42>>3,s=(n=r.pending_buf_size-n>65535?65535:r.pending_buf_size-n)>r.w_size?r.w_size:n,((i=r.strstart-r.block_start)>=s||(i||e===le)&&e!==He&&r.strm.avail_in===0&&i<=n)&&(t=i>n?n:i,a=e===le&&r.strm.avail_in===0&&t===i?1:0,Fi(r,r.block_start,t,a),r.block_start+=t,ae(r.strm)),a?3:1)},Ki=function(r,e){for(var t,i;;){if(r.lookahead<262){if(bt(r),r.lookahead<262&&e===He)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=Ke(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=yo(r,t)),r.match_length>=3)if(i=je(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=Ke(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=Ke(r,r.ins_h,r.window[r.strstart+1]);else i=je(r,0,r.window[r.strstart]),r.lookahead--,r.strstart++;if(i&&(ce(r,!1),r.strm.avail_out===0))return 1}return r.insert=r.strstart<2?r.strstart:2,e===le?(ce(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(ce(r,!1),r.strm.avail_out===0)?1:2},St=function(r,e){for(var t,i,n;;){if(r.lookahead<262){if(bt(r),r.lookahead<262&&e===He)return 1;if(r.lookahead===0)break}if(t=0,r.lookahead>=3&&(r.ins_h=Ke(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=yo(r,t),r.match_length<=5&&(r.strategy===df||r.match_length===3&&r.strstart-r.match_start>4096)&&(r.match_length=2)),r.prev_length>=3&&r.match_length<=r.prev_length){n=r.strstart+r.lookahead-3,i=je(r,r.strstart-1-r.prev_match,r.prev_length-3),r.lookahead-=r.prev_length-1,r.prev_length-=2;do++r.strstart<=n&&(r.ins_h=Ke(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++,i&&(ce(r,!1),r.strm.avail_out===0))return 1}else if(r.match_available){if((i=je(r,0,r.window[r.strstart-1]))&&ce(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&&(i=je(r,0,r.window[r.strstart-1]),r.match_available=0),r.insert=r.strstart<2?r.strstart:2,e===le?(ce(r,!0),r.strm.avail_out===0?3:4):r.sym_next&&(ce(r,!1),r.strm.avail_out===0)?1:2};function Ce(r,e,t,i,n){this.good_length=r,this.max_lazy=e,this.nice_length=t,this.max_chain=i,this.func=n}var Wt=[new Ce(0,0,0,0,bo),new Ce(4,4,8,4,Ki),new Ce(4,5,16,8,Ki),new Ce(4,6,32,32,Ki),new Ce(4,4,16,16,St),new Ce(8,16,32,32,St),new Ce(8,16,128,128,St),new Ce(8,32,128,256,St),new Ce(32,128,258,1024,St),new Ce(32,258,258,4096,St)];function Sf(){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=xr,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(2*vf),this.dyn_dtree=new Uint16Array(2*(2*_f+1)),this.bl_tree=new Uint16Array(2*(2*gf+1)),$e(this.dyn_ltree),$e(this.dyn_dtree),$e(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(yf+1),this.heap=new Uint16Array(2*Hi+1),$e(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*Hi+1),$e(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}var Jt=function(r){if(!r)return 1;var 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},So=function(r){if(Jt(r))return nt(r,Ee);r.total_in=r.total_out=0,r.data_type=mf;var 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,nf(e),X},Eo=function(r){var e,t=So(r);return t===X&&((e=r.state).window_size=2*e.w_size,$e(e.head),e.max_lazy_match=Wt[e.level].max_lazy,e.good_match=Wt[e.level].good_length,e.nice_match=Wt[e.level].nice_length,e.max_chain_length=Wt[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0),t},Co=function(r,e,t,i,n,s){if(!r)return Ee;var a=1;if(e===hf&&(e=6),i<0?(a=0,i=-i):i>15&&(a=2,i-=16),n<1||n>9||t!==xr||i<8||i>15||e<0||e>9||s<0||s>pf||i===8&&a!==1)return nt(r,Ee);i===8&&(i=9);var o=new Sf;return r.state=o,o.strm=r,o.status=42,o.wrap=a,o.gzhead=null,o.w_bits=i,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=n+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<<n+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,Eo(r)},Zt={deflateInit:function(r,e){return Co(r,e,xr,15,8,ff)},deflateInit2:Co,deflateReset:Eo,deflateResetKeep:So,deflateSetHeader:function(r,e){return Jt(r)||r.state.wrap!==2?Ee:(r.state.gzhead=e,X)},deflate:function(r,e){if(Jt(r)||e>_o||e<0)return r?nt(r,Ee):Ee;var t=r.state;if(!r.output||r.avail_in!==0&&!r.input||t.status===666&&e!==le)return nt(r,r.avail_out===0?ji:Ee);var i=t.last_flush;if(t.last_flush=e,t.pending!==0){if(ae(r),r.avail_out===0)return t.last_flush=-1,X}else if(r.avail_in===0&&vo(e)<=vo(i)&&e!==le)return nt(r,ji);if(t.status===666&&r.avail_in!==0)return nt(r,ji);if(t.status===42&&t.wrap===0&&(t.status=113),t.status===42){var n=xr+(t.w_bits-8<<4)<<8;if(n|=(t.strategy>=Dr||t.level<2?0:t.level<6?1:t.level===6?2:3)<<6,t.strstart!==0&&(n|=32),qt(t,n+=31-n%31),t.strstart!==0&&(qt(t,r.adler>>>16),qt(t,65535&r.adler)),r.adler=1,t.status=113,ae(r),t.pending!==0)return t.last_flush=-1,X}if(t.status===57){if(r.adler=0,G(t,31),G(t,139),G(t,8),t.gzhead)G(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)),G(t,255&t.gzhead.time),G(t,t.gzhead.time>>8&255),G(t,t.gzhead.time>>16&255),G(t,t.gzhead.time>>24&255),G(t,t.level===9?2:t.strategy>=Dr||t.level<2?4:0),G(t,255&t.gzhead.os),t.gzhead.extra&&t.gzhead.extra.length&&(G(t,255&t.gzhead.extra.length),G(t,t.gzhead.extra.length>>8&255)),t.gzhead.hcrc&&(r.adler=q(r.adler,t.pending_buf,t.pending,0)),t.gzindex=0,t.status=69;else if(G(t,0),G(t,0),G(t,0),G(t,0),G(t,0),G(t,t.level===9?2:t.strategy>=Dr||t.level<2?4:0),G(t,3),t.status=113,ae(r),t.pending!==0)return t.last_flush=-1,X}if(t.status===69){if(t.gzhead.extra){for(var s=t.pending,a=(65535&t.gzhead.extra.length)-t.gzindex;t.pending+a>t.pending_buf_size;){var 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>s&&(r.adler=q(r.adler,t.pending_buf,t.pending-s,s)),t.gzindex+=o,ae(r),t.pending!==0)return t.last_flush=-1,X;s=0,a-=o}var h=new Uint8Array(t.gzhead.extra);t.pending_buf.set(h.subarray(t.gzindex,t.gzindex+a),t.pending),t.pending+=a,t.gzhead.hcrc&&t.pending>s&&(r.adler=q(r.adler,t.pending_buf,t.pending-s,s)),t.gzindex=0}t.status=73}if(t.status===73){if(t.gzhead.name){var c,u=t.pending;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>u&&(r.adler=q(r.adler,t.pending_buf,t.pending-u,u)),ae(r),t.pending!==0)return t.last_flush=-1,X;u=0}c=t.gzindex<t.gzhead.name.length?255&t.gzhead.name.charCodeAt(t.gzindex++):0,G(t,c)}while(c!==0);t.gzhead.hcrc&&t.pending>u&&(r.adler=q(r.adler,t.pending_buf,t.pending-u,u)),t.gzindex=0}t.status=91}if(t.status===91){if(t.gzhead.comment){var l,d=t.pending;do{if(t.pending===t.pending_buf_size){if(t.gzhead.hcrc&&t.pending>d&&(r.adler=q(r.adler,t.pending_buf,t.pending-d,d)),ae(r),t.pending!==0)return t.last_flush=-1,X;d=0}l=t.gzindex<t.gzhead.comment.length?255&t.gzhead.comment.charCodeAt(t.gzindex++):0,G(t,l)}while(l!==0);t.gzhead.hcrc&&t.pending>d&&(r.adler=q(r.adler,t.pending_buf,t.pending-d,d))}t.status=103}if(t.status===103){if(t.gzhead.hcrc){if(t.pending+2>t.pending_buf_size&&(ae(r),t.pending!==0))return t.last_flush=-1,X;G(t,255&r.adler),G(t,r.adler>>8&255),r.adler=0}if(t.status=113,ae(r),t.pending!==0)return t.last_flush=-1,X}if(r.avail_in!==0||t.lookahead!==0||e!==He&&t.status!==666){var p=t.level===0?bo(t,e):t.strategy===Dr?function(f,v){for(var m;;){if(f.lookahead===0&&(bt(f),f.lookahead===0)){if(v===He)return 1;break}if(f.match_length=0,m=je(f,0,f.window[f.strstart]),f.lookahead--,f.strstart++,m&&(ce(f,!1),f.strm.avail_out===0))return 1}return f.insert=0,v===le?(ce(f,!0),f.strm.avail_out===0?3:4):f.sym_next&&(ce(f,!1),f.strm.avail_out===0)?1:2}(t,e):t.strategy===lf?function(f,v){for(var m,E,y,_,C=f.window;;){if(f.lookahead<=258){if(bt(f),f.lookahead<=258&&v===He)return 1;if(f.lookahead===0)break}if(f.match_length=0,f.lookahead>=3&&f.strstart>0&&(E=C[y=f.strstart-1])===C[++y]&&E===C[++y]&&E===C[++y]){_=f.strstart+258;do;while(E===C[++y]&&E===C[++y]&&E===C[++y]&&E===C[++y]&&E===C[++y]&&E===C[++y]&&E===C[++y]&&E===C[++y]&&y<_);f.match_length=258-(_-y),f.match_length>f.lookahead&&(f.match_length=f.lookahead)}if(f.match_length>=3?(m=je(f,1,f.match_length-3),f.lookahead-=f.match_length,f.strstart+=f.match_length,f.match_length=0):(m=je(f,0,f.window[f.strstart]),f.lookahead--,f.strstart++),m&&(ce(f,!1),f.strm.avail_out===0))return 1}return f.insert=0,v===le?(ce(f,!0),f.strm.avail_out===0?3:4):f.sym_next&&(ce(f,!1),f.strm.avail_out===0)?1:2}(t,e):Wt[t.level].func(t,e);if(p!==3&&p!==4||(t.status=666),p===1||p===3)return r.avail_out===0&&(t.last_flush=-1),X;if(p===2&&(e===af?of(t):e!==_o&&(Fi(t,0,0,!1),e===cf&&($e(t.head),t.lookahead===0&&(t.strstart=0,t.block_start=0,t.insert=0))),ae(r),r.avail_out===0))return t.last_flush=-1,X}return e!==le?X:t.wrap<=0?go:(t.wrap===2?(G(t,255&r.adler),G(t,r.adler>>8&255),G(t,r.adler>>16&255),G(t,r.adler>>24&255),G(t,255&r.total_in),G(t,r.total_in>>8&255),G(t,r.total_in>>16&255),G(t,r.total_in>>24&255)):(qt(t,r.adler>>>16),qt(t,65535&r.adler)),ae(r),t.wrap>0&&(t.wrap=-t.wrap),t.pending!==0?X:go)},deflateEnd:function(r){if(Jt(r))return Ee;var e=r.state.status;return r.state=null,e===113?nt(r,uf):X},deflateSetDictionary:function(r,e){var t=e.length;if(Jt(r))return Ee;var i=r.state,n=i.wrap;if(n===2||n===1&&i.status!==42||i.lookahead)return Ee;if(n===1&&(r.adler=Kt(r.adler,e,t,0)),i.wrap=0,t>=i.w_size){n===0&&($e(i.head),i.strstart=0,i.block_start=0,i.insert=0);var s=new Uint8Array(i.w_size);s.set(e.subarray(t-i.w_size,t),0),e=s,t=i.w_size}var a=r.avail_in,o=r.next_in,h=r.input;for(r.avail_in=t,r.next_in=0,r.input=e,bt(i);i.lookahead>=3;){var c=i.strstart,u=i.lookahead-2;do i.ins_h=Ke(i,i.ins_h,i.window[c+3-1]),i.prev[c&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=c,c++;while(--u);i.strstart=c,i.lookahead=2,bt(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,r.next_in=o,r.input=h,r.avail_in=a,i.wrap=n,X},deflateInfo:"pako deflate (from Nodeca project)"},Ef=function(r,e){return Object.prototype.hasOwnProperty.call(r,e)},Or={assign:function(r){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var t=e.shift();if(t){if(typeof t!="object")throw new TypeError(t+"must be non-object");for(var i in t)Ef(t,i)&&(r[i]=t[i])}}return r},flattenChunks:function(r){for(var e=0,t=0,i=r.length;t<i;t++)e+=r[t].length;for(var n=new Uint8Array(e),s=0,a=0,o=r.length;s<o;s++){var h=r[s];n.set(h,a),a+=h.length}return n}},wo=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{wo=!1}for(var Xt=new Uint8Array(256),qe=0;qe<256;qe++)Xt[qe]=qe>=252?6:qe>=248?5:qe>=240?4:qe>=224?3:qe>=192?2:1;Xt[254]=Xt[254]=1;var Yt={string2buf:function(r){if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(r);var e,t,i,n,s,a=r.length,o=0;for(n=0;n<a;n++)(64512&(t=r.charCodeAt(n)))==55296&&n+1<a&&(64512&(i=r.charCodeAt(n+1)))==56320&&(t=65536+(t-55296<<10)+(i-56320),n++),o+=t<128?1:t<2048?2:t<65536?3:4;for(e=new Uint8Array(o),s=0,n=0;s<o;n++)(64512&(t=r.charCodeAt(n)))==55296&&n+1<a&&(64512&(i=r.charCodeAt(n+1)))==56320&&(t=65536+(t-55296<<10)+(i-56320),n++),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},buf2string:function(r,e){var t,i,n=e||r.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(r.subarray(0,e));var s=new Array(2*n);for(i=0,t=0;t<n;){var a=r[t++];if(a<128)s[i++]=a;else{var o=Xt[a];if(o>4)s[i++]=65533,t+=o-1;else{for(a&=o===2?31:o===3?15:7;o>1&&t<n;)a=a<<6|63&r[t++],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 function(h,c){if(c<65534&&h.subarray&&wo)return String.fromCharCode.apply(null,h.length===c?h:h.subarray(0,c));for(var u="",l=0;l<c;l++)u+=String.fromCharCode(h[l]);return u}(s,i)},utf8border:function(r,e){(e=e||r.length)>r.length&&(e=r.length);for(var t=e-1;t>=0&&(192&r[t])==128;)t--;return t<0||t===0?e:t+Xt[r[t]]>e?t:e}},To=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},zo=Object.prototype.toString,Cf=x.Z_NO_FLUSH,wf=x.Z_SYNC_FLUSH,Tf=x.Z_FULL_FLUSH,zf=x.Z_FINISH,Mr=x.Z_OK,kf=x.Z_STREAM_END,Af=x.Z_DEFAULT_COMPRESSION,Rf=x.Z_DEFAULT_STRATEGY,Df=x.Z_DEFLATED;function Qt(r){this.options=Or.assign({level:Af,method:Df,chunkSize:16384,windowBits:15,memLevel:8,strategy:Rf},r||{});var 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 To,this.strm.avail_out=0;var t=Zt.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(t!==Mr)throw new Error(it[t]);if(e.header&&Zt.deflateSetHeader(this.strm,e.header),e.dictionary){var i;if(i=typeof e.dictionary=="string"?Yt.string2buf(e.dictionary):zo.call(e.dictionary)==="[object ArrayBuffer]"?new Uint8Array(e.dictionary):e.dictionary,(t=Zt.deflateSetDictionary(this.strm,i))!==Mr)throw new Error(it[t]);this._dict_set=!0}}function qi(r,e){var t=new Qt(e);if(t.push(r,!0),t.err)throw t.msg||it[t.err];return t.result}Qt.prototype.push=function(r,e){var t,i,n=this.strm,s=this.options.chunkSize;if(this.ended)return!1;for(i=e===~~e?e:e===!0?zf:Cf,typeof r=="string"?n.input=Yt.string2buf(r):zo.call(r)==="[object ArrayBuffer]"?n.input=new Uint8Array(r):n.input=r,n.next_in=0,n.avail_in=n.input.length;;)if(n.avail_out===0&&(n.output=new Uint8Array(s),n.next_out=0,n.avail_out=s),(i===wf||i===Tf)&&n.avail_out<=6)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else{if((t=Zt.deflate(n,i))===kf)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),t=Zt.deflateEnd(this.strm),this.onEnd(t),this.ended=!0,t===Mr;if(n.avail_out!==0){if(i>0&&n.next_out>0)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else if(n.avail_in===0)break}else this.onData(n.output)}return!0},Qt.prototype.onData=function(r){this.chunks.push(r)},Qt.prototype.onEnd=function(r){r===Mr&&(this.result=Or.flattenChunks(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var Ir={Deflate:Qt,deflate:qi,deflateRaw:function(r,e){return(e=e||{}).raw=!0,qi(r,e)},gzip:function(r,e){return(e=e||{}).gzip=!0,qi(r,e)},constants:x},xf=function(r,e){var t,i,n,s,a,o,h,c,u,l,d,p,f,v,m,E,y,_,C,z,w,O,k,T,A=r.state;t=r.next_in,k=r.input,i=t+(r.avail_in-5),n=r.next_out,T=r.output,s=n-(e-r.avail_out),a=n+(r.avail_out-257),o=A.dmax,h=A.wsize,c=A.whave,u=A.wnext,l=A.window,d=A.hold,p=A.bits,f=A.lencode,v=A.distcode,m=(1<<A.lenbits)-1,E=(1<<A.distbits)-1;e:do{p<15&&(d+=k[t++]<<p,p+=8,d+=k[t++]<<p,p+=8),y=f[d&m];t:for(;;){if(d>>>=_=y>>>24,p-=_,(_=y>>>16&255)===0)T[n++]=65535&y;else{if(!(16&_)){if(!(64&_)){y=f[(65535&y)+(d&(1<<_)-1)];continue t}if(32&_){A.mode=16191;break e}r.msg="invalid literal/length code",A.mode=16209;break e}C=65535&y,(_&=15)&&(p<_&&(d+=k[t++]<<p,p+=8),C+=d&(1<<_)-1,d>>>=_,p-=_),p<15&&(d+=k[t++]<<p,p+=8,d+=k[t++]<<p,p+=8),y=v[d&E];r:for(;;){if(d>>>=_=y>>>24,p-=_,!(16&(_=y>>>16&255))){if(!(64&_)){y=v[(65535&y)+(d&(1<<_)-1)];continue r}r.msg="invalid distance code",A.mode=16209;break e}if(z=65535&y,p<(_&=15)&&(d+=k[t++]<<p,(p+=8)<_&&(d+=k[t++]<<p,p+=8)),(z+=d&(1<<_)-1)>o){r.msg="invalid distance too far back",A.mode=16209;break e}if(d>>>=_,p-=_,z>(_=n-s)){if((_=z-_)>c&&A.sane){r.msg="invalid distance too far back",A.mode=16209;break e}if(w=0,O=l,u===0){if(w+=h-_,_<C){C-=_;do T[n++]=l[w++];while(--_);w=n-z,O=T}}else if(u<_){if(w+=h+u-_,(_-=u)<C){C-=_;do T[n++]=l[w++];while(--_);if(w=0,u<C){C-=_=u;do T[n++]=l[w++];while(--_);w=n-z,O=T}}}else if(w+=u-_,_<C){C-=_;do T[n++]=l[w++];while(--_);w=n-z,O=T}for(;C>2;)T[n++]=O[w++],T[n++]=O[w++],T[n++]=O[w++],C-=3;C&&(T[n++]=O[w++],C>1&&(T[n++]=O[w++]))}else{w=n-z;do T[n++]=T[w++],T[n++]=T[w++],T[n++]=T[w++],C-=3;while(C>2);C&&(T[n++]=T[w++],C>1&&(T[n++]=T[w++]))}break}}break}}while(t<i&&n<a);t-=C=p>>3,d&=(1<<(p-=C<<3))-1,r.next_in=t,r.next_out=n,r.avail_in=t<i?i-t+5:5-(t-i),r.avail_out=n<a?a-n+257:257-(n-a),A.hold=d,A.bits=p},Of=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]),Mf=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]),If=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]),Pf=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]),er=function(r,e,t,i,n,s,a,o){var h,c,u,l,d,p,f,v,m,E=o.bits,y=0,_=0,C=0,z=0,w=0,O=0,k=0,T=0,A=0,P=0,ie=null,J=new Uint16Array(16),ue=new Uint16Array(16),he=null;for(y=0;y<=15;y++)J[y]=0;for(_=0;_<i;_++)J[e[t+_]]++;for(w=E,z=15;z>=1&&J[z]===0;z--);if(w>z&&(w=z),z===0)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(C=1;C<z&&J[C]===0;C++);for(w<C&&(w=C),T=1,y=1;y<=15;y++)if(T<<=1,(T-=J[y])<0)return-1;if(T>0&&(r===0||z!==1))return-1;for(ue[1]=0,y=1;y<15;y++)ue[y+1]=ue[y]+J[y];for(_=0;_<i;_++)e[t+_]!==0&&(a[ue[e[t+_]]++]=_);if(r===0?(ie=he=a,p=20):r===1?(ie=Of,he=Mf,p=257):(ie=If,he=Pf,p=0),P=0,_=0,y=C,d=s,O=w,k=0,u=-1,l=(A=1<<w)-1,r===1&&A>852||r===2&&A>592)return 1;for(;;){f=y-k,a[_]+1<p?(v=0,m=a[_]):a[_]>=p?(v=he[a[_]-p],m=ie[a[_]-p]):(v=96,m=0),h=1<<y-k,C=c=1<<O;do n[d+(P>>k)+(c-=h)]=f<<24|v<<16|m|0;while(c!==0);for(h=1<<y-1;P&h;)h>>=1;if(h!==0?(P&=h-1,P+=h):P=0,_++,--J[y]==0){if(y===z)break;y=e[t+a[_]]}if(y>w&&(P&l)!==u){for(k===0&&(k=w),d+=C,T=1<<(O=y-k);O+k<z&&!((T-=J[O+k])<=0);)O++,T<<=1;if(A+=1<<O,r===1&&A>852||r===2&&A>592)return 1;n[u=P&l]=w<<24|O<<16|d-s|0}}return P!==0&&(n[d+P]=y-k<<24|64<<16|0),o.bits=w,0},ko=x.Z_FINISH,Lf=x.Z_BLOCK,Pr=x.Z_TREES,st=x.Z_OK,Uf=x.Z_STREAM_END,Nf=x.Z_NEED_DICT,pe=x.Z_STREAM_ERROR,Ao=x.Z_DATA_ERROR,Ro=x.Z_MEM_ERROR,Gf=x.Z_BUF_ERROR,Do=x.Z_DEFLATED,xo=function(r){return(r>>>24&255)+(r>>>8&65280)+((65280&r)<<8)+((255&r)<<24)};function Bf(){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}var Wi,Ji,ot=function(r){if(!r)return 1;var e=r.state;return!e||e.strm!==r||e.mode<16180||e.mode>16211?1:0},Oo=function(r){if(ot(r))return pe;var 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,st},Mo=function(r){if(ot(r))return pe;var e=r.state;return e.wsize=0,e.whave=0,e.wnext=0,Oo(r)},Io=function(r,e){var t;if(ot(r))return pe;var i=r.state;return e<0?(t=0,e=-e):(t=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?pe:(i.window!==null&&i.wbits!==e&&(i.window=null),i.wrap=t,i.wbits=e,Mo(r))},Po=function(r,e){if(!r)return pe;var t=new Bf;r.state=t,t.strm=r,t.window=null,t.mode=16180;var i=Io(r,e);return i!==st&&(r.state=null),i},Lo=!0,Vf=function(r){if(Lo){Wi=new Int32Array(512),Ji=new Int32Array(32);for(var e=0;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(er(1,r.lens,0,288,Wi,0,r.work,{bits:9}),e=0;e<32;)r.lens[e++]=5;er(2,r.lens,0,32,Ji,0,r.work,{bits:5}),Lo=!1}r.lencode=Wi,r.lenbits=9,r.distcode=Ji,r.distbits=5},Uo=function(r,e,t,i){var n,s=r.state;return s.window===null&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),i>=s.wsize?(s.window.set(e.subarray(t-s.wsize,t),0),s.wnext=0,s.whave=s.wsize):((n=s.wsize-s.wnext)>i&&(n=i),s.window.set(e.subarray(t-i,t-i+n),s.wnext),(i-=n)?(s.window.set(e.subarray(t-i,t),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=n))),0},Le={inflateReset:Mo,inflateReset2:Io,inflateResetKeep:Oo,inflateInit:function(r){return Po(r,15)},inflateInit2:Po,inflate:function(r,e){var t,i,n,s,a,o,h,c,u,l,d,p,f,v,m,E,y,_,C,z,w,O,k,T,A=0,P=new Uint8Array(4),ie=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(ot(r)||!r.output||!r.input&&r.avail_in!==0)return pe;(t=r.state).mode===16191&&(t.mode=16192),a=r.next_out,n=r.output,h=r.avail_out,s=r.next_in,i=r.input,o=r.avail_in,c=t.hold,u=t.bits,l=o,d=h,O=st;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+=i[s++]<<u,u+=8}if(2&t.wrap&&c===35615){t.wbits===0&&(t.wbits=15),t.check=0,P[0]=255&c,P[1]=c>>>8&255,t.check=q(t.check,P,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)!==Do){r.msg="unknown compression method",t.mode=16209;break}if(u-=4,w=8+(15&(c>>>=4)),t.wbits===0&&(t.wbits=w),w>15||w>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+=i[s++]<<u,u+=8}if(t.flags=c,(255&t.flags)!==Do){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&&(P[0]=255&c,P[1]=c>>>8&255,t.check=q(t.check,P,2,0)),c=0,u=0,t.mode=16182;case 16182:for(;u<32;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}t.head&&(t.head.time=c),512&t.flags&&4&t.wrap&&(P[0]=255&c,P[1]=c>>>8&255,P[2]=c>>>16&255,P[3]=c>>>24&255,t.check=q(t.check,P,4,0)),c=0,u=0,t.mode=16183;case 16183:for(;u<16;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}t.head&&(t.head.xflags=255&c,t.head.os=c>>8),512&t.flags&&4&t.wrap&&(P[0]=255&c,P[1]=c>>>8&255,t.check=q(t.check,P,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+=i[s++]<<u,u+=8}t.length=c,t.head&&(t.head.extra_len=c),512&t.flags&&4&t.wrap&&(P[0]=255&c,P[1]=c>>>8&255,t.check=q(t.check,P,2,0)),c=0,u=0}else t.head&&(t.head.extra=null);t.mode=16185;case 16185:if(1024&t.flags&&((p=t.length)>o&&(p=o),p&&(t.head&&(w=t.head.extra_len-t.length,t.head.extra||(t.head.extra=new Uint8Array(t.head.extra_len)),t.head.extra.set(i.subarray(s,s+p),w)),512&t.flags&&4&t.wrap&&(t.check=q(t.check,i,p,s)),o-=p,s+=p,t.length-=p),t.length))break e;t.length=0,t.mode=16186;case 16186:if(2048&t.flags){if(o===0)break e;p=0;do w=i[s+p++],t.head&&w&&t.length<65536&&(t.head.name+=String.fromCharCode(w));while(w&&p<o);if(512&t.flags&&4&t.wrap&&(t.check=q(t.check,i,p,s)),o-=p,s+=p,w)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;p=0;do w=i[s+p++],t.head&&w&&t.length<65536&&(t.head.comment+=String.fromCharCode(w));while(w&&p<o);if(512&t.flags&&4&t.wrap&&(t.check=q(t.check,i,p,s)),o-=p,s+=p,w)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+=i[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+=i[s++]<<u,u+=8}r.adler=t.check=xo(c),c=0,u=0,t.mode=16190;case 16190:if(t.havedict===0)return r.next_out=a,r.avail_out=h,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,Nf;r.adler=t.check=1,t.mode=16191;case 16191:if(e===Lf||e===Pr)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+=i[s++]<<u,u+=8}switch(t.last=1&c,u-=1,3&(c>>>=1)){case 0:t.mode=16193;break;case 1:if(Vf(t),t.mode=16199,e===Pr){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+=i[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===Pr)break e;case 16194:t.mode=16195;case 16195:if(p=t.length){if(p>o&&(p=o),p>h&&(p=h),p===0)break e;n.set(i.subarray(s,s+p),a),o-=p,s+=p,h-=p,a+=p,t.length-=p;break}t.mode=16191;break;case 16196:for(;u<14;){if(o===0)break e;o--,c+=i[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+=i[s++]<<u,u+=8}t.lens[ie[t.have++]]=7&c,c>>>=3,u-=3}for(;t.have<19;)t.lens[ie[t.have++]]=0;if(t.lencode=t.lendyn,t.lenbits=7,k={bits:t.lenbits},O=er(0,t.lens,0,19,t.lencode,0,t.work,k),t.lenbits=k.bits,O){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(;E=(A=t.lencode[c&(1<<t.lenbits)-1])>>>16&255,y=65535&A,!((m=A>>>24)<=u);){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}if(y<16)c>>>=m,u-=m,t.lens[t.have++]=y;else{if(y===16){for(T=m+2;u<T;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}if(c>>>=m,u-=m,t.have===0){r.msg="invalid bit length repeat",t.mode=16209;break}w=t.lens[t.have-1],p=3+(3&c),c>>>=2,u-=2}else if(y===17){for(T=m+3;u<T;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}u-=m,w=0,p=3+(7&(c>>>=m)),c>>>=3,u-=3}else{for(T=m+7;u<T;){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}u-=m,w=0,p=11+(127&(c>>>=m)),c>>>=7,u-=7}if(t.have+p>t.nlen+t.ndist){r.msg="invalid bit length repeat",t.mode=16209;break}for(;p--;)t.lens[t.have++]=w}}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,k={bits:t.lenbits},O=er(1,t.lens,0,t.nlen,t.lencode,0,t.work,k),t.lenbits=k.bits,O){r.msg="invalid literal/lengths set",t.mode=16209;break}if(t.distbits=6,t.distcode=t.distdyn,k={bits:t.distbits},O=er(2,t.lens,t.nlen,t.ndist,t.distcode,0,t.work,k),t.distbits=k.bits,O){r.msg="invalid distances set",t.mode=16209;break}if(t.mode=16199,e===Pr)break e;case 16199:t.mode=16200;case 16200:if(o>=6&&h>=258){r.next_out=a,r.avail_out=h,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,xf(r,d),a=r.next_out,n=r.output,h=r.avail_out,s=r.next_in,i=r.input,o=r.avail_in,c=t.hold,u=t.bits,t.mode===16191&&(t.back=-1);break}for(t.back=0;E=(A=t.lencode[c&(1<<t.lenbits)-1])>>>16&255,y=65535&A,!((m=A>>>24)<=u);){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}if(E&&!(240&E)){for(_=m,C=E,z=y;E=(A=t.lencode[z+((c&(1<<_+C)-1)>>_)])>>>16&255,y=65535&A,!(_+(m=A>>>24)<=u);){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}c>>>=_,u-=_,t.back+=_}if(c>>>=m,u-=m,t.back+=m,t.length=y,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(T=t.extra;u<T;){if(o===0)break e;o--,c+=i[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(;E=(A=t.distcode[c&(1<<t.distbits)-1])>>>16&255,y=65535&A,!((m=A>>>24)<=u);){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}if(!(240&E)){for(_=m,C=E,z=y;E=(A=t.distcode[z+((c&(1<<_+C)-1)>>_)])>>>16&255,y=65535&A,!(_+(m=A>>>24)<=u);){if(o===0)break e;o--,c+=i[s++]<<u,u+=8}c>>>=_,u-=_,t.back+=_}if(c>>>=m,u-=m,t.back+=m,64&E){r.msg="invalid distance code",t.mode=16209;break}t.offset=y,t.extra=15&E,t.mode=16203;case 16203:if(t.extra){for(T=t.extra;u<T;){if(o===0)break e;o--,c+=i[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(h===0)break e;if(p=d-h,t.offset>p){if((p=t.offset-p)>t.whave&&t.sane){r.msg="invalid distance too far back",t.mode=16209;break}p>t.wnext?(p-=t.wnext,f=t.wsize-p):f=t.wnext-p,p>t.length&&(p=t.length),v=t.window}else v=n,f=a-t.offset,p=t.length;p>h&&(p=h),h-=p,t.length-=p;do n[a++]=v[f++];while(--p);t.length===0&&(t.mode=16200);break;case 16205:if(h===0)break e;n[a++]=t.length,h--,t.mode=16200;break;case 16206:if(t.wrap){for(;u<32;){if(o===0)break e;o--,c|=i[s++]<<u,u+=8}if(d-=h,r.total_out+=d,t.total+=d,4&t.wrap&&d&&(r.adler=t.check=t.flags?q(t.check,n,d,a-d):Kt(t.check,n,d,a-d)),d=h,4&t.wrap&&(t.flags?c:xo(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+=i[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:O=Uf;break e;case 16209:O=Ao;break e;case 16210:return Ro;case 16211:default:return pe}return r.next_out=a,r.avail_out=h,r.next_in=s,r.avail_in=o,t.hold=c,t.bits=u,(t.wsize||d!==r.avail_out&&t.mode<16209&&(t.mode<16206||e!==ko))&&Uo(r,r.output,r.next_out,d-r.avail_out),l-=r.avail_in,d-=r.avail_out,r.total_in+=l,r.total_out+=d,t.total+=d,4&t.wrap&&d&&(r.adler=t.check=t.flags?q(t.check,n,d,r.next_out-d):Kt(t.check,n,d,r.next_out-d)),r.data_type=t.bits+(t.last?64:0)+(t.mode===16191?128:0)+(t.mode===16199||t.mode===16194?256:0),(l===0&&d===0||e===ko)&&O===st&&(O=Gf),O},inflateEnd:function(r){if(ot(r))return pe;var e=r.state;return e.window&&(e.window=null),r.state=null,st},inflateGetHeader:function(r,e){if(ot(r))return pe;var t=r.state;return 2&t.wrap?(t.head=e,e.done=!1,st):pe},inflateSetDictionary:function(r,e){var t,i=e.length;return ot(r)||(t=r.state).wrap!==0&&t.mode!==16190?pe:t.mode===16190&&Kt(1,e,i,0)!==t.check?Ao:Uo(r,e,i,i)?(t.mode=16210,Ro):(t.havedict=1,st)},inflateInfo:"pako inflate (from Nodeca project)"},Ff=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},No=Object.prototype.toString,jf=x.Z_NO_FLUSH,Hf=x.Z_FINISH,tr=x.Z_OK,Zi=x.Z_STREAM_END,Xi=x.Z_NEED_DICT,$f=x.Z_STREAM_ERROR,Go=x.Z_DATA_ERROR,Kf=x.Z_MEM_ERROR;function rr(r){this.options=Or.assign({chunkSize:65536,windowBits:15,to:""},r||{});var 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 To,this.strm.avail_out=0;var t=Le.inflateInit2(this.strm,e.windowBits);if(t!==tr)throw new Error(it[t]);if(this.header=new Ff,Le.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=Yt.string2buf(e.dictionary):No.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(t=Le.inflateSetDictionary(this.strm,e.dictionary))!==tr))throw new Error(it[t])}function Yi(r,e){var t=new rr(e);if(t.push(r),t.err)throw t.msg||it[t.err];return t.result}rr.prototype.push=function(r,e){var t,i,n,s=this.strm,a=this.options.chunkSize,o=this.options.dictionary;if(this.ended)return!1;for(i=e===~~e?e:e===!0?Hf:jf,No.call(r)==="[object ArrayBuffer]"?s.input=new Uint8Array(r):s.input=r,s.next_in=0,s.avail_in=s.input.length;;){for(s.avail_out===0&&(s.output=new Uint8Array(a),s.next_out=0,s.avail_out=a),(t=Le.inflate(s,i))===Xi&&o&&((t=Le.inflateSetDictionary(s,o))===tr?t=Le.inflate(s,i):t===Go&&(t=Xi));s.avail_in>0&&t===Zi&&s.state.wrap>0&&r[s.next_in]!==0;)Le.inflateReset(s),t=Le.inflate(s,i);switch(t){case $f:case Go:case Xi:case Kf:return this.onEnd(t),this.ended=!0,!1}if(n=s.avail_out,s.next_out&&(s.avail_out===0||t===Zi))if(this.options.to==="string"){var h=Yt.utf8border(s.output,s.next_out),c=s.next_out-h,u=Yt.buf2string(s.output,h);s.next_out=c,s.avail_out=a-c,c&&s.output.set(s.output.subarray(h,h+c),0),this.onData(u)}else this.onData(s.output.length===s.next_out?s.output:s.output.subarray(0,s.next_out));if(t!==tr||n!==0){if(t===Zi)return t=Le.inflateEnd(this.strm),this.onEnd(t),this.ended=!0,!0;if(s.avail_in===0)break}}return!0},rr.prototype.onData=function(r){this.chunks.push(r)},rr.prototype.onEnd=function(r){r===tr&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Or.flattenChunks(this.chunks)),this.chunks=[],this.err=r,this.msg=this.strm.msg};var ir,Lr={Inflate:rr,inflate:Yi,inflateRaw:function(r,e){return(e=e||{}).raw=!0,Yi(r,e)},ungzip:Yi,constants:x},qf={Deflate:Ir.Deflate,deflate:Ir.deflate,deflateRaw:Ir.deflateRaw,gzip:Ir.gzip,Inflate:Lr.Inflate,inflate:Lr.inflate,inflateRaw:Lr.inflateRaw,ungzip:Lr.ungzip,constants:x},Wf=function(){return!(!window.navigator||!window.navigator.sendBeacon)},Jf=function(){function r(e,t){var i=this;this.collector=e,this.config=t,this.requestType=t.request_type||"xhr",this.supportBeacon=Wf(),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||{},this.collector.on("custom-request-header",function(n){i.setRequestHeader(n)})}return r.prototype.setRequestHeader=function(e){this.customHeader=Object.assign(this.customHeader,e)},r.prototype.useFetch=function(e){var t=e.url,i=e.data,n=e.method,s=e.success,a=e.fail,o={"Content-Type":"application/json; charset=utf-8"};if(Object.keys(this.customHeader).length)for(var h in this.customHeader)o[h]=this.customHeader[h];window.fetch?fetch(t,{method:n||"POST",headers:o,body:JSON.stringify(i)}).then(function(c){return c.json()}).then(function(c){s&&s(c)}).catch(function(c){a&&a(i,c)}):(this.requestType="xhr",console.log("your brwoser not support fetch, use xhr"),this.useRequest({url:t,data:i,method:n,success:s,fail:a}))},r.prototype.useBeacon=function(e){var t=e.url,i=e.data,n=e.success,s=e.fail;window.navigator.sendBeacon(t,JSON.stringify(i))?n&&n():s&&s(i,this.errorCode.BEACON_FALSE)},r.prototype.useRequest=function(e){var t=this,i=e.url,n=e.data,s=e.method,a=e.success,o=e.fail,h=e.timeout,c=e.useBeacon,u=e.withCredentials,l=e.app_key,d=e.forceXhr,p=e.zip;if(c&&this.supportBeacon)this.useBeacon({url:i,data:n,method:s,success:a,fail:o});else if(this.requestType!=="fetch"||d)try{var f=new XMLHttpRequest,v=s||"POST";if(f.open(v,""+i,!0),f.setRequestHeader("Content-Type","application/json; charset=utf-8"),l&&f.setRequestHeader("X-MCS-AppKey",""+l),Object.keys(this.customHeader).length)for(var m in this.customHeader)f.setRequestHeader(m,this.customHeader[m]);u&&(f.withCredentials=!0),h&&(f.timeout=h,f.ontimeout=function(){o&&o(n,t.errorCode.TIMEOUT)}),f.onload=function(){if(a){var C=null;if(f.responseText){try{C=JSON.parse(f.responseText)}catch{C={}}a(C,n)}}},f.onerror=function(){f.abort(),o&&o(n,t.errorCode.XHR_ON)};try{var E=JSON.stringify(n);if(this.config.need_zip&&p){var y=new TextEncoder().encode(E),_=qf.gzip(y);f.setRequestHeader("Content-Encoding","gzip"),f.send(_)}else f.send(E)}catch(C){this.collector.emit("sdk-inner-error",{type:"sdk_error_send",eventData:n,errorCode:1e3,msg:C.message||C.stack||"sdk_error_send"})}}catch(C){this.collector.emit("sdk-inner-error",{type:"sdk_error_request",eventData:n,errorCode:1001,msg:C.message||C.stack||"sdk_error_request"})}else this.useFetch({url:i,data:n,method:s,success:a,fail:o})},r}(),Zf=function(){function r(e,t){if(this.devToolReady=!1,this.devToolOrigin="*",this.sendAlready=!1,!t.disable_debug&&e.configManager.get("browser")!=="Microsoft Internet Explorer"){this.collect=e,this.config=t,this.app_id=t.app_id;var i=e.adapters.storage;this.cacheStorgae=new i(!1),this.loadUrl=t.devtool_url||K("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z21z22z18z22z1gz1az4az18z1nz1nz1jz1mz1ez1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz18z1nz1nz1jz1mz1ez49z21z1bz1iz49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz1bz1cz24z22z1mz1mz1jz4bz1bz1cz19z23z1ez49z25z1cz19z4az24z4ez4az4cz4az4cz4az1hz21"),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(i){console.log("devTool load fail, "+i.message)}},r.prototype.parseUrl=function(){var e={};try{var t=window.location.href.split("?")[1].split("&");t.length&&t.forEach(function(i){var n=i.split("=");e[decodeURIComponent(n[0])]=decodeURIComponent(n[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)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:"基本信息",key:"base",type:1,content:[{name:"app_id",desc:"APP_ID",value:this.config.app_id},{name:"channel",desc:"CHANNEL",value:this.config.channel},{name:"domain",desc:"上报域名",value:this.collect.configManager.getDomain()},{name:"sdk_version",desc:"SDK版本",value:Fe},{name:"sdk_type",desc:"SDK引入方式",value:"npm"}]},{title:"用户信息",key:"user",type:2,content:[{name:"uuid",desc:"UUID",value:this.collect.configManager.get("user").user_unique_id||""},{name:"web_id",desc:"WEB_ID",value:this.collect.configManager.get("user").web_id||""}]},{title:"公共参数信息",type:2,key:"common",content:[{name:"browser",desc:"浏览器",value:this.collect.configManager.get("browser")},{name:"browser_version",desc:"浏览器版本",value:this.collect.configManager.get("browser_version")},{name:"platform",desc:"平台",value:this.collect.configManager.get("platform")},{name:"device_model",desc:"设备型号",value:this.collect.configManager.get("device_model")},{name:"os_name",desc:"操作系统",value:this.collect.configManager.get("os_name")},{name:"os_version",desc:"操作系统版本",value:this.collect.configManager.get("os_version")},{name:"resolution",desc:"屏幕分辨率",value:this.collect.configManager.get("resolution")},{name:"referrer",desc:"来源",value:this.collect.configManager.get("referrer")},{name:"custom",desc:"自定义信息",value:JSON.stringify(this.collect.configManager.get("custom"))}]},{title:"配置信息",key:"config",type:3,content:[{name:"autotrack",desc:"全埋点",value:!!this.config.autotrack},{name:"stay",desc:"停留时长",value:!!this.config.enable_stay_duration}]},{title:"A/B配置信息",key:"ab",type:4,content:[{name:"ab",desc:"A/B实验",value:!!this.config.enable_ab_test}]}],this.config.enable_ab_test){var e=this.getInfo("ab"),t=[{name:"ab",desc:"A/B实验",value:!!this.config.enable_ab_test},{name:"vid",desc:"已曝光VID",value:this.collect.configManager.getAbVersion()},{name:"ab_domain",desc:"A/B域名",value:this.config.ab_channel_domain||K(Ys[this.config.channel])},{name:"all_values",desc:"全部配置",value:this.collect.configManager.getAbCache()}];e.content=t,this.setInfo("ab",e)}if(this.config.enable_native||this.config.Native){var i={title:"客户端信息",type:3,content:[{name:"native",desc:"是否打通",value:!!this.collect.bridgeReport}]};this.setInfo("native",i)}if(Fe.includes("tob")){var n=this.getInfo("user");n.content.push({name:"sid",desc:"DISS".split("").reverse().join(""),value:"点击获取"}),this.setInfo("user",n)}},r.prototype.getInfo=function(e){var t=null;return this.info.forEach(function(i){i.key===e&&(t=i)}),t},r.prototype.setInfo=function(e,t){var i=!1;this.info.forEach(function(n){n.key===e&&(i=!0,n=t)}),i||this.info.push(t)},r.prototype.getSecondInfo=function(e,t){var i=this.getInfo(e),n=null;return i.content.forEach(function(s){s.name===t&&(n=s)}),n},r.prototype.setSecondInfo=function(e,t,i){var n=this.getInfo(e),s=!1;if(n.content.forEach(function(o){o.name===t&&(o.value=i,s=!0)}),!s){var a={name:t,value:i,desc:t.toLocaleUpperCase()};n.content.push(a)}this.setInfo(e,n)},r.prototype.loadHook=function(){var e=this;this.collect.on(g.DEBUGGER_MESSAGE,function(t){switch(t.type){case g.DEBUGGER_MESSAGE_SDK:var i={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&&(i.desc={content:JSON.stringify(t.data)}),e.updateLog(i),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 n=e.collect.configManager.get(t.common);e.setSecondInfo("common",t.common,t.common==="custom"?JSON.stringify(n):n)}return void e.updateInfo();case g.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(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:Fe.includes("tob")?"tob":"inner",appId:e.app_id}),e.sendAlready=!0}t&&t.data&&t.data.type==="devtool:web:ssid"&&e.collect.getToken(function(i){e.setSecondInfo("user","sid",i.tobid),e.updateInfo()})})},r.prototype.sendData=function(e,t){try{var i={type:e,payload:t};window&&window.postMessage(i,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
|
+
position: fixed;
|
|
58
|
+
width: 45px;
|
|
59
|
+
height: 45px;
|
|
60
|
+
background-image: url(`+K("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z1az1bz1lz49z22z1mz21z4az19z27z22z1cz21z1az1kz4az1az1mz1kz4bz1mz19z1hz4bz21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz1bz1cz24z22z1mz1mz1jz4bz18z1nz1nz1jz1mz1ez4az1nz1lz1e")+`);
|
|
61
|
+
bottom: 5%;
|
|
62
|
+
right: 10%;
|
|
63
|
+
cursor: pointer;
|
|
64
|
+
z-index:100;
|
|
65
|
+
background-size: 45px;
|
|
66
|
+
}`,t=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.appendChild(document.createTextNode(e)),t.appendChild(i);var n=document.createElement("div");n.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(n),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}(),Qi={autotrack:{src:{cn:K("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z21z22z18z22z1gz1az4az18z1nz1nz1jz1mz1ez1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz18z1nz1nz1jz1mz1ez49z21z1bz1iz49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz4hz4bz1nz1jz23z1ez1gz1lz4bz18z23z22z1mz22z20z18z1az1iz4az1hz21"),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:{cn:K("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z21z22z18z22z1gz1az4az18z1nz1nz1jz1mz1ez1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz18z1nz1nz1jz1mz1ez49z21z1bz1iz49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz4hz4bz1nz1jz23z1ez1gz1lz4bz18z19z4az1hz21"),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:{cn:K("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z21z22z18z22z1gz1az4az18z1nz1nz1jz1mz1ez1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz18z1nz1nz1jz1mz1ez49z21z1bz1iz49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz4hz4bz1nz1jz23z1ez1gz1lz4bz21z22z18z27z4az1hz21"),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:{cn:K("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z21z22z18z22z1gz1az4az18z1nz1nz1jz1mz1ez1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz18z1nz1nz1jz1mz1ez49z21z1bz1iz49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz4hz4bz1nz1jz23z1ez1gz1lz4bz20z1mz23z22z1cz4az1hz21"),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:{cn:K("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z21z22z18z22z1gz1az4az18z1nz1nz1jz1mz1ez1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz18z1nz1nz1jz1mz1ez49z21z1bz1iz49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz4hz4bz1nz1jz23z1ez1gz1lz4bz22z20z18z1az1cz20z4az1hz21"),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:{cn:K("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z21z22z18z22z1gz1az4az18z1nz1nz1jz1mz1ez1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz18z1nz1nz1jz1mz1ez49z21z1bz1iz49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz4hz4bz1nz1jz23z1ez1gz1lz4bz20z1cz22z20z27z4az1hz21"),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:{cn:K("1fz22z22z1nz21z4mz4bz4bz1jz1dz49z21z22z18z22z1gz1az4az18z1nz1nz1jz1mz1ez1az1bz1lz4az1az1mz1kz4bz1mz19z1hz4bz18z1nz1nz1jz1mz1ez49z21z1bz1iz49z21z22z18z22z1gz1az4bz1jz1mz1ez49z21z1bz1iz4bz1az1mz1jz1jz1cz1az22z4bz4hz4bz1nz1jz23z1ez1gz1lz4bz24z1gz21z23z18z1jz4az1hz21"),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"}},Xf=["ab","autotrack","Stay","store","et","profile","cep","heartbeat","monitor","route","tracer"],fe=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 Pp,this.remotePlugin=new Map,this.Types=S,this.adapters.storage=Ie,this.loadType="full"}return r.usePlugin=function(e,t,i){if(t){for(var n=!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=i||{},n=!0;break}n||r.plugins.push({name:t,plugin:e,options:i})}else r.plugins.push({plugin:e})},r.prototype.usePlugin=function(e,t,i){e&&(this.loadType==="full"&&Xf.includes(e)?console.info("your sdk version has "+e+" plugin already ~"):t?typeof t=="string"?this.remotePlugin.get(e)||this.remotePlugin.set(e,{src:t,call:i}):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,i=this;this.logger=new Jp(this.name,e.log),this.inited?this.logger.warn("[instance: "+this.name+"], every instance's api: init, can be call only one time!"):e&&Gt(e)?e.app_id&&typeof(t=e.app_id)=="number"&&!isNaN(t)?!e.app_key||function(n){return typeof n=="string"}(e.app_key)?(e.channel_domain||["cn","sg","va","my"].indexOf(e.channel)!==-1||(this.logger.warn("channel must be `cn`, `sg`,`va`, `my` !"),e.channel="cn"),this.spider=new Zp,this.spider.checkSpider(e)?this.logger.warn("your env may be a spider, can not report!"):(this.appBridge=new Xp(this,e.enable_native),this.requestManager=new Jf(this,e),this.bridgeReport=this.appBridge.bridgeInject(),this.configManager=new Wp(this,e),this.debugger=new Zf(this,e),this.initConfig=e,this.emit(S.Init),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行Init",data:e,level:"info",time:Date.now(),infoType:"cus"}),this.destroy=!1,e.disable_auto_pv&&(this.disableAutoPageView=!0),this.bridgeReport||(this.configManager.set({app_id:e.app_id}),this.eventManager=new Qp,this.tokenManager=new ef,this.sessionManager=new Yp,Promise.all([new Promise(function(n){i.once(S.TokenComplete,function(){n(!0)})}),new Promise(function(n){i.once(S.Start,function(){n(!0)})})]).then(function(){try{r.plugins.reduce(function(n,s){var a=s.plugin,o=s.options,h=Object.assign(i.initConfig,o),c=new a;return c.apply(i,h),n.push(c),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK加载"+s.name+"插件",level:"info",time:Date.now(),infoType:"sdk"}),n},i.pluginInstances)}catch(n){console.warn("load plugin error, "+n.message),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK加载插件发生了异常",level:"error",time:Date.now(),data:n.message,infoType:"sdk"})}i.sdkReady=!0,i.emit(S.Ready),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 用户信息初始化完成",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"}),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 初始化完成",time:Date.now(),level:"info",data:i.configManager.get("user"),infoType:"sdk"}),i.logger.info("appid: "+e.app_id+", userInfo:"+JSON.stringify(i.configManager.get("user"))),i.logger.info("appid: "+e.app_id+", sdk is ready, version type is "+i.loadType+", version is "+Fe+", you can report now !!!"),e.disable_auto_pv&&(i.disableAutoPageView=!0);try{i.loadType==="full"&&(e.enable_ab_test||e.autotrack)&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")}catch(n){i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK发生了异常",level:"error",time:Date.now(),data:n.message,infoType:"sdk"})}i.pageView(),i.on(S.TokenChange,function(n){n==="webid"&&i.pageView(),i.logger.info("appid: "+e.app_id+" token change, new userInfo:"+JSON.stringify(i.configManager.get("user"))),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 设置了用户信息",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(S.TokenReset,function(){i.logger.info("appid: "+e.app_id+" token reset, new userInfo:"+JSON.stringify(i.configManager.get("user"))),i.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 重置了用户信息",time:Date.now(),secType:"USER",level:"info",data:i.configManager.get("user"),infoType:"sdk"})}),i.on(S.RouteChange,function(n){n.init||e.disable_route_report||i.pageView()})}),this.tokenManager.apply(this,e),this.eventManager.apply(this,e),this.sessionManager.apply(this,e)),this.inited=!0)):this.logger.warn("app_key param is error, must be string, please check!"):this.logger.warn("app_id param is error, must be number, please check!"):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(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK执行Config发生了异常",level:"error",time:Date.now(),data:"config must be use after function init",infoType:"sdk"});if(!e||!Gt(e))return console.warn("config params is error, please check"),void this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK执行Config发生了异常",level:"error",time:Date.now(),data:"config params is error, please check",infoType:"sdk"});if(this.bridgeReport)this.appBridge.setConfig(e);else{e._staging_flag&&e._staging_flag===1&&(this.staging=!0),e.disable_auto_pv&&(this.disableAutoPageView=!0,delete e.disable_auto_pv);var t=U({},e),i=this.initConfig.configPersist||this.initConfig.config_persist||!1;if(this.initConfig&&i){var n=this.configManager.getStore();n&&(t=Object.assign(n,e)),this.configManager.setStore(e)}t.web_id,t.user_unique_id;var s=function(a,o){var h={};for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&o.indexOf(c)<0&&(h[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&&(h[c[u]]=a[c[u]])}return h}(t,["web_id","user_unique_id"]);this.configManager.set(s),t.hasOwnProperty("web_id")&&this.emit(S.ConfigWebId,t.web_id),t.hasOwnProperty("user_unique_id")&&this.emit(S.ConfigUuid,t.user_unique_id),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行Config",level:"info",time:Date.now(),data:t,infoType:"cus"})}},r.prototype.setUserUniqueID=function(e){this.config({user_unique_id:e})},r.prototype.setHeaderInfo=function(e,t){var i={};i[e]=t,this.config(i)},r.prototype.removeHeaderInfo=function(e){var t={};t[e]=void 0,this.config(t)},r.prototype.setDomain=function(e){this.configManager&&this.configManager.setDomain(e),this.emit(S.ConfigDomain)},r.prototype.getConfig=function(e){var t;return(t=this.configManager)===null||t===void 0?void 0:t.get(e)},r.prototype.send=function(){this.start()},r.prototype.start=function(){this.inited&&!this.sended&&(this.sended=!0,this.started=!0,this.emit(S.Start),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行Start",level:"info",time:Date.now(),infoType:"cus"}),this.bridgeReport&&(this.pageView(),this.emit(S.Ready)))},r.prototype.event=function(e,t){var i=this;try{var n=[];if(Array.isArray(e))e.forEach(function(a){var o=i.processEvent(a[0],a[1]||{});o&&n.push(o)});else{var s=this.processEvent(e,t);if(!s)return;n.push(s)}this.bridgeReport?n.forEach(function(a){var o=a.event,h=a.params;i.appBridge.onEventV3(o,JSON.stringify(h))}):n.length&&(this.emit(S.Event,n),this.emit(S.SessionResetTime)),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行Event",level:"info",time:Date.now(),data:e,infoType:"cus"})}catch(a){this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行Event发生了异常",level:"error",time:Date.now(),data:a.message,infoType:"sdk"})}},r.prototype.beconEvent=function(e,t){if(Array.isArray(e))console.warn("beconEvent not support batch report, please check");else{var i=[],n=this.processEvent(e,t||{});n&&(i.push(n),i.length&&(this.emit(S.BeconEvent,i),this.emit(S.SessionResetTime)),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行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 i=e;/^event\./.test(e)&&(i=e.slice(6));var n=t;typeof n!="object"&&(n={}),n.profile?delete n.profile:n.event_index=Lp();var s=void 0;return n.local_ms?(s=n.local_ms,delete n.local_ms):s=+new Date,{event:i,params:n,local_time_ms:s,is_bav:this.initConfig&&this.initConfig.autotrack?1:0}}catch(a){return this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK发生了异常",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,i){this.hook.emit(e,t,i)},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:this.handlePath(),time:Date.now(),referrer:window.document.referrer,$is_first_time:""+(this.configManager&&this.configManager.is_first_time||!1)},i=U(U({},t),e);this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 上报PV",level:"info",time:Date.now(),infoType:"sdk"}),this.event("predefine_pageview",i)}else console.warn("predefinePageView must be use after function init")},r.prototype.handlePath=function(){var e=location.pathname;try{if(this.initConfig.allow_hash){var t=new URL(location.href).hash.match(/#\/([^?#]+)/i);return t&&t.length?t[1]:location.pathname}}catch{e=location.pathname}return e},r.prototype.clearEventCache=function(){this.emit(S.CleanEvents)},r.prototype.setWebIDviaUnionID=function(e){if(e){var t=Zs(e);this.config({web_id:""+t,wechat_unionid:e}),this.emit(S.CustomWebId)}},r.prototype.setWebId=function(e){this.config({web_id:""+e})},r.prototype.setWebIDviaOpenID=function(e){if(e){var t=Zs(e);this.config({web_id:""+t,wechat_openid:e}),this.emit(S.CustomWebId)}},r.prototype.setNativeAppId=function(e){this.bridgeReport&&this.appBridge.setNativeAppId(e)},r.prototype.setRequestHeaders=function(e){this.emit(S.CustomHeader,e)},r.prototype.getSessionId=function(){return vt()},r.prototype.setSessionId=function(e){this.emit(S.SessionReset,e)},r.prototype.resetStayDuration=function(e,t,i){this.emit(S.ResetStay,{url_path:e,title:t,url:i},S.Stay)},r.prototype.resetStayParams=function(e,t,i){e===void 0&&(e=""),t===void 0&&(t=""),i===void 0&&(i=""),this.emit(S.SetStay,{url_path:e,title:t,url:i},S.Stay)},r.prototype.getToken=function(e,t){var i=this;if(this.inited){var n=!1,s=function(o){if(!n){n=!0;var h=i.configManager.get().user;return o&&(h.tobid=o,h["diss".split("").reverse().join("")]=o),e(U({},h))}},a=function(){i.tokenManager.getTobId().then(function(o){s(o)})};this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行GetToken",level:"info",time:Date.now(),infoType:"cus"}),this.sdkReady?a():(t&&setTimeout(function(){s()},t),this.on(S.Ready,function(){a()}))}else console.warn("getToken must be use after function init")},r.prototype.profileSet=function(e){this.bridgeReport?this.appBridge.profileSet(JSON.stringify(e)):this.emit(S.ProfileSet,e,S.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileSet",level:"info",time:Date.now(),data:e,infoType:"cus"})},r.prototype.profileSetOnce=function(e){this.bridgeReport?this.appBridge.profileSetOnce(JSON.stringify(e)):this.emit(S.ProfileSetOnce,e,S.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileSetOnce",level:"info",time:Date.now(),data:e,infoType:"cus"})},r.prototype.profileIncrement=function(e){this.bridgeReport?this.appBridge.profileIncrement(JSON.stringify(e)):this.emit(S.ProfileIncrement,e,S.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileIncrement",level:"info",time:Date.now(),data:e,infoType:"cus"})},r.prototype.profileUnset=function(e){this.bridgeReport?this.appBridge.profileUnset(e):this.emit(S.ProfileUnset,e,S.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileUnset",level:"info",time:Date.now(),data:e,infoType:"cus"})},r.prototype.profileAppend=function(e){this.bridgeReport?this.appBridge.profileAppend(JSON.stringify(e)):this.emit(S.ProfileAppend,e,S.Profile),this.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行profileAppend",level:"info",time:Date.now(),data:e,infoType:"cus"})},r.prototype.setExternalAbVersion=function(e){this.emit(S.AbExternalVersion,typeof e=="string"&&e?(""+e).trim():null,S.Ab)},r.prototype.getVar=function(e,t,i){this.emit(S.AbVar,{name:e,defaultValue:t,callback:i},S.Ab)},r.prototype.getABconfig=function(e,t){this.emit(S.AbConfig,{params:e,callback:t},S.Ab)},r.prototype.getABConfig=function(e,t){this.emit(S.AbConfig,{params:e,callback:t},S.Ab)},r.prototype.getAbSdkVersion=function(){return this.configManager.getAbVersion()},r.prototype.onAbSdkVersionChange=function(e){var t=this;return this.emit(S.AbVersionChangeOn,e,S.Ab),function(){t.emit(S.AbVersionChangeOff,e,S.Ab)}},r.prototype.offAbSdkVersionChange=function(e){this.emit(S.AbVersionChangeOff,e,S.Ab)},r.prototype.openOverlayer=function(){this.emit(S.AbOpenLayer,"",S.Ab)},r.prototype.closeOverlayer=function(){this.emit(S.AbCloseLayer,"",S.Ab)},r.prototype.getAllVars=function(e){this.emit(S.AbAllVars,e,S.Ab)},r.prototype.destoryInstace=function(){this.destroy||(this.destroy=!0,this.off(S.TokenComplete),this.emit(S.DestoryInstance))},r.prototype.destroyInstance=function(){this.destroy||(this.destroy=!0,this.off(S.TokenComplete),this.emit(S.DestoryInstance))},r.plugins=[],r}(),en="__rangers_ab_style__";(function(r){r[r.Var=0]="Var",r[r.All=1]="All"})(ir||(ir={}));var Yf=function(){function r(){this.fetchStatus="no",this.refreshFetchStatus="complete",this.versions=[],this.extVersions=[],this.mulilinkVersions=[],this.enable_multilink=!1,this.enable_ab_visual=!1,this.editMode=!1,this.callbacks=[],this.data=null,this.changeListener=new Map,this.readyStatus=!1,this.exposureCache=[]}return r.prototype.apply=function(e,t){var i=this;if(t.enable_ab_test){this.collect=e,this.config=t;var n=t.enable_multilink,s=t.ab_channel_domain,a=t.enable_ab_visual,o=t.ab_cross,h=t.ab_cookie_domain,c=t.ab_timeout,u=s||K(Ys[t.channel||"cn"]),l=e.adapters.storage,d=this.collect.Types;this.types=d,this.cacheStorgae=new l(!1),this.timeout=c||3e3,this.enable_multilink=n,this.enable_ab_visual=a,this.abKey="__tea_sdk_ab_version_"+t.app_id,this.ab_cross=o,this.ab_cookie_domain=h||"",this.fetchUrl=u+"/service/2/abtest_config/",this.reportUrl=""+e.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.collect.on(d.TokenChange,function(p){p==="uuid"&&i.readyStatus&&(i.clearCache(),i.fetchAB())}),this.collect.on(d.TokenReset,function(p){p==="uuid"&&i.readyStatus&&(i.clearCache(),i.fetchAB())}),this.collect.on(d.AbVar,function(p){var f=p.name,v=p.defaultValue,m=p.callback;i.getVar(f,v,m)}),this.collect.on(d.AbAllVars,function(p){i.getAllVars(p)}),this.collect.on(d.AbConfig,function(p){var f=p.params,v=p.callback;i.getABconfig(f,v)}),this.collect.on(d.AbExternalVersion,function(p){i.setExternalAbVersion(p)}),this.collect.on(d.AbOpenLayer,function(){i.openOverlayer()}),this.collect.on(d.AbCloseLayer,function(){i.closeOverlayer()}),this.collect.on(d.AbVersionChangeOn,function(p){i.changeListener.set(p,p)}),this.collect.on(d.AbVersionChangeOff,function(p){i.changeListener.get(p)&&i.changeListener.delete(p)}),this.loadMode(),(this.enable_ab_visual||this.enable_multilink)&&this.openOverlayer(this.config.multilink_timeout_ms||500),this.checkLocal(),this.ready("ab"),this.readyStatus||(this.fetchAB(),this.readyStatus=!0),this.collect.emit(d.AbReady)}},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var i=this.collect.hook._hooksCache[e];if(!Object.keys(i).length)return;var n=function(a){i[a].length&&i[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in i)n(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 i=e.scenario,n=e.href;i?(this.editMode=!0,t=i):!n||n.indexOf("datatester")===-1&&n.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,i=e.ab_ext_version,n=e.ab_version_multilink,s=e.data,a=this.checkFromUrl();a?this.mulilinkVersions.push(a):this.mulilinkVersions=n||[],this.extVersions=i||[],this.versions=t||[],this.data=s;var o=this.versions.concat(this.extVersions);this.enable_multilink&&(o=o.concat(this.mulilinkVersions)),this.configVersions(o.join(","))},r.prototype.checkFromUrl=function(){var e=kr(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,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 i!="function")throw new Error("getVar callback must be a function");var n={name:e,defaultValue:t,callback:i,type:ir.Var};this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK 调用GetVar",level:"info",time:Date.now(),data:e,infoType:"cus"}),this.fetchStatus==="complete"&&this.refreshFetchStatus==="complete"?this.getRealVar(n,e):(this.callbackMap.get(e),this.callbackMap.set(e,n))},r.prototype.getRealVar=function(e,t){var i=e.name,n=e.defaultValue,s=e.callback,a=this.data;if(a){var o=a[i];if(o&&Gt(o)){var h=a[i].vid;return t==="$ab_url"?this.mulilinkVersions.includes(h)||this.mulilinkVersions.push(h):this.versions.includes(h)||this.versions.push(h),this.updateVersions(),this.fechEvent(h,t||i,n,s,o.val),void this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK执行GetVar,并曝光了实验"+i,level:"info",time:Date.now(),data:a[i],infoType:"sdk"})}this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK执行GerVar默认回调",level:"info",time:Date.now(),data:this.data,infoType:"sdk"}),s(n)}else s(n)},r.prototype.getAllVars=function(e){if(typeof e!="function")throw new Error("getAllVars callback must be a function");var t={callback:e,type:ir.All};this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK 调用GetAllVars",level:"info",time:Date.now(),infoType:"cus"}),this.fetchStatus==="complete"&&this.refreshFetchStatus==="complete"?this.getRealAllVars(t):this.callbackMap.set("allVars",t)},r.prototype.getRealAllVars=function(e){(0,e.callback)(this.data?JSON.parse(JSON.stringify(this.data)):{}),this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"SDK 执行GetAllVars",level:"info",time:Date.now(),data:this.data,infoType:"sdk"})},r.prototype.fechEvent=function(e,t,i,n,s){try{if(this.config.disable_track_event||!e)return;var a=this.collect.configManager.get(),o=a.header,h=a.user,c=this.getABCache(),u=h[this.ab_user_mode]||h.user_unique_id;if(c&&c.uuid&&c.uuid!==u)return;var l={event:"abtest_exposure",ab_sdk_version:""+e,params:JSON.stringify({app_id:this.config.appId,ab_url:t==="$ab_url"?i:window.location.href}),local_time_ms:Date.now()};o.custom=JSON.stringify(o.custom);var d={events:[l],user:h,header:o};this.reportExposure(d,t),n&&n(s)}catch(p){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 发生了异常",level:"error",time:Date.now(),data:p.message,infoType:"sdk"})}},r.prototype.reportExposure=function(e,t){var i=this;this.exposureCache.push(e),this.reportTimeout&&clearTimeout(this.reportTimeout),this.exposureCache.length>=this.exposureLimit?this.report(t):this.reportTimeout=setTimeout(function(){i.report(t),clearTimeout(i.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(i){t.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"曝光埋点上报成功",time:Date.now(),data:[i],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 i=Object.keys(e);i&&i.length&&this.collect.configManager.set(e),this.fetchAB(t)},r.prototype.get=function(e){if(this.ab_cross){var t=this.cacheStorgae.getCookie(e,this.ab_cookie_domain);return t?JSON.parse(t):{}}return this.cacheStorgae.getItem(e)},r.prototype.set=function(e,t){this.ab_cross?this.cacheStorgae.setCookie(e,t,2592e6,this.ab_cookie_domain):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(en)){var n="body { opacity: 0 !important; }",s=document.head||document.getElementsByTagName("head")[0],a=document.createElement("style");a.id=en,a.type="text/css",a.styleSheet?a.styleSheet.cssText=n:a.appendChild(document.createTextNode(n)),s.appendChild(a)}}(),e)var i=setTimeout(function(){t.closeOverlayer(),clearTimeout(i)},e)},r.prototype.closeOverlayer=function(){var e;(e=document.getElementById(en))&&e.parentElement.removeChild(e)},r.prototype.fetchComplete=function(e,t){var i=this;try{if(e&&Object.prototype.toString.call(e)=="[object Object]"){var n=this.collect.configManager.get().user;if(t&&t!==n.user_unique_id)return;this.data=e,this.setAbCache(t);var s=[];Object.keys(e).forEach(function(u){var l=e[u].vid;l&&s.push(l)}),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;this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行可视化实验",level:"info",logType:"fetch",time:Date.now(),infoType:"sdk",data:{$ab_modification:o}})}else if(a&&this.enable_multilink){this.mulilinkVersions=this.mulilinkVersions.filter(function(u){return s.includes(u)}),this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行多链接实验",level:"info",logType:"fetch",time:Date.now(),infoType:"sdk",data:{$ab_url:a}});var h=a.val,c=a.vid;h&&c&&this.getVar("$ab_url",h,function(){i.editMode||(h!==window.location.href?setTimeout(function(){if(!i.collect.destroy){var u=""+h;u=u.indexOf("http")===-1?"https://"+u:u,Ri(u).host!==location.host?u=u+"&vid="+c:window.history.replaceState("","",u),window.location.href=u}},100):i.closeOverlayer())})}this.updateVersions()}else this.closeOverlayer();this.callbackMap.forEach(function(u){return i[u.type===ir.Var?"getRealVar":"getRealAllVars"](u,"")})}catch{}},r.prototype.fetchAB=function(e){var t=this,i=this.collect.configManager.get(),n={header:U(U(U({aid:this.config.app_id},i.user||{}),i.header||{}),{ab_sdk_version:this.collect.configManager.getAbVersion(),ab_url:window.location.href})};this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 发起AB实验请求",level:"info",logType:"fetch",time:Date.now(),data:n,infoType:"sdk"});var s=i.user[this.ab_user_mode]||i.user.user_unique_id;this.collect.requestManager.useRequest({url:this.fetchUrl,data:n,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(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"AB实验请求成功",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(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,secType:"AB",info:"AB实验请求网络异常",level:"error",logType:"fetch",time:Date.now(),infoType:"sdk"})},timeout:this.timeout})},r}(),Qf=function(){function r(){}return r.prototype.apply=function(e,t){var i=this;t.event_verify_url&&(typeof t.event_verify_url=="string"?(this.collect=e,this.url=t.event_verify_url+"/v1/list_test",e.on(e.Types.SubmitBefore,function(n){i.verify(n)}),e.on(e.Types.AbVerify,function(n){i.verify(n)})):console.log("please use correct et_test url"))},r.prototype.verify=function(e){this.collect.requestManager.useBeacon({url:this.url,data:e}),this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"SDK Report ByteIo Verify Request",time:Date.now(),data:e,code:200,status:"success",verifyType:!0})},r}();function Ur(r,e,t){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")||t&&r.hasAttribute&&r.hasAttribute(t))return!0;return!1}var Bo=function(r,e){return!!tm(r,e)};function tn(r,e){for(var t=r;t&&!Ur(t,"container",e.container_attr||"");){if(t.nodeName==="HTML"||t.nodeName==="BODY")return r;t=t.parentElement}return t||r}var em=function(r){if(!r)return"";var e="";try{r.textContent?e=r.textContent.trim().replace(/\s+/g,","):r.innerText&&(e=r.innerText.trim().replace(/\s+/g,",")),r.tagName!=="input"&&r.tagName!=="INPUT"||(e=r.value||"")}finally{return e}};function Vo(r){try{for(var e=r;e&&e.parentNode;){if(e.hasAttribute("data-tea-ignore")||e.classList&&e.classList.contains("applog-web-devtools-con"))return!0;if(e.nodeName==="HTML"||e.nodeName==="body")return!1;e=e.parentNode}return!1}catch{return!1}}var Nr=function(r,e){return r.hasAttribute?r.hasAttribute(e):r.attributes?!(!r.attributes[e]||!r.attributes[e].specified):void 0},tm=function(r,e){if(typeof e=="string")return Nr(r,e);if(zr(e)){for(var t=!1,i=0;i<e.length;i++)if(Nr(r,e[i])){t=!0;break}return t}},Fo=function(r,e){var t={};if(typeof e=="string")Nr(r,e)&&(t[e]=r.getAttribute(e));else if(zr(e))for(var i=0;i<e.length;i++)Nr(r,e[i])&&(t[e[i]]=r.getAttribute(e[i]));return t};function jo(r){var e=[];if(!r)return{element_path:"",positions:[]};for(;r.parentElement!==null;)e.push(r),r=r.parentElement;var t=[],i=[];return e.forEach(function(n){var s=function(h){if(h===null)return{str:"",index:0};var c=0,u=h.parentElement;if(u)for(var l=u.children,d=0;d<l.length&&l[d]!==h;d++)l[d].nodeName===h.nodeName&&c++;return{str:[h.nodeName.toLowerCase(),Ur(h,"list")?"[]":""].join(""),index:c}}(n),a=s.str,o=s.index;t.unshift(a),i.unshift(o)}),{element_path:"/"+t.join("/"),positions:i}}var rm=function(){function r(e,t){this.maxDuration=432e5,this.aliveDTime=6e4,this.options={aliveName:"predefine_page_alive",params:{},container:null},this.focusState=!0,this.collect=e,this.config=t,this.pageStartTime=Date.now(),this.sessionStartTime=this.pageStartTime,this.timerHandler=null,Gt(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.aliveDTime=this.options.aliveTime||6e4}return r.prototype.setParams=function(e,t,i){this.set_path=e,this.set_url=i,this.set_title=t},r.prototype.enable=function(e,t,i){this.url_path=e,this.url=i,this.title=t,this.disableCallback=this.enablePageAlive(),this.hard&&(this.removeMode=this.hardMode())},r.prototype.disable=function(){this.disableCallback(),this.pageStartTime=Date.now(),this.hard&&this.removeMode&&this.removeMode()},r.prototype.sendEvent=function(e,t){t===void 0&&(t=!1);var i=t?this.aliveDTime:Date.now()-this.sessionStartTime;if(!(i<0||i>this.aliveDTime||Date.now()-this.pageStartTime>this.maxDuration)&&(!t||document.visibilityState!=="hidden")&&(!this.hard||this.focusState)){var n=U({url_path:this.getParams("url_path"),title:this.getParams("title"),url:this.getParams("url"),duration:i,is_support_visibility_change:Js(),startTime:this.sessionStartTime,hidden:document.visibilityState,leave:e,mode:this.hard?"hard":"normal",focusState:this.focusState,aliveType:this.options.container?"dom":"page"},this.options.params);if(this.options.container){var s=jo(this.options.container).element_path;n=Object.assign(n,{element_path:s,aliveType:this.options.container?"dom":"page"})}this.collect.beconEvent(this.options.aliveName,n),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(){this.getDisplayStatus()==="hidden"?this.timerHandler&&(clearInterval(this.timerHandler),this.sendEvent(!1)):this.getDisplayStatus()==="visible"&&(this.sessionStartTime=Date.now(),this.timerHandler=this.setUpTimer())},r.prototype.getDisplayStatus=function(){if(!this.options.container)return document.visibilityState;try{var e=window.getComputedStyle(this.options.container);return e.display!=="none"&&e.visibility!=="hidden"&&e.opacity!=="0"?"visible":"hidden"}catch{return"visible"}},r.prototype.beforeunload=function(){document.hidden||this.sendEvent(!0)},r.prototype.muition=function(){var e=this;new MutationObserver(function(t){t.forEach(function(i){e.visibilitychange()})}).observe(this.options.container,{attributes:!0,attributeFilter:["style"]})},r.prototype.enablePageAlive=function(){var e=this;this.timerHandler=this.setUpTimer();var t=this.visibilitychange.bind(this),i=this.beforeunload.bind(this);return this.options.container?this.muition():document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",i),function(){e.beforeunload(),document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",i)}},r.prototype.hardMode=function(){var e=this,t=function(){e.timerHandler&&(clearInterval(e.timerHandler),e.sendEvent(!1)),e.focusState=!1},i=function(){e.focusState=!0,e.sessionStartTime=Date.now(),e.timerHandler=e.setUpTimer()};return window.addEventListener("blur",t),window.addEventListener("focus",i),function(){window.removeEventListener("blur",t),window.removeEventListener("focus",i)}},r}(),im=function(){function r(e,t){var i=this;this.maxDuration=432e5,this.aliveDTime=6e4,this.options={closeName:"predefine_page_close",params:{}},this.focusState=!0,this.visibilitychange=function(){document.visibilityState==="hidden"?i.activeEndTime=Date.now():document.visibilityState==="visible"&&(i.activeEndTime&&(i.totalTime+=i.activeEndTime-i.activeStartTime,i.activeTimes+=1),i.activeEndTime=void 0,i.activeStartTime=Date.now())},this.beforeunload=function(){if(i.totalTime+=(i.activeEndTime||Date.now())-i.activeStartTime,i.config.autotrack)try{window.sessionStorage.setItem("_tea_cache_duration",JSON.stringify({duration:i.totalTime,page_title:document.title||location.pathname}))}catch{}i.sendEventPageClose()},this.collect=e,this.config=t,this.maxDuration=t.maxDuration||t.max_duration||864e5,this.pageStartTime=Date.now(),Gt(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,i){this.set_path=e,this.set_url=i,this.set_title=t},r.prototype.resetParams=function(e,t,i){this.url_path=e,this.url=i,this.title=t},r.prototype.enable=function(e,t,i){this.url_path=e,this.url=i,this.title=t,this.disableCallback=this.enablePageClose(),this.hard&&(this.removeMode=this.hardMode())},r.prototype.disable=function(){this.disableCallback(),this.hard&&this.removeMode&&this.removeMode(),this.resetData()},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,U({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:Js(),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),i=this.beforeunload.bind(this);return document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",i),function(){e.beforeunload(),document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",i)}},r.prototype.hardMode=function(){var e=this,t=function(){e.focusState=!1},i=function(){e.focusState=!0};return window.addEventListener("blur",t),window.addEventListener("focus",i),function(){window.removeEventListener("blur",t),window.removeEventListener("focus",i)}},r}(),nm=function(){function r(){}return r.prototype.apply=function(e,t){var i=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 rm(e,t),this.pageClose=new im(e,t);var n=this.collect.Types;this.collect.on(n.DestoryInstance,function(){i.disable()}),this.collect.on(n.ResetStay,function(s){var a=s.url_path,o=s.title,h=s.url;i.resetStayDuration(a,o,h)}),this.collect.on(n.RouteChange,function(s){s.init||t.disable_route_report||i.resetStayDuration()}),this.collect.on(n.SetStay,function(s){var a=s.url_path,o=s.title,h=s.url;i.setStayParmas(a,o,h)}),this.enable(this.url_path,this.title,this.url),this.ready(n.Stay),this.collect.emit(n.StayReady)}},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var i=this.collect.hook._hooksCache[e];if(!Object.keys(i).length)return;var n=function(a){i[a].length&&i[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in i)n(s)}},r.prototype.enable=function(e,t,i){this.pageAlive.enable(e,t,i),this.pageClose.enable(e,t,i)},r.prototype.disable=function(){this.pageAlive.disable(),this.pageClose.disable()},r.prototype.setStayParmas=function(e,t,i){e===void 0&&(e=""),t===void 0&&(t=""),i===void 0&&(i=""),this.pageAlive.setParams(e,t,i),this.pageClose.setParams(e,t,i),this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行 resetStayParams",level:"info",time:Date.now(),data:{url_path:e,title:t,url:i}})},r.prototype.reset=function(e,t,i){this.disable(),this.enable(e,t,i)},r.prototype.resetStayDuration=function(e,t,i){this.reset(e,t,i),this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"SDK 执行 resetStayDuration",level:"info",time:Date.now(),data:{url_path:e,title:t,url:i}})},r}(),sm=function(){function r(){}return r.prototype.apply=function(e,t){var i=this;this.collect=e,this.config=t,this.duration=6e4,this.reportUrl=e.configManager.getDomain()+"/profile/list";var n=e.Types;this.eventCheck=new Pi(e,t),this.cache={},this.collect.on(n.ProfileSet,function(s){i.setProfile(s)}),this.collect.on(n.ProfileSetOnce,function(s){i.setOnceProfile(s)}),this.collect.on(n.ProfileUnset,function(s){i.unsetProfile(s)}),this.collect.on(n.ProfileIncrement,function(s){i.incrementProfile(s)}),this.collect.on(n.ProfileAppend,function(s){i.appendProfile(s)}),this.collect.on(n.ProfileClear,function(){i.cache={}}),this.ready(n.Profile)},r.prototype.ready=function(e){var t=this;if(this.collect.set(e),this.collect.hook._hooksCache.hasOwnProperty(e)){var i=this.collect.hook._hooksCache[e];if(!Object.keys(i).length)return;var n=function(a){i[a].length&&i[a].forEach(function(o){t.collect.hook.emit(a,o)})};for(var s in i)n(s)}},r.prototype.report=function(e,t){t===void 0&&(t={});try{if(this.config.disable_track_event)return;var i=[];i.push(this.collect.processEvent(e,t));var n=this.collect.eventManager.merge(i);this.collect.requestManager.useRequest({url:this.reportUrl,data:n}),this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_EVENT,info:"埋点上报成功",time:Date.now(),data:n,code:200,status:"success"})}catch(s){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:s.message})}},r.prototype.setProfile=function(e){var t=this.formatParams(e);t&&Object.keys(t).length&&(this.pushCache(t),this.report("__profile_set",U(U({},t),{profile:!0})))},r.prototype.setOnceProfile=function(e){var t=this.formatParams(e,!0);t&&Object.keys(t).length&&(this.pushCache(t),this.report("__profile_set_once",U(U({},t),{profile:!0})))},r.prototype.incrementProfile=function(e){e?this.report("__profile_increment",U(U({},e),{profile:!0})):console.warn("please check the params, must be object!!!")},r.prototype.unsetProfile=function(e){if(e){var t={};t[e]="1",this.report("__profile_unset",U(U({},t),{profile:!0}))}else console.warn("please check the key, must be string!!!")},r.prototype.appendProfile=function(e){if(e){var t={};for(var i in e)typeof e[i]=="string"||Object.prototype.toString.call(e[i]).slice(8,-1)==="Array"?t[i]=e[i]:console.warn("please check the value of param: "+i+", must be string or array !!!");Object.keys(t).length&&this.report("__profile_append",U(U({},t),{profile:!0}))}else console.warn("please check the params, must be object!!!")},r.prototype.pushCache=function(e){var t=this;Object.keys(e).forEach(function(i){t.cache[i]={val:t.clone(e[i]),timestamp:Date.now()}})},r.prototype.formatParams=function(e,t){var i=this;t===void 0&&(t=!1);try{if(!e||Object.prototype.toString.call(e)!=="[object Object]")return void console.warn("please check the params type, must be object !!!");var n={};for(var s in e)typeof e[s]=="string"||typeof e[s]=="number"||Object.prototype.toString.call(e[s]).slice(8,-1)==="Array"?n[s]=e[s]:console.warn("please check the value of params:"+s+", must be string,number,Array !!!");var a=Object.keys(n);if(!a.length||!this.eventCheck.checkEventParams(n))return;var o=Date.now();return a.filter(function(h){var c=i.cache[h];return t?!c:!(c&&i.compare(c.val,e[h])&&o-c.timestamp<i.duration)}).reduce(function(h,c){return h[c]=n[c],h},{})}catch(h){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:h.message}),console.log("error")}},r.prototype.compare=function(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch(i){return this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:i.message}),!1}},r.prototype.clone=function(e){try{return JSON.parse(JSON.stringify(e))}catch(t){return this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:t.message}),e}},r.prototype.unReady=function(){console.warn("sdk is not ready, please use this api after start")},r}(),om=function(){function r(){var e=this;this.setInterval=function(){e.clearIntervalFunc=Np(function(){e.isSessionhasEvent&&e.endCurrentSession()},e.sessionInterval)},this.clearInterval=function(){e.clearIntervalFunc&&e.clearIntervalFunc()}}return r.prototype.apply=function(e,t){var i=this;if(this.collect=e,!t.disable_heartbeat){this.sessionInterval=6e4,this.startTime=0,this.lastTime=0,this.setInterval();var n=this.collect.Types;this.collect.on(n.SessionResetTime,function(){i.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}(),am=function(){function r(){}return r.prototype.apply=function(e,t){var i=this;t.channel_domain||t.disable_track_event||t.disable_sdk_monitor||(this.collect=e,this.config=t,this.url=e.configManager.getUrl("event"),this.collect.on(e.Types.Ready,function(){i.sdkOnload()}),this.collect.on(e.Types.SubmitError,function(n){var s=n.type,a=n.eventData,o=n.errorCode,h=n.response;s==="f_data"&&i.sdkError(a,o,h)}),this.collect.on(e.Types.SDKInnerError,function(n){var s=n.type,a=n.eventData,o=n.errorCode,h=n.msg;i.sdkInnerError(s,a,o,h)}))},r.prototype.sdkOnload=function(){var e=this;try{var t=this.collect.configManager.get(),i=t.header,n=t.user,s=i.app_id,a=i.app_name,o=i.sdk_version,h=n.web_id,c={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",url:location.href}),local_time_ms:Date.now()}],user:{user_unique_id:h},header:{}};setTimeout(function(){e.collect.requestManager.useRequest({url:e.url,data:[c],timeout:3e4,app_key:"566f58151b0ed37e",forceXhr:!0})},16)}catch{}},r.prototype.sdkError=function(e,t,i){var n=this;try{var s=e[0],a=s.user,o=s.header,h=[];e.forEach(function(u){u.events.forEach(function(l){h.push(l)})});var c={events:h.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:i.m||""}),local_time_ms:Date.now()}}),user:{user_unique_id:a.user_unique_id},header:{}};setTimeout(function(){n.collect.requestManager.useRequest({url:n.url,data:[c],timeout:3e4,app_key:"566f58151b0ed37e",forceXhr:!0})},16)}catch{}},r.prototype.sdkInnerError=function(e,t,i,n){var s=this;try{var a=t[0],o=a.user,h=a.header,c=[];t.forEach(function(l){l.events.forEach(function(d){c.push(d)})});var u={events:c.map(function(l){return{event:"on_error",params:JSON.stringify({type:e,error_code:i,app_id:h.app_id,app_name:h.app_name||"",error_event:l.event,sdk_version:h.sdk_version,local_time_ms:l.local_time_ms,tea_event_index:Date.now(),params:l.params,header:h,user:o,ua:window.navigator.userAgent,err_msg:n}),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}(),cm=function(r){if(r.children.length){var e=r.children;return![].slice.call(e).some(function(t){return t.children.length>0})}return!0},um=function(r){if(r.tagName.toLowerCase()==="svg")return!0;for(var e=r.parentElement,t=!1;e;)e.tagName.toLowerCase()==="svg"?(e=null,t=!0):e=e.parentElement;return t};function hm(r,e){if(r.nodeType!==1||!e.svg&&um(r)||["HTML","BODY"].includes(r.tagName.toUpperCase()))return!1;var t=r;return t.style.display!=="none"&&(!!Ur(t,"container",e.container_attr||"")||!!(function(i,n){for(var s=i,a=!1;s&&!Ur(s,"container",n.container_attr||"");){if(s.nodeName==="HTML"||s.nodeName==="BODY")return a;s=s.parentElement}return a=!0}(t,e)||cm(t)||e.svg))}var dm=function(){function r(e,t,i){var n=this;this.statistics=!1,this.pageView=!1,this.clickEvent=function(s){hm(s.target,n.options)&&n.eventHandel({eventType:"dom",eventName:"click"},s)},this.changeEvent=function(s){n.eventHandel({eventType:"dom",eventName:"change"},s)},this.submitEvent=function(s){n.eventHandel({eventType:"dom",eventName:"submit"},s)},this.getPageViewEvent=function(s,a){a&&a==="pushState"&&n.eventHandel({eventType:"dom",eventName:"beat"},U({beat_type:0},s)),n.eventHandel({eventType:"dom",eventName:"page_view"},s)},this.getPageLoadEvent=function(s){n.eventHandel({eventType:"dom",eventName:"page_statistics"},{lcp:s})},this.config=i.getConfig().eventConfig,this.collect=t,this.options=e,this.beatTime=e.beat,this.domContainer=e.container||document}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&&(zr(this.domContainer)?this.domContainer.forEach(function(c){c.addEventListener("click",t.clickEvent,!0)}):this.domContainer.addEventListener("click",this.clickEvent,!0)),this.config.pv){this.collect.on("route-change",function(c){var u=c.config,l=c.name;t.getPageViewEvent(u,l),t.pageView=!0});var i=setTimeout(function(){t.pageView||(t.getPageViewEvent(t.getDefaultConfig()),t.pageView=!0,clearTimeout(i))},2e3)}if(this.config.beat){try{document.readyState==="complete"?this.beatEvent(this.beatTime):window.addEventListener("load",function(){t.beatEvent(t.beatTime)});var n=0,s=null;window.addEventListener("scroll",function(){clearTimeout(s),s=setTimeout(a,500),n=document.documentElement.scrollTop||document.body.scrollTop});var a=function(){(document.documentElement.scrollTop||document.body.scrollTop)==n&&t.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:1})}}catch{}try{var o=window.performance&&window.performance.getEntriesByType("paint");if(o&&o.length){new PerformanceObserver(function(c){var u=c.getEntries(),l=u[u.length-1],d=l.renderTime||l.loadTime;t.statistics||(t.getPageLoadEvent(d),t.statistics=!0)}).observe({entryTypes:["largest-contentful-paint"]});var h=setTimeout(function(){t.statistics||(t.getPageLoadEvent(o[0].startTime||0),t.statistics=!0,clearTimeout(h))},2e3)}else this.getPageLoadEvent(0)}catch{this.getPageLoadEvent(0)}}}},r.prototype.removeListener=function(){var e=this;zr(this.domContainer)?this.domContainer.forEach(function(t){t.removeEventListener("click",e.clickEvent,!0)}):this.domContainer.removeEventListener("click",this.clickEvent,!0)},r.prototype.beatEvent=function(e){var t=this;try{var i;this.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:3}),this.beatTime&&(i=setInterval(function(){t.eventHandel({eventType:"dom",eventName:"beat"},{beat_type:2})},e)),Ai(function(){t.eventHandel({eventType:"dom",eventName:"beat",eventSend:"becon"},{beat_type:0}),t.beatTime&&clearInterval(i)})}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}(),lm={eventConfig:{mode:"proxy-capturing",submit:!1,click:!0,change:!1,pv:!0,beat:!0,hashTag:!1,impr:!1},scoutConfig:{mode:"xpath"}},pm=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 fm(r,e,t,i){var n={},s=function(k){if(k){var T=k.getBoundingClientRect(),A=T.width,P=T.height;return{left:T.left,top:T.top,element_width:A,element_height:P}}}(e=tn(e,t)),a=function(k,T){k===void 0&&(k={}),T===void 0&&(T={});var A=k.clientX,P=k.clientY,ie=T.left,J=T.top,ue=A-ie>=0?A-ie:0,he=P-J>=0?P-J:0;return{touch_x:Math.floor(ue),touch_y:Math.floor(he)}}(r,s),o=s.element_width,h=s.element_height,c=a.touch_x,u=a.touch_y,l=jo(e),d=l.element_path,p=l.positions,f=function(k,T){var A=tn(k,T),P=[];return function ie(J){var ue=function(re){var Ue="";return re.nodeType===3?Ue=re.textContent.trim():re.dataset&&re.dataset.hasOwnProperty("teaTitle")||re.hasAttribute("ata-tea-title")?Ue=re.getAttribute("data-tea-title"):re.nodeName==="INPUT"&&["button","submit"].includes(re.getAttribute("type"))?Ue=re.getAttribute("value"):re.nodeName==="IMG"&&re.getAttribute("alt")&&(Ue=re.getAttribute("alt")),Ue.slice(0,200)}(J);if(ue&&P.indexOf(ue)===-1&&P.push(ue),J.childNodes.length>0)for(var he=J.childNodes,ht=0;ht<he.length;ht++)he[ht].nodeType!==8&&ie(he[ht])}(A),P}(e,t),v=window.performance.timing.navigationStart,m=Date.now()-v,E=p.map(function(k){return""+k}),y=null;if(window.TEAVisualEditor&&window.TEAVisualEditor.getOriginXpath&&(y=window.TEAVisualEditor.getOriginXpath({xpath:d,positions:E})),n.element_path=y&&y.xpath||d,n.positions=y&&y.positions||E,i&&!i.text&&(n.texts=f,n.element_title=e.getAttribute("data-tea-title")||e.getAttribute("title")||em(e)),n.element_id=e.getAttribute("id")||"",n.element_class_name=e.getAttribute("class")||"",n.element_type=e.nodeType,n.element_width=Math.floor(o),n.element_height=Math.floor(h),n.touch_x=c,n.touch_y=u,n.page_manual_key="",n.elememt_manual_key="",n.since_page_start_ms=m,n.page_start_ms=v,n.page_path=location.pathname,n.page_host=location.host,t.track_attr&&Bo(e,t.track_attr)){var _=Fo(e,t.track_attr);for(var C in _)n[C]=_[C]}if(t.custom_attr)try{if(Bo(e,t.custom_attr)){_=Fo(e,t.custom_attr),C=decodeURIComponent(_[t.custom_attr]);var z=JSON.parse(C);if(Object.keys(z))for(var w in z)n[w]=z[w]}}catch{console.log("custom attr error")}var O=tn(e,t);return O.tagName==="A"&&(n.href=O.getAttribute("href")),e.tagName==="IMG"&&(n.src=e.getAttribute("src")),n}var Et=function(r,e,t,i,n){return U(U({event:r},fm(e,t,i,n)),{is_html:1,page_key:window.location.href,page_title:document.title})},mm=function(){function r(e,t){this.ignore={text:!1},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",scroll:"__bav_slide"}:{click:"bav2b_click",page:"bav2b_page",beat:"bav2b_beat",static:"bav2b_page_statistics",exposure:"bav2b_exposure",scroll:"$bav2b_slide"},t&&t.text===!1&&(this.ignore.text=!0),t&&t.exposure&&t.exposure.eventName&&(this.eventName.exposure=t.exposure.eventName)}return r.prototype.handleEvent=function(e,t){try{if(Vo(e.target))return null;var i="bav2b_click";switch(t){case"click":return i=e.target.getAttribute("data-applog-click-event")||this.eventName.click||"",Et(i,e,e.target,this.options,this.ignore);case"exposure":return i=e.target.getAttribute("data-applog-exposure-event")||this.eventName.exposure||"",Et(i,e,e.target||e,this.options,this.ignore);case"change":return U(U({},Et(i="bav2b_change",e,e.target,this.options)),function(n,s){try{if(n==="bav2b_change")return s.hasAttribute("data-tea-track")?{value:s.value}:{}}catch{return{}}}(i,e.target));case"submit":return Et(i="bav2b_submit",e,e.target,this.options)}}catch(n){return console.error(n),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 i=JSON.parse(t);e.refer_page_duration_ms=i?i.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(n){console.log("page event error "+JSON.stringify(n))}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 i=e.lcp,n=window.performance.timing,s=n.loadEventEnd-n.navigationStart;t.page_init_cost_ms=parseInt(i||(s>0?s:0)),t.page_start_ms=n.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(Vo(t.target))return null;var i=Et(e.event||this.eventName.exposure,t,t.target||t,this.options,this.ignore);if(i.$exposure_type=e.exposureType,this.options.exposure.callback){var n=this.options.exposure.callback(i);return n||Object.keys(n).length?n:(console.warn("exposure callback must return data!"),i)}return i},r.prototype.handleScrollEvent=function(e,t){var i=Et(e.event||this.eventName.scroll,t,t.target||t,this.options,this.ignore);if(i=Object.assign(i,e.params),!this.options.scroll.callback||(i=this.options.scroll.callback(i))||Object.keys(i).length)return i;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 i=t.event;delete t.event,e&&e.eventSend==="becon"?this.collect.beconEvent(i,t):this.collect.event(i,t)},r.prototype.get=function(e,t){var i=Object.assign({headers:{"content-type":"application/json"},method:"GET"},t);fetch(e,i)},r.prototype.post=function(e,t){var i=Object.assign({headers:{"content-type":"application/json"},method:"POST"},t);fetch(e,i)},r}(),nr={},Ho=[],gm=function(r){r.length&&r.forEach(function(e){Ho.push(e)})};function $o(r,e,t,i){var n=r&&r.source||window.opener||window.parent,s=r&&r.origin||i||"*",a={type:e,payload:t};n.postMessage(JSON.stringify(a),s)}function vm(r){if(Ho.some(function(n){return r.origin.indexOf(n)>-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,i=e.payload;nr[t]&&nr[t].forEach(function(n){typeof n=="function"&&n(r,i)})}}var rn=!1;function ym(r,e){window.TEAVisualEditor=window.TEAVisualEditor||{},window.TEAVisualEditor.appId=e.app_id;var t=e.channel_domain,i="";if(gm(Hp),t){var n=void 0,s="";try{var a=window.performance.getEntriesByType("resource");if(a&&a.length&&(a.forEach(function(c){c.initiatorType==="script"&&c.name&&c.name.indexOf("collect")!==-1&&(s=c.name)}),s&&(n=s.split("/"))&&n.length)){i="https:/";for(var o=2;o<n.length&&o!==n.length-1;o++)i=i+"/"+n[o];if(i&&i.indexOf("/5.0")){var h=i.split("/5.0");i=h[0]||i}}}catch{}}(function(c,u){var l={};if(Object.keys(c).length)for(var d in c){if(d==="filter"||d==="autotrack"||d==="enable_stay_duration")break;l[d]=c[d]}var p=c.domain;(window.opener||window.parent).postMessage({type:"tea:sdk:info",config:l,version:u},p),window.addEventListener("message",vm,!1)})(e,Fe);try{(function(c,u){nr[c]=nr[c]||[],nr[c].push(u)})("tea:openHeatMapCore",function(c){var u=jp,l=c.data.app_id;l&&l!==e.app_id||function(d){var p=d.event,f=d.editorUrl,v=d.autoTrackInstance;rn||(rn=!0,Up(f,function(){$o(p,"editorScriptloadSuccess"),v.destroy()},function(){p&&$o(p,"editorScriptloadError"),rn=!1}))}({event:c,editorUrl:u+".js?query="+Date.now(),autoTrackInstance:r})})}catch{console.log("openHeatMapCore error")}}var we,bm=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(i){i.forEach(function(n){n.type==="attributes"&&e.attributeChangeObserve(n),n.type==="childList"&&e.modifyNodeObserve(n)})}),!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(i){i.nodeType===1&&i.hasAttribute("data-exposure")&&t.exposureAdd(i,"intersect"),t.mapChild(i,t.exposureAdd.bind(t))}),Array.prototype.forEach.call(e.removedNodes,function(i){i.nodeType===1&&i.hasAttribute("data-exposure")&&t.exposureRemove(i),t.mapChild(i,t.exposureRemove.bind(t))})},r.prototype.mapChild=function(e,t){var i=this;e.nodeType===1&&e.children.length&&Array.prototype.forEach.call(e.children,function(n){n.nodeType===1&&n.hasAttribute("data-exposure")&&t(n),i.mapChild(n,t)})},r.prototype.exposureAdd=function(e,t){try{this._intersection&&this._intersection.exposureAdd(e,t)}catch(i){console.log("intersection error",JSON.stringify(i.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"})(we||(we={}));var at,Sm=function(){function r(e,t,i){var n=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=we.NOT_EXPOSURE,this.eventHandle=i,this.hashMap=new Map,this.backStatus=!1,this.lastState=null,this.collect.on("re-start-sdk",function(){n.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=[],i=0;i<=1;i+=.01)t.push(i);t.push(1);try{r._observer_instance=new IntersectionObserver(function(n){n.forEach(function(s){var a=s.target.observeId,o=e.observeMap.get(a),h=(s.target,s.isIntersecting,s.intersectionRatio);if(o.intersectionRatio=h,h<=.1&&(s.target.backStatus=!1),e.observeMap.set(a,o),h<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(l){console.log("IntersectionObserver setTimeout error,msg: "+JSON.stringify(l))}},e.timeLimit);o.wait=c}e.observeMap.set(a,o)}Date.now()-o.startTime>=e.timeLimit&&!o.exposured&&e.exposureEvent(s,h,a,o)})},{threshold:t})}catch(n){console.log("IntersectionObserver error,msg: "+JSON.stringify(n))}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 i=t==="mutation"?e.target:e,n=i.observeId,s=Bt();if(n||this.observeMap.has(n)){var a=this.observeMap.get(n);if(a&&i!==a.instance)this.unobserve(i),this.observeMap.delete(n),i.observeId=s,i.visible=!1,this.observeMap.set(s,{instance:i.cloneNode(!0),isIntersecting:!1}),this.observe(i);else{if(i.visible===!0)return;this.handleBoundingExposure(i)}}else i.observeId=s,i.visible=!1,this.observeMap.set(s,{instance:i.cloneNode(!0),isIntersecting:!1}),this.observe(i)},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,i,n){if(t>=this.ratio){if(e.target.style.opacity==="0"||e.target.style.visibility==="hidden"||n.exposured===!0)return;n.startWait&&clearTimeout(n.startWait);var s=e.target.getAttribute("data-exposure-event");this.eventHandle({eventType:"dom",eventName:"exposure",event:s,exposureType:this.getExposureType(e.target)},e),e.target.visible=!0,e.target.hasExposure=!0,n.startTime=Date.now(),n.exposured=!0}else n.startTime=Date.now(),n.exposured=!1;this.observeMap.set(i,n)},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||we.RESUME_FORM_BACK},e)}},r.prototype.getBoundingRatio=function(e){var t=e.getBoundingClientRect(),i=t.top,n=t.left,s=t.width,a=t.height,o=window.innerWidth||document.documentElement.clientWidth,h=window.innerHeight||document.documentElement.clientHeight;return i>=0&&n>=0&&i<=h&&n<=o?(s>o?o:s)*(h-i)/(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=we.RESUME_FORM_PAGE:this.exposureType=we.LIFECYCLE_SHOW_NEW:(e.hasExposure,e.backStatus!==!1&&(this.backStatus||this.customType||window.performance.navigation.type===2)?this.exposureType=we.RESUME_FORM_PAGE:this.exposureType=we.EXPOSURE_ONCE),this.exposureType},r.prototype.addListen=function(){var e=this;this.collect.on("set-exposure-type",function(c){e.customType=c});var t,i,n,s,a=this.visibilitychange.bind(this);if(t=document,i="visibilitychange",n=a,s=!1,t.addEventListener?t.addEventListener(i,n,s):t.attachEven?t.attachEven("on"+i,n):t["on"+i]=n,window.addEventListener("hashchange",function(c){var u=e.hashMap.get(c.oldURL);u&&location.href===u.prev?(e.backStatus=!0,e.exposureType=we.RESUME_FORM_PAGE):(e.backStatus=!1,e.hashMap.set(location.href,{current:c.newURL,prev:c.oldURL}))}),this.collect.bridgeReport){var o=window.history.pushState;history.pushState=function(c){for(var u=[],l=1;l<arguments.length;l++)u[l-1]=arguments[l];typeof history.onpushstate=="function"&&history.onpushstate({state:c});var d=o.call.apply(o,rt([history,c],u));return e.lastState=c,d};var h=history.replaceState;history.replaceState=function(c){for(var u=[],l=1;l<arguments.length;l++)u[l-1]=arguments[l];typeof history.onreplacestate=="function"&&history.onreplacestate({state:c});var d=h.call.apply(h,rt([history,c],u));return e.lastState=c,d}}else this.collect.on("STATE_CHANGE",function(c){e.lastState=c});return window.addEventListener("popstate",function(c){var u=c.state;u&&u.current&&e.lastState&&e.lastState.back&&u.current===e.lastState.back?(e.backStatus=!0,e.exposureType=we.RESUME_FORM_PAGE):e.backStatus=!1}),function(){(function(c,u,l,d){c.addEventListener?c.removeEventListener(u,l,d):c.attachEven&&c.detachEven("on"+u,l)})(document,"visibilitychange",a,!1)}},r._observer_instance=null,r._observer_map=new Map,r}(),Em=function(){function r(e,t,i){t.autotrack&&t.autotrack.exposure&&(this._intersection=new Sm(e,t,i),this._observer=new bm(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 Ko,Cm=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(i){i.forEach(function(n){n.type==="childList"&&e.modifyNodeObserve(n)})});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(i){i.nodeType===1&&i.hasAttribute("data-scroll")&&t.scrollHandle(i),t.mapChild(i,t.scrollHandle.bind(t))}),Array.prototype.forEach.call(e.removedNodes,function(i){i.nodeType===1&&i.hasAttribute("data-scroll")&&t.scrollHandle(i,"remove"),t.mapChild(i,t.scrollHandle.bind(t))})},r.prototype.mapChild=function(e,t){var i=this;e.nodeType===1&&e.children.length&&Array.prototype.forEach.call(e.children,function(n){n.nodeType===1&&n.hasAttribute("data-scroll")&&t(n),i.mapChild(n,t)})},r.prototype.scrollHandle=function(e,t){var i=this;try{var n=e.scrollTop,s=e.scrollLeft,a=null,o=0,h=0,c=function(u){clearTimeout(a),a=setTimeout(function(){var f=e.scrollTop,v=e.scrollLeft,m=u.target&&u.target.getAttribute("data-scroll-event")||"";p===1||p===2?f===l&&(h=l-n,Math.abs(h)>=i.distance&&i.distance&&i.eventHandle({eventType:"dom",eventName:"scroll",event:m,params:{$direction:p,$offsetY:h,$offsetX:o}},u)):p!==3&&p!==4||v===d&&(o=d-s,Math.abs(o)>=i.distance&&i.distance&&i.eventHandle({eventType:"dom",eventName:"scroll",event:m,params:{$direction:p,$offsetY:h,$offsetX:o}},u)),n=l,s=d},100);var l=e.scrollTop,d=e.scrollLeft,p=at.NOT_SCROLL;l>n?p=at.SCROLL_DOWN:l<n?p=at.SCROLL_UP:d>s?p=at.SCROLL_LEFT:d<s&&(p=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}(),wm={hashTag:!1,impr:!1},Tm=function(){function r(){}return r.prototype.apply=function(e,t){if(this.autoTrackStart=!1,this.collect=e,this.config=t,t.autotrack){var i=e.Types;this.ready(i.Autotrack),this.collect.emit(i.AutotrackReady)}},r.prototype.ready=function(e){this.collect.set(e);var t=this.config.autotrack;t=typeof t=="object"?t:{},t=Object.assign(wm,t),this.destroyed=!1,this.options=t,this.Config=new pm(lm,this.options),this.Exposure=new Em(this.collect,this.config,this.handle.bind(this)),this.Scroll=new Cm(this.config,this.handle.bind(this)),this.Listener=new dm(t,this.collect,this.Config),this.EventHandle=new mm(this.config,t),this.Request=new _m(this.collect),this.autoTrackStart=!0,this.init(),ym(this,this.config)},r.prototype.init=function(){this.Listener.init(this.handle.bind(this));try{this.collect.loadType==="base"&&(window.opener||window.parent).postMessage("[tea-sdk]ready","*")}catch{}},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 i=e.eventName;if(i==="click"||i==="change"||i==="submit")(o=this.EventHandle.handleEvent(t,i))&&this.Request.send({eventType:"custom"},o);else if(i==="page_view"||i==="page_statistics"){var n=void 0;(n=i==="page_view"?this.EventHandle.handleViewEvent(t):this.EventHandle.handleStatisticsEvent(t))&&this.Request.send({eventType:"custom"},n)}else if(i==="beat"){var s=this.EventHandle.handleBeadtEvent(t),a=e.eventSend;s&&this.Request.send({eventType:"custom",eventSend:a},s)}else if(i==="exposure")(o=this.EventHandle.handleExposureEvent(e,t))&&this.Request.send({eventType:"custom"},o);else if(i==="scroll"){var o;(o=this.EventHandle.handleScrollEvent(e,t))&&this.Request.send({eventType:"custom"},o)}}catch(h){console.log("handel dom event error "+JSON.stringify(h))}},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"})(Ko||(Ko={}));var qo={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"]},zm=function(){function r(){}return r.prototype.apply=function(e,t){var i=this;if(t.app_id&&t.enable_tracer&&!t.disable_track_event){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 n=this.collect.Types;this.collect.on(n.Event,function(){i.addCount("log")}),this.collect.on(n.SubmitError,function(s){var a=s.type,o=s.eventDate,h=s.errorCode,c=s.response;i.addErrorCount(o,a,h,c)}),this.listener(),this.collect.emit(n.TracerReady)}},r.prototype.addCount=function(e,t,i){t===void 0&&(t="net"),i===void 0&&(i=1);try{this.tracerCache||(this.tracerCache=new Map);var n=void 0;if(this.tracerCache.has(e))(s=this.tracerCache.get(e)).has(t)?(n=s.get(t).params.count,n++,s.set(t,this.processTracer(n,e,t))):(n=i,s.set(t,this.processTracer(i,e,t)));else{var s=new Map;n=i,s.set(t,this.processTracer(i,e,t)),this.tracerCache.set(e,s)}t==="net"&&n>=this.limit[e]&&this.report(!1)}catch(a){console.log(a)}},r.prototype.addErrorCount=function(e,t,i,n){var s=this;try{if(e&&e.length){var a=e[0].events;a&&a.length&&(t==="f_data"?(n&&n.hasOwnProperty("sc")?this.addCount("log",t,a.length-n.sc):this.addCount("log",t,a.length),this.errorCode[t]=i):a.forEach(function(o){var h="log";for(var c in qo)if(qo[c].indexOf(o.event)!==-1){h=c;break}s.addCount(h,t,1),s.errorCode[t]=i}))}}catch{}},r.prototype.report=function(e){if(this.tracerCache){var t=[];this.tracerCache.forEach(function(i){console.log(i),i.forEach(function(n){t.push(n)})}),t&&t.length&&this.sendTracer(t,e)}},r.prototype.sendTracer=function(e,t){try{var i=this.collect.eventManager.merge(e);this.collect.requestManager.useRequest({url:this.reportUrl,data:i,useBeacon:t}),this.tracerCache=null}catch{}},r.prototype.processTracer=function(e,t,i){var n={count:e,state:i,key:t,params_for_special:"applog_trace",aid:this.appid,platform:"web",_staging_flag:1,sdk_version:Fe};i!=="f_net"&&i!=="f_data"||(n.errorCode=this.errorCode[i]);var s=this.collect.processEvent("applog_trace",n);if(s&&s.event)return delete s.is_bav,s},r.prototype.listener=function(){var e=this;document.addEventListener("visibilitychange",function(){document.visibilityState==="hidden"&&e.leavePage()}),Ai(function(){e.leavePage()})},r.prototype.leavePage=function(){this.report(!0)},r}(),km=function(){function r(){this.retryWaitTime=3e3,this.retryStatus=!1,this.retryCacheStatus=!1}return r.prototype.apply=function(e,t){var i=this;if(t.enable_storage&&!t.disable_storage&&(this.collect=e,this.config=t,!this.collect.destroy)){var n=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(n.SubmitError,function(a){a.type!=="f_data"&&i.storeData(a)}),e.on(n.Ready,function(){i.checkStorage()})}},r.prototype.retryRightNow=function(e){var t=this;if(this.retryStatus)this.errorCache.push(e);else{var i=0;this.retryStatus=!0;var n=setInterval(function(){if(i===3)return t.storeData(t.errorCache),t.retryStatus=!1,void clearInterval(n);var s=e.eventData;t.fetchData(s,function(){t.retryStatus=!1,clearInterval(n),t.retryCacheStatus&&t.errorCache.splice(0,1),t.errorCache.length&&(t.retryCacheStatus=!0,t.retryRightNow(t.errorCache[0]))},function(){i++})},this.retryInterval)}},r.prototype.storeData=function(e){var t=this.storage.getItem(this.eventKey),i=e.eventData;Object.keys(t).length!==this.storageNum&&(t[Date.now()]=i,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 i={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([i],function(){var n=JSON.parse(JSON.stringify(t)),s=function(o){e.fetchData(t[o],function(){delete n[o],e.storage.setItem(e.eventKey,n)},function(){},!1)};for(var a in t)s(a)},function(){console.log("network error,compensate report fail")},!0)}catch{console.warn("error check storage")}},r.prototype.fetchData=function(e,t,i,n){this.collect.requestManager.useRequest({url:this.eventUrl,data:e,timeout:3e4,success:t,fail:i,app_key:n?"566f58151b0ed37e":""})},r}(),nn=typeof window<"u"?(window.LogPluginObject||(window.LogPluginObject={}),window.LogPluginObject):null,Am=function(){function r(){}return r.prototype.apply=function(e,t){this._plugin={},this.config=t,this.collect=e,this.channel=t.channel||"cn",this.loadExtend()},r.prototype.loadExtend=function(){var e=this;try{this.collect.remotePlugin.forEach(function(t,i){if(t==="sdk")if(Qi.hasOwnProperty(i)){var n=Qi[i].object,s=Qi[i].src[e.channel]+"?query="+Date.now();e.exist(i,n,s)}else console.warn("your "+i+" is not exist,please check plugin name");else typeof t=="object"&&(t.src?e.exist(i,t.call,t.src):e.process(i,t.instance,"INSTANCE"))})}catch(t){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:t.message}),console.log("load extend error")}},r.prototype.exist=function(e,t,i){var n=this;nn[t]?(this.process(e,nn[t]),console.log("已有"+e+"插件,避免重复加载~")):this.loadPlugin(e,i,function(){n.process(e,nn[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,i){try{if(i){var n=new t;n.apply&&n.apply(this.collect,this.config),console.log("excude "+e+" success")}else t&&t(this.collect,this.config)}catch(s){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:s.message}),console.log("excude "+e+" error, message:"+s.message)}},r.prototype.loadPlugin=function(e,t,i,n){var s=this;try{var a=document.createElement("script");a.src=t,this._plugin[e]||(this._plugin[e]=[]),this._plugin[e].push(i),a.onerror=function(){n(t)},a.onload=function(){s._plugin[e].forEach(function(o){o()})},document.getElementsByTagName("head")[0].appendChild(a)}catch(o){this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:o.message})}},r}(),Rm=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 i=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(i.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(n){for(var s=[],a=1;a<arguments.length;a++)s[a-1]=arguments[a];typeof history.onpushstate=="function"&&history.onpushstate({state:n});var o=t.call.apply(t,rt([history,n],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 h=e.getPopStateChangeEventData();return e.lastLocation=location.href,e.sendPv(h,"pushState"),o}};var i=history.replaceState;history.replaceState=function(n){for(var s=[],a=1;a<arguments.length;a++)s[a-1]=arguments[a];typeof history.onreplacestate=="function"&&history.onreplacestate({state:n});var o=i.call.apply(i,rt([history,n],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 h=e.getPopStateChangeEventData();return e.lastLocation=location.href,e.sendPv(h),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 i=e.getPopStateChangeEventData();e.sendPv(i)}}),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 i=e.getPopStateChangeEventData();e.sendPv(i)}})},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,i=this.storage.getItem("__tea_cache_first_"+this.appid);return t=!i||i!=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(n){return this.collect.emit(g.DEBUGGER_MESSAGE,{type:g.DEBUGGER_MESSAGE_SDK,info:"发生了异常",level:"error",time:Date.now(),data:n.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)||{},i=this.removeQuery(e);t.refer_key=i,t.routeChange=!0,this.storage.setItem(this.cache_key,t)},r}();fe.usePlugin(Am,"extend"),fe.usePlugin(Qf,"et"),fe.usePlugin(Yf,"ab"),fe.usePlugin(nm,"stay"),fe.usePlugin(Tm,"autotrack"),fe.usePlugin(sm,"profile"),fe.usePlugin(km,"retry"),fe.usePlugin(om,"heartbeat"),fe.usePlugin(am,"monitor"),fe.usePlugin(Rm,"route"),fe.usePlugin(zm,"tracer");var sr=new fe("default");const sn="VEPUSHER_DEVICE_ID",on="VEPUSHER_USER_ID",Wo=r=>Math.floor((Math.random()*9+1)*Math.pow(10,r-1)).toString();function Dm(r){const e={};if(!(r instanceof Object))throw new Error("params type error");for(const[t,i]of Object.entries(r))if(["string","number","boolean"].includes(typeof i))e[t]=i;else try{e[t]=JSON.stringify(i)}catch(n){console.error("serialize error",n)}return e}function xm(r){if(r)return localStorage.setItem(on,r),r;const e=localStorage.getItem(on);if(e)return e;const t=Wo(12);return localStorage.setItem(on,t),r}function Om(r){if(r)return localStorage.setItem(sn,r),r;const e=localStorage.getItem(sn);if(e)return e;const t=Wo(11);return localStorage.setItem(sn,t),t}class Mm{constructor({showLogInConsole:e=!1}){this._showLogInConsole=!1,this.markCollectTeaEventReady=()=>{this.isReady=!0,sr.start(),this.queueTeaEvent.forEach(t=>this.sendTeaEvent(...t)),this.queueTeaEvent=[]},this.configTea=(t,i)=>{const n={...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.89",...i}};sr.config(n),this.markCollectTeaEventReady()},this.isReady=!1,this.queueTeaEvent=[],sr.init({app_id:699880,channel:"cn"}),this._showLogInConsole=e}sendTeaEvent(e,t,i=!1){if(e)if(this.isReady)try{const n={...Dm(t||{})};sr.event(e,n),this._showLogInConsole&&!i&&console.log("[VePusher logger]:",e,n)}catch(n){console.error(n)}else this._showLogInConsole&&!i&&console.log("[VePusher logger]:",e,t),this.queueTeaEvent.push([e,t])}getIsReady(){return this.isReady}getRawTea(){return sr}}let or;function Im({showLogInConsole:r}){or=new Mm({showLogInConsole:r})}function R(r,e,t=!1){or&&or.sendTeaEvent(r,e,t)}function Pm(r,e){or&&or.configTea(r,e)}const D={PUSHER_INIT:"pusher_init",SET_PROPERTY_CALL:"set_property_call",SET_VIDEO_QUALITY:"set_video_quality",SET_AUDIO_QUALITY:"set_audio_quality",...{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"}};function Ct(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 Lm extends Ge{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:i,frameRate:n}=gt(xn,"video"),{sampleRate:s}=gt(On,"audio");this._videoConstraints={width:t,height:i,frameRate:n},this._audioConstraints={sampleRate:s,enableAutoGainControl:!0,enableNoiseSuppression:!0,enableEchoCancellation:!0},this._livePusher=e}_notifyCaptured(e){this.emit(ye.DeviceCaptured,e)}_notifyStopCapture(e){this.emit(ye.DeviceStopCapture,e)}_bindStreamEvent(e){e.bindTrackEnd(()=>{this.emit(ye.Interrupted,e),this.stopCapture({streamId:e.id,type:e.type})})}_handleError(e,t){const i=new _t(t,e.message);this.emit(ye.Error,i)}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 fu(e?[e]:["audioinput","videoinput"]);return R(D.GET_DEVICES_RESULT,{type:e,is_success:!0,devices:t}),t}catch(t){return R(D.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 i;switch(t){case N.Camera:i="_cameraStreams";break;case N.Screen:i="_screenStreams";break;case N.VideoFile:i="_videoFileStreams";break;case N.Microphone:i="_microphoneStreams";break;case N.AudioFile:i="_audioFileStreams";break;case N.Image:i="_imageStreams";break;case N.CustomVideo:i="_customVideoStreams";break;case N.CustomAudio:i="_customAudioStreams";break}if(i){let n=[];if(e){const s=this[i][e];n.push(s)}else n=Me(this[i]);R(D.STOP_CAPTURE,{stream_id:e,type:t,number:n.length}),n.forEach(s=>{this._notifyStopCapture(s),s.destroy(),delete this[i][s.id]})}}async startCameraCapture(e){let t={};xp.includes(e)?t={facingMode:e}:t={deviceId:e};const i={...t,...this._videoConstraints};try{const n=await mu(i,!this._livePusher.isEnableMixing),s=new Vu(n);return this._cameraStreams[s.id]=s,this._notifyCaptured(s),this._bindStreamEvent(s),R(D.CAMERA_CAPTURE_RESULT,{is_success:!0,stream_id:s.id,device_id:e,capture_params:i}),s.id}catch(n){throw R(D.CAMERA_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:i,...Ct(n)}),this._handleError(n,oe.OPEN_CAMERA_FAILED),n}}async startMicrophoneCapture(e){const t={...this._audioConstraints,deviceId:e};try{const i=await gu(t),n=new wp(i);return this._microphoneStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),R(D.MICROPHONE_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,device_id:e,capture_params:t}),n.id}catch(i){throw R(D.MICROPHONE_CAPTURE_RESULT,{is_success:!1,device_id:e,capture_params:t,...Ct(i)}),this._handleError(i,oe.OPEN_MICROPHONE_FAILED),i}}async startScreenCapture(e){const t={audio:e,video:this._videoConstraints};try{const i=await vu(t,void 0,!this._livePusher.isEnableMixing),n=new zp(i);return this._screenStreams[n.id]=n,this._notifyCaptured(n),this._bindStreamEvent(n),R(D.SCREEN_CAPTURE_RESULT,{is_success:!0,stream_id:n.id,capture_params:t}),n.id}catch(i){throw R(D.SCREEN_CAPTURE_RESULT,{is_success:!1,capture_params:t,...Ct(i)}),this._handleError(i,oe.OPEN_SCREEN_FAILED),i}}async startVideoFileCapture(e){try{const t=await Xn({url:e,video:!0,audio:!0,loop:!0}),i=new Tp(t);return this._videoFileStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),R(D.VIDEO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,file_url:e}),i.id}catch(t){throw this._handleError(t,oe.VIDEO_FILE_CAPTURE_FAILED),R(D.VIDEO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...Ct(t)}),t}}async startAudioFileCapture(e){try{const t=await Xn({url:e,video:!1,audio:!0,loop:!0}),i=new kp(t);return this._audioFileStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),R(D.AUDIO_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,file_url:e}),i.id}catch(t){throw R(D.AUDIO_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...Ct(t)}),this._handleError(t,oe.AUDIO_FILE_CAPTURE_FAILED),t}}async startImageCapture(e){try{const t=await _u({url:e,width:0,height:0,frameRate:30}),i=new Ap(t);return this._imageStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),R(D.IMAGE_FILE_CAPTURE_RESULT,{is_success:!0,stream_id:i.id,file_url:e}),i.id}catch(t){throw R(D.IMAGE_FILE_CAPTURE_RESULT,{is_success:!1,file_url:e,...Ct(t)}),this._handleError(t,oe.IMAGE_FILE_CAPTURE_FAILED),t}}startCustomVideoCapture(e){const t=bu(e);if(t){const i=new Rp(t);return this._customVideoStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}}startCustomAudioCapture(e){const t=Su(e);if(t){const i=new Dp(t);return this._customAudioStreams[i.id]=i,this._notifyCaptured(i),this._bindStreamEvent(i),i.id}}async startVolumeDetect(e){const t=this.getStreamById(e);if(t)try{await t.startVolumeDetect(),R(D.VOLUME_DETECTOR_START_RESULT,{is_success:!0,stream_id:t.id})}catch(i){R(D.VOLUME_DETECTOR_START_RESULT,{is_success:!1,stream_id:t.id,error_message:i.message}),this._handleError(i,oe.VOLUME_DETECT_FAILED)}}stopVolumeDetect(e){const t=this.getStreamById(e);t&&t.stopVolumeDetect()}getDefaultVideoStream(){return Me(this._cameraStreams)[0]||Me(this._screenStreams)[0]||Me(this._videoFileStreams)[0]||Me(this._imageStreams)[0]||Me(this._customVideoStreams)[0]}getDefaultAudioStream(){return Me(this._microphoneStreams)[0]||Me(this._audioFileStreams)[0]||Me(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(N).forEach(e=>{this.stopCapture({type:e})})}}let We=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 an{constructor({streamManagerController:e,composedStream:t,streamComposeController:i}){this._streamManagerController=e,this._composedStream=t,this._streamComposeController=i,this._active=!1,this.bindStreamManagerControllerEvent()}bindStreamManagerControllerEvent(){this._streamManagerController.on(ye.DeviceCaptured,e=>{this._active&&this.onStreamCapture(e)}),this._streamManagerController.on(ye.DeviceStopCapture,e=>{this._active&&this.onStreamStopCapture(e)})}getComposedStream(){return this._composedStream}enable(){this._active=!0}disable(){this._active=!1}}const Jo=new We("SingleComposer");class Um extends an{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:i}){var n,s;if(this._active)try{await((s=(n=this._composedStream.videoStream)==null?void 0:n.videoTrack)==null?void 0:s.applyConstraints({width:{min:e,ideal:e},height:{min:t,ideal:t},frameRate:{min:i,ideal:i}}))}catch(a){Jo.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(i=>{this._streamComposeController.removeAudioStream(i.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 i=this._streamManagerController.getDefaultVideoStream();i?this._handleVideoStreamCapture(i):Jo.error("all video stream stop capture")}}_handleAudioStreamStopCapture(e){this._streamComposeController.removeAudioStream(e.id)}getComposedStream(){return this._composedStream}}class Nm extends Ge{constructor(e,{width:t,height:i,x:n,y:s,zOrder:a,keepRatio:o,mirrorType:h}){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=i??e.height,this._rect.x=n??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=h,this._stream=e,this._bindVideoTrackSizeChange()}_getPaintSize({elementWidth:e,elementHeight:t}){const i=this._rect.width,n=this._rect.height;if(i===0&&n===0)return{width:0,height:0};if(i===0)return{height:n,width:e*(n/t)};if(n===0)return{width:i,height:t*(i/e)};const s=e/t,a=i/n;let o=i,h=n;return s>a?(o=i,h=2*Math.round(i/s/2)):s<a&&(o=2*Math.round(n*s/2),h=n),{width:o,height:h}}_bindVideoTrackSizeChange(){this._stream.on(Dn.SizeChange,({width:e,height:t})=>{this.setBaseProps("sourceWidth",e),this.setBaseProps("sourceHeight",t)})}getViewNode(){var n;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=(n=this._stream.viewNode)==null?void 0:n.size(e.width,e.height);let i;return this._rect.mirrorType!==void 0&&this._rect.mirrorType!==Tn.None?i=t==null?void 0:t.mirror(this._rect.mirrorType):i=t,i=i==null?void 0:i.position(this._rect.x,this._rect.y),i}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 i=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}i&&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 Zo extends lt{constructor(e){super({type:N.MixVideo,stream:e}),this._trackMap.video=e}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 Gm=Object.defineProperty,Bm=Object.getOwnPropertyDescriptor,ar=(r,e,t,i)=>{for(var n=Bm(e,t),s=r.length-1,a;s>=0;s--)(a=r[s])&&(n=a(e,t,n)||n);return n&&Gm(e,t,n),n};const Xo=new We("composition-composer");function cr(r,e,t){const i=t.value;return t.value=function(...n){return this._active||Xo.error("composer is not active"),i.apply(this,n)},t}class wt extends an{constructor(e){super(e),this._compositionViewConfig={width:1080,height:720,frameRate:30,backgroundColor:"#000000"},this._sprites=[],this._videoMixer=new Lu}onStreamCapture(e){}onStreamStopCapture(e){e&&e.isVideoStream&&this.removeVideoStream(e.id)}enable(){var i;if(this._active)return;super.enable();const e=this._videoMixer.track(),t=this._mixedVideoStream;this._mixedVideoStream=new Zo(e),this._composedStream.setVideoStream(this._mixedVideoStream),t&&((i=t.videoTrack)==null?void 0:i.id)!==e.id&&t.destroy()}disable(){super.disable(),this._videoMixer.stop()}_updateSpriteToMixer(){const e=$s(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,i)=>t.zOrder-i.zOrder),e.on("propsChange",t=>{Cp(t.zOrder)||(this._sprites=this._sprites.sort((i,n)=>i.zOrder-n.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 i=this._mixedVideoStream,n=this._videoMixer.updateFps();this._mixedVideoStream=new Zo(n),this._composedStream.setVideoStream(this._mixedVideoStream),i.destroy()}}getMixingConfig(){return this._compositionViewConfig}addVideoStream(e,t){if(!e.viewNode){Xo.error("have no viewNode for composition");return}e.audioTrack&&this._streamComposeController.addAudioStream({streamId:e.id,volume:100});const i=new Nm(e,t);this._addSprite(i)}_updateSingleVideoStream(e){const t=e.streamId;if(!t)return;const i=this._sprites.find(n=>n.stream.id===t);i&&(i.height=e.height,i.width=e.width,i.x=e.x,i.y=e.y,i.zOrder=e.zOrder,i.keepRatio=e.keepRatio??!1,i.mirrorType=e.mirrorType)}updateVideoStream(e){e.forEach(t=>{this._updateSingleVideoStream(t)}),this._updateSpriteToMixer()}removeVideoStream(e){if(!e)return;const t=this._sprites.find(i=>i.stream.id===e);t&&this._removeSprite(t)}muteVideoStream(e){if(e){const t=this._sprites.find(i=>i.stream.id===e);t&&t.hide()}else this._sprites.forEach(t=>{t.hide()});this._updateSpriteToMixer()}unmuteVideoStream(e){if(e){const t=this._sprites.find(i=>i.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(i=>i.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}}}ar([cr],wt.prototype,"addVideoStream"),ar([cr],wt.prototype,"updateVideoStream"),ar([cr],wt.prototype,"removeVideoStream"),ar([cr],wt.prototype,"muteVideoStream"),ar([cr],wt.prototype,"unmuteVideoStream");class Vm extends Ge{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 Fm extends gr{constructor(e){super({type:N.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 jm extends an{constructor(e){super(e),this._spriteList=[],this._audioMixer=new Cu({keepAlive:!0})}onStreamCapture(e){}onStreamStopCapture(e){e&&this.removeAudioStream(e.id)}_updateSpriteToMixer(){const e=$s(this._spriteList.map(t=>t.isMute?null:t.getMixerNode()));this._audioMixer.mix(e)}_updateSingleAudioStream(e){const{streamId:t,volume:i}=e,n=this._spriteList.find(s=>s.stream.id===t);n?i!==void 0&&(n.volume=i):console.error("can not find stream"+t)}enable(){super.enable();const e=this._audioMixer.track(),t=new Fm(e);this._composedStream.setAudioStream(t),this._audioMixer.mix([])}addAudioStream(e,t){const i=new Vm(e,t);this._spriteList.push(i),this._updateSpriteToMixer()}tryResume(){return this._audioMixer.resume()}removeAudioStream(e){const t=this._spriteList.find(i=>i.stream.id===e);t&&(this._spriteList=this._spriteList.filter(i=>i!==t),this._updateSpriteToMixer())}updateAudioStream(e){e.forEach(t=>{this._updateSingleAudioStream(t)}),this._updateSpriteToMixer()}muteAudioStream(e){if(e){const t=this._spriteList.find(i=>i.stream.id===e);t&&t.mute()}else this._spriteList.forEach(t=>{t.mute()});this._updateSpriteToMixer()}unmuteAudioStream(e){if(e){const t=this._spriteList.find(i=>i.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 Hm extends Ge{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(Ye.VideoStreamChange,e))}setAudioStream(e){var t;((t=this._audioStream)==null?void 0:t.id)!==e.id&&(this._audioStream=e,this.emit(Ye.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 $m=new We("streamComposeController");class Km{constructor(e){this._streamManagerController=e,this._composedStream=new Hm,this.singleComposer=new Um({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.compositionComposer=new wt({streamManagerController:this._streamManagerController,composedStream:this._composedStream,streamComposeController:this}),this.mixerComposer=new jm({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:i}){this.singleComposer.setVideoQuality({width:e,height:t,frameRate:i}),this.compositionComposer.setMixingConfig({width:e,height:t,frameRate:i})}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){$m.error("can not find video stream"+e.streamId);return}this.compositionComposer.addVideoStream(t,e)}updateVideoStream(e){this.compositionComposer.updateVideoStream(e);const t=e.map(i=>({streamId:i.streamId,volume:i.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()}}class Yo{constructor(e){this._hasBindComposedStreamEvent=!1,this._composedStream=e}bindComposedStreamEvent(){this._hasBindComposedStreamEvent||(this._composedStream.on(Ye.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.on(Ye.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!0)}unbindComposedStreamEvent(){this._hasBindComposedStreamEvent&&(this._composedStream.off(Ye.VideoStreamChange,this.handleVideoStreamChange),this._composedStream.off(Ye.AudioStreamChange,this.handleAudioStreamChange),this._hasBindComposedStreamEvent=!1)}}const Tt=new We("PreviewConsumer");class qm extends Yo{constructor(e,{streamConsumeController:t}){super(e),this._isPreviewing=!1,this._previewElement=null,this.handleAudioStreamChange=i=>{this.startPreview()},this.handleVideoStreamChange=i=>{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 i=document.createElement("video");i.style.width="100%",i.style.height="100%",i.autoplay=!0,i.playsInline=!0,i.setAttribute("webkit-playsinline",""),i.setAttribute("x5-playsinline",""),this._previewElement=i;const n={video:null,audio:null};i.addEventListener("loadeddata",()=>{const s=i.srcObject.getVideoTracks()[0],a=i.srcObject.getAudioTracks()[0];s&&s!==n.video&&(this._streamConsumeController.emit(j.CaptureFirstVideoFrame),n.video=s),a&&a!==n.audio&&(this._streamConsumeController.emit(j.CaptureFirstAudioFrame),n.audio=a)}),t.appendChild(i)}startPreview(){if(Tt.log("startPreview"),!this._previewElement){Tt.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(i=>{this._streamConsumeController.emit(j.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 i=e.srcObject||new MediaStream;i.getTracks().find(n=>n.id===t.id)||(t.kind==="audio"&&i.getTracks().forEach(n=>{n.kind==="audio"&&(Tt.log(`remove preview track, ${n.label}, readyState=${n.readyState}`),i.removeTrack(n))}),t.kind==="video"&&i.getTracks().forEach(n=>{n.kind==="video"&&(i.removeTrack(n),Tt.log(`remove preview track, ${n.label}, readyState=${n.readyState}`))}),i.addTrack(t),e.srcObject?e.load():e.srcObject=i)}_removeTrack(e,t){if(!e)return;const i=e.srcObject;i&&(i.getTracks().forEach(n=>{(n.id===(t==null?void 0:t.id)||n.readyState==="ended")&&(Tt.log(`remove preview track ${n.label}`),i.removeTrack(n))}),i.getTracks().length===0&&(e.srcObject=null,Tt.log("set srcObject null")))}getPreviewElement(){if(this.isPreviewing)return this._previewElement}get isPreviewing(){return this._isPreviewing}}var ve={},cn={},un={exports:{}},Qo;function hn(){if(Qo)return un.exports;Qo=1;var r=un.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(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),un.exports}var ea;function Wm(){return ea||(ea=1,function(r){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,h,c,u){if(u&&!c)h[u]=e(o[1]);else for(var l=0;l<c.length;l+=1)o[l+1]!=null&&(h[c[l]]=e(o[l+1]))},i=function(o,h,c){var u=o.name&&o.names;o.push&&!h[o.push]?h[o.push]=[]:u&&!h[o.name]&&(h[o.name]={});var l=o.push?{}:u?h[o.name]:h;t(c.match(o.reg),l,o.names,o.name),o.push&&h[o.push].push(l)},n=hn(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);r.parse=function(o){var h={},c=[],u=h;return o.split(/(\r\n|\r|\n)/).filter(s).forEach(function(l){var d=l[0],p=l.slice(2);d==="m"&&(c.push({rtp:[],fmtp:[]}),u=c[c.length-1]);for(var f=0;f<(n[d]||[]).length;f+=1){var v=n[d][f];if(v.reg.test(p))return i(v,u,p)}}),h.media=c,h};var a=function(o,h){var c=h.split(/=(.+)/,2);return c.length===2?o[c[0]]=e(c[1]):c.length===1&&h.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 h=[],c=o.split(" ").map(e),u=0;u<c.length;u+=3)h.push({component:c[u],ip:c[u+1],port:c[u+2]});return h},r.parseImageAttributes=function(o){return o.split(" ").map(function(h){return h.substring(1,h.length-1).split(",").reduce(a,{})})},r.parseSimulcastStreamList=function(o){return o.split(";").map(function(h){return h.split(",").map(function(c){var u,l=!1;return c[0]!=="~"?u=e(c):(u=e(c.substring(1,c.length)),l=!0),{scid:u,paused:l}})})}}(cn)),cn}var dn,ta;function Jm(){if(ta)return dn;ta=1;var r=hn(),e=/%[sdv%]/g,t=function(a){var o=1,h=arguments,c=h.length;return a.replace(e,function(u){if(o>=c)return u;var l=h[o];switch(o+=1,u){case"%%":return"%";case"%s":return String(l);case"%d":return Number(l);case"%v":return""}})},i=function(a,o,h){var c=o.format instanceof Function?o.format(o.push?h:h[o.name]):o.format,u=[a+"="+c];if(o.names)for(var l=0;l<o.names.length;l+=1){var d=o.names[l];o.name?u.push(h[o.name][d]):u.push(h[o.names[l]])}else u.push(h[o.name]);return t.apply(null,u)},n=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return dn=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(l){l.payloads==null&&(l.payloads="")});var h=o.outerOrder||n,c=o.innerOrder||s,u=[];return h.forEach(function(l){r[l].forEach(function(d){d.name in a&&a[d.name]!=null?u.push(i(l,d,a)):d.push in a&&a[d.push]!=null&&a[d.push].forEach(function(p){u.push(i(l,d,p))})})}),a.media.forEach(function(l){u.push(i("m",r.m[0],l)),c.forEach(function(d){r[d].forEach(function(p){p.name in l&&l[p.name]!=null?u.push(i(d,p,l)):p.push in l&&l[p.push]!=null&&l[p.push].forEach(function(f){u.push(i(d,p,f))})})})}),u.join(`\r
|
|
57
67
|
`)+`\r
|
|
58
|
-
`},Ut}var Ai;function wu(){if(Ai)return B;Ai=1;var r=Ru(),e=Au(),t=Vt();return B.grammar=t,B.write=e,B.parse=r.parse,B.parseParams=r.parseParams,B.parseFmtpConfig=r.parseFmtpConfig,B.parsePayloads=r.parsePayloads,B.parseRemoteCandidates=r.parseRemoteCandidates,B.parseImageAttributes=r.parseImageAttributes,B.parseSimulcastStreamList=r.parseSimulcastStreamList,B}var Ou=wu();const Xe=D(Ou);function wi(r){return new Promise(e=>{setTimeout(e,r)})}async function Du(r,e={},t=0){const i=new AbortController;let s=!1;e=Object.assign({},e,{signal:i.signal});const n=[fetch(r,e)];t&&n.push(new Promise((a,o)=>{setTimeout(()=>{s||(o({httpCode:0,message:"Timeout"}),i.abort())},t)}));try{const a=await Promise.race(n);if(s=!0,!a.ok||a.status<200||a.status>=300)throw{httpCode:a.status,message:a.statusText};return a.json()}catch(a){throw s=!0,a}}async function Oi(r,e={},t={}){const{timeout:i=0,retryDelay:s=0}=t;let{retryCount:n=0}=t;try{return await Du(r,e,i)}catch(a){if(n--,t.retryCount=n,n<0)throw a;return await wi(s),await Oi(r,e,t)}}function w(r,e){let t;return e.forEach(i=>{i.type===r&&(t=i)}),t}async function $t(r,e){const t={},i=await(r==null?void 0:r.getStats()),s=await(e==null?void 0:e.getStats());return i&&(t.audio={mediaSource:w("media-source",i),codec:w("codec",i),candidatePair:w("candidate-pair",i),remoteCandidate:w("remote-candidate",i),localCandidate:w("local-candidate",i),track:w("track",i),outboundRtp:w("outbound-rtp",i),remoteInboundRtp:w("remote-inbound-rtp",i),transport:w("transport",i)}),s&&(t.video={mediaSource:w("media-source",s),codec:w("codec",s),candidatePair:w("candidate-pair",s),remoteCandidate:w("remote-candidate",s),localCandidate:w("local-candidate",s),track:w("track",s),outboundRtp:w("outbound-rtp",s),remoteInboundRtp:w("remote-inbound-rtp",s),transport:w("transport",s)}),t}async function Iu(r,e,t){var c,h,p,l,f,g,_,T,b,v,j,R,ws,Os,Ds,Is,Ms,Ls,Fs,Ns,Vs,Us,$s,Bs,js,zs,Gs,Hs,qs,Ws,Xs,Ks,Js,Ys,Zs,Qs;const i=await $t(e,t);await wi(r);const s=await $t(e,t),{audio:n,video:a}=i,{audio:o,video:u}=s,d={};if(n!=null&&n.codec&&(o!=null&&o.codec)){const Yt=((c=o.outboundRtp)==null?void 0:c.timestamp)-((h=n.outboundRtp)==null?void 0:h.timestamp),Zt=((p=o.outboundRtp)==null?void 0:p.bytesSent)-((l=n.outboundRtp)==null?void 0:l.bytesSent),Qt=((f=o.remoteInboundRtp)==null?void 0:f.packetsLost)-((g=n.remoteInboundRtp)==null?void 0:g.packetsLost),er=((_=o.outboundRtp)==null?void 0:_.packetsSent)-((T=n.outboundRtp)==null?void 0:T.packetsSent);d.audio={codec:o.codec.mimeType,channels:o.codec.channels,sendBitrate:Zt/Yt*8e3,packetsSent:(b=o.outboundRtp)==null?void 0:b.packetsSent,nackCount:(v=o.outboundRtp)==null?void 0:v.nackCount,packetsLost:(j=o.remoteInboundRtp)==null?void 0:j.packetsLost,packetsLostPercent:Qt/er}}if(a!=null&&a.codec&&(u!=null&&u.codec)){const Yt=((R=u.outboundRtp)==null?void 0:R.timestamp)-((ws=a.outboundRtp)==null?void 0:ws.timestamp),Zt=((Os=u.outboundRtp)==null?void 0:Os.bytesSent)-((Ds=a.outboundRtp)==null?void 0:Ds.bytesSent),Qt=((Is=u.outboundRtp)==null?void 0:Is.framesEncoded)-((Ms=a.outboundRtp)==null?void 0:Ms.framesEncoded),er=((Ls=u.outboundRtp)==null?void 0:Ls.totalEncodeTime)-((Fs=a.outboundRtp)==null?void 0:Fs.totalEncodeTime),en=((Ns=u.outboundRtp)==null?void 0:Ns.packetsSent)-((Vs=a.outboundRtp)==null?void 0:Vs.packetsSent),hh=((Us=u.outboundRtp)==null?void 0:Us.totalPacketSendDelay)-(($s=a.outboundRtp)==null?void 0:$s.totalPacketSendDelay),ph=((Bs=u.remoteInboundRtp)==null?void 0:Bs.packetsLost)-((js=a.remoteInboundRtp)==null?void 0:js.packetsLost);d.video={codec:u.codec.mimeType,sendBitrate:Zt/Yt*8e3,frameWidth:(zs=u.outboundRtp)==null?void 0:zs.frameWidth,frameHeight:(Gs=u.outboundRtp)==null?void 0:Gs.frameHeight,framesPerSecond:(Hs=u.outboundRtp)==null?void 0:Hs.framesPerSecond,framesEncoded:(qs=u.outboundRtp)==null?void 0:qs.framesEncoded,keyFramesEncoded:(Ws=u.outboundRtp)==null?void 0:Ws.keyFramesEncoded,framesSent:(Xs=u.outboundRtp)==null?void 0:Xs.frameHeight,frameEncodeAvgTime:er*1e3/Qt,packetsSent:(Ks=u.outboundRtp)==null?void 0:Ks.packetsSent,packetSendDelay:hh*1e3/en,nackCount:(Js=u.outboundRtp)==null?void 0:Js.nackCount,firCount:(Ys=u.outboundRtp)==null?void 0:Ys.firCount,pliCount:(Zs=u.outboundRtp)==null?void 0:Zs.pliCount,packetsLost:(Qs=u.remoteInboundRtp)==null?void 0:Qs.packetsLost,packetsLostPercent:ph/en}}return d}const Mu=r=>{var t;if(!fr)return;const e=(t=r.rtp.filter(i=>i.codec==="opus")[0])==null?void 0:t.payload;e&&r.fmtp.forEach(i=>{i.payload===e&&(i.config="minptime=10;useinbandfec=1")})},Lu=r=>{r.ext&&(pn||Le)&&(r.ext=r.ext.filter(e=>{var t;return!((t=e.uri)!=null&&t.includes("video-orientation"))}))};function Fu(r,e){r==null||r.rtp.forEach(({codec:t,payload:i})=>{if(["vp8","h264"].includes(t.toLocaleLowerCase())){const s=r.fmtp.find(n=>n.payload===i);s?s.config=[...s.config.split(";"),"x-google-min-bitrate=100",`x-google-start-bitrate=${e}`].join(";"):r.fmtp.push({payload:i,config:`x-google-min-bitrate=100;x-google-start-bitrate=${e}`})}})}const M=new de("PCConnect");class Nu{constructor(e,t,i){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=i}get isPushing(){var e,t,i,s;return((t=(e=this._videoTransceiver)==null?void 0:e.sender)==null?void 0:t.track)||((s=(i=this._audioTransceiver)==null?void 0:i.sender)==null?void 0:s.track)}get pushUrl(){return this._signalUrl}get sessionId(){return this._sessionId}async publish(e,t){const i=new RTCPeerConnection;this._pc=i,this._bindRTCEvent();const s=e.filter(c=>(c==null?void 0:c.kind)==="audio")[0],n=e.filter(c=>(c==null?void 0:c.kind)==="video")[0];s&&this._ms.addTrack(s),n&&this._ms.addTrack(n),this._audioTransceiver=i.addTransceiver(s||"audio",{direction:"sendonly",sendEncodings:[{maxBitrate:t[0]}],streams:[this._ms]}),M.log("add track to pc,",s),this._videoTransceiver=i.addTransceiver(n||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),M.log("add track to pc,",n);const a=await i.createOffer();M.groupCollapsed("local offer"),M.log(a.sdp);const o=Xe.parse(a.sdp);o.media.forEach(c=>{c.type==="audio"?Mu(c):c.type==="video"&&(Lu(c),Fu(c,t[1]))}),a.sdp=Xe.write(o),M.log("local offer modified"),M.log(a.sdp),await i.setLocalDescription(a);const u=await Oi(this._signalUrl,{method:"POST",mode:"cors",body:JSON.stringify({sessionId:""+this._sessionId,version:"1.0-html",localSdp:a,metadata:{platform:"Web"}})},this._opts);if((u==null?void 0:u.code)!==200)throw{code:u.code,message:u.message};M.log("remote answer:"),M.log(u.remoteSdp.sdp);const d=Xe.parse(u.remoteSdp.sdp);d.media.forEach(c=>{var h;(h=c.fingerprint)!=null&&h.hash&&(c.fingerprint.hash=c.fingerprint.hash.toUpperCase())}),u.remoteSdp.sdp=Xe.write(d),M.log("remote answer modified"),M.log(u.remoteSdp.sdp),M.groupEnd(),await i.setRemoteDescription(u.remoteSdp)}async updatePublish(e,t){var n,a;let i;t==="video"?i=this._videoTransceiver:i=this._audioTransceiver;const s=(n=i==null?void 0:i.sender)==null?void 0:n.track;(s==null?void 0:s.id)!==(e==null?void 0:e.id)&&(await((a=i==null?void 0:i.sender)==null?void 0:a.replaceTrack(e)),M.log(`replace ${t} track done! ${s==null?void 0:s.label} -> ${e==null?void 0:e.label}`))}applyBitrate(e,t,i){var a,o,u;const s=t==="video"?(a=this._videoTransceiver)==null?void 0:a.sender:(o=this._audioTransceiver)==null?void 0:o.sender;if(!s)return;const n=s.getParameters();n.encodings=(u=n.encodings)!=null&&u.length?n.encodings:[{}],i?n.encodings[0].minBitrate=e:n.encodings[0].maxBitrate=e,s.setParameters(n),M.log(`set bitrate for ${t}, ${e} bps, min:${i}`)}unpublish(){var e,t;(e=this._pc)==null||e.getSenders().forEach(i=>{var s;(s=this._pc)==null||s.removeTrack(i)}),(t=this._pc)==null||t.close(),this._audioTransceiver=null,this._videoTransceiver=null,this._pc=null,M.log("close pc!")}getStats(){var e,t;return $t((e=this._audioTransceiver)==null?void 0:e.sender,(t=this._videoTransceiver)==null?void 0:t.sender)}getStatsSnapshoot(e){var t,i;return Iu(e||100,(t=this._audioTransceiver)==null?void 0:t.sender,(i=this._videoTransceiver)==null?void 0:i.sender)}_bindRTCEvent(){const e=this._pc;e==null||e.addEventListener("connectionstatechange",()=>{M.log("onconnectionstatechange:",e.connectionState),this._onConnectStateChange(e.connectionState)})}}var ue=(r=>(r.OnError="onerror",r.OnConnectClosed="onconnectclosed",r.OnFirstFramePushed="onfirstframepushed",r))(ue||{}),ie=(r=>(r.Video="video",r.Audio="audio",r))(ie||{}),V=(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))(V||{}),he=(r=>(r.Ready="ready",r.Error="error",r.FirstFramePushed="firstframepushed",r.Flvfile="flvfile",r.STATS="stats",r.Close="close",r))(he||{}),Bt={exports:{}},Di;function Vu(){return Di||(Di=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(u,d,c){this.fn=u,this.context=d,this.once=c||!1}function n(u,d,c,h,p){if(typeof c!="function")throw new TypeError("The listener must be a function");var l=new s(c,h||u,p),f=t?t+d:d;return u._events[f]?u._events[f].fn?u._events[f]=[u._events[f],l]:u._events[f].push(l):(u._events[f]=l,u._eventsCount++),u}function a(u,d){--u._eventsCount===0?u._events=new i:delete u._events[d]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],c,h;if(this._eventsCount===0)return d;for(h in c=this._events)e.call(c,h)&&d.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(c)):d},o.prototype.listeners=function(d){var c=t?t+d:d,h=this._events[c];if(!h)return[];if(h.fn)return[h.fn];for(var p=0,l=h.length,f=new Array(l);p<l;p++)f[p]=h[p].fn;return f},o.prototype.listenerCount=function(d){var c=t?t+d:d,h=this._events[c];return h?h.fn?1:h.length:0},o.prototype.emit=function(d,c,h,p,l,f){var g=t?t+d:d;if(!this._events[g])return!1;var _=this._events[g],T=arguments.length,b,v;if(_.fn){switch(_.once&&this.removeListener(d,_.fn,void 0,!0),T){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,c),!0;case 3:return _.fn.call(_.context,c,h),!0;case 4:return _.fn.call(_.context,c,h,p),!0;case 5:return _.fn.call(_.context,c,h,p,l),!0;case 6:return _.fn.call(_.context,c,h,p,l,f),!0}for(v=1,b=new Array(T-1);v<T;v++)b[v-1]=arguments[v];_.fn.apply(_.context,b)}else{var j=_.length,R;for(v=0;v<j;v++)switch(_[v].once&&this.removeListener(d,_[v].fn,void 0,!0),T){case 1:_[v].fn.call(_[v].context);break;case 2:_[v].fn.call(_[v].context,c);break;case 3:_[v].fn.call(_[v].context,c,h);break;case 4:_[v].fn.call(_[v].context,c,h,p);break;default:if(!b)for(R=1,b=new Array(T-1);R<T;R++)b[R-1]=arguments[R];_[v].fn.apply(_[v].context,b)}}return!0},o.prototype.on=function(d,c,h){return n(this,d,c,h,!1)},o.prototype.once=function(d,c,h){return n(this,d,c,h,!0)},o.prototype.removeListener=function(d,c,h,p){var l=t?t+d:d;if(!this._events[l])return this;if(!c)return a(this,l),this;var f=this._events[l];if(f.fn)f.fn===c&&(!p||f.once)&&(!h||f.context===h)&&a(this,l);else{for(var g=0,_=[],T=f.length;g<T;g++)(f[g].fn!==c||p&&!f[g].once||h&&f[g].context!==h)&&_.push(f[g]);_.length?this._events[l]=_.length===1?_[0]:_:a(this,l)}return this},o.prototype.removeAllListeners=function(d){var c;return d?(c=t?t+d:d,this._events[c]&&a(this,c)):(this._events=new i,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}(Bt)),Bt.exports}var Uu=Vu();const $u=D(Uu);var jt=(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))(jt||{});class Bu extends Error{constructor(e,t,i){super(),this.code=e,this.message=t,i&&(this.ext=i),this.toJson=()=>({code:this.code,message:this.message,ext:this.ext})}}function Ii(r,e,t){return new Bu(r,e,t)}const Te=class Te{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 Te.enable}get _enableLong(){return Te.enableLong}get long(){return this._enableLong}};Te.enable=!1,Te.enableLong=!1;let se=Te;const U=new se("RTMP_Capture");class ju{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(U.log(`replace ${e} track`),e===ie.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 s;if(!this.videoTrack){U.log("no video track to capture");return}if(this.videoTrack.readyState!=="live"){U.warn("video track not live");return}const e=new MediaStreamTrackProcessor(this.videoTrack);e.track=this.videoTrack;const t=e.readable.getReader();this._videoProcessorReader=t,U.log("start capture video frame",this.videoTrack);let i;for(;;){i&&clearInterval(i),i=setTimeout(()=>{U.warn("long time no capture output"),this._bridge._postMockVideoEncodeFlag()},1500);const n=await t.read();if(clearInterval(i),this._videoFirstframeCaptured||(this._videoFirstframeCaptured=!0,U.log("video first frame captured")),n.done||!n.value){(s=n.value)==null||s.close();break}this._bridge._postVideoFrame(n.value,this.videoTrack.getSettings())}clearInterval(i),this._videoFirstframeCaptured=!1,this._videoProcessorReader=null,U.log("video track read done!",e.track)}async _startAudioCapture(){if(!this.audioTrack){U.log("no audio track to capture");return}if(this.audioTrack.readyState!=="live"){U.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,U.log("start capture audio frame");;){const i=await t.read();if(this._audioFirstframeCaptured||(this._audioFirstframeCaptured=!0,U.log("audio first frame captured")),i.done||!i.value)break;this._bridge._postAudioFrame(i.value,this.audioTrack.getSettings())}this._audioFirstframeCaptured=!1,this._audioProcessorReader=null,U.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 Mi='(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',Li=typeof self<"u"&&self.Blob&&new Blob([Mi],{type:"text/javascript;charset=utf-8"});function zu(r){let e;try{if(e=Li&&(self.URL||self.webkitURL).createObjectURL(Li),!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(Mi),{name:r==null?void 0:r.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}try{se.enable=location.href.indexOf("rtmpdebug")!==-1,se.enableLong=location.href.indexOf("rtmpdebug=long")!==-1}catch{}const Ke=new se("Bridge");class Fi extends $u{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new ju(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 n,a;let e,t;const i=new Promise((o,u)=>{e=o,t=u}),s=o=>{var u;switch((u=this._worker)==null||u.removeEventListener("message",s),o.data.type){case he.Error:t(o.data.data);break;default:this._bindWorkerEvent(),Ke.log("rtmp ready!"),e(!0)}};try{this._worker=new zu}catch(o){t(Ii(jt.RTMP_INIT_FAIL,o.message))}return(n=this._worker)==null||n.postMessage({type:V.Init,options:{logEnable:se.enable,logEnableLong:se.enableLong}}),(a=this._worker)==null||a.addEventListener("message",s),i}_bindWorkerEvent(){var e,t;(e=this._worker)==null||e.addEventListener("message",i=>{switch(i.data.type){case he.Error:Ke.table(i.data.data),this.emit(ue.OnError,i.data.data);break;case he.Flvfile:Gu(i.data.buffer);break;case he.FirstFramePushed:this.emit(ue.OnFirstFramePushed);break;case he.Close:this.emit(ue.OnConnectClosed),this.destroy();break}}),(t=this._worker)==null||t.addEventListener("error",i=>{this.emit(ue.OnError,Ii(jt.WORKER_ERROR,i.message))})}addTrack(e){e.kind===ie.Video&&(this._videoMsTrack=e),e.kind===ie.Audio&&(this._audioMsTrack=e),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack)}replaceTrack(e,t){e===ie.Video&&(this._videoMsTrack=t),e===ie.Audio&&(this._audioMsTrack=t),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack),this._capture.restartCapture(e)}async getStats(){var n,a;let e,t;const i=new Promise((o,u)=>{e=o,t=u});this._worker||setTimeout(()=>{t()},0);const s=o=>{var u;switch(o.data.type){case he.STATS:e(o.data.data),(u=this._worker)==null||u.removeEventListener("message",s);break}};return(n=this._worker)==null||n.addEventListener("message",s),(a=this._worker)==null||a.postMessage({type:V.GetStats}),i}_postVideoFrame(e,t){var i;(i=this._worker)==null||i.postMessage({type:V.VideoFrame,frame:e,setting:t},[e])}_postMockVideoEncodeFlag(){var e;(e=this._worker)==null||e.postMessage({type:V.MockVideoEncode})}_setAVExist(e,t){var i;(i=this._worker)==null||i.postMessage({type:V.AvExist,hasVideo:e,hasAudio:t})}_postAudioFrame(e,t){var i;(i=this._worker)==null||i.postMessage({type:V.AudioFrame,frame:e,setting:t},[e])}setEncodeCapacity(e){var t;(t=this._worker)==null||t.postMessage({type:V.EncodeConfig,cfg:e})}adjustBitrate(e,t){var i;(i=this._worker)==null||i.postMessage({type:V.AdjustBitrate,kind:e,bitrate:t})}publish(e){var t;Ke.log("start capture & connect"),this._capture.start(),(t=this._worker)==null||t.postMessage({type:V.Publish,url:e})}unpublish(){var e;this._capture.destroy(),(e=this._worker)==null||e.postMessage({type:V.UnPublish})}destroy(){var e;Ke.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:V.Download})}}function Gu(r){const e=document.createElement("a");e.href=URL.createObjectURL(new Blob([r])),e.download=Date.now()+".flv",e.click()}const Ni=new de("RTMPConnect");class Hu{constructor(e,t,i,s){this._opts=void 0,this._isPushing=!1,this._url=e,this._opts=t,this._onError=i,this._OnSuccess=s,this._rtmp=new Fi,this._bindEvents()}get isPushing(){return this._isPushing}get pushUrl(){return this._url}get sessionId(){return 0}_bindEvents(){this._rtmp.on(ue.OnError,e=>{this._isPushing=!1,this._onError(e)}),this._rtmp.on(ue.OnFirstFramePushed,()=>{this._isPushing=!0,this._OnSuccess()})}async publish(e,t,i){await this._rtmp.ready(),i&&this._rtmp.setEncodeCapacity(i),e.filter(Boolean).forEach(s=>this._rtmp.addTrack(s)),t[0]&&this._rtmp.adjustBitrate(ie.Audio,t[0]),t[1]&&this._rtmp.adjustBitrate(ie.Video,t[1]),this._rtmp.publish(this._url)}updatePublish(e,t){Ni.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(){return this._rtmp.getStats()}unpublish(){Ni.warn("unpublish"),this._rtmp.unpublish(),this._isPushing=!1}}const qu=new de("PushController");class Wu extends ki{constructor(e,{config:t,streamConsumeController:i}){super(e),this._connect=null,this._pushMode="rtm",this._pushConfig={timeout:5e3,retryCount:1,retryDelay:1e3},this._audioBitrate=ve(cr,"audio").bitrate,this._videoBitrate=ve(ar,"video").bitrate,this.handleAudioStreamChange=s=>{this.updatePush({audioTrack:s.audioTrack})},this.handleVideoStreamChange=s=>{this.updatePush({videoTrack:s.videoTrack})},this._OnRTMPSuccess=()=>{this._streamConsumeController.emit(A.PushStart)},this._OnRTMPError=s=>{const n=new De(N.PUBLISH_FAILED,`code:${s.code}, message: ${s.message}`);this._streamConsumeController.emit(A.PushError,n),this.unpublish()},this._OnRtcStateChange=s=>{if(s==="failed"){this.unpublish();const n=new De(N.PUSH_CONNECT_FAILED,"pc disconnect");this._streamConsumeController.emit(A.PushError,n)}s==="connected"&&this._streamConsumeController.emit(A.PushStart),this._streamConsumeController.emit(A.RTCConnectStateChanged,s)},this._pushMode=(t==null?void 0:t.mode)||"rtm",this._streamConsumeController=i,t&&(this._pushConfig=t)}get isPushing(){var e;return!!((e=this._connect)!=null&&e.isPushing)}get pushUrl(){var e;return((e=this._connect)==null?void 0:e.pushUrl)||""}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)}async getStats(e=2e3){var t;return(t=this._connect)==null?void 0:t.getStatsSnapshoot(e)}async startPush(e,t){if(!e)throw new Error("lack publish url");if(this._connect)return;this.start();const i=this._composedStream.videoTrack,s=this._composedStream.audioTrack;if(!i&&!s)return;let n;this._pushMode==="rtm"?n=new Nu(e,this._pushConfig,this._OnRtcStateChange):n=new Hu(e,this._pushConfig,this._OnRTMPError,this._OnRTMPSuccess),this._connect=n;try{await n.publish([s,i],[this._audioBitrate,this._videoBitrate],t)}catch(a){qu.groupEnd(),n.unpublish();const o=new De(N.PUBLISH_FAILED,a.message,a);this._streamConsumeController.emit(A.PushError,o)}}async updatePush({videoTrack:e,audioTrack:t}){if(this._connect)try{const i=[];e&&i.push(()=>{var s;return(s=this._connect)==null?void 0:s.updatePublish(e,"video")}),t&&i.push(()=>{var s;return(s=this._connect)==null?void 0:s.updatePublish(t,"audio")}),await Promise.all(i.map(s=>s()))}catch(i){const s=new De(N.UPDATE_PUBLISH_FAILED,`${i.name}, code:${i.code}`);this._streamConsumeController.emit(A.PushError,s)}}unpublish(){var e;(e=this._connect)==null||e.unpublish(),this._connect=null,this._streamConsumeController.emit(A.PushStop)}async destroy(){this._connect&&await this.unpublish(),this.unbindComposedStreamEvent()}setPushMode(e){this._pushMode=e}setBitrate(e,t,i){var s;t==="video"?this._videoBitrate=e:this._audioBitrate=e,(s=this._connect)==null||s.applyBitrate(e,t,i)}get pushMode(){return this._pushMode}}class Xu extends Q{constructor(e){super(),this._previewConsumer=new xu(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new Wu(e.getComposedStream(),{streamConsumeController:this})}startPreview(){this._previewConsumer.startPreview()}setRenderView(e){this._previewConsumer.setRenderView(e)}async startPush(e,t){return this._pushConsumer.startPush(e,t)}async stopPush(){return this._pushConsumer.unpublish()}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,i){this._pushConsumer.setBitrate(e,t,i)}setPushConfig(e){this._pushConsumer.setPushConfig(e)}get pushMode(){return this._pushConsumer.pushMode}async destroy(){await this._pushConsumer.destroy(),this._previewConsumer.destroy()}}const Ku=()=>typeof window>"u",H={},Je=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 Vi(r){const e=r.split(`
|
|
59
|
-
`);let t=!1;for(const i of e)if(i.includes("level-asymmetry-allowed=1")&&i.includes("packetization-mode=1")&&i.includes("profile-level-id=42e0")){t=!0;break}if(t){const i=navigator.userAgent.toLowerCase();let s=!1;const n=[/miuibrowser/,/70.*HeyTapBrowser/i];for(const a of n)a.test(i)&&(s=!0);return!s}return!1}const Ju=async()=>{let r=await Je("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Je("sendonly")),H.h264encode=Vi(r),H.vp8encode=r.indexOf("vp8")>-1,H},Yu=async()=>{let r=await Je("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await Je("recvonly")),H.h264decode=Vi(r),H.vp8decode=r.indexOf("vp8")>-1,H},Zu=async()=>{if(typeof H.h264encode>"u")try{await Ju()}catch{return!1}return H.h264encode||!1},Qu=async()=>{if(typeof H.h264decode>"u")try{await Yu()}catch{return!1}return H.h264decode||!1};class eh{constructor(){this.onError=(e,t,i)=>{},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=>{}}}const th=new eh;let Ui=!0,$i=!0;function Ye(r,e,t){const i=r.match(e);return i&&i.length>=t&&parseInt(i[t],10)}function pe(r,e,t){if(!r.RTCPeerConnection)return;const i=r.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(a,o){if(a!==e)return s.apply(this,arguments);const u=d=>{const c=t(d);c&&(o.handleEvent?o.handleEvent(c):o(c))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,u),s.apply(this,[a,u])};const n=i.removeEventListener;i.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return n.apply(this,arguments);if(!this._eventMap[e].has(o))return n.apply(this,arguments);const u=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,n.apply(this,[a,u])},Object.defineProperty(i,"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 rh(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(Ui=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function ih(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):($i=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function Bi(){if(typeof window=="object"){if(Ui)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function zt(r,e){$i&&console.warn(r+" is deprecated, please use "+e+" instead.")}function sh(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 i=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=Ye(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=Ye(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Ye(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 ji(r){return Object.prototype.toString.call(r)==="[object Object]"}function zi(r){return ji(r)?Object.keys(r).reduce(function(e,t){const i=ji(r[t]),s=i?zi(r[t]):r[t],n=i&&!Object.keys(s).length;return s===void 0||n?e:Object.assign(e,{[t]:s})},{}):r}function Gt(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?Gt(r,r.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(s=>{Gt(r,r.get(s),t)})}))}function Gi(r,e,t){const i=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const n=[];return r.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&n.push(a)}),n.forEach(a=>{r.forEach(o=>{o.type===i&&o.trackId===a.id&&Gt(r,o,s)})}),s}const Hi=Bi;function qi(r,e){const t=r&&r.navigator;if(!t.mediaDevices)return;const i=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const u={};return Object.keys(o).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const c=typeof o[d]=="object"?o[d]:{ideal:o[d]};c.exact!==void 0&&typeof c.exact=="number"&&(c.min=c.max=c.exact);const h=function(p,l){return p?p+l.charAt(0).toUpperCase()+l.slice(1):l==="deviceId"?"sourceId":l};if(c.ideal!==void 0){u.optional=u.optional||[];let p={};typeof c.ideal=="number"?(p[h("min",d)]=c.ideal,u.optional.push(p),p={},p[h("max",d)]=c.ideal,u.optional.push(p)):(p[h("",d)]=c.ideal,u.optional.push(p))}c.exact!==void 0&&typeof c.exact!="number"?(u.mandatory=u.mandatory||{},u.mandatory[h("",d)]=c.exact):["min","max"].forEach(p=>{c[p]!==void 0&&(u.mandatory=u.mandatory||{},u.mandatory[h(p,d)]=c[p])})}),o.advanced&&(u.optional=(u.optional||[]).concat(o.advanced)),u},s=function(o,u){if(e.version>=61)return u(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const d=function(c,h,p){h in c&&!(p in c)&&(c[p]=c[h],delete c[h])};o=JSON.parse(JSON.stringify(o)),d(o.audio,"autoGainControl","googAutoGainControl"),d(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(o.audio)}if(o&&typeof o.video=="object"){let d=o.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const c=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!c)){delete o.video.facingMode;let h;if(d.exact==="environment"||d.ideal==="environment"?h=["back","rear"]:(d.exact==="user"||d.ideal==="user")&&(h=["front"]),h)return t.mediaDevices.enumerateDevices().then(p=>{p=p.filter(f=>f.kind==="videoinput");let l=p.find(f=>h.some(g=>f.label.toLowerCase().includes(g)));return!l&&p.length&&h.includes("back")&&(l=p[p.length-1]),l&&(o.video.deviceId=d.exact?{exact:l.deviceId}:{ideal:l.deviceId}),o.video=i(o.video),Hi("chrome: "+JSON.stringify(o)),u(o)})}o.video=i(o.video)}return Hi("chrome: "+JSON.stringify(o)),u(o)},n=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,u,d){s(o,c=>{t.webkitGetUserMedia(c,u,h=>{d&&d(n(h))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(u){return s(u,d=>o(d).then(c=>{if(d.audio&&!c.getAudioTracks().length||d.video&&!c.getVideoTracks().length)throw c.getTracks().forEach(h=>{h.stop()}),new DOMException("","NotFoundError");return c},c=>Promise.reject(n(c))))}}}function Wi(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function Xi(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=i=>{i.stream.addEventListener("addtrack",s=>{let n;r.RTCPeerConnection.prototype.getReceivers?n=this.getReceivers().find(o=>o.track&&o.track.id===s.track.id):n={track:s.track};const a=new Event("track");a.track=s.track,a.receiver=n,a.transceiver={receiver:n},a.streams=[i.stream],this.dispatchEvent(a)}),i.stream.getTracks().forEach(s=>{let n;r.RTCPeerConnection.prototype.getReceivers?n=this.getReceivers().find(o=>o.track&&o.track.id===s.id):n={track:s};const a=new Event("track");a.track=s,a.receiver=n,a.transceiver={receiver:n},a.streams=[i.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else pe(r,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Ki(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("getSenders"in r.RTCPeerConnection.prototype)&&"createDTMFSender"in r.RTCPeerConnection.prototype){const e=function(s,n){return{track:n,get dtmf(){return this._dtmf===void 0&&(n.kind==="audio"?this._dtmf=s.createDTMFSender(n):this._dtmf=null),this._dtmf},_pc:s}};if(!r.RTCPeerConnection.prototype.getSenders){r.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(o,u){let d=s.apply(this,arguments);return d||(d=e(this,o),this._senders.push(d)),d};const n=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(o){n.apply(this,arguments);const u=this._senders.indexOf(o);u!==-1&&this._senders.splice(u,1)}}const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(n){this._senders=this._senders||[],t.apply(this,[n]),n.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(n){this._senders=this._senders||[],i.apply(this,[n]),n.getTracks().forEach(a=>{const o=this._senders.find(u=>u.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 i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i},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 Ji(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 n=t.apply(this,[]);return n.forEach(a=>a._pc=this),n});const i=r.RTCPeerConnection.prototype.addTrack;i&&(r.RTCPeerConnection.prototype.addTrack=function(){const n=i.apply(this,arguments);return n._pc=this,n}),r.RTCRtpSender.prototype.getStats=function(){const n=this;return this._pc.getStats().then(a=>Gi(a,n.track,!0))}}if(!("getStats"in r.RTCRtpReceiver.prototype)){const t=r.RTCPeerConnection.prototype.getReceivers;t&&(r.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(n=>n._pc=this),s}),pe(r,"track",i=>(i.receiver._pc=i.srcElement,i)),r.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(n=>Gi(n,s.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 i=arguments[0];let s,n,a;return this.getSenders().forEach(o=>{o.track===i&&(s?a=!0:s=o)}),this.getReceivers().forEach(o=>(o.track===i&&(n?a=!0:n=o),o.track===i)),a||s&&n?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():n?n.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Yi(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 u=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(u)===-1&&this._shimmedLocalStreams[o.id].push(u):this._shimmedLocalStreams[o.id]=[o,u],u};const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(d=>{if(this.getSenders().find(h=>h.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const u=this.getSenders().filter(d=>o.indexOf(d)===-1);this._shimmedLocalStreams[a.id]=[a].concat(u)};const i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],i.apply(this,arguments)};const s=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const u=this._shimmedLocalStreams[o].indexOf(a);u!==-1&&this._shimmedLocalStreams[o].splice(u,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),s.apply(this,arguments)}}function Zi(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Yi(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const c=t.apply(this);return this._reverseStreams=this._reverseStreams||{},c.map(h=>this._reverseStreams[h.id])};const i=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(c){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},c.getTracks().forEach(h=>{if(this.getSenders().find(l=>l.track===h))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[c.id]){const h=new r.MediaStream(c.getTracks());this._streams[c.id]=h,this._reverseStreams[h.id]=c,c=h}i.apply(this,[c])};const s=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(c){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[c.id]||c]),delete this._reverseStreams[this._streams[c.id]?this._streams[c.id].id:c.id],delete this._streams[c.id]},r.RTCPeerConnection.prototype.addTrack=function(c,h){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const p=[].slice.call(arguments,1);if(p.length!==1||!p[0].getTracks().find(g=>g===c))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(g=>g.track===c))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const f=this._streams[h.id];if(f)f.addTrack(c),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const g=new r.MediaStream([c]);this._streams[h.id]=g,this._reverseStreams[g.id]=h,this.addStream(g)}return this.getSenders().find(g=>g.track===c)};function n(d,c){let h=c.sdp;return Object.keys(d._reverseStreams||[]).forEach(p=>{const l=d._reverseStreams[p],f=d._streams[l.id];h=h.replace(new RegExp(f.id,"g"),l.id)}),new RTCSessionDescription({type:c.type,sdp:h})}function a(d,c){let h=c.sdp;return Object.keys(d._reverseStreams||[]).forEach(p=>{const l=d._reverseStreams[p],f=d._streams[l.id];h=h.replace(new RegExp(l.id,"g"),f.id)}),new RTCSessionDescription({type:c.type,sdp:h})}["createOffer","createAnswer"].forEach(function(d){const c=r.RTCPeerConnection.prototype[d],h={[d](){const p=arguments;return arguments.length&&typeof arguments[0]=="function"?c.apply(this,[f=>{const g=n(this,f);p[0].apply(null,[g])},f=>{p[1]&&p[1].apply(null,f)},arguments[2]]):c.apply(this,arguments).then(f=>n(this,f))}};r.RTCPeerConnection.prototype[d]=h[d]});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 u=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){const d=u.get.apply(this);return d.type===""?d:n(this,d)}}),r.RTCPeerConnection.prototype.removeTrack=function(c){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!c._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(c._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let p;Object.keys(this._streams).forEach(l=>{this._streams[l].getTracks().find(g=>c.track===g)&&(p=this._streams[l])}),p&&(p.getTracks().length===1?this.removeStream(this._reverseStreams[p.id]):p.removeTrack(c.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Ht(r,e){!r.RTCPeerConnection&&r.webkitRTCPeerConnection&&(r.RTCPeerConnection=r.webkitRTCPeerConnection),r.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=r.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=s[t]})}function Qi(r,e){pe(r,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}const es=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:Qi,shimAddTrackRemoveTrack:Zi,shimAddTrackRemoveTrackWithNative:Yi,shimGetSendersWithDtmf:Ki,shimGetUserMedia:qi,shimMediaStream:Wi,shimOnTrack:Xi,shimPeerConnection:Ht,shimSenderReceiverGetStats:Ji},Symbol.toStringTag,{value:"Module"}));function ts(r,e){const t=r&&r.navigator,i=r&&r.MediaStreamTrack;if(t.getUserMedia=function(s,n,a){zt("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(n,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(a,o,u){o in a&&!(u in a)&&(a[u]=a[o],delete a[o])},n=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)),s(a.audio,"autoGainControl","mozAutoGainControl"),s(a.audio,"noiseSuppression","mozNoiseSuppression")),n(a)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return s(o,"mozAutoGainControl","autoGainControl"),s(o,"mozNoiseSuppression","noiseSuppression"),o}}if(i&&i.prototype.applyConstraints){const a=i.prototype.applyConstraints;i.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o,"autoGainControl","mozAutoGainControl"),s(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function nh(r,e){r.navigator.mediaDevices&&"getDisplayMedia"in r.navigator.mediaDevices||r.navigator.mediaDevices&&(r.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,r.navigator.mediaDevices.getUserMedia(i)})}function rs(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 qt(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(s){const n=r.RTCPeerConnection.prototype[s],a={[s](){return arguments[0]=new(s==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};r.RTCPeerConnection.prototype[s]=a[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){const[n,a,o]=arguments;return i.apply(this,[n||null]).then(u=>{if(e.version<53&&!a)try{u.forEach(d=>{d.type=t[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;u.forEach((c,h)=>{u.set(h,Object.assign({},c,{type:t[c.type]||c.type}))})}return u}).then(a,o)}}function is(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 s=e.apply(this,[]);return s.forEach(n=>n._pc=this),s});const t=r.RTCPeerConnection.prototype.addTrack;t&&(r.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),r.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function ss(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 i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i}),pe(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ns(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){zt("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function os(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function as(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.addTransceiver;e&&(r.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const s=i.length>0;s&&i.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 n=e.apply(this,arguments);if(s){const{sender:a}=n,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=i,a.sendEncodings=i,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return n})}function cs(r){if(!(typeof r=="object"&&r.RTCRtpSender))return;const e=r.RTCRtpSender.prototype.getParameters;e&&(r.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function ds(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 us(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 hs=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:as,shimCreateAnswer:us,shimCreateOffer:ds,shimGetDisplayMedia:nh,shimGetParameters:cs,shimGetUserMedia:ts,shimOnTrack:rs,shimPeerConnection:qt,shimRTCDataChannel:os,shimReceiverGetStats:ss,shimRemoveStream:ns,shimSenderGetStats:is},Symbol.toStringTag,{value:"Module"}));function ps(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(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(s=>e.call(this,s,i)),i.getVideoTracks().forEach(s=>e.call(this,s,i))},r.RTCPeerConnection.prototype.addTrack=function(i,...s){return s&&s.forEach(n=>{this._localStreams?this._localStreams.includes(n)||this._localStreams.push(n):this._localStreams=[n]}),e.apply(this,arguments)}}"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const s=t.getTracks();this.getSenders().forEach(n=>{s.includes(n.track)&&this.removeTrack(n)})})}}function ls(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=i=>{i.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const n=new Event("addstream");n.stream=s,this.dispatchEvent(n)})})}});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(n=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(n)>=0)return;i._remoteStreams.push(n);const a=new Event("addstream");a.stream=n,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function ms(r){if(typeof r!="object"||!r.RTCPeerConnection)return;const e=r.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,s=e.setLocalDescription,n=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(d,c){const h=arguments.length>=2?arguments[2]:arguments[0],p=t.apply(this,[h]);return c?(p.then(d,c),Promise.resolve()):p},e.createAnswer=function(d,c){const h=arguments.length>=2?arguments[2]:arguments[0],p=i.apply(this,[h]);return c?(p.then(d,c),Promise.resolve()):p};let o=function(u,d,c){const h=s.apply(this,[u]);return c?(h.then(d,c),Promise.resolve()):h};e.setLocalDescription=o,o=function(u,d,c){const h=n.apply(this,[u]);return c?(h.then(d,c),Promise.resolve()):h},e.setRemoteDescription=o,o=function(u,d,c){const h=a.apply(this,[u]);return c?(h.then(d,c),Promise.resolve()):h},e.addIceCandidate=o}function fs(r){const e=r&&r.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>i(_s(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,s,n){e.mediaDevices.getUserMedia(i).then(s,n)}).bind(e))}function _s(r){return r&&r.video!==void 0?Object.assign({},r,{video:zi(r.video)}):r}function gs(r){if(!r.RTCPeerConnection)return;const e=r.RTCPeerConnection;r.RTCPeerConnection=function(i,s){if(i&&i.iceServers){const n=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?(zt("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,n.push(o)):n.push(i.iceServers[a])}i.iceServers=n}return new e(i,s)},r.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(r.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function vs(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 Cs(r){const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const n=this.getTransceivers().find(a=>a.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):i.offerToReceiveVideo===!0&&!n&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function ys(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const Ss=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:ys,shimCallbacksAPI:ms,shimConstraints:_s,shimCreateOfferLegacy:Cs,shimGetUserMedia:fs,shimLocalStreamsAPI:ps,shimRTCIceServerUrls:gs,shimRemoteStreamsAPI:ls,shimTrackEventTransceiver:vs},Symbol.toStringTag,{value:"Module"}));var Wt={exports:{}},Ts;function oh(){return Ts||(Ts=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
|
+
`},dn}var ra;function Zm(){if(ra)return ve;ra=1;var r=Wm(),e=Jm(),t=hn();return ve.grammar=t,ve.write=e,ve.parse=r.parse,ve.parseParams=r.parseParams,ve.parseFmtpConfig=r.parseFmtpConfig,ve.parsePayloads=r.parsePayloads,ve.parseRemoteCandidates=r.parseRemoteCandidates,ve.parseImageAttributes=r.parseImageAttributes,ve.parseSimulcastStreamList=r.parseSimulcastStreamList,ve}var Xm=Zm();const Gr=Y(Xm);function Br(r){return new Promise(e=>{setTimeout(e,r)})}async function Ym(r,e={},t=0){const i=new AbortController;let n=!1;e=Object.assign({},e,{signal:i.signal});const s=[fetch(r,e)];t&&s.push(new Promise((a,o)=>{setTimeout(()=>{n||(o({httpCode:0,message:"Timeout"}),i.abort())},t)}));try{const a=await Promise.race(s);if(n=!0,!a.ok||a.status<200||a.status>=300)throw{httpCode:a.status,message:a.statusText};return a.json()}catch(a){throw n=!0,a}}async function ia(r,e={},t={}){const{timeout:i=0,retryDelay:n=0}=t;let{retryCount:s=0}=t;try{return await Ym(r,e,i)}catch(a){if(s--,t.retryCount=s,s<0)throw a;return await Br(n),await ia(r,e,t)}}const Qm=-1;function W(r,e){let t;return e.forEach(i=>{i.type===r&&(t=i)}),t}async function ln(r,e){const t={},i=await(r==null?void 0:r.getStats()),n=await(e==null?void 0:e.getStats());return i&&(t.audio={mediaSource:W("media-source",i),codec:W("codec",i),candidatePair:W("candidate-pair",i),remoteCandidate:W("remote-candidate",i),localCandidate:W("local-candidate",i),track:W("track",i),outboundRtp:W("outbound-rtp",i),remoteInboundRtp:W("remote-inbound-rtp",i),transport:W("transport",i)}),n&&(t.video={mediaSource:W("media-source",n),codec:W("codec",n),candidatePair:W("candidate-pair",n),remoteCandidate:W("remote-candidate",n),localCandidate:W("local-candidate",n),track:W("track",n),outboundRtp:W("outbound-rtp",n),remoteInboundRtp:W("remote-inbound-rtp",n),transport:W("transport",n)}),t}async function e_(r,e,t){var u,l,d,p,f,v,m,E,y,_,C,z,w,O,k,T,A,P,ie,J,ue,he,ht,re,Ue,nc,sc,oc,ac,cc,uc,hc,dc,lc,pc,fc;const i=await ln(e,t);await Br(r);const n=await ln(e,t),{audio:s,video:a}=i,{audio:o,video:h}=n,c={};if(s!=null&&s.codec&&(o!=null&&o.codec)){const hr=((u=o.outboundRtp)==null?void 0:u.timestamp)-((l=s.outboundRtp)==null?void 0:l.timestamp),En=((d=o.outboundRtp)==null?void 0:d.bytesSent)-((p=s.outboundRtp)==null?void 0:p.bytesSent),Zr=((f=o.remoteInboundRtp)==null?void 0:f.packetsLost)-((v=s.remoteInboundRtp)==null?void 0:v.packetsLost),Cn=((m=o.outboundRtp)==null?void 0:m.packetsSent)-((E=s.outboundRtp)==null?void 0:E.packetsSent);c.audio={codec:o.codec.mimeType,channels:o.codec.channels,sendBitrate:En/hr*8e3,packetsSent:(y=o.outboundRtp)==null?void 0:y.packetsSent,nackCount:(_=o.outboundRtp)==null?void 0:_.nackCount,packetsLost:(C=o.remoteInboundRtp)==null?void 0:C.packetsLost,packetsLostPercent:Zr/Cn}}if(a!=null&&a.codec&&(h!=null&&h.codec)){const hr=((z=h.outboundRtp)==null?void 0:z.timestamp)-((w=a.outboundRtp)==null?void 0:w.timestamp),En=((O=h.outboundRtp)==null?void 0:O.bytesSent)-((k=a.outboundRtp)==null?void 0:k.bytesSent),Zr=((T=h.outboundRtp)==null?void 0:T.framesEncoded)-((A=a.outboundRtp)==null?void 0:A.framesEncoded),Cn=((P=h.outboundRtp)==null?void 0:P.totalEncodeTime)-((ie=a.outboundRtp)==null?void 0:ie.totalEncodeTime),mc=((J=h.outboundRtp)==null?void 0:J.packetsSent)-((ue=a.outboundRtp)==null?void 0:ue.packetsSent),M_=((he=h.outboundRtp)==null?void 0:he.totalPacketSendDelay)-((ht=a.outboundRtp)==null?void 0:ht.totalPacketSendDelay),I_=((re=h.remoteInboundRtp)==null?void 0:re.packetsLost)-((Ue=a.remoteInboundRtp)==null?void 0:Ue.packetsLost);c.video={codec:h.codec.mimeType,sendBitrate:En/hr*8e3,frameWidth:(nc=h.outboundRtp)==null?void 0:nc.frameWidth,frameHeight:(sc=h.outboundRtp)==null?void 0:sc.frameHeight,framesPerSecond:(oc=h.outboundRtp)==null?void 0:oc.framesPerSecond,framesEncoded:(ac=h.outboundRtp)==null?void 0:ac.framesEncoded,framesEncodedPerSecond:Zr*1e3/hr,keyFramesEncoded:(cc=h.outboundRtp)==null?void 0:cc.keyFramesEncoded,framesSent:(uc=h.outboundRtp)==null?void 0:uc.frameHeight,frameEncodeAvgTime:Cn*1e3/Zr,packetsSent:(hc=h.outboundRtp)==null?void 0:hc.packetsSent,packetSendDelay:M_*1e3/mc,nackCount:(dc=h.outboundRtp)==null?void 0:dc.nackCount,firCount:(lc=h.outboundRtp)==null?void 0:lc.firCount,pliCount:(pc=h.outboundRtp)==null?void 0:pc.pliCount,packetsLost:(fc=h.remoteInboundRtp)==null?void 0:fc.packetsLost,packetsLostPercent:I_/mc,deltaTime:hr}}return c}function ee(r,e=Qm){return r??e}function t_(r){var e,t,i,n,s,a,o,h,c,u,l,d,p,f,v,m,E,y,_,C,z;return{video_send_k_bitrate:ee((e=r.video)==null?void 0:e.sendBitrate)/1e3,video_send_frame_rate:ee((t=r.video)==null?void 0:t.framesPerSecond),video_encoder_output_frame_rate:ee((i=r.video)==null?void 0:i.framesEncodedPerSecond),video_encoded_frame_width:ee((n=r.video)==null?void 0:n.frameWidth),video_encoded_frame_height:ee((s=r.video)==null?void 0:s.frameHeight),video_encoded_key_frames:ee((a=r.video)==null?void 0:a.keyFramesEncoded),video_delta_time:ee((o=r.video)==null?void 0:o.deltaTime,2e3),video_packets_sent:ee((h=r.video)==null?void 0:h.packetsSent),video_nack_count:ee((c=r.video)==null?void 0:c.nackCount),video_fir_count:ee((u=r.video)==null?void 0:u.firCount),video_pli_count:ee((l=r.video)==null?void 0:l.pliCount),video_packets_lost:ee((d=r.video)==null?void 0:d.packetsLost),video_packets_lost_percent:(p=r.video)==null?void 0:p.packetsLostPercent,video_codec:(f=r.video)==null?void 0:f.codec,video_duration:(v=r.video)==null?void 0:v.deltaTime,audio_send_k_bitrate:ee((m=r.audio)==null?void 0:m.sendBitrate)/1e3,audio_send_channels:ee((E=r.audio)==null?void 0:E.channels),audio_packets_sent:ee((y=r.audio)==null?void 0:y.packetsSent),audio_packets_lost:ee((_=r.audio)==null?void 0:_.packetsLost),audio_packets_lost_percent:(C=r.audio)==null?void 0:C.packetsLostPercent,audio_codec:(z=r.audio)==null?void 0:z.codec}}function r_(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 i_=r=>{var t;if(!Gn)return;const e=(t=r.rtp.filter(i=>i.codec==="opus")[0])==null?void 0:t.payload;e&&r.fmtp.forEach(i=>{i.payload===e&&(i.config="minptime=10;useinbandfec=1")})},n_=r=>{r.ext&&(zc||dr)&&(r.ext=r.ext.filter(e=>{var t;return!((t=e.uri)!=null&&t.includes("video-orientation"))}))};function s_(r,e){r==null||r.rtp.forEach(({codec:t,payload:i})=>{if(["vp8","h264"].includes(t.toLocaleLowerCase())){const n=r.fmtp.find(s=>s.payload===i);n?n.config=[...n.config.split(";"),"x-google-min-bitrate=100",`x-google-start-bitrate=${e}`].join(";"):r.fmtp.push({payload:i,config:`x-google-min-bitrate=100;x-google-start-bitrate=${e}`})}})}const te=new We("PCConnect");class o_{constructor(e,t,i){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=i}get isPushing(){var e,t,i,n;return!!((t=(e=this._videoTransceiver)==null?void 0:e.sender)!=null&&t.track||(n=(i=this._audioTransceiver)==null?void 0:i.sender)!=null&&n.track)}get pushUrl(){return this._signalUrl}get sessionId(){return this._sessionId}async publish(e,t,i){var l;const n=new RTCPeerConnection;this._pc=n,this._bindRTCEvent();const s=e.filter(d=>(d==null?void 0:d.kind)==="audio")[0],a=e.filter(d=>(d==null?void 0:d.kind)==="video")[0];s&&this._ms.addTrack(s),a&&this._ms.addTrack(a),this._audioTransceiver=n.addTransceiver(s||"audio",{direction:"sendonly",sendEncodings:[{maxBitrate:t[0]}],streams:[this._ms]}),te.log("add track to pc,",s),this._videoTransceiver=n.addTransceiver(a||"video",{direction:"sendonly",sendEncodings:[{maxBitrate:t[1]}],streams:[this._ms]}),te.log("add track to pc,",a);const o=await n.createOffer();te.groupCollapsed("local offer"),te.log(o.sdp);const h=Gr.parse(o.sdp);h.media.forEach(d=>{d.type==="audio"?i_(d):d.type==="video"&&(n_(d),s_(d,t[1]))}),o.sdp=Gr.write(h),te.log("local offer modified"),te.log(o.sdp),await n.setLocalDescription(o);const c=await ia(this._signalUrl,{method:"POST",mode:"cors",body:JSON.stringify({sessionId:""+this._sessionId,version:"1.0-html",localSdp:o,metadata:{platform:"Web"}})},{...this._opts,timeout:i!=null&&i.isReconnect?10*Ks:(l=this._opts)==null?void 0:l.timeout});if((c==null?void 0:c.code)!==200)throw{code:c.code,message:c.message};te.log("remote answer:"),te.log(c.remoteSdp.sdp);const u=Gr.parse(c.remoteSdp.sdp);if(u.media.forEach(d=>{var p;(p=d.fingerprint)!=null&&p.hash&&(d.fingerprint.hash=d.fingerprint.hash.toUpperCase())}),c.remoteSdp.sdp=Gr.write(u),te.log("remote answer modified"),te.log(c.remoteSdp.sdp),te.groupEnd(),n.connectionState==="closed"){te.log("PeerConnection is closed, skipping setRemoteDescription");return}await n.setRemoteDescription(c.remoteSdp)}async updatePublish(e,t){var s,a;let i;t==="video"?i=this._videoTransceiver:i=this._audioTransceiver;const n=(s=i==null?void 0:i.sender)==null?void 0:s.track;(n==null?void 0:n.id)!==(e==null?void 0:e.id)&&(await((a=i==null?void 0:i.sender)==null?void 0:a.replaceTrack(e)),te.log(`replace ${t} track done! ${n==null?void 0:n.label} -> ${e==null?void 0:e.label}`))}applyBitrate(e,t,i){var a,o,h;const n=t==="video"?(a=this._videoTransceiver)==null?void 0:a.sender:(o=this._audioTransceiver)==null?void 0:o.sender;if(!n)return;const s=n.getParameters();s.encodings=(h=s.encodings)!=null&&h.length?s.encodings:[{}],i?s.encodings[0].minBitrate=e:s.encodings[0].maxBitrate=e,n.setParameters(s),te.log(`set bitrate for ${t}, ${e} bps, min:${i}`)}unpublish(){var e,t;(e=this._pc)==null||e.getSenders().forEach(i=>{var n;(n=this._pc)==null||n.removeTrack(i)}),(t=this._pc)==null||t.close(),this._audioTransceiver=null,this._videoTransceiver=null,this._pc=null,te.log("close pc!")}getStats(){var e,t;return ln((e=this._audioTransceiver)==null?void 0:e.sender,(t=this._videoTransceiver)==null?void 0:t.sender)}getStatsSnapshoot(e){var t,i;return e_(e||100,(t=this._audioTransceiver)==null?void 0:t.sender,(i=this._videoTransceiver)==null?void 0:i.sender)}_bindRTCEvent(){const e=this._pc;e==null||e.addEventListener("connectionstatechange",()=>{te.log("onconnectionstatechange:",e.connectionState),this._onConnectStateChange(e.connectionState)})}}var Je=(r=>(r.OnError="onerror",r.OnConnectClosed="onconnectclosed",r.OnFirstFramePushed="onfirstframepushed",r))(Je||{}),Ze=(r=>(r.Video="video",r.Audio="audio",r))(Ze||{}),me=(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))(me||{}),ct=(r=>(r.Ready="ready",r.Error="error",r.FirstFramePushed="firstframepushed",r.Flvfile="flvfile",r.STATS="stats",r.Close="close",r))(ct||{}),pn={exports:{}},na;function a_(){return na||(na=1,function(r){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function n(h,c,u){this.fn=h,this.context=c,this.once=u||!1}function s(h,c,u,l,d){if(typeof u!="function")throw new TypeError("The listener must be a function");var p=new n(u,l||h,d),f=t?t+c:c;return h._events[f]?h._events[f].fn?h._events[f]=[h._events[f],p]:h._events[f].push(p):(h._events[f]=p,h._eventsCount++),h}function a(h,c){--h._eventsCount===0?h._events=new i:delete h._events[c]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,l;if(this._eventsCount===0)return c;for(l in u=this._events)e.call(u,l)&&c.push(t?l.slice(1):l);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,l=this._events[u];if(!l)return[];if(l.fn)return[l.fn];for(var d=0,p=l.length,f=new Array(p);d<p;d++)f[d]=l[d].fn;return f},o.prototype.listenerCount=function(c){var u=t?t+c:c,l=this._events[u];return l?l.fn?1:l.length:0},o.prototype.emit=function(c,u,l,d,p,f){var v=t?t+c:c;if(!this._events[v])return!1;var m=this._events[v],E=arguments.length,y,_;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),E){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,u),!0;case 3:return m.fn.call(m.context,u,l),!0;case 4:return m.fn.call(m.context,u,l,d),!0;case 5:return m.fn.call(m.context,u,l,d,p),!0;case 6:return m.fn.call(m.context,u,l,d,p,f),!0}for(_=1,y=new Array(E-1);_<E;_++)y[_-1]=arguments[_];m.fn.apply(m.context,y)}else{var C=m.length,z;for(_=0;_<C;_++)switch(m[_].once&&this.removeListener(c,m[_].fn,void 0,!0),E){case 1:m[_].fn.call(m[_].context);break;case 2:m[_].fn.call(m[_].context,u);break;case 3:m[_].fn.call(m[_].context,u,l);break;case 4:m[_].fn.call(m[_].context,u,l,d);break;default:if(!y)for(z=1,y=new Array(E-1);z<E;z++)y[z-1]=arguments[z];m[_].fn.apply(m[_].context,y)}}return!0},o.prototype.on=function(c,u,l){return s(this,c,u,l,!1)},o.prototype.once=function(c,u,l){return s(this,c,u,l,!0)},o.prototype.removeListener=function(c,u,l,d){var p=t?t+c:c;if(!this._events[p])return this;if(!u)return a(this,p),this;var f=this._events[p];if(f.fn)f.fn===u&&(!d||f.once)&&(!l||f.context===l)&&a(this,p);else{for(var v=0,m=[],E=f.length;v<E;v++)(f[v].fn!==u||d&&!f[v].once||l&&f[v].context!==l)&&m.push(f[v]);m.length?this._events[p]=m.length===1?m[0]:m:a(this,p)}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 i,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}(pn)),pn.exports}var c_=a_();const u_=Y(c_);var Vr=(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))(Vr||{});class sa extends Error{constructor(e,t,i){super(),this.code=e,this.message=t,i&&(this.ext=i),this.toJson=()=>({code:this.code,message:this.message,ext:this.ext})}}function oa(r,e,t){return new sa(r,e,t)}const At=class At{constructor(e){this.group=(...t)=>{this._enabled&&console.group(`[${this._prefix}]: `,...t)},this.groupCollapsed=(...t)=>{this._enabled&&console.groupCollapsed(`[${this._prefix}]: `,...t)},this.groupEnd=()=>{this._enabled&&console.groupEnd()},this.log=(...t)=>{this._enabled&&console.log(`[${this._prefix}]: `,...t)},this.warn=(...t)=>{this._enabled&&console.warn(`[${this._prefix}]: `,...t)},this.error=(...t)=>{this._enabled&&console.error(`[${this._prefix}]: `,...t)},this.table=(...t)=>{this._enabled&&console.table(...t)},this._prefix=e}get _enabled(){return At.enable}get _enableLong(){return At.enableLong}get long(){return this._enableLong}};At.enable=!1,At.enableLong=!1;let Xe=At;const _e=new Xe("RTMP_Capture");class h_{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(_e.log(`replace ${e} track`),e===Ze.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 n;if(!this.videoTrack){_e.log("no video track to capture");return}if(this.videoTrack.readyState!=="live"){_e.warn("video track not live");return}const e=new MediaStreamTrackProcessor(this.videoTrack);e.track=this.videoTrack;const t=e.readable.getReader();this._videoProcessorReader=t,_e.log("start capture video frame",this.videoTrack);let i;for(;;){i&&clearInterval(i),i=setTimeout(()=>{_e.warn("long time no capture output"),this._bridge._postMockVideoEncodeFlag()},1500);const s=await t.read();if(clearInterval(i),this._videoFirstframeCaptured||(this._videoFirstframeCaptured=!0,_e.log("video first frame captured")),s.done||!s.value){(n=s.value)==null||n.close();break}this._bridge._postVideoFrame(s.value,this.videoTrack.getSettings())}clearInterval(i),this._videoFirstframeCaptured=!1,this._videoProcessorReader=null,_e.log("video track read done!",e.track)}async _startAudioCapture(){if(!this.audioTrack){_e.log("no audio track to capture");return}if(this.audioTrack.readyState!=="live"){_e.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,_e.log("start capture audio frame");;){const i=await t.read();if(this._audioFirstframeCaptured||(this._audioFirstframeCaptured=!0,_e.log("audio first frame captured")),i.done||!i.value)break;this._bridge._postAudioFrame(i.value,this.audioTrack.getSettings())}this._audioFirstframeCaptured=!1,this._audioProcessorReader=null,_e.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 aa='(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',ca=typeof self<"u"&&self.Blob&&new Blob([aa],{type:"text/javascript;charset=utf-8"});function d_(r){let e;try{if(e=ca&&(self.URL||self.webkitURL).createObjectURL(ca),!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(aa),{name:r==null?void 0:r.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}try{Xe.enable=location.href.indexOf("rtmpdebug")!==-1,Xe.enableLong=location.href.indexOf("rtmpdebug=long")!==-1}catch{}const Fr=new Xe("Bridge");class ua extends u_{constructor(){super(),this._worker=null,this._audioMsTrack=null,this._videoMsTrack=null,this._capture=new h_(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 i=new Promise((o,h)=>{e=o,t=h}),n=o=>{var h;switch((h=this._worker)==null||h.removeEventListener("message",n),o.data.type){case ct.Error:t(o.data.data);break;default:this._bindWorkerEvent(),Fr.log("rtmp ready!"),e(!0)}};try{this._worker=new d_}catch(o){t(oa(Vr.RTMP_INIT_FAIL,o.message))}return(s=this._worker)==null||s.postMessage({type:me.Init,options:{logEnable:Xe.enable,logEnableLong:Xe.enableLong}}),(a=this._worker)==null||a.addEventListener("message",n),i}_bindWorkerEvent(){var e,t;(e=this._worker)==null||e.addEventListener("message",i=>{switch(i.data.type){case ct.Error:Fr.table(i.data.data),this.emit(Je.OnError,i.data.data);break;case ct.Flvfile:l_(i.data.buffer);break;case ct.FirstFramePushed:this.emit(Je.OnFirstFramePushed);break;case ct.Close:this.emit(Je.OnConnectClosed),this.destroy();break}}),(t=this._worker)==null||t.addEventListener("error",i=>{this.emit(Je.OnError,oa(Vr.WORKER_ERROR,i.message))})}addTrack(e){e.kind===Ze.Video&&(this._videoMsTrack=e),e.kind===Ze.Audio&&(this._audioMsTrack=e),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack)}replaceTrack(e,t){e===Ze.Video&&(this._videoMsTrack=t),e===Ze.Audio&&(this._audioMsTrack=t),this._setAVExist(!!this._videoMsTrack,!!this._audioMsTrack),this._capture.restartCapture(e)}async getStats(){var s,a;let e,t;const i=new Promise((o,h)=>{e=o,t=h});this._worker||setTimeout(()=>{t()},0);const n=o=>{var h;switch(o.data.type){case ct.STATS:e(o.data.data),(h=this._worker)==null||h.removeEventListener("message",n);break}};return(s=this._worker)==null||s.addEventListener("message",n),(a=this._worker)==null||a.postMessage({type:me.GetStats}),i}_postVideoFrame(e,t){var i;(i=this._worker)==null||i.postMessage({type:me.VideoFrame,frame:e,setting:t},[e])}_postMockVideoEncodeFlag(){var e;(e=this._worker)==null||e.postMessage({type:me.MockVideoEncode})}_setAVExist(e,t){var i;(i=this._worker)==null||i.postMessage({type:me.AvExist,hasVideo:e,hasAudio:t})}_postAudioFrame(e,t){var i;(i=this._worker)==null||i.postMessage({type:me.AudioFrame,frame:e,setting:t},[e])}setEncodeCapacity(e){var t;(t=this._worker)==null||t.postMessage({type:me.EncodeConfig,cfg:e})}adjustBitrate(e,t){var i;(i=this._worker)==null||i.postMessage({type:me.AdjustBitrate,kind:e,bitrate:t})}publish(e){var t;Fr.log("start capture & connect"),this._capture.start(),(t=this._worker)==null||t.postMessage({type:me.Publish,url:e})}unpublish(){var e;this._capture.destroy(),(e=this._worker)==null||e.postMessage({type:me.UnPublish})}destroy(){var e;Fr.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:me.Download})}}function l_(r){const e=document.createElement("a");e.href=URL.createObjectURL(new Blob([r])),e.download=Date.now()+".flv",e.click()}const ha=new We("RTMPConnect");class p_{constructor(e,t,i,n){this._opts=void 0,this._isPushing=!1,this._url=e,this._opts=t,this._onError=i,this._OnSuccess=n,this._rtmp=new ua,this._bindEvents()}get isPushing(){return this._isPushing}get pushUrl(){return this._url}get sessionId(){return 0}_bindEvents(){this._rtmp.on(Je.OnError,e=>{this._isPushing=!1,this._onError(e)}),this._rtmp.on(Je.OnConnectClosed,()=>{this._isPushing=!1,this._onError(new sa(Vr.WTP_CONNECT_FAIL,"connect lost"))}),this._rtmp.on(Je.OnFirstFramePushed,()=>{this._isPushing=!0,this._OnSuccess()})}async publish(e,t,i){await this._rtmp.ready(),i!=null&&i.cfg&&this._rtmp.setEncodeCapacity(i.cfg),e.filter(Boolean).forEach(n=>this._rtmp.addTrack(n)),t[0]&&this._rtmp.adjustBitrate(Ze.Audio,t[0]),t[1]&&this._rtmp.adjustBitrate(Ze.Video,t[1]),this._rtmp.publish(this._url)}updatePublish(e,t){ha.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 Br(e),this._rtmp.getStats()}unpublish(){ha.warn("unpublish"),this._rtmp.unpublish(),this._isPushing=!1}}class f_{constructor(e,t=Op){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=(i=!1)=>{var n;this._logger.log("start reconnect strategy"),this.state==="idle"&&(this._reconnectStartTime=Date.now(),this._totalReconnectInfo.totalReconnectCount+=1,R(D.PUSH_RECONNECT_START,{start_time:this._reconnectStartTime,session_id:this._pushConsumer.pushSessionId,max_timeout:this._maxTimeout}),this.bindOnlineEvent(),this.setStrategyState("executing"),(n=this._logger)==null||n.log("start reconnecting with max timeout: ",this._maxTimeout),this.startTimeoutTimer(this._maxTimeout),this._pushConsumer.emitReconnectStateChange({state:dt.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(i))},this.attemptReconnect=async()=>{var i;if(this.state==="executing"){this.setStrategyState("reconnecting"),this._reconnectCount+=1;const n=this.getNextPushUrl();try{if(this._pushConsumer.emitReconnectStateChange({state:dt.RECONNECTING,params:{retryTime:this._reconnectCount},teaParams:{retry_push_url:n,session_id:this._pushConsumer.pushSessionId}}),await this._pushConsumer.reconnect(n),!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:Yr.PushUrlInvalid,failedError:s}),(i=this._onReconnectError)==null||i.call(this,"pushError",s);else{if(!this.isActive())return;this.setStrategyState("executing"),this.execute()}}}},this.executeStrategy=(i=!1)=>{const n=i?0:this._reconnectDelay;this._pushConsumer.emitReconnectStateChange({state:dt.WAITING,params:{waitingTime:n,retryTime:this._reconnectCount+1},teaParams:{is_online:navigator.onLine,session_id:this._pushConsumer.pushSessionId}}),this._logger.log("reconnect after delay: ",n,Date.now()),this._reconnectTimeout=window.setTimeout(this.attemptReconnect,n),this._reconnectDelay=this._reconnectDelay===0?2e3:Math.min(this._reconnectDelay*2,Mp)},this.state="idle",this._pushConsumer=e,this._maxTimeout=t,this._logger=new We("ReconnectStrategy")}getNextPushUrl(){const e=this._pushConsumer.pushUrl;if(!e)return"";const t=new URL(e),i=Date.now();return t.searchParams.set("pri",i.toString()),t.href}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:i=!1,failedError:n}){var a;if(this.state==="idle")return;const s=(Date.now()-this._reconnectStartTime)/1e3;i||(e?this._pushConsumer.emitReconnectStateChange({state:dt.SUCCESS,teaParams:{reconnect_duration:s,session_id:this._pushConsumer.pushSessionId}}):(this._logger.log("Reconnect strategy stopped: ",t),this._pushConsumer.emitReconnectStateChange({state:dt.FAILED,params:{failedCode:t},teaParams:{reason:t,reconnect_duration:s,error_message:n==null?void 0:n.message,http_code:(a=n==null?void 0:n.ext)==null?void 0:a.httpCode,ext:n==null?void 0:n.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:Yr.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 ur={ManualStop:0,ReconnectFailed:1,StartPushError:2,PushError:3},zt={PushCheck:0,PushError:1},da=new We("PushController");class m_ extends Yo{constructor(e,{config:t,streamConsumeController:i}){var n,s;if(super(e),this._connect=null,this._connectionState=de.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=gt(On,"audio").bitrate,this._videoBitrate=gt(xn,"video").bitrate,this.handleReconnectError=(a,o)=>{var h,c;R(D.STOP_PUSH_STREAM,{reason:ur.ReconnectFailed,error_message:a,session_id:this._pushSessionId,push_mode:this._pushMode,duration:this.pushDuration,reconnect_times:(h=this._reconnectStrategy)==null?void 0:h.getReconnectInfo().totalReconnectCount,reconnect_duration:(c=this._reconnectStrategy)==null?void 0:c.getReconnectInfo().totalReconnectDuration}),this.unpublish()},this.handleAudioStreamChange=a=>{this.updatePush({audioTrack:a.audioTrack})},this.handleVideoStreamChange=a=>{this.updatePush({videoTrack:a.videoTrack})},this._OnRTMPSuccess=()=>{this.setConnectState(de.CONNECTED)},this._OnRTMPError=a=>{const o=new _t(oe.PUBLISH_FAILED,`code:${a.code}, message: ${a.message}`);this._streamConsumeController.emit(j.PushError,o),R(D.STOP_PUSH_STREAM,{reason:ur.PushError,duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode,error_msg:a.message,error_code:a.code}),R(D.START_PUSH_STATUS,{is_success:!1,reason:zt.PushError,error_message:a.message,session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish()},this._executeReconnect=()=>{var a;(a=this._reconnectStrategy)==null||a.execute(),this.setConnectState(de.RECONNECTING),this.unpublish({isReconnecting:!0})},this._OnRtcStateChange=a=>{var o;switch(this._streamConsumeController.emit(j.RTCConnectStateChanged,a),a){case"connected":this.setConnectState(de.CONNECTED);break;case"disconnected":this._reconnectStrategy&&this._executeReconnect();break;case"failed":(o=this._reconnectStrategy)!=null&&o.isActive()?this._executeReconnect():(this.connectionState===de.CONNECTED?R(D.STOP_PUSH_STREAM,{reason:ur.PushError,error_message:"peerconnection failed",duration:this.pushDuration,session_id:this._pushSessionId,push_mode:this._pushMode}):R(D.START_PUSH_STATUS,{is_success:!1,reason:zt.PushError,error_message:"peerconnection failed",session_id:this._pushSessionId,push_mode:this._pushMode,push_url:this._pushUrl}),this.unpublish(),this._streamConsumeController.emit(j.PushError,new _t(oe.PUSH_CONNECT_FAILED,"pc failed")));break}},this._pushMode=(t==null?void 0:t.mode)||"rtm",this._streamConsumeController=i,t&&(this._pushConfig=t,this._needCheckAudioTrack=t.checkAudio??!1),(n=t==null?void 0:t.reconnectConfig)!=null&&n.enable||!(t!=null&&t.reconnectConfig)){const a=(s=t==null?void 0:t.reconnectConfig)!=null&&s.maxTimeout?t.reconnectConfig.maxTimeout*Ks:void 0;this._reconnectStrategy=new f_(this,a),this._reconnectStrategy.onReconnectError=this.handleReconnectError}}get isPushing(){return this._connectionState===de.CONNECTED||this._connectionState===de.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(j.LiveConnectStateChange,e),e){case de.CONNECTED:(t=this._reconnectStrategy)!=null&&t.isActive()?this._reconnectStrategy.stop({isSuccess:!0}):(this._streamConsumeController.emit(j.PushStart),this.setPushStatsInterval(),R(D.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,h;if(t.isReconnect||(this._pushSessionId=Date.now(),R(D.START_PUSH,{push_url:e,session_id:this._pushSessionId})),!e)throw R(D.START_PUSH_STATUS,{is_success:!1,session_id:this._pushSessionId,reason:zt.PushCheck,push_url:this._pushUrl}),new Error("lack publish url");if(this._connect)return;this.start(),this._pushUrl=e,this._pushEncodeConfig=t.cfg;const i=this._composedStream.videoTrack,n=this._composedStream.audioTrack;if(this._needCheckAudioTrack&&(!i||!n)){R(D.START_PUSH_STATUS,{is_success:!1,reason:zt.PushCheck,push_url:this._pushUrl,error_message:"lack videoTrack or audioTrack",video_track_id:i==null?void 0:i.id,audio_track_id:n==null?void 0:n.id,video_track_name:i==null?void 0:i.label,audio_track_name:n==null?void 0:n.label,push_mode:this._pushMode,session_id:this._pushSessionId}),console.warn("lack videoTrack or audioTrack","videoTrack: ",i==null?void 0:i.id,"audioTrack: ",n==null?void 0:n.id);return}else if(!i&&!n){R(D.START_PUSH_STATUS,{is_success:!1,reason:zt.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 o_(e,this._pushConfig,this._OnRtcStateChange):s=new p_(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(de.CONNECTING),await s.publish([n,i],[this._audioBitrate,this._videoBitrate],{cfg:t.cfg,isReconnect:t.isReconnect}),t.isReconnect||(da.log("startPush begin"),this._connectionStartDate=Date.now())}catch(c){const u=new _t(oe.PUBLISH_FAILED,c.message,c);if(da.groupEnd(),(h=this._reconnectStrategy)!=null&&h.isActive())throw this.unpublish({isReconnecting:!0}),u;this._streamConsumeController.emit(j.PushError,u),R(D.STOP_PUSH_STREAM,{reason:ur.PushError,error_message:u.message,enable_reconnect:!1,push_mode:this._pushMode,session_id:this._pushSessionId,duration:this.pushDuration}),R(D.START_PUSH_STATUS,{is_success:!1,push_url:this._pushUrl,reason:zt.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,i,n;if((t=this._connect)!=null&&t.isPushing){const s=Date.now(),a=await((i=this._connect)==null?void 0:i.getStatsSnapshoot(2e3)),h=Date.now()-s;Ep(a)?this._prevStats=void 0:this._prevStats=a;const c=this.pushMode==="rtm"?t_(a):r_(a);R(D.PUSH_STATS,{...c,stats:a,push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:c.video_duration||h,video_duration:c.video_duration||h,is_push:!0},!0)}else await Br(2e3),R(D.PUSH_STATS,{push_url:this._pushUrl,push_mode:this._pushMode,session_id:this._pushSessionId,duration:2e3,is_push:!1,is_reconnecting:((n=this._reconnectStrategy)==null?void 0:n.isActive())??!1},!0);this.connectionState!==de.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 i=[];e&&i.push(()=>{var n;return(n=this._connect)==null?void 0:n.updatePublish(e,"video")}),t&&i.push(()=>{var n;return(n=this._connect)==null?void 0:n.updatePublish(t,"audio")}),await Promise.all(i.map(n=>n()))}catch(i){const n=new _t(oe.UPDATE_PUBLISH_FAILED,`${i.name}, code:${i.code}`);this._streamConsumeController.emit(j.PushError,n)}}unpublish(e={isReconnecting:!1,isManual:!1}){var t,i,n,s,a;(t=this._connect)==null||t.unpublish(),this._connect=null,e.isManual&&(R(D.STOP_PUSH_STREAM,{reason:ur.ManualStop,duration:this.pushDuration,session_id:this._streamConsumeController.pushSessionId,push_mode:this._pushMode,reconnect_times:(i=this._reconnectStrategy)==null?void 0:i.getReconnectInfo().totalReconnectCount,reconnect_duration:(n=this._reconnectStrategy)==null?void 0:n.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(de.DISCONNECTED),(a=this._reconnectStrategy)==null||a.stop({quiet:!0}),this._streamConsumeController.emit(j.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,i){var n;t==="video"?this._videoBitrate=e:this._audioBitrate=e,(n=this._connect)==null||n.applyBitrate(e,t,i)}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:i}){R(D.PUSH_RECONNECT_STATUS,{status:e,...t,...i}),this._streamConsumeController.emit(j.ReconnectStateChange,e,t)}}class __ extends Ge{constructor(e,t){super(),this._previewConsumer=new qm(e.getComposedStream(),{streamConsumeController:this}),this._pushConsumer=new m_(e.getComposedStream(),{streamConsumeController:this,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,i){this._pushConsumer.setBitrate(e,t,i)}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 g_=()=>typeof window>"u",Te={},jr=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 la(r){const e=r.split(`
|
|
69
|
+
`);let t=!1;for(const i of e)if(i.includes("level-asymmetry-allowed=1")&&i.includes("packetization-mode=1")&&i.includes("profile-level-id=42e0")){t=!0;break}if(t){const i=navigator.userAgent.toLowerCase();let n=!1;const s=[/miuibrowser/,/70.*HeyTapBrowser/i];for(const a of s)a.test(i)&&(n=!0);return!n}return!1}const v_=async()=>{let r=await jr("sendonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await jr("sendonly")),Te.h264encode=la(r),Te.vp8encode=r.indexOf("vp8")>-1,Te},y_=async()=>{let r=await jr("recvonly");return navigator.userAgent.includes("VivoBrowser")&&(r=await jr("recvonly")),Te.h264decode=la(r),Te.vp8decode=r.indexOf("vp8")>-1,Te},b_=async()=>{if(typeof Te.h264encode>"u")try{await v_()}catch{return!1}return Te.h264encode||!1},S_=async()=>{if(typeof Te.h264decode>"u")try{await y_()}catch{return!1}return Te.h264decode||!1};class E_{constructor(){this.onError=(e,t,i)=>{},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 C_=new E_;let pa=!0,fa=!0;function Hr(r,e,t){const i=r.match(e);return i&&i.length>=t&&parseInt(i[t],10)}function ut(r,e,t){if(!r.RTCPeerConnection)return;const i=r.RTCPeerConnection.prototype,n=i.addEventListener;i.addEventListener=function(a,o){if(a!==e)return n.apply(this,arguments);const h=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,h),n.apply(this,[a,h])};const s=i.removeEventListener;i.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 h=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,h])},Object.defineProperty(i,"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 w_(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(pa=r,r?"adapter.js logging disabled":"adapter.js logging enabled")}function T_(r){return typeof r!="boolean"?new Error("Argument type: "+typeof r+". Please use a boolean."):(fa=!r,"adapter.js deprecation warnings "+(r?"disabled":"enabled"))}function ma(){if(typeof window=="object"){if(pa)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function fn(r,e){fa&&console.warn(r+" is deprecated, please use "+e+" instead.")}function z_(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 i=t.userAgentData.brands.find(n=>n.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=Hr(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||r.isSecureContext===!1&&r.webkitRTCPeerConnection)e.browser="chrome",e.version=Hr(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=Hr(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 _a(r){return Object.prototype.toString.call(r)==="[object Object]"}function ga(r){return _a(r)?Object.keys(r).reduce(function(e,t){const i=_a(r[t]),n=i?ga(r[t]):r[t],s=i&&!Object.keys(n).length;return n===void 0||s?e:Object.assign(e,{[t]:n})},{}):r}function mn(r,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?mn(r,r.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(n=>{mn(r,r.get(n),t)})}))}function va(r,e,t){const i=t?"outbound-rtp":"inbound-rtp",n=new Map;if(e===null)return n;const s=[];return r.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&s.push(a)}),s.forEach(a=>{r.forEach(o=>{o.type===i&&o.trackId===a.id&&mn(r,o,n)})}),n}const ya=ma;function ba(r,e){const t=r&&r.navigator;if(!t.mediaDevices)return;const i=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const h={};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 l=function(d,p){return d?d+p.charAt(0).toUpperCase()+p.slice(1):p==="deviceId"?"sourceId":p};if(u.ideal!==void 0){h.optional=h.optional||[];let d={};typeof u.ideal=="number"?(d[l("min",c)]=u.ideal,h.optional.push(d),d={},d[l("max",c)]=u.ideal,h.optional.push(d)):(d[l("",c)]=u.ideal,h.optional.push(d))}u.exact!==void 0&&typeof u.exact!="number"?(h.mandatory=h.mandatory||{},h.mandatory[l("",c)]=u.exact):["min","max"].forEach(d=>{u[d]!==void 0&&(h.mandatory=h.mandatory||{},h.mandatory[l(d,c)]=u[d])})}),o.advanced&&(h.optional=(h.optional||[]).concat(o.advanced)),h},n=function(o,h){if(e.version>=61)return h(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const c=function(u,l,d){l in u&&!(d in u)&&(u[d]=u[l],delete u[l])};o=JSON.parse(JSON.stringify(o)),c(o.audio,"autoGainControl","googAutoGainControl"),c(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(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 l;if(c.exact==="environment"||c.ideal==="environment"?l=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(l=["front"]),l)return t.mediaDevices.enumerateDevices().then(d=>{d=d.filter(f=>f.kind==="videoinput");let p=d.find(f=>l.some(v=>f.label.toLowerCase().includes(v)));return!p&&d.length&&l.includes("back")&&(p=d[d.length-1]),p&&(o.video.deviceId=c.exact?{exact:p.deviceId}:{ideal:p.deviceId}),o.video=i(o.video),ya("chrome: "+JSON.stringify(o)),h(o)})}o.video=i(o.video)}return ya("chrome: "+JSON.stringify(o)),h(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,h,c){n(o,u=>{t.webkitGetUserMedia(u,h,l=>{c&&c(s(l))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(h){return n(h,c=>o(c).then(u=>{if(c.audio&&!u.getAudioTracks().length||c.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(l=>{l.stop()}),new DOMException("","NotFoundError");return u},u=>Promise.reject(s(u))))}}}function Sa(r){r.MediaStream=r.MediaStream||r.webkitMediaStream}function Ea(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=i=>{i.stream.addEventListener("addtrack",n=>{let s;r.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===n.track.id):s={track:n.track};const a=new Event("track");a.track=n.track,a.receiver=s,a.transceiver={receiver:s},a.streams=[i.stream],this.dispatchEvent(a)}),i.stream.getTracks().forEach(n=>{let s;r.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(o=>o.track&&o.track.id===n.id):s={track:n};const a=new Event("track");a.track=n,a.receiver=s,a.transceiver={receiver:s},a.streams=[i.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else ut(r,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Ca(r){if(typeof r=="object"&&r.RTCPeerConnection&&!("getSenders"in r.RTCPeerConnection.prototype)&&"createDTMFSender"in r.RTCPeerConnection.prototype){const e=function(n,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=n.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:n}};if(!r.RTCPeerConnection.prototype.getSenders){r.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const n=r.RTCPeerConnection.prototype.addTrack;r.RTCPeerConnection.prototype.addTrack=function(o,h){let c=n.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 h=this._senders.indexOf(o);h!==-1&&this._senders.splice(h,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 i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],i.apply(this,[s]),s.getTracks().forEach(a=>{const o=this._senders.find(h=>h.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 i=e.apply(this,[]);return i.forEach(n=>n._pc=this),i},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 wa(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 i=r.RTCPeerConnection.prototype.addTrack;i&&(r.RTCPeerConnection.prototype.addTrack=function(){const s=i.apply(this,arguments);return s._pc=this,s}),r.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(a=>va(a,s.track,!0))}}if(!("getStats"in r.RTCRtpReceiver.prototype)){const t=r.RTCPeerConnection.prototype.getReceivers;t&&(r.RTCPeerConnection.prototype.getReceivers=function(){const n=t.apply(this,[]);return n.forEach(s=>s._pc=this),n}),ut(r,"track",i=>(i.receiver._pc=i.srcElement,i)),r.RTCRtpReceiver.prototype.getStats=function(){const n=this;return this._pc.getStats().then(s=>va(s,n.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 i=arguments[0];let n,s,a;return this.getSenders().forEach(o=>{o.track===i&&(n?a=!0:n=o)}),this.getReceivers().forEach(o=>(o.track===i&&(s?a=!0:s=o),o.track===i)),a||n&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):n?n.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Ta(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 h=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(h)===-1&&this._shimmedLocalStreams[o.id].push(h):this._shimmedLocalStreams[o.id]=[o,h],h};const t=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(c=>{if(this.getSenders().find(l=>l.track===c))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const h=this.getSenders().filter(c=>o.indexOf(c)===-1);this._shimmedLocalStreams[a.id]=[a].concat(h)};const i=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],i.apply(this,arguments)};const n=r.RTCPeerConnection.prototype.removeTrack;r.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const h=this._shimmedLocalStreams[o].indexOf(a);h!==-1&&this._shimmedLocalStreams[o].splice(h,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),n.apply(this,arguments)}}function za(r,e){if(!r.RTCPeerConnection)return;if(r.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Ta(r);const t=r.RTCPeerConnection.prototype.getLocalStreams;r.RTCPeerConnection.prototype.getLocalStreams=function(){const u=t.apply(this);return this._reverseStreams=this._reverseStreams||{},u.map(l=>this._reverseStreams[l.id])};const i=r.RTCPeerConnection.prototype.addStream;r.RTCPeerConnection.prototype.addStream=function(u){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(l=>{if(this.getSenders().find(p=>p.track===l))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){const l=new r.MediaStream(u.getTracks());this._streams[u.id]=l,this._reverseStreams[l.id]=u,u=l}i.apply(this,[u])};const n=r.RTCPeerConnection.prototype.removeStream;r.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.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,l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const d=[].slice.call(arguments,1);if(d.length!==1||!d[0].getTracks().find(v=>v===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(v=>v.track===u))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const f=this._streams[l.id];if(f)f.addTrack(u),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const v=new r.MediaStream([u]);this._streams[l.id]=v,this._reverseStreams[v.id]=l,this.addStream(v)}return this.getSenders().find(v=>v.track===u)};function s(c,u){let l=u.sdp;return Object.keys(c._reverseStreams||[]).forEach(d=>{const p=c._reverseStreams[d],f=c._streams[p.id];l=l.replace(new RegExp(f.id,"g"),p.id)}),new RTCSessionDescription({type:u.type,sdp:l})}function a(c,u){let l=u.sdp;return Object.keys(c._reverseStreams||[]).forEach(d=>{const p=c._reverseStreams[d],f=c._streams[p.id];l=l.replace(new RegExp(p.id,"g"),f.id)}),new RTCSessionDescription({type:u.type,sdp:l})}["createOffer","createAnswer"].forEach(function(c){const u=r.RTCPeerConnection.prototype[c],l={[c](){const d=arguments;return arguments.length&&typeof arguments[0]=="function"?u.apply(this,[f=>{const v=s(this,f);d[0].apply(null,[v])},f=>{d[1]&&d[1].apply(null,f)},arguments[2]]):u.apply(this,arguments).then(f=>s(this,f))}};r.RTCPeerConnection.prototype[c]=l[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 h=Object.getOwnPropertyDescriptor(r.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(r.RTCPeerConnection.prototype,"localDescription",{get(){const c=h.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 d;Object.keys(this._streams).forEach(p=>{this._streams[p].getTracks().find(v=>u.track===v)&&(d=this._streams[p])}),d&&(d.getTracks().length===1?this.removeStream(this._reverseStreams[d.id]):d.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function _n(r,e){!r.RTCPeerConnection&&r.webkitRTCPeerConnection&&(r.RTCPeerConnection=r.webkitRTCPeerConnection),r.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=r.RTCPeerConnection.prototype[t],n={[t](){return arguments[0]=new(t==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};r.RTCPeerConnection.prototype[t]=n[t]})}function ka(r,e){ut(r,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}const Aa=Object.freeze(Object.defineProperty({__proto__:null,fixNegotiationNeeded:ka,shimAddTrackRemoveTrack:za,shimAddTrackRemoveTrackWithNative:Ta,shimGetSendersWithDtmf:Ca,shimGetUserMedia:ba,shimMediaStream:Sa,shimOnTrack:Ea,shimPeerConnection:_n,shimSenderReceiverGetStats:wa},Symbol.toStringTag,{value:"Module"}));function Ra(r,e){const t=r&&r.navigator,i=r&&r.MediaStreamTrack;if(t.getUserMedia=function(n,s,a){fn("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(n).then(s,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const n=function(a,o,h){o in a&&!(h in a)&&(a[h]=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)),n(a.audio,"autoGainControl","mozAutoGainControl"),n(a.audio,"noiseSuppression","mozNoiseSuppression")),s(a)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return n(o,"mozAutoGainControl","autoGainControl"),n(o,"mozNoiseSuppression","noiseSuppression"),o}}if(i&&i.prototype.applyConstraints){const a=i.prototype.applyConstraints;i.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),n(o,"autoGainControl","mozAutoGainControl"),n(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function k_(r,e){r.navigator.mediaDevices&&"getDisplayMedia"in r.navigator.mediaDevices||r.navigator.mediaDevices&&(r.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const n=new DOMException("getDisplayMedia without video constraints is undefined");return n.name="NotFoundError",n.code=8,Promise.reject(n)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,r.navigator.mediaDevices.getUserMedia(i)})}function Da(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 gn(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(n){const s=r.RTCPeerConnection.prototype[n],a={[n](){return arguments[0]=new(n==="addIceCandidate"?r.RTCIceCandidate:r.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};r.RTCPeerConnection.prototype[n]=a[n]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=r.RTCPeerConnection.prototype.getStats;r.RTCPeerConnection.prototype.getStats=function(){const[s,a,o]=arguments;return i.apply(this,[s||null]).then(h=>{if(e.version<53&&!a)try{h.forEach(c=>{c.type=t[c.type]||c.type})}catch(c){if(c.name!=="TypeError")throw c;h.forEach((u,l)=>{h.set(l,Object.assign({},u,{type:t[u.type]||u.type}))})}return h}).then(a,o)}}function xa(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 n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n});const t=r.RTCPeerConnection.prototype.addTrack;t&&(r.RTCPeerConnection.prototype.addTrack=function(){const n=t.apply(this,arguments);return n._pc=this,n}),r.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Oa(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 i=e.apply(this,[]);return i.forEach(n=>n._pc=this),i}),ut(r,"track",t=>(t.receiver._pc=t.srcElement,t)),r.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Ma(r){!r.RTCPeerConnection||"removeStream"in r.RTCPeerConnection.prototype||(r.RTCPeerConnection.prototype.removeStream=function(t){fn("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function Ia(r){r.DataChannel&&!r.RTCDataChannel&&(r.RTCDataChannel=r.DataChannel)}function Pa(r){if(!(typeof r=="object"&&r.RTCPeerConnection))return;const e=r.RTCPeerConnection.prototype.addTransceiver;e&&(r.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const n=i.length>0;n&&i.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(n){const{sender:a}=s,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=i,a.sendEncodings=i,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return s})}function La(r){if(!(typeof r=="object"&&r.RTCRtpSender))return;const e=r.RTCRtpSender.prototype.getParameters;e&&(r.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function Ua(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 Na(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 Ga=Object.freeze(Object.defineProperty({__proto__:null,shimAddTransceiver:Pa,shimCreateAnswer:Na,shimCreateOffer:Ua,shimGetDisplayMedia:k_,shimGetParameters:La,shimGetUserMedia:Ra,shimOnTrack:Da,shimPeerConnection:gn,shimRTCDataChannel:Ia,shimReceiverGetStats:Oa,shimRemoveStream:Ma,shimSenderGetStats:xa},Symbol.toStringTag,{value:"Module"}));function Ba(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(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(n=>e.call(this,n,i)),i.getVideoTracks().forEach(n=>e.call(this,n,i))},r.RTCPeerConnection.prototype.addTrack=function(i,...n){return n&&n.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 i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const n=t.getTracks();this.getSenders().forEach(s=>{n.includes(s.track)&&this.removeTrack(s)})})}}function Va(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=i=>{i.streams.forEach(n=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(n))return;this._remoteStreams.push(n);const s=new Event("addstream");s.stream=n,this.dispatchEvent(s)})})}});const e=r.RTCPeerConnection.prototype.setRemoteDescription;r.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(n){n.streams.forEach(s=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(s)>=0)return;i._remoteStreams.push(s);const a=new Event("addstream");a.stream=s,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function Fa(r){if(typeof r!="object"||!r.RTCPeerConnection)return;const e=r.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,n=e.setLocalDescription,s=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(c,u){const l=arguments.length>=2?arguments[2]:arguments[0],d=t.apply(this,[l]);return u?(d.then(c,u),Promise.resolve()):d},e.createAnswer=function(c,u){const l=arguments.length>=2?arguments[2]:arguments[0],d=i.apply(this,[l]);return u?(d.then(c,u),Promise.resolve()):d};let o=function(h,c,u){const l=n.apply(this,[h]);return u?(l.then(c,u),Promise.resolve()):l};e.setLocalDescription=o,o=function(h,c,u){const l=s.apply(this,[h]);return u?(l.then(c,u),Promise.resolve()):l},e.setRemoteDescription=o,o=function(h,c,u){const l=a.apply(this,[h]);return u?(l.then(c,u),Promise.resolve()):l},e.addIceCandidate=o}function ja(r){const e=r&&r.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=n=>i(Ha(n))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,n,s){e.mediaDevices.getUserMedia(i).then(n,s)}).bind(e))}function Ha(r){return r&&r.video!==void 0?Object.assign({},r,{video:ga(r.video)}):r}function $a(r){if(!r.RTCPeerConnection)return;const e=r.RTCPeerConnection;r.RTCPeerConnection=function(i,n){if(i&&i.iceServers){const s=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?(fn("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,s.push(o)):s.push(i.iceServers[a])}i.iceServers=s}return new e(i,n)},r.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(r.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Ka(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 qa(r){const e=r.RTCPeerConnection.prototype.createOffer;r.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const n=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):i.offerToReceiveAudio===!0&&!n&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="video");i.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"):i.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Wa(r){typeof r!="object"||r.AudioContext||(r.AudioContext=r.webkitAudioContext)}const Ja=Object.freeze(Object.defineProperty({__proto__:null,shimAudioContext:Wa,shimCallbacksAPI:Fa,shimConstraints:Ha,shimCreateOfferLegacy:qa,shimGetUserMedia:ja,shimLocalStreamsAPI:Ba,shimRTCIceServerUrls:$a,shimRemoteStreamsAPI:Va,shimTrackEventTransceiver:Ka},Symbol.toStringTag,{value:"Module"}));var vn={exports:{}},Za;function A_(){return Za||(Za=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(`
|
|
60
70
|
`).map(i=>i.trim())},e.splitSections=function(t){return t.split(`
|
|
61
|
-
m=`).map((s
|
|
62
|
-
`)},e.getDescription=function(t){const i=e.splitSections(t);return i&&i[0]},e.getMediaSections=function(t){const i=e.splitSections(t);return i.shift(),i},e.matchPrefix=function(t,i){return e.splitLines(t).filter(
|
|
71
|
+
m=`).map((n,s)=>(s>0?"m="+n:n).trim()+`\r
|
|
72
|
+
`)},e.getDescription=function(t){const i=e.splitSections(t);return i&&i[0]},e.getMediaSections=function(t){const i=e.splitSections(t);return i.shift(),i},e.matchPrefix=function(t,i){return e.splitLines(t).filter(n=>n.indexOf(i)===0)},e.parseCandidate=function(t){let i;t.indexOf("a=candidate:")===0?i=t.substring(12).split(" "):i=t.substring(10).split(" ");const n={foundation:i[0],component:{1:"rtp",2:"rtcp"}[i[1]]||i[1],protocol:i[2].toLowerCase(),priority:parseInt(i[3],10),ip:i[4],address:i[4],port:parseInt(i[5],10),type:i[7]};for(let s=8;s<i.length;s+=2)switch(i[s]){case"raddr":n.relatedAddress=i[s+1];break;case"rport":n.relatedPort=parseInt(i[s+1],10);break;case"tcptype":n.tcpType=i[s+1];break;case"ufrag":n.ufrag=i[s+1],n.usernameFragment=i[s+1];break;default:n[i[s]]===void 0&&(n[i[s]]=i[s+1]);break}return n},e.writeCandidate=function(t){const i=[];i.push(t.foundation);const n=t.component;n==="rtp"?i.push(1):n==="rtcp"?i.push(2):i.push(n),i.push(t.protocol.toUpperCase()),i.push(t.priority),i.push(t.address||t.ip),i.push(t.port);const s=t.type;return i.push("typ"),i.push(s),s!=="host"&&t.relatedAddress&&t.relatedPort&&(i.push("raddr"),i.push(t.relatedAddress),i.push("rport"),i.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(i.push("tcptype"),i.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(i.push("ufrag"),i.push(t.usernameFragment||t.ufrag)),"candidate:"+i.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let i=t.substring(9).split(" ");const n={payloadType:parseInt(i.shift(),10)};return i=i[0].split("/"),n.name=i[0],n.clockRate=parseInt(i[1],10),n.channels=i.length===3?parseInt(i[2],10):1,n.numChannels=n.channels,n},e.writeRtpMap=function(t){let i=t.payloadType;t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType);const n=t.channels||t.numChannels||1;return"a=rtpmap:"+i+" "+t.name+"/"+t.clockRate+(n!==1?"/"+n:"")+`\r
|
|
63
73
|
`},e.parseExtmap=function(t){const i=t.substring(9).split(" ");return{id:parseInt(i[0],10),direction:i[0].indexOf("/")>0?i[0].split("/")[1]:"sendrecv",uri:i[1],attributes:i.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
|
|
64
|
-
`},e.parseFmtp=function(t){const i={};let
|
|
65
|
-
`}return i},e.parseRtcpFb=function(t){const i=t.substring(t.indexOf(" ")+1).split(" ");return{type:i.shift(),parameter:i.join(" ")}},e.writeRtcpFb=function(t){let i="",
|
|
66
|
-
`}),i},e.parseSsrcMedia=function(t){const i=t.indexOf(" "),
|
|
67
|
-
`;return t.fingerprints.forEach(
|
|
68
|
-
`}),
|
|
69
|
-
`},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const i=t.substring(7).split("|");return{keyMethod:"inline",keySalt:i[0],lifeTime:i[1],mkiValue:i[2]?i[2].split(":")[0]:void 0,mkiLength:i[2]?i[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,i){return e.matchPrefix(t+i,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,i){const
|
|
74
|
+
`},e.parseFmtp=function(t){const i={};let n;const s=t.substring(t.indexOf(" ")+1).split(";");for(let a=0;a<s.length;a++)n=s[a].trim().split("="),i[n[0].trim()]=n[1];return i},e.writeFmtp=function(t){let i="",n=t.payloadType;if(t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const s=[];Object.keys(t.parameters).forEach(a=>{t.parameters[a]!==void 0?s.push(a+"="+t.parameters[a]):s.push(a)}),i+="a=fmtp:"+n+" "+s.join(";")+`\r
|
|
75
|
+
`}return i},e.parseRtcpFb=function(t){const i=t.substring(t.indexOf(" ")+1).split(" ");return{type:i.shift(),parameter:i.join(" ")}},e.writeRtcpFb=function(t){let i="",n=t.payloadType;return t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(s=>{i+="a=rtcp-fb:"+n+" "+s.type+(s.parameter&&s.parameter.length?" "+s.parameter:"")+`\r
|
|
76
|
+
`}),i},e.parseSsrcMedia=function(t){const i=t.indexOf(" "),n={ssrc:parseInt(t.substring(7,i),10)},s=t.indexOf(":",i);return s>-1?(n.attribute=t.substring(i+1,s),n.value=t.substring(s+1)):n.attribute=t.substring(i+1),n},e.parseSsrcGroup=function(t){const i=t.substring(13).split(" ");return{semantics:i.shift(),ssrcs:i.map(n=>parseInt(n,10))}},e.getMid=function(t){const i=e.matchPrefix(t,"a=mid:")[0];if(i)return i.substring(6)},e.parseFingerprint=function(t){const i=t.substring(14).split(" ");return{algorithm:i[0].toLowerCase(),value:i[1].toUpperCase()}},e.getDtlsParameters=function(t,i){return{role:"auto",fingerprints:e.matchPrefix(t+i,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,i){let n="a=setup:"+i+`\r
|
|
77
|
+
`;return t.fingerprints.forEach(s=>{n+="a=fingerprint:"+s.algorithm+" "+s.value+`\r
|
|
78
|
+
`}),n},e.parseCryptoLine=function(t){const i=t.substring(9).split(" ");return{tag:parseInt(i[0],10),cryptoSuite:i[1],keyParams:i[2],sessionParams:i.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 i=t.substring(7).split("|");return{keyMethod:"inline",keySalt:i[0],lifeTime:i[1],mkiValue:i[2]?i[2].split(":")[0]:void 0,mkiLength:i[2]?i[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,i){return e.matchPrefix(t+i,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,i){const n=e.matchPrefix(t+i,"a=ice-ufrag:")[0],s=e.matchPrefix(t+i,"a=ice-pwd:")[0];return n&&s?{usernameFragment:n.substring(12),password:s.substring(10)}:null},e.writeIceParameters=function(t){let i="a=ice-ufrag:"+t.usernameFragment+`\r
|
|
70
80
|
a=ice-pwd:`+t.password+`\r
|
|
71
81
|
`;return t.iceLite&&(i+=`a=ice-lite\r
|
|
72
|
-
`),i},e.parseRtpParameters=function(t){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},
|
|
73
|
-
`,
|
|
74
|
-
`,
|
|
75
|
-
`,i.codecs.forEach(a=>{
|
|
76
|
-
`),i.headerExtensions&&i.headerExtensions.forEach(a=>{
|
|
82
|
+
`),i},e.parseRtpParameters=function(t){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=e.splitLines(t)[0].split(" ");i.profile=s[2];for(let o=3;o<s.length;o++){const h=s[o],c=e.matchPrefix(t,"a=rtpmap:"+h+" ")[0];if(c){const u=e.parseRtpMap(c),l=e.matchPrefix(t,"a=fmtp:"+h+" ");switch(u.parameters=l.length?e.parseFmtp(l[0]):{},u.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+h+" ").map(e.parseRtcpFb),i.codecs.push(u),u.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(u.name.toUpperCase());break}}}e.matchPrefix(t,"a=extmap:").forEach(o=>{i.headerExtensions.push(e.parseExtmap(o))});const a=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return i.codecs.forEach(o=>{a.forEach(h=>{o.rtcpFeedback.find(u=>u.type===h.type&&u.parameter===h.parameter)||o.rtcpFeedback.push(h)})}),i},e.writeRtpDescription=function(t,i){let n="";n+="m="+t+" ",n+=i.codecs.length>0?"9":"0",n+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",n+=i.codecs.map(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r
|
|
83
|
+
`,n+=`c=IN IP4 0.0.0.0\r
|
|
84
|
+
`,n+=`a=rtcp:9 IN IP4 0.0.0.0\r
|
|
85
|
+
`,i.codecs.forEach(a=>{n+=e.writeRtpMap(a),n+=e.writeFmtp(a),n+=e.writeRtcpFb(a)});let s=0;return i.codecs.forEach(a=>{a.maxptime>s&&(s=a.maxptime)}),s>0&&(n+="a=maxptime:"+s+`\r
|
|
86
|
+
`),i.headerExtensions&&i.headerExtensions.forEach(a=>{n+=e.writeExtmap(a)}),n},e.parseRtpEncodingParameters=function(t){const i=[],n=e.parseRtpParameters(t),s=n.fecMechanisms.indexOf("RED")!==-1,a=n.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(t,"a=ssrc:").map(d=>e.parseSsrcMedia(d)).filter(d=>d.attribute==="cname"),h=o.length>0&&o[0].ssrc;let c;const u=e.matchPrefix(t,"a=ssrc-group:FID").map(d=>d.substring(17).split(" ").map(f=>parseInt(f,10)));u.length>0&&u[0].length>1&&u[0][0]===h&&(c=u[0][1]),n.codecs.forEach(d=>{if(d.name.toUpperCase()==="RTX"&&d.parameters.apt){let p={ssrc:h,codecPayloadType:parseInt(d.parameters.apt,10)};h&&c&&(p.rtx={ssrc:c}),i.push(p),s&&(p=JSON.parse(JSON.stringify(p)),p.fec={ssrc:h,mechanism:a?"red+ulpfec":"red"},i.push(p))}}),i.length===0&&h&&i.push({ssrc:h});let l=e.matchPrefix(t,"b=");return l.length&&(l[0].indexOf("b=TIAS:")===0?l=parseInt(l[0].substring(7),10):l[0].indexOf("b=AS:")===0?l=parseInt(l[0].substring(5),10)*1e3*.95-50*40*8:l=void 0,i.forEach(d=>{d.maxBitrate=l})),i},e.parseRtcpParameters=function(t){const i={},n=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);const s=e.matchPrefix(t,"a=rtcp-rsize");i.reducedSize=s.length>0,i.compound=s.length===0;const a=e.matchPrefix(t,"a=rtcp-mux");return i.mux=a.length>0,i},e.writeRtcpParameters=function(t){let i="";return t.reducedSize&&(i+=`a=rtcp-rsize\r
|
|
77
87
|
`),t.mux&&(i+=`a=rtcp-mux\r
|
|
78
88
|
`),t.ssrc!==void 0&&t.cname&&(i+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
|
|
79
|
-
`),i},e.parseMsid=function(t){let i;const
|
|
89
|
+
`),i},e.parseMsid=function(t){let i;const n=e.matchPrefix(t,"a=msid:");if(n.length===1)return i=n[0].substring(7).split(" "),{stream:i[0],track:i[1]};const s=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(s.length>0)return i=s[0].value.split(" "),{stream:i[0],track:i[1]}},e.parseSctpDescription=function(t){const i=e.parseMLine(t),n=e.matchPrefix(t,"a=max-message-size:");let s;n.length>0&&(s=parseInt(n[0].substring(19),10)),isNaN(s)&&(s=65536);const a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:i.fmt,maxMessageSize:s};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const h=o[0].substring(10).split(" ");return{port:parseInt(h[0],10),protocol:h[1],maxMessageSize:s}}},e.writeSctpDescription=function(t,i){let n=[];return t.protocol!=="DTLS/SCTP"?n=["m="+t.kind+" 9 "+t.protocol+" "+i.protocol+`\r
|
|
80
90
|
`,`c=IN IP4 0.0.0.0\r
|
|
81
91
|
`,"a=sctp-port:"+i.port+`\r
|
|
82
|
-
`]:
|
|
92
|
+
`]:n=["m="+t.kind+" 9 "+t.protocol+" "+i.port+`\r
|
|
83
93
|
`,`c=IN IP4 0.0.0.0\r
|
|
84
94
|
`,"a=sctpmap:"+i.port+" "+i.protocol+` 65535\r
|
|
85
|
-
`],i.maxMessageSize!==void 0&&
|
|
86
|
-
`),
|
|
87
|
-
o=`+(
|
|
95
|
+
`],i.maxMessageSize!==void 0&&n.push("a=max-message-size:"+i.maxMessageSize+`\r
|
|
96
|
+
`),n.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,i,n){let s;const a=i!==void 0?i:2;return t?s=t:s=e.generateSessionId(),`v=0\r
|
|
97
|
+
o=`+(n||"thisisadapterortc")+" "+s+" "+a+` IN IP4 127.0.0.1\r
|
|
88
98
|
s=-\r
|
|
89
99
|
t=0 0\r
|
|
90
|
-
`},e.getDirection=function(t,i){const
|
|
91
|
-
a=extmap-allow-mixed`)!==-1){const n
|
|
100
|
+
`},e.getDirection=function(t,i){const n=e.splitLines(t);for(let s=0;s<n.length;s++)switch(n[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[s].substring(2)}return i?e.getDirection(i):"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 n=e.splitLines(t)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},e.parseOLine=function(t){const n=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const i=e.splitLines(t);for(let n=0;n<i.length;n++)if(i[n].length<2||i[n].charAt(1)!=="=")return!1;return!0},r.exports=e}(vn)),vn.exports}var Xa=A_();const kt=Y(Xa),R_=ge({__proto__:null,default:kt},[Xa]);function $r(r){if(!r.RTCIceCandidate||r.RTCIceCandidate&&"foundation"in r.RTCIceCandidate.prototype)return;const e=r.RTCIceCandidate;r.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&(i=JSON.parse(JSON.stringify(i)),i.candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const n=new e(i),s=kt.parseCandidate(i.candidate);for(const a in s)a in n||Object.defineProperty(n,a,{value:s[a]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new e(i)},r.RTCIceCandidate.prototype=e.prototype,ut(r,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new r.RTCIceCandidate(t.candidate),writable:"false"}),t))}function yn(r){!r.RTCIceCandidate||r.RTCIceCandidate&&"relayProtocol"in r.RTCIceCandidate.prototype||ut(r,"icecandidate",e=>{if(e.candidate){const t=kt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Kr(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(o){if(!o||!o.sdp)return!1;const h=kt.splitSections(o.sdp);return h.shift(),h.some(c=>{const u=kt.parseMLine(c);return u&&u.kind==="application"&&u.protocol.indexOf("SCTP")!==-1})},i=function(o){const h=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(h===null||h.length<2)return-1;const c=parseInt(h[1],10);return c!==c?-1:c},n=function(o){let h=65536;return e.browser==="firefox"&&(e.version<57?o===-1?h=16384:h=2147483637:e.version<60?h=e.version===57?65535:65536:h=2147483637),h},s=function(o,h){let c=65536;e.browser==="firefox"&&e.version===57&&(c=65535);const u=kt.matchPrefix(o.sdp,"a=max-message-size:");return u.length>0?c=parseInt(u[0].substring(19),10):e.browser==="firefox"&&h!==-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:h}=this.getConfiguration();h==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const h=i(arguments[0]),c=n(h),u=s(arguments[0],h);let l;c===0&&u===0?l=Number.POSITIVE_INFINITY:c===0||u===0?l=Math.max(c,u):l=Math.min(c,u);const d={};Object.defineProperty(d,"maxMessageSize",{get(){return l}}),this._sctp=d}return a.apply(this,arguments)}}function qr(r){if(!(r.RTCPeerConnection&&"createDataChannel"in r.RTCPeerConnection.prototype))return;function e(i,n){const s=i.send;i.send=function(){const o=arguments[0],h=o.length||o.size||o.byteLength;if(i.readyState==="open"&&n.sctp&&h>n.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+n.sctp.maxMessageSize+" bytes)");return s.apply(i,arguments)}}const t=r.RTCPeerConnection.prototype.createDataChannel;r.RTCPeerConnection.prototype.createDataChannel=function(){const n=t.apply(this,arguments);return e(n,this),n},ut(r,"datachannel",i=>(e(i.channel,i.target),i))}function bn(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 i=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=n=>{const s=n.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;const a=new Event("connectionstatechange",n);s.dispatchEvent(a)}return n},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function Sn(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(n){if(n&&n.sdp&&n.sdp.indexOf(`
|
|
101
|
+
a=extmap-allow-mixed`)!==-1){const s=n.sdp.split(`
|
|
92
102
|
`).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
|
|
93
|
-
`);r.RTCSessionDescription&&s instanceof r.RTCSessionDescription?arguments[0]=new r.RTCSessionDescription({type:s.type,sdp:n}):s.sdp=n}return t.apply(this,arguments)}}function tt(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 rt(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 s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}const ch=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:Jt,shimAddIceCandidateNullOrEmpty:tt,shimConnectionState:Kt,shimMaxMessageSize:Qe,shimParameterlessSetLocalDescription:rt,shimRTCIceCandidate:Ze,shimRTCIceCandidateRelayProtocol:Xt,shimSendThrowTypeError:et},Symbol.toStringTag,{value:"Module"}));function dh({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=Bi,i=sh(r),s={browserDetails:i,commonShim:ch,extractVersion:Ye,disableLog:rh,disableWarnings:ih,sdp:ah};switch(i.browser){case"chrome":if(!es||!Ht||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=es,tt(r,i),rt(r),qi(r,i),Wi(r),Ht(r,i),Xi(r),Zi(r,i),Ki(r),Ji(r),Qi(r,i),Ze(r),Xt(r),Kt(r),Qe(r,i),et(r),Jt(r,i);break;case"firefox":if(!hs||!qt||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=hs,tt(r,i),rt(r),ts(r,i),qt(r,i),rs(r),ns(r),is(r),ss(r),os(r),as(r),cs(r),ds(r),us(r),Ze(r),Kt(r),Qe(r,i),et(r);break;case"safari":if(!Ss||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=Ss,tt(r,i),rt(r),gs(r),Cs(r),ms(r),ps(r),ls(r),vs(r),fs(r),ys(r),Ze(r),Xt(r),Qe(r,i),et(r),Jt(r,i);break;default:t("Unsupported browser!");break}return s}dh({window:typeof window>"u"?void 0:window});class uh extends Q{static async isSupported(e){if(e==="webTransport")return Promise.resolve(Fi.isSupported());try{return Ku()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await Qu()&&await Zu()}catch{return!1}}constructor(e){super(),this._streamManagerController=new _u,this._streamComposeController=new Pu(this._streamManagerController),this._streamConsumeController=new Xu(this._streamComposeController),this._streamConsumeController.setPushConfig(e),this._observer=th,this._bindEvent()}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:S.Camera})}async startMicrophone(e){return await this._streamManagerController.startMicrophoneCapture(e)}stopMicrophone(e){this._streamManagerController.stopCapture({streamId:e,type:S.Microphone})}async startVideoFileCapture(e){return e?await this._streamManagerController.startVideoFileCapture(e):void 0}stopVideoFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.VideoFile})}async startScreenCapture(e=!1){return await this._streamManagerController.startScreenCapture(e)}stopScreenCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.Screen})}async startAudioFileCapture(e){return e?await this._streamManagerController.startAudioFileCapture(e):void 0}stopAudioFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.AudioFile})}async startImageCapture(e){return e?await this._streamManagerController.startImageCapture(e):void 0}stopImageCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.Image})}startCustomVideoCapture(e){return e?this._streamManagerController.startCustomVideoCapture(e):void 0}stopCustomVideoCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.CustomVideo})}startCustomAudioCapture(e){return e?this._streamManagerController.startCustomAudioCapture(e):void 0}stopCustomAudioCapture(e){this._streamManagerController.stopCapture({streamId:e,type:S.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(this.isPushing())throw new Error("can not change mixing while pushing");this._streamComposeController.enableMixing(e)}setMixingConfig(e){this._streamComposeController.setMixingConfig(e)}setRenderView(e){return this._streamConsumeController.setRenderView(e)}startPreview(){return this._streamConsumeController.startPreview()}stopPreview(){return this._streamConsumeController.stopPreview()}async startPush(e){return this._streamConsumeController.startPush(e)}addVideoStream(e){F(e)?e.forEach(t=>{this._streamComposeController.addVideoStream(t)}):this._streamComposeController.addVideoStream(e)}removeVideoStream(e){this._streamComposeController.removeVideoStream(e)}updateVideoStream(e){F(e)?this._streamComposeController.updateVideoStream(e):this._streamComposeController.updateVideoStream([e])}muteVideoStream(e){this._streamComposeController.muteVideoStream(e)}unmuteVideoStream(e){this._streamComposeController.unmuteVideoStream(e)}addAudioStream(e){F(e)?e.map(t=>this._streamComposeController.addAudioStream(t)):this._streamComposeController.addAudioStream(e)}removeAudioStream(e){this._streamComposeController.removeAudioStream(e)}updateAudioStream(e){F(e)?this._streamComposeController.updateAudioStream(e):this._streamComposeController.updateAudioStream([e])}muteAudioStream(e){this._streamComposeController.muteAudioStream(e)}unmuteAudioStream(e){this._streamComposeController.unmuteAudioStream(e)}setProperty(e,t){switch(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":$e.instance.volumeDetectScriptUrl=t;break;case"setMixerWorkerScriptUrl":this._streamComposeController.setMixerWorkerScript(t);break}}setVideoQuality(e){if(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:i,frameRate:s,bitrate:n}=ve(e,"video");this._streamManagerController.setVideoResolution({width:t,height:i}),this._streamManagerController.setVideoFps(s),this._streamComposeController.setVideoQuality({width:t,height:i,frameRate:s}),this._streamConsumeController.setBitrate(n,"video")}setAudioQuality(e){const{sampleRate:t,bitrate:i}=ve(e,"audio");this._streamManagerController.setAudioSampleRate(t),this._streamConsumeController.setBitrate(i,"audio")}getMediaStream(e){return this._streamManagerController.getStreamById(e).mediaStream}stopPush(){return this._streamConsumeController.stopPush()}isPushing(){return this._streamConsumeController.isPushing()}getStats(){return this._streamConsumeController.getStats()}getPreviewElement(){return this._streamConsumeController.getPreviewElement()}_bindEvent(){this._streamManagerController.on(z.Error,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(z.Interrupted,e=>{this.observer.onCaptureInterrupted(e.id)}),this._streamConsumeController.on(A.PushStart,()=>{this.observer.onPushStart()}),this._streamConsumeController.on(A.PushStop,()=>{this.observer.onPushStop()}),this._streamConsumeController.on(A.RTCConnectStateChanged,e=>{this.observer.onPushStatusUpdate(or[e],e)}),this._streamConsumeController.on(A.PushError,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(z.DeviceStopCapture,e=>{this.observer.onStopCapture(e.id)}),this._streamConsumeController.on(A.CaptureFirstAudioFrame,()=>{this.observer.onCaptureFirstAudioFrame()}),this._streamConsumeController.on(A.CaptureFirstVideoFrame,()=>{this.observer.onCaptureFirstVideoFrame()}),no(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()}get observer(){return this._observer}get isEnableMixing(){return this._streamComposeController.isEnableMixing}get pushMode(){return this._streamConsumeController.pushMode}}return uh});
|
|
103
|
+
`);r.RTCSessionDescription&&n instanceof r.RTCSessionDescription?arguments[0]=new r.RTCSessionDescription({type:n.type,sdp:s}):n.sdp=s}return t.apply(this,arguments)}}function Wr(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 Jr(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 n=arguments[0]||{};if(typeof n!="object"||n.type&&n.sdp)return t.apply(this,arguments);if(n={type:n.type,sdp:n.sdp},!n.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":n.type="offer";break;default:n.type="answer";break}return n.sdp||n.type!=="offer"&&n.type!=="answer"?t.apply(this,[n]):(n.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}const D_=Object.freeze(Object.defineProperty({__proto__:null,removeExtmapAllowMixed:Sn,shimAddIceCandidateNullOrEmpty:Wr,shimConnectionState:bn,shimMaxMessageSize:Kr,shimParameterlessSetLocalDescription:Jr,shimRTCIceCandidate:$r,shimRTCIceCandidateRelayProtocol:yn,shimSendThrowTypeError:qr},Symbol.toStringTag,{value:"Module"}));function x_({window:r}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const t=ma,i=z_(r),n={browserDetails:i,commonShim:D_,extractVersion:Hr,disableLog:w_,disableWarnings:T_,sdp:R_};switch(i.browser){case"chrome":if(!Aa||!_n||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),n;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),n;t("adapter.js shimming chrome."),n.browserShim=Aa,Wr(r,i),Jr(r),ba(r,i),Sa(r),_n(r,i),Ea(r),za(r,i),Ca(r),wa(r),ka(r,i),$r(r),yn(r),bn(r),Kr(r,i),qr(r),Sn(r,i);break;case"firefox":if(!Ga||!gn||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),n;t("adapter.js shimming firefox."),n.browserShim=Ga,Wr(r,i),Jr(r),Ra(r,i),gn(r,i),Da(r),Ma(r),xa(r),Oa(r),Ia(r),Pa(r),La(r),Ua(r),Na(r),$r(r),bn(r),Kr(r,i),qr(r);break;case"safari":if(!Ja||!e.shimSafari)return t("Safari shim is not included in this adapter release."),n;t("adapter.js shimming safari."),n.browserShim=Ja,Wr(r,i),Jr(r),$a(r),qa(r),Fa(r),Ba(r),Va(r),Ka(r),ja(r),Wa(r),$r(r),yn(r),Kr(r,i),qr(r),Sn(r,i);break;default:t("Unsupported browser!");break}return n}x_({window:typeof window>"u"?void 0:window});class O_ extends Ge{static async isSupported(e){if(e==="webTransport")return Promise.resolve(ua.isSupported());try{return g_()||!window.RTCPeerConnection||!window.RTCPeerConnection.prototype.addTransceiver||!window.RTCPeerConnection.prototype.createDataChannel?!1:await S_()&&await b_()}catch{return!1}}constructor(e){var t,i,n,s,a,o,h,c,u,l;if(super(),this._options=e??{},this._streamManagerController=new Lm(this),this._streamComposeController=new Km(this._streamManagerController),this._streamConsumeController=new __(this._streamComposeController,e),this._streamConsumeController.setPushConfig(e),this._observer=C_,this._bindEvent(),!(e!=null&&e.loggerConfig)||(t=e==null?void 0:e.loggerConfig)!=null&&t.enable){Im({showLogInConsole:((i=e==null?void 0:e.loggerConfig)==null?void 0:i.showInConsole)??!1});const d=xm((n=e==null?void 0:e.loggerConfig)==null?void 0:n.userId),p=Om((s=e==null?void 0:e.loggerConfig)==null?void 0:s.deviceId);Pm({user_unique_id:d,device_id:p,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:((h=e==null?void 0:e.loggerConfig)==null?void 0:h.appId)??0},{user_id:d,device_id:p,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:((l=e==null?void 0:e.loggerConfig)==null?void 0:l.appId)??0}),R(D.PUSHER_INIT,e)}}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:N.Camera})}async startMicrophone(e){return await this._streamManagerController.startMicrophoneCapture(e)}stopMicrophone(e){this._streamManagerController.stopCapture({streamId:e,type:N.Microphone})}async startVideoFileCapture(e){return e?await this._streamManagerController.startVideoFileCapture(e):void 0}stopVideoFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.VideoFile})}async startScreenCapture(e=!1){return await this._streamManagerController.startScreenCapture(e)}stopScreenCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.Screen})}async startAudioFileCapture(e){return e?await this._streamManagerController.startAudioFileCapture(e):void 0}stopAudioFileCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.AudioFile})}async startImageCapture(e){return e?await this._streamManagerController.startImageCapture(e):void 0}stopImageCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.Image})}startCustomVideoCapture(e){return e?this._streamManagerController.startCustomVideoCapture(e):void 0}stopCustomVideoCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.CustomVideo})}startCustomAudioCapture(e){return e?this._streamManagerController.startCustomAudioCapture(e):void 0}stopCustomAudioCapture(e){this._streamManagerController.stopCapture({streamId:e,type:N.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(R(D.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){R(D.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(R(D.PUSH_AUDIO_CONTEXT_START_FAILED,{error:t}),this._options.checkAudio)throw new _t(oe.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){R(D.ADD_VIDEO_STREAM,{number:$(e)?e.length:1,config:e}),$(e)?e.forEach(t=>{this._streamComposeController.addVideoStream(t)}):this._streamComposeController.addVideoStream(e)}removeVideoStream(e){R(D.DELETE_VIDEO_STREAM,{stream_id:e}),this._streamComposeController.removeVideoStream(e)}updateVideoStream(e){R(D.UPDATE_VIDEO_STREAM,{number:$(e)?e.length:1,config:e}),$(e)?this._streamComposeController.updateVideoStream(e):this._streamComposeController.updateVideoStream([e])}muteVideoStream(e){R(D.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.muteVideoStream(e)}unmuteVideoStream(e){R(D.CHANGE_VIDEO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.unmuteVideoStream(e)}addAudioStream(e){R(D.ADD_AUDIO_STREAM,{number:$(e)?e.length:1,config:e}),$(e)?e.map(t=>this._streamComposeController.addAudioStream(t)):this._streamComposeController.addAudioStream(e)}removeAudioStream(e){R(D.DELETE_AUDIO_STREAM,{stream_id:e}),this._streamComposeController.removeAudioStream(e)}updateAudioStream(e){R(D.UPDATE_AUDIO_STREAM,{number:$(e)?e.length:1,config:e}),$(e)?this._streamComposeController.updateAudioStream(e):this._streamComposeController.updateAudioStream([e])}muteAudioStream(e){R(D.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!0}),this._streamComposeController.muteAudioStream(e)}unmuteAudioStream(e){R(D.CHANGE_AUDIO_STREAM_MUTE,{stream_id:e,mute:!1}),this._streamComposeController.unmuteAudioStream(e)}setProperty(e,t){switch(R(D.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":_r.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(R(D.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:i,frameRate:n,bitrate:s}=gt(e,"video");this._streamManagerController.setVideoResolution({width:t,height:i}),this._streamManagerController.setVideoFps(n),this._streamComposeController.setVideoQuality({width:t,height:i,frameRate:n}),this._streamConsumeController.setBitrate(s,"video")}setAudioQuality(e){R(D.SET_AUDIO_QUALITY,{quality:e});const{sampleRate:t,bitrate:i}=gt(e,"audio");this._streamManagerController.setAudioSampleRate(t),this._streamConsumeController.setBitrate(i,"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(ye.Error,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(ye.Interrupted,e=>{this.observer.onCaptureInterrupted(e.id)}),this._streamConsumeController.on(j.PushStart,()=>{this.observer.onPushStart()}),this._streamConsumeController.on(j.PushStop,()=>{this.observer.onPushStop()}),this._streamConsumeController.on(j.RTCConnectStateChanged,e=>{this.observer.onPushStatusUpdate(Rn[e],e)}),this._streamConsumeController.on(j.PushError,e=>{this.observer.onError(e.code,e.message,e.ext)}),this._streamManagerController.on(ye.DeviceStopCapture,e=>{this.observer.onStopCapture(e.id)}),this._streamConsumeController.on(j.CaptureFirstAudioFrame,()=>{this.observer.onCaptureFirstAudioFrame()}),this._streamConsumeController.on(j.CaptureFirstVideoFrame,()=>{this.observer.onCaptureFirstVideoFrame()}),this._streamConsumeController.on(j.ReconnectStateChange,(e,t)=>{this.observer.onReconnectStateChange(e,t)}),this._streamConsumeController.on(j.LiveConnectStateChange,e=>{this.observer.onLiveConnectStateChange(e)}),yu(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()}get observer(){return this._observer}get isEnableMixing(){return this._streamComposeController.isEnableMixing}get pushMode(){return this._streamConsumeController.pushMode}}return O_});
|