@livedigital/client 3.12.0-prefer-relay-option.2 → 3.12.0

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.js CHANGED
@@ -238,4 +238,4 @@ let zt;Ft.AwaitQueue=class{constructor(){this.pendingTasks=new Map,this.nextTask
238
238
  personMask = smoothstep(u_coverage.x, u_coverage.y, personMask);
239
239
  outColor = vec4(frameColor * personMask + backgroundColor * (1.0 - personMask), 1.0);
240
240
  }
241
- `,{width:c,height:d}=n,l=c/d,p=lc(e,e.VERTEX_SHADER,o),u=lc(e,e.FRAGMENT_SHADER,a),h=hc(e,p,u,t,r),f=e.getUniformLocation(h,"u_backgroundScale"),m=e.getUniformLocation(h,"u_backgroundOffset"),g=e.getUniformLocation(h,"u_inputFrame"),v=e.getUniformLocation(h,"u_personMask"),y=e.getUniformLocation(h,"u_background"),b=e.getUniformLocation(h,"u_coverage"),w=e.getUniformLocation(h,"u_lightWrapping"),S=e.getUniformLocation(h,"u_blendMode");e.useProgram(h),e.uniform2f(f,1,1),e.uniform2f(m,0,0),e.uniform1i(g,0),e.uniform1i(v,1),e.uniform2f(b,0,1),e.uniform1f(w,0),e.uniform1f(S,0);let _=null;function R(t){_=pc(e,e.RGBA8,t.naturalWidth,t.naturalHeight,e.LINEAR,e.LINEAR),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.naturalWidth,t.naturalHeight,e.RGBA,e.UNSIGNED_BYTE,t);let r=0,i=0,s=t.naturalWidth,n=t.naturalHeight;s/n<l?(n=s/l,i=(t.naturalHeight-n)/2):(s=n*l,r=(t.naturalWidth-s)/2);const o=s/t.naturalWidth,a=n/t.naturalHeight;r/=t.naturalWidth,i/=t.naturalHeight,e.uniform2f(f,o,a),e.uniform2f(m,r,i)}return(null==s?void 0:s.complete)?R(s):s&&(s.onload=()=>{R(s)}),{render:function(){e.viewport(0,0,c,d),e.useProgram(h),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,i),null!==_&&(e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,_),e.uniform1i(y,2)),e.bindFramebuffer(e.FRAMEBUFFER,null),e.drawArrays(e.TRIANGLE_STRIP,0,4)},updateCoverage:function(t){e.useProgram(h),e.uniform2f(b,t[0],t[1])},updateLightWrapping:function(t){e.useProgram(h),e.uniform1f(w,t)},updateBlendMode:function(t){e.useProgram(h),e.uniform1f(S,"screen"===t?0:1)},cleanUp:function(){e.deleteTexture(_),e.deleteProgram(h),e.deleteShader(u),e.deleteShader(p)}}}(u,m,g,b,t,n);return{render:function(){return r(this,void 0,void 0,(function*(){u.activeTexture(u.TEXTURE0),u.bindTexture(u.TEXTURE_2D,v),u.texImage2D(u.TEXTURE_2D,0,u.RGBA,u.RGBA,u.UNSIGNED_BYTE,e.htmlElement),u.bindVertexArray(f),yield w.render(),o._runInference(),S.render(),_.render(),R.render()}))},updatePostProcessingConfig:function(e){if(_.updateSigmaSpace(e.jointBilateralFilter.sigmaSpace),_.updateSigmaColor(e.jointBilateralFilter.sigmaColor),"image"===i.type){const t=R;t.updateCoverage(e.coverage),t.updateLightWrapping(e.lightWrapping),t.updateBlendMode(e.blendMode)}else if("blur"===i.type){R.updateCoverage(e.coverage)}else{const e=R;e.updateCoverage([0,.9999]),e.updateLightWrapping(0)}},cleanUp:function(){R.cleanUp(),_.cleanUp(),S.cleanUp(),w.cleanUp(),u.deleteTexture(b),u.deleteTexture(y),u.deleteTexture(v),u.deleteBuffer(g),u.deleteBuffer(m),u.deleteVertexArray(f),u.deleteShader(h)}}}var wc,Sc,_c,Rc,kc,Cc,Pc,Tc,Ec,Dc;class Mc{constructor(e){wc.set(this,!1),Sc.set(this,void 0),_c.set(this,void 0),Rc.set(this,void 0),s(this,Rc,new Ge({logLevel:e,namespace:"TensorFlowLoader"}),"f")}get isLoaded(){return i(this,wc,"f")}get tfliteModule(){return i(this,Sc,"f")||i(this,_c,"f")}loadTFLite(){return r(this,void 0,void 0,(function*(){yield Promise.all([this.loadTFLiteRegular(),this.loadTFLiteSIMD()]),this.tfliteModule&&s(this,wc,!0,"f")}))}loadTFLiteModel(e){return r(this,void 0,void 0,(function*(){if(this.tfliteModule)try{const t=Mc.getTFLiteModelFileName(e);i(this,Rc,"f").info("loading model",{modelFileName:t});const r=yield fetch(`${window.location.origin}/tflite/models/${t}.tflite`),s=yield r.arrayBuffer(),n=this.tfliteModule._getModelBufferMemoryOffset();this.tfliteModule.HEAPU8.set(new Uint8Array(s),n);const o=this.tfliteModule._loadModel(s.byteLength);i(this,Rc,"f").info("loading model result",{result:o})}catch(e){i(this,Rc,"f").warn("loadTFLiteModel()",{error:e})}else i(this,Rc,"f").warn("loadTFLiteModel()",{description:"TFLite module is not loaded"})}))}loadTFLiteRegular(){return r(this,void 0,void 0,(function*(){try{s(this,Sc,yield createTFLiteModule(),"f")}catch(e){i(this,Rc,"f").error("Failed to create TFLite WebAssembly module.",{error:e})}}))}loadTFLiteSIMD(){return r(this,void 0,void 0,(function*(){try{s(this,_c,yield createTFLiteSIMDModule(),"f")}catch(e){i(this,Rc,"f").error("Failed to create TFLite SIMD WebAssembly module.",{error:e})}}))}static getTFLiteModelFileName({model:e,inputResolution:t}){switch(e){case"meet":return"256x144"===t?"segm_full_v679":"segm_lite_v681";case"mlkit":return"selfiesegmentation_mlkit-256x256-2021_01_19-v1215.f16";default:throw new Error(`No TFLite file for this segmentation model: ${e}`)}}}function xc({sourcePlayback:e,backgroundConfig:t,segmentationConfig:i,canvas:s,tflite:n}){const o=s.getContext("2d");o.scale(1.031,1.031),o.translate(-11,-11);const[a,c]=mc[i.inputResolution],d=a*c,l=new ImageData(a,c),p=document.createElement("canvas");p.width=a,p.height=c;const u=p.getContext("2d"),h=n._getInputMemoryOffset()/4,f=n._getOutputMemoryOffset()/4;let m;return{render:function(){return r(this,void 0,void 0,(function*(){"none"!==t.type&&(function(){if(u.drawImage(e.htmlElement,0,0,e.width,e.height,0,0,a,c),"meet"===i.model||"mlkit"===i.model){const e=u.getImageData(0,0,a,c);for(let t=0;t<d;t+=1)n.HEAPF32[h+3*t]=e.data[4*t]/255,n.HEAPF32[h+3*t+1]=e.data[4*t+1]/255,n.HEAPF32[h+3*t+2]=e.data[4*t+2]/255}}(),function(){n._runInference();for(let e=0;e<d;e+=1)if("meet"===i.model){const t=n.HEAPF32[f+2*e],r=n.HEAPF32[f+2*e+1],i=Math.max(t,r),s=Math.exp(t-i),o=Math.exp(r-i);l.data[4*e+3]=255*o/(s+o)}else if("mlkit"===i.model){const t=n.HEAPF32[f+e];l.data[4*e+3]=255*t}u.putImageData(l,0,0)}()),o.globalCompositeOperation="copy",o.filter="none",(null==m?void 0:m.smoothSegmentationMask)&&("blur"===t.type||"image"===t.type)&&(o.filter="blur(8px)"),"none"!==t.type&&(o.drawImage(p,0,0,a,c,0,0,e.width,e.height),o.globalCompositeOperation="source-in",o.filter="none"),o.drawImage(e.htmlElement,0,0),"blur"===t.type&&(o.globalCompositeOperation="destination-over",o.filter="blur(8px)",o.drawImage(e.htmlElement,0,0))}))},updatePostProcessingConfig:function(e){m=e},cleanUp:function(){}}}wc=new WeakMap,Sc=new WeakMap,_c=new WeakMap,Rc=new WeakMap;class Lc{constructor(e){kc.set(this,void 0),Cc.set(this,void 0),Pc.set(this,!1),Tc.set(this,void 0),s(this,kc,new Mc(e.logLevel),"f"),s(this,Tc,new Ge({namespace:"VideoTrackProcessor",logLevel:e.logLevel}),"f")}get isProcessing(){return i(this,Pc,"f")}processTrack(e){return r(this,void 0,void 0,(function*(){const{track:t,pipelineConfig:n}=e;i(this,Pc,"f")&&this.stopProcessing();try{i(this,kc,"f").isLoaded||(yield i(this,kc,"f").loadTFLite(),yield i(this,kc,"f").loadTFLiteModel(n.segmentationConfig));const{tfliteModule:o}=i(this,kc,"f");if(!o)throw new Error("TensorFlow model is not available");const{targetFps:a}=n.segmentationConfig,c=yield Lc.buildSourcePlayback(t),d=document.createElement("canvas");d.width=c.width,d.height=c.height;const l=function(){const e=new Map,t=new Worker(`${window.location.origin}/timerWorker.js`);t.onmessage=t=>{const r=e.get(t.data.callbackId);r&&(e.delete(t.data.callbackId),r())};let r=1;return{setTimeout:function(i,s){return r+=1,e.set(r,i),t.postMessage({callbackId:r,timeoutMs:s}),r},clearTimeout:function(r){e.has(r)&&(t.postMessage({callbackId:r}),e.delete(r))},terminate:function(){e.clear(),t.terminate()}}}(),p={config:n,sourcePlayback:c,destinationPlayback:d,tflite:o},u="canvas2dCpu"===e.pipelineConfig.segmentationConfig.pipeline?Lc.buildCanvas2dPipeline(p):Lc.buildWebGL2Pipeline(p),h=()=>r(this,void 0,void 0,(function*(){const e=performance.now();return yield u.render(),l.setTimeout(h,performance.now()-e)})),f=yield h();u.updatePostProcessingConfig(n.postprocessingConfig);const m=d.captureStream(a),[g]=m.getVideoTracks();return s(this,Cc,{pipeline:u,destination:d,source:c.htmlElement,track:g,timerWorker:l,timerId:f},"f"),s(this,Pc,!0,"f"),g}catch(e){throw i(this,Tc,"f").error("processTrack()",{error:e,track:t}),new Error("Can not process this track")}}))}stopProcessing(){if(this.isProcessing)if(i(this,Cc,"f"))try{i(this,Cc,"f").pipeline.cleanUp(),i(this,Cc,"f").source.remove(),i(this,Cc,"f").destination.remove(),i(this,Cc,"f").timerWorker.clearTimeout(i(this,Cc,"f").timerId),i(this,Cc,"f").timerWorker.terminate(),i(this,Cc,"f").destination.remove(),i(this,Cc,"f").track.stop(),s(this,Cc,void 0,"f"),s(this,Pc,!1,"f")}catch(e){i(this,Tc,"f").error("cleanUp()",{error:e})}else i(this,Tc,"f").warn("cleanUp()",{description:"This track is not processing"});else i(this,Tc,"f").debug("stopProcessing()",{description:"Track is not processed"})}static buildWebGL2Pipeline(e){return bc({backgroundImage:e.config.backgroundConfig.imageSource,sourcePlayback:e.sourcePlayback,backgroundConfig:e.config.backgroundConfig,segmentationConfig:e.config.segmentationConfig,canvas:e.destinationPlayback,tflite:e.tflite})}static buildCanvas2dPipeline(e){return xc({sourcePlayback:e.sourcePlayback,backgroundConfig:e.config.backgroundConfig,segmentationConfig:e.config.segmentationConfig,canvas:e.destinationPlayback,tflite:e.tflite})}static buildSourcePlayback(e){return r(this,void 0,void 0,(function*(){const t=document.createElement("video");return t.srcObject=new MediaStream([e]),t.autoplay=!0,yield t.play(),{htmlElement:t,width:t.videoWidth,height:t.videoHeight}}))}}kc=new WeakMap,Cc=new WeakMap,Pc=new WeakMap,Tc=new WeakMap;class Ic extends cc{constructor(e){super(e),Ec.set(this,void 0),Dc.set(this,void 0),this.transformParams={},s(this,Ec,new Lc({logLevel:e.logLevel}),"f"),this.watchOrientation(),this.watchDocumentVisibility()}get isEffectsProcessing(){return i(this,Ec,"f").isProcessing}getEncoderConfig(){return this.encoderConfig}getCodecOptions(){return{videoGoogleStartBitrate:this.getEncoderConfig().videoGoogleStartBitrate||1e3}}getPreferredCodec(){const{preferredCodec:e}=this.getEncoderConfig();return e||(this.getLabel()===u.ScreenVideo?"vp8":"h264")}getEncodings(){return this.getEncoderConfig().encodings||La}setTransformParams(e){this.transformParams=e}setMaxSpatialLayer(e){return r(this,void 0,void 0,(function*(){const t=this.getProducer();t?(yield t.setMaxSpatialLayer(e),this.logger.debug("setMaxSpatialLayer()",{label:this.getLabel(),spatialLayer:e})):this.logger.warn("setMaxSpatialLayer()",{message:"Not produced yet"})}))}getMaxSpatialLayer(){const e=this.getProducer();if(e)return e.maxSpatialLayer;this.logger.warn("getMaxSpatialLayer()",{message:"Not produced yet"})}enableBlur(){return r(this,void 0,void 0,(function*(){try{s(this,Dc,this.mediaStreamTrack.clone(),"f");const e=yield i(this,Ec,"f").processTrack({track:this.mediaStreamTrack,pipelineConfig:document.hidden?vc:gc});yield this.replaceTrack(e),this.logger.info("enableBlur()",{track:this})}catch(e){throw this.logger.warn("enableBlur()",{track:this,error:e}),new Error("Can not enable virtual background")}}))}disableBlur(){return r(this,void 0,void 0,(function*(){try{if(!i(this,Ec,"f").isProcessing)return void this.logger.debug("disableBlur()",{description:"Track is not processed"});if(!i(this,Dc,"f"))return void this.logger.warn("disableBlur()",{description:"Original track missing"});this.isPublished&&(yield this.replaceTrack(i(this,Dc,"f"))),i(this,Ec,"f").stopProcessing(),this.logger.info("disableBlur()",{track:this})}catch(e){throw this.logger.warn("disableBlur()",{track:this,error:e}),new Error("Can not disable virtual background")}}))}publish(e={}){var t;return r(this,void 0,void 0,(function*(){yield this.produce({encodings:this.getEncodings(),preferredCodec:this.getPreferredCodec(),transformParams:this.transformParams,codecOptions:this.getCodecOptions(),keyFrameRequestDelay:null!==(t=e.keyFrameRequestDelay)&&void 0!==t?t:0}),this.clientEventEmitter.emit(W,this)}))}watchOrientation(){window.screen.orientation&&(this.logger.debug("watchOrientation()",{description:"Watching started"}),window.screen.orientation.addEventListener("change",(()=>r(this,void 0,void 0,(function*(){if(this.isEffectsProcessing)try{this.mediaStreamTrack.enabled=!1;const e=yield i(this,Ec,"f").processTrack({track:this.mediaStreamTrack,pipelineConfig:document.hidden?vc:gc});yield this.replaceTrack(e)}catch(e){this.logger.warn("watchOrientation()",{description:"Restart blur error after orientation change",error:e})}})))))}watchDocumentVisibility(){this.logger.debug("watchDocumentVisibility()",{description:"Watching started"}),window.addEventListener("visibilitychange",(()=>r(this,void 0,void 0,(function*(){if(this.isEffectsProcessing)try{yield this.disableBlur(),yield this.enableBlur()}catch(e){this.logger.warn("watchDocumentVisibility()",{description:"Restart blur error after change document visibility",error:e})}}))))}}Ec=new WeakMap,Dc=new WeakMap;const Oc=new class{sleepMs(e){return r(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}))}now(){return new Date(Date.now())}},Ac=(e,t={})=>r(void 0,void 0,void 0,(function*(){var r;const i=t.maxRetries||2,s=t.minBackoffDelayMs||50;let n,o=0;for(;o<i;){o+=1;try{return yield e()}catch(e){if(n=e,t.logger&&t.logger.info("Action retry failed",{currentAttempt:o,actionName:t.actionName,error:e}),t.abortOnError&&t.abortOnError(e))throw n;if(o<i){const e=Math.pow(2,o-1)*s;yield Oc.sleepMs(Math.min(e,null!==(r=t.maxBackoffDelayMs)&&void 0!==r?r:e))}}}throw n}));class jc extends g{constructor(e,t){super(e,null!=t?t:"need_join_first")}}class Fc{constructor(e){this.initialized=!1,this.isJoined=!1,this.isChannelJoining=!1,this.rejoinRequested=!1,this.isReleasing=!1;const{clientEventEmitter:t,network:i,media:s,dependenciesFactory:n,logLevel:o}=e;this.logLevel=o||Be,this.system=n.createSystem({logLevel:this.logLevel,clientEventEmitter:t,onLogMessage:e.onLogMessage}),this.media=n.createMedia({logLevel:this.logLevel,engine:this,clientEventEmitter:t,mediaTracksFactory:s.mediaTracksFactory,onLogMessage:e.onLogMessage}),this.network=n.createNetwork({logLevel:this.logLevel,loadbalancer:i.loadbalancer,onLogMessage:e.onLogMessage}),this.peersRepository=new Map,this.clientEventEmitter=t,this.channelEventsHandler=n.createChannelEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.mediaSoupEventsHandler=n.createMediaSoupEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.channelAudioObserverEventHandler=n.createAudioObserverEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.channelStateSyncEventHandler=n.createChannelStateSyncEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.handleChannelAudioObserverEvent=e=>{this.channelAudioObserverEventHandler.handle(e)},this.handleDataChannelEvent=e=>{this.channelEventsHandler.handleDataChannelEvent(e)},this.handleChannelStateSyncEvent=e=>r(this,void 0,void 0,(function*(){this.channelStateSyncEventHandler.handle(e)})),this.logger=new Ge({logLevel:this.logLevel,namespace:"Engine",onLogMessage:e.onLogMessage}),this.webRtcIssueDetector=e.disableWid?void 0:n.createIssueDetector({onIssues:e.onIssues,onNetworkScoresUpdated:e.onNetworkScoresUpdated,ignoreSSRCList:[1234],logger:new Ge({logLevel:this.logLevel,namespace:"WID"})}),this.watchSocketState()}initialize(){var e,t,i;return r(this,void 0,void 0,(function*(){try{const{rtpCapabilities:r}=yield this.network.socket.request("router.getRtpCapabilities");yield this.media.createNoiseSuppressor(),yield this.media.loadDevice(r),this.logger.info("Supported capabilities",{codecs:Ba(this.media.mediasoupDevice)}),null===(e=this.webRtcIssueDetector)||void 0===e||e.watchNewPeerConnections(),yield Promise.all([this.network.createSendTransport(this.media.mediasoupDevice),this.network.createRecvTransport(this.media.mediasoupDevice)]),this.initialized=!0,this.logger.debug("initialize()",{sendTransportId:null===(t=this.network.sendTransport)||void 0===t?void 0:t.id,recvTransportId:null===(i=this.network.receiveTransport)||void 0===i?void 0:i.id})}catch(e){this.logger.error("initialize()",{error:e});const t=e instanceof f&&"device not supported"===e.message,r=e instanceof Error&&"RTCPeerConnection is not defined"===e.message;if(t||r)throw new v("Device not supported",v.UNSUPPORTED_DEVICE_CODE);throw new Error("Error initialize engine")}}))}release(){var e,t,i,s,n,o,a;return r(this,void 0,void 0,(function*(){if(!this.isReleasing){this.isReleasing=!0;try{this.initialized=!1,this.isJoined=!1,this.app=void 0,this.channel=void 0,null===(e=this.webRtcIssueDetector)||void 0===e||e.stopWatchingNewPeerConnections(),this.peersRepository.forEach((e=>e.reset())),this.peersRepository.clear(),yield this.network.closeSendTransport(),yield this.network.closeReceiveTransport(),yield this.media.clearTracks(),null===(t=this.audioObserver)||void 0===t||t.removeListener("message",this.handleChannelAudioObserverEvent),null===(i=this.audioObserver)||void 0===i||i.close(),null===(s=this.generalDataConsumer)||void 0===s||s.removeListener("message",this.handleDataChannelEvent),null===(n=this.generalDataConsumer)||void 0===n||n.close(),null===(o=this.channelStateSyncDataConsumer)||void 0===o||o.removeListener("message",this.handleChannelStateSyncEvent),null===(a=this.channelStateSyncDataConsumer)||void 0===a||a.close(),this.channelEventsHandler.reset(),this.mediaSoupEventsHandler.reset(),this.removeClientEventEmitterListeners(),yield this.network.reset(),this.network.socket.disconnect(),this.logger.debug("release()",{socketId:this.mySocketId})}catch(e){throw this.logger.error("release()",{error:e}),new Error("Error release engine")}finally{this.isReleasing=!1}}}))}removeClientEventEmitterListeners(){[W,V,z,$,G,H].forEach((e=>this.clientEventEmitter.removeAllListeners(e)))}watchSocketState(){this.network.socket.observer.on(Ha.State,(e=>{var t;if(this.isReleasing)return;const{state:r,code:i,error:s}=e;this.clientEventEmitter.emit(r,{code:i,error:s});const n="unauthorized"===(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.errorCode);r===Ha.Error&&this.isJoined&&n?this.triggerRejoinEventIfAppropriate("unauthorized error"):r===Ha.Reconnected&&this.triggerRejoinEventIfAppropriate("reconnected socket")}))}get activeSpeaker(){return this.activeSpeakerPeer}get peers(){return Array.from(this.peersRepository.values())}get hostPeers(){return this.peers.filter((e=>"host"===e.role))}get audiencePeers(){return this.peers.filter((e=>"audience"===e.role))}get mySocketId(){return this.network.socket.id}getPeerById(e){return this.peersRepository.get(e)}checkConnectionActivity(){var e;return r(this,void 0,void 0,(function*(){if(!this.channel||this.isChannelJoining)throw new Error("Connect to the channel first");if(!(null===(e=this.network.socket.connection)||void 0===e?void 0:e.active))throw new Error("Socket is inactive")}))}confirmActivity(){return r(this,void 0,void 0,(function*(){this.checkConnectionActivity(),yield this.network.socket.request(R)}))}join(e){return r(this,void 0,void 0,(function*(){try{this.logger.debug("join()",{params:e}),this.isChannelJoining=!0,this.watchClientEvents(),yield this.connectToSocketServerWithRetry(e),yield this.performJoin({appData:e.appData})}catch(e){throw this.logger.error("join()",{error:e}),e}finally{this.isChannelJoining=!1,this.rejoinRequested=!1}}))}loadPeers(e){return r(this,void 0,void 0,(function*(){const{peers:t}=yield this.network.socket.request(w,{role:e});t.filter((e=>!this.peersRepository.has(e.id))).forEach((e=>this.setPeer(e)))}))}setPeer(e){const t=this.peersRepository.get(e.id);if(t)return t;const r=new Ma(Object.assign(Object.assign({},e),{engine:this,loginDate:new Date}));return this.peersRepository.set(r.id,r),r}removePeer(e){const t=this.peersRepository.get(e);t&&(t.tracks.forEach((e=>e.close())),t.reset(),this.peersRepository.delete(e))}updateAppData(e){return r(this,void 0,void 0,(function*(){const{myPeer:t}=this;if(!t)throw new Error("Need join to channel first");try{Ea(e),yield this.network.updatePeerAppData({peerId:t.id,appData:e})}catch(e){throw this.logger.error("updateAppData()",{error:e}),new Error("Can not update peer appData")}}))}createCameraVideoTrack(e){return r(this,void 0,void 0,(function*(){const t=Ja.getCameraVideoTrackParams(e);try{const[r]=yield this.media.createUserMediaTracks({audio:!1,video:t.videoTrackOptions});if(r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof Ic&&(r.setLabel(u.Camera),r.setEncoderConfig(t.encoderConfig),r.setTransformParams(Ja.getVideoTrackTransformParams(r.mediaStreamTrack)),null==e?void 0:e.blur))try{yield r.enableBlur()}catch(e){this.logger.warn("Failed to start virtual background, featured original track",{track:this})}return this.media.setTrack(r),this.logger.debug("createCameraVideoTrack()",{trackParams:t,track:r}),r}catch(e){throw this.logger.error("createCameraVideoTrack()",{error:e,trackParams:t}),new Error(`Can not create camera track: ${e.message}`)}}))}createMicrophoneAudioTrack(e){return r(this,void 0,void 0,(function*(){try{const[t]=yield this.media.createUserMediaTracks({video:!1,audio:null==e?void 0:e.audio});if(t.setLabel(u.Microphone),t.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),(null==e?void 0:e.encoderConfig)&&t.setEncoderConfig(e.encoderConfig),"audio"===t.kind&&(null==e?void 0:e.noiseSuppression))try{yield t.enableNoiseSuppression()}catch(e){this.logger.warn("Failed to start noise suppression, featured original track",{track:this})}return this.media.setTrack(t),this.logger.debug("createMicrophoneAudioTrack()",{options:e,track:t}),t}catch(t){throw this.logger.error("createMicrophoneAudioTrack()",{error:t,options:e}),new Error(`Can not create microphone track: ${t.message}`)}}))}createScreenMediaTracks(e){return r(this,void 0,void 0,(function*(){const t=Ja.getScreenVideoTrackParams(e);try{const r=yield this.media.createDisplayMediaTracks({audio:null==e?void 0:e.audio,video:null==e?void 0:e.video});return r.forEach((r=>{if(r.mediaStreamTrack.addEventListener("ended",(()=>{r.unpublish()}),{once:!0}),r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof Ic){r.setLabel(u.ScreenVideo),r.setEncoderConfig(t.encoderConfig);const e=Ja.getVideoTrackTransformParams(r.mediaStreamTrack);return r.setTransformParams(e),this.media.setTrack(r),void this.logger.debug("createScreenMediaTrack()",{trackParams:t,transformParams:e,track:r})}r.setLabel(u.ScreenAudio),(null==e?void 0:e.audioEncoderConfig)&&r.setEncoderConfig(e.audioEncoderConfig),this.media.setTrack(r),this.logger.debug("createScreenMediaTrack()",{trackParams:null==e?void 0:e.audio,encoderConfig:null==e?void 0:e.audioEncoderConfig,track:r})})),r}catch(e){throw this.logger.error("createScreenMediaTrack()",{error:e,trackParams:t}),new Error(`Can not create screen media tracks: ${e.message}`)}}))}deleteTrack(e){return this.media.deleteTrack(e)}get channelId(){return this.channel}get appId(){return this.app}get canUseNoiseSuppression(){return this.media.isNoiseSuppressorLoaded}setActiveSpeakerPeer(e){this.activeSpeaker!==e&&(this.activeSpeakerPeer=e,this.clientEventEmitter.safeEmit(U,{peer:e}))}getNodeActiveStreamsStat(){var e;const t=this.network.socket.getServerUrl(),r=this.hostPeers.filter((e=>{var t;return e.id!==(null===(t=this.myPeer)||void 0===t?void 0:t.id)})).reduce(((e,t)=>e+t.getActiveTracksCount()),0);return{node:t,inboundActiveStreams:r,outboundActiveStreams:(null===(e=this.myPeer)||void 0===e?void 0:e.getActivePublishersCount())||0}}connectToSocketServerWithRetry(e){return r(this,void 0,void 0,(function*(){return Ac((()=>r(this,void 0,void 0,(function*(){return this.connectToSocketServer(e)}))),{maxRetries:15,minBackoffDelayMs:150,maxBackoffDelayMs:5e3,actionName:"connectToSocketServer",logger:new Ge({namespace:"RetrySocketConnect",logLevel:this.logLevel}),abortOnError:e=>{var t;return"unauthorized"===(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.errorCode)}})}))}connectToSocketServer(e){return r(this,void 0,void 0,(function*(){const{webSocketUrl:t}=yield this.getAvailableNode({channelId:e.channelId,role:e.role});this.network.socket.connect(t,e.token);try{yield this.waitForSocketConnection()}catch(r){throw this.logger.error("Failed to connect to socket server",{error:r,role:e.role,channelId:e.channelId,webSocketUrl:t}),this.network.socket.disconnect(),r}}))}getAvailableNode(e){return r(this,void 0,void 0,(function*(){try{return{webSocketUrl:(yield this.network.loadBalancerClient.getNode(e)).webSocketUrl}}catch(e){throw this.logger.error("getAvailableNode()",{error:"No available nodes"}),e}}))}waitForSocketConnection(){return new Promise(((e,t)=>{const i=s=>r(this,void 0,void 0,(function*(){const{error:r,state:n}=s,o=()=>this.network.socket.observer.removeListener(Ha.State,i),a=[Ha.Disconnected,Ha.Reconnecting].includes(n);return r?(o(),void t(r)):this.isChannelJoining&&a?(o(),void t(new Error(`Not expected socket state for new connection: ${n}`))):void(this.isChannelJoining&&[Ha.Connected,Ha.Reconnected].includes(n)&&(o(),e()))}));this.network.socket.observer.on(Ha.State,i)}))}performJoin(e){return r(this,void 0,void 0,(function*(){try{const{appId:t,channelId:r}=yield this.sendJoinChannelRequestWithRetry(e);this.app=t,this.channel=r,yield this.initialize(),this.channelEventsHandler.subscribeToEvents(),this.mediaSoupEventsHandler.subscribeToEvents(),this.isJoined=!0,this.logger.debug("Successfully joined channel",{channelId:r}),yield Promise.all([this.createAudioObserver(),this.createGeneralDataConsumer(),this.createChannelStateSyncDataConsumer()])}catch(e){throw this.logger.error("performJoin()",{error:e}),e}}))}sendJoinChannelRequestWithRetry(e){return r(this,void 0,void 0,(function*(){return Ac((()=>r(this,void 0,void 0,(function*(){return this.sendJoinChannelRequest(e)}))),{maxRetries:3,minBackoffDelayMs:300,actionName:"sendJoinChannelRequest",logger:new Ge({namespace:"RetryJoin",logLevel:this.logLevel})})}))}sendJoinChannelRequest(e){return r(this,void 0,void 0,(function*(){return this.network.socket.request(b,e)}))}get cahPublish(){var e;return"host"===(null===(e=this.peers.find((e=>e.isMe)))||void 0===e?void 0:e.role)}get myPeer(){return this.peers.find((e=>e.isMe))}watchClientEvents(){this.clientEventEmitter.on(W,(e=>r(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.clientEventEmitter.on(V,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.close(),this.media.deleteTrack(e)})),this.clientEventEmitter.on(z,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.pause()})),this.clientEventEmitter.on($,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.resume()})),this.clientEventEmitter.on(G,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.close()})),this.clientEventEmitter.on(H,(e=>r(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)}))))}createSelfPeerTrack(e){var t;return r(this,void 0,void 0,(function*(){const r=this.peersRepository.get(this.mySocketId);if(!r)return;yield null===(t=r.tracks.get(e.getLabel()))||void 0===t?void 0:t.close();const i=new Ta({mediaStreamTrack:e.mediaStreamTrack,label:e.getLabel(),engine:this,muted:!1,paused:e.isPaused,peerEventEmitter:r.observer});r.tracks.set(i.label,i)}))}createAudioObserver(){var e;return r(this,void 0,void 0,(function*(){if(!this.isJoined)throw new jc("Need to join first");const t={channelId:this.channelId,appId:this.appId,peerId:null===(e=this.myPeer)||void 0===e?void 0:e.id};try{const{producerId:e}=yield this.network.getAudioObserverProducer(),r=yield this.network.createDataConsumer({producerId:e,appId:this.appId,channelId:this.channelId});r.on("message",this.handleChannelAudioObserverEvent),this.audioObserver=r,this.logger.debug("Successfully create audio observer",t)}catch(e){this.logger.error("Failed to create audio observer",t)}}))}createGeneralDataConsumer(){var e;return r(this,void 0,void 0,(function*(){if(!this.isJoined)throw new jc("Need to join first");const t={channelId:this.channelId,appId:this.appId,peerId:null===(e=this.myPeer)||void 0===e?void 0:e.id};try{const{producerId:e}=yield this.network.getGeneralDataProducer();this.generalDataConsumer=yield this.network.createDataConsumer({producerId:e,appId:this.appId,channelId:this.channelId,ordered:!0}),this.generalDataConsumer.on("message",this.handleDataChannelEvent),this.logger.debug("Successfully created general data consumer",Object.assign(Object.assign({},t),{producerId:e}))}catch(e){this.logger.error("Failed to create general data consumer",Object.assign(Object.assign({},t),{error:e}))}}))}createChannelStateSyncDataConsumer(){var e;return r(this,void 0,void 0,(function*(){if(!this.isJoined)throw new jc("Need to join first");const t={channelId:this.channelId,appId:this.appId,peerId:null===(e=this.myPeer)||void 0===e?void 0:e.id};try{const{producerId:e}=yield this.network.getChannelStateSyncDataProducer();this.channelStateSyncDataConsumer=yield this.network.createDataConsumer({producerId:e,appId:this.appId,channelId:this.channelId}),this.channelStateSyncDataConsumer.on("message",this.handleChannelStateSyncEvent),this.logger.debug("Successfully created ChannelStateSyncDataConsumer",t)}catch(e){this.logger.error("Failed to create ChannelStateSyncDataConsumer",Object.assign(Object.assign({},t),{error:e}))}}))}triggerRejoinEventIfAppropriate(e){this.rejoinRequested&&!this.isChannelJoining||(this.logger.debug("Triggering channel rejoin required event",{reason:e}),this.rejoinRequested=!0,this.clientEventEmitter.emit(j))}}var Nc,Bc,Uc;function qc(){}function Wc(){Wc.init.call(this)}function Vc(e){return void 0===e._maxListeners?Wc.defaultMaxListeners:e._maxListeners}function zc(e,t,r){if(t)e.call(r);else for(var i=e.length,s=Yc(e,i),n=0;n<i;++n)s[n].call(r)}function $c(e,t,r,i){if(t)e.call(r,i);else for(var s=e.length,n=Yc(e,s),o=0;o<s;++o)n[o].call(r,i)}function Gc(e,t,r,i,s){if(t)e.call(r,i,s);else for(var n=e.length,o=Yc(e,n),a=0;a<n;++a)o[a].call(r,i,s)}function Hc(e,t,r,i,s,n){if(t)e.call(r,i,s,n);else for(var o=e.length,a=Yc(e,o),c=0;c<o;++c)a[c].call(r,i,s,n)}function Jc(e,t,r,i){if(t)e.apply(r,i);else for(var s=e.length,n=Yc(e,s),o=0;o<s;++o)n[o].apply(r,i)}function Kc(e,t,r,i){var s,n,o,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((n=e._events)?(n.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),n=e._events),o=n[t]):(n=e._events=new qc,e._eventsCount=0),o){if("function"==typeof o?o=n[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),!o.warned&&(s=Vc(e))&&s>0&&o.length>s){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,"function"==typeof console.warn?console.warn(a):console.log(a)}}else o=n[t]=r,++e._eventsCount;return e}function Qc(e,t,r){var i=!1;function s(){e.removeListener(t,s),i||(i=!0,r.apply(e,arguments))}return s.listener=r,s}function Xc(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Yc(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}qc.prototype=Object.create(null),Wc.EventEmitter=Wc,Wc.usingDomains=!1,Wc.prototype.domain=void 0,Wc.prototype._events=void 0,Wc.prototype._maxListeners=void 0,Wc.defaultMaxListeners=10,Wc.init=function(){this.domain=null,Wc.usingDomains&&(void 0).active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new qc,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Wc.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},Wc.prototype.getMaxListeners=function(){return Vc(this)},Wc.prototype.emit=function(e){var t,r,i,s,n,o,a,c="error"===e;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var d=new Error('Uncaught, unspecified "error" event. ('+t+")");throw d.context=t,d}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=o[e]))return!1;var l="function"==typeof r;switch(i=arguments.length){case 1:zc(r,l,this);break;case 2:$c(r,l,this,arguments[1]);break;case 3:Gc(r,l,this,arguments[1],arguments[2]);break;case 4:Hc(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(i-1),n=1;n<i;n++)s[n-1]=arguments[n];Jc(r,l,this,s)}return!0},Wc.prototype.addListener=function(e,t){return Kc(this,e,t,!1)},Wc.prototype.on=Wc.prototype.addListener,Wc.prototype.prependListener=function(e,t){return Kc(this,e,t,!0)},Wc.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,Qc(this,e,t)),this},Wc.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,Qc(this,e,t)),this},Wc.prototype.removeListener=function(e,t){var r,i,s,n,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(r=i[e]))return this;if(r===t||r.listener&&r.listener===t)0==--this._eventsCount?this._events=new qc:(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(s=-1,n=r.length;n-- >0;)if(r[n]===t||r[n].listener&&r[n].listener===t){o=r[n].listener,s=n;break}if(s<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new qc,this;delete i[e]}else!function(e,t){for(var r=t,i=r+1,s=e.length;i<s;r+=1,i+=1)e[r]=e[i];e.pop()}(r,s);i.removeListener&&this.emit("removeListener",e,o||t)}return this},Wc.prototype.off=function(e,t){return this.removeListener(e,t)},Wc.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new qc,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new qc:delete r[e]),this;if(0===arguments.length){for(var i,s=Object.keys(r),n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=new qc,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},Wc.prototype.listeners=function(e){var t,r=this._events;return r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[]},Wc.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Xc.call(e,t)},Wc.prototype.listenerCount=Xc,Wc.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class Zc extends Wc{}!function(e){e.Issue="issue",e.NetworkScoresUpdated="network-scores-updated",e.StatsParsingFinished="stats-parsing-finished"}(Nc||(Nc={})),function(e){e.Network="network",e.CPU="cpu",e.Server="server",e.Stream="stream"}(Bc||(Bc={})),function(e){e.OutboundNetworkQuality="outbound-network-quality",e.InboundNetworkQuality="inbound-network-quality",e.OutboundNetworkMediaLatency="outbound-network-media-latency",e.InboundNetworkMediaLatency="inbound-network-media-latency",e.NetworkMediaSyncFailure="network-media-sync-failure",e.OutboundNetworkThroughput="outbound-network-throughput",e.InboundNetworkThroughput="inbound-network-throughput",e.EncoderCPUThrottling="encoder-cpu-throttling",e.DecoderCPUThrottling="decoder-cpu-throttling",e.ServerIssue="server-issue",e.UnknownVideoDecoderIssue="unknown-video-decoder",e.LowInboundMOS="low-inbound-mean-opinion-score",e.LowOutboundMOS="low-outbound-mean-opinion-score"}(Uc||(Uc={}));class ed extends Wc{static STATS_REPORT_READY_EVENT="stats-report-ready";static STATS_REPORTS_PARSED="stats-reports-parsed";isStopped=!1;reportTimer;getStatsInterval;compositeStatsParser;constructor(e){super(),this.compositeStatsParser=e.compositeStatsParser,this.getStatsInterval=e.getStatsInterval??1e4}get isRunning(){return!!this.reportTimer&&!this.isStopped}startReporting(){if(this.reportTimer)return;const e=()=>setTimeout((()=>{this.isStopped?this.reportTimer=void 0:this.parseReports().finally((()=>{this.reportTimer=e()}))}),this.getStatsInterval);this.isStopped=!1,this.reportTimer=e()}stopReporting(){this.isStopped=!0,this.reportTimer&&(clearTimeout(this.reportTimer),this.reportTimer=void 0)}async parseReports(){const e=Date.now(),t=await this.compositeStatsParser.parse(),r=Date.now()-e;this.emit(ed.STATS_REPORTS_PARSED,{timeTaken:r}),t.forEach((e=>{this.emit(ed.STATS_REPORT_READY_EVENT,e)}))}}const td=(()=>{const e=new Map;return t=>{const{taskId:r,delayMs:i,maxJitterMs:s,callback:n}=t,o=Math.ceil(Math.random()*(s||0)),a=e.get(r);a&&clearTimeout(a);const c=setTimeout((()=>{n(),e.delete(r)}),i+o);e.set(r,c)}})();class rd{#e={};calculate(e){const{connection:{id:t}}=e,{mos:r,stats:i}=this.calculateOutboundScore(e)||{},{mos:s,stats:n}=this.calculateInboundScore(e)||{};return this.#e[t]=e,td({taskId:t,delayMs:35e3,callback:()=>delete this.#e[t]}),{outbound:r,inbound:s,statsSamples:{inboundStatsSample:n,outboundStatsSample:i}}}calculateOutboundScore(e){const t=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!t.length)return;const r=this.#e[e.connection.id];if(!r)return;const i=[...r.remote?.audio.inbound||[],...r.remote?.video.inbound||[]],{packetsSent:s}=e.connection,n=r.connection.packetsSent,o=t.reduce(((e,t)=>{const r=i.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=c/t.length,l=s-n,p=o.packetsLost-o.lastPacketsLost,u=l&&p?Math.round(100*p/(l+p)):0;return{mos:this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:u}),stats:{avgJitter:d,rtt:a,packetsLoss:u}}}calculateInboundScore(e){const t=[...e.audio?.inbound,...e.video?.inbound];if(!t.length)return;const r=this.#e[e.connection.id];if(!r)return;const i=[...r.video?.inbound,...r.audio?.inbound],{packetsReceived:s}=e.connection,n=r.connection.packetsReceived,o=t.reduce(((e,t)=>{const r=i.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=c/t.length,l=s-n,p=o.packetsLost-o.lastPacketsLost,u=l&&p?Math.round(100*p/(l+p)):0;return{mos:this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:u}),stats:{avgJitter:d,rtt:a,packetsLoss:u}}}calculateMOS({avgJitter:e,rtt:t,packetsLoss:r}){const i=t+2*e+10;let s=i<160?93.2-i/40:93.2-i/120-10;return s-=2.5*r,1+.035*s+7e-6*s*(s-60)*(100-s)}}class id{#e;#t;constructor(e={}){this.#e=new Map,this.#t=e.statsCleanupTtlMs??35e3}detect(e){const t=this.performDetection(e);return this.performPrevStatsCleanup({connectionId:e.connection.id}),t}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:r}=e;this.#e.has(t)&&td({taskId:t,delayMs:this.#t,callback:()=>{this.deleteLastProcessedStats(t),"function"==typeof r&&r()}})}setLastProcessedStats(e,t){this.#e.set(e,t)}getLastProcessedStats(e){return this.#e.get(e)}deleteLastProcessedStats(e){this.#e.delete(e)}}class sd extends id{#r;constructor(e={}){super(e),this.#r=e.availableOutgoingBitrateThreshold??1e5}performDetection(e){const t=[],{availableOutgoingBitrate:r}=e.connection;if(void 0===r)return t;const i=e.audio.outbound.reduce(((e,t)=>e+t.targetBitrate),0),s=e.video.outbound.reduce(((e,t)=>e+t.bitrate),0);if(!i&&!s)return t;const n={availableOutgoingBitrate:r,videoStreamsTotalBitrate:s,audioStreamsTotalTargetBitrate:i};return i>r||s>0&&r<this.#r?(t.push({statsSample:n,type:Bc.Network,reason:Uc.OutboundNetworkThroughput}),t):t}}class nd extends id{#i;constructor(e={}){super(e),this.#i=e.framesDroppedThreshold??.5}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=e.video.inbound.filter((e=>e.framesDropped>0)),r=[],i=this.getLastProcessedStats(e.connection.id)?.video.inbound;return i?(t.forEach((e=>{const t=i.find((t=>t.ssrc===e.ssrc));if(!t)return;if(e.framesDropped===t.framesDropped)return;const s=e.framesReceived-t.framesReceived,n=e.framesDecoded-t.framesDecoded,o=e.framesDropped-t.framesDropped,a=o/s;if(0===s||0===n)return;const c={deltaFramesDropped:o,deltaFramesReceived:s,deltaFramesDecoded:n,framesDroppedPct:Math.round(100*a)};a>=this.#i&&r.push({statsSample:c,type:Bc.CPU,reason:Uc.DecoderCPUThrottling,ssrc:e.ssrc})})),r):r}}class od extends id{#s;constructor(e={}){super(e),this.#s=e.missedFramesThreshold??.15}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=e.video.outbound.filter((e=>e.framesEncoded>0)),r=[],i=this.getLastProcessedStats(e.connection.id)?.video.outbound;return i?(t.forEach((e=>{const t=i.find((t=>t.ssrc===e.ssrc));if(!t)return;if(e.framesEncoded===t.framesEncoded)return;const s=e.framesEncoded-t.framesEncoded,n=e.framesSent-t.framesSent,o=1-n/s;if(0===s)return;if(s===n)return;const a={deltaFramesSent:n,deltaFramesEncoded:s,missedFramesPct:Math.round(100*o)};o>=this.#s&&r.push({statsSample:a,type:Bc.Network,reason:Uc.OutboundNetworkThroughput,ssrc:e.ssrc})})),r):r}}class ad extends id{highPacketLossThresholdPct;highJitterThreshold;highJitterBufferDelayThresholdMs;highRttThresholdMs;constructor(e={}){super(),this.highPacketLossThresholdPct=e.highPacketLossThresholdPct??5,this.highJitterThreshold=e.highJitterThreshold??200,this.highJitterBufferDelayThresholdMs=e.highJitterBufferDelayThresholdMs??500,this.highRttThresholdMs=e.highRttThresholdMs??250}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=[],r=[...e.audio?.inbound,...e.video?.inbound];if(!r.length)return t;const i=this.getLastProcessedStats(e.connection.id);if(!i)return t;const s=[...i.video?.inbound,...i.audio?.inbound],{packetsReceived:n}=e.connection,o=i.connection.packetsReceived,a=r.reduce(((e,t)=>{const r=s.find((e=>e.ssrc===t.ssrc)),i=r?.jitterBufferDelay||0,n=r?.jitterBufferEmittedCount||0,o=t.jitterBufferDelay-i,a=t.jitterBufferEmittedCount-n,c=o&&a?1e3*o/a:0;return{sumJitter:e.sumJitter+t.jitter,sumJitterBufferDelayMs:e.sumJitterBufferDelayMs+c,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,sumJitterBufferDelayMs:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:d,sumJitterBufferDelayMs:l}=a,p=d/r.length,u=l/r.length,h=n-o,f=a.packetsLost-a.lastPacketsLost,m=h&&f?Math.round(100*f/(h+f)):0,g=m>this.highPacketLossThresholdPct,v=p>=this.highJitterThreshold,y=c>=this.highRttThresholdMs,b=u>this.highJitterBufferDelayThresholdMs,w=y&&!v&&!g,S=g&&v,_=v&&b,R={rtt:c,packetLossPct:m,avgJitter:p,avgJitterBufferDelay:u};return(v||g)&&t.push({statsSample:R,type:Bc.Network,reason:Uc.InboundNetworkQuality,iceCandidate:e.connection.local.id}),w&&t.push({statsSample:R,type:Bc.Server,reason:Uc.ServerIssue,iceCandidate:e.connection.remote.id}),S&&t.push({statsSample:R,type:Bc.Network,reason:Uc.InboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),_&&t.push({statsSample:R,type:Bc.Network,reason:Uc.NetworkMediaSyncFailure,iceCandidate:e.connection.local.id}),t}}class cd extends id{performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=e.audio.inbound,r=[],i=this.getLastProcessedStats(e.connection.id)?.audio.inbound;return i?(t.forEach((e=>{const t=i.find((t=>t.ssrc===e.ssrc));if(!t)return;const s=e.track.insertedSamplesForDeceleration+e.track.removedSamplesForAcceleration,n=t.track.insertedSamplesForDeceleration+t.track.removedSamplesForAcceleration;if(s===n)return;const o=e.track.totalSamplesReceived-t.track.totalSamplesReceived,a=s-n,c=Math.round(100*a/o),d={correctedSamplesPct:c};c>5&&r.push({statsSample:d,type:Bc.Network,reason:Uc.NetworkMediaSyncFailure,ssrc:e.ssrc})})),r):r}}class dd extends id{performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=[],r=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!r.length)return t;const i=this.getLastProcessedStats(e.connection.id);if(!i)return t;const s=[...i.remote?.audio.inbound||[],...i.remote?.video.inbound||[]],{packetsSent:n}=e.connection,o=i.connection.packetsSent,a=r.reduce(((e,t)=>{const r=s.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:d}=a,l=d/r.length,p=n-o,u=a.packetsLost-a.lastPacketsLost,h=p&&u?Math.round(100*u/(p+u)):0,f=h>5,m=l>=200,g=!f&&m||m||f,v={rtt:c,avgJitter:l,packetLossPct:h};return f&&m&&t.push({statsSample:v,type:Bc.Network,reason:Uc.OutboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),g&&t.push({statsSample:v,type:Bc.Network,reason:Uc.OutboundNetworkQuality,iceCandidate:e.connection.local.id}),t}}class ld extends id{performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=e.video.outbound.filter((e=>"none"!==e.qualityLimitationReason)),r=[],i=this.getLastProcessedStats(e.connection.id)?.video.outbound;return i?(t.forEach((e=>{const t=i.find((t=>t.ssrc===e.ssrc));if(!t)return;const s={qualityLimitationReason:e.qualityLimitationReason};e.framesSent>t.framesSent||("cpu"===e.qualityLimitationReason&&r.push({statsSample:s,type:Bc.CPU,reason:Uc.EncoderCPUThrottling,ssrc:e.ssrc}),"bandwidth"===e.qualityLimitationReason&&r.push({statsSample:s,type:Bc.Network,reason:Uc.OutboundNetworkThroughput,ssrc:e.ssrc}))})),r):r}}class pd extends id{UNKNOWN_DECODER="unknown";#n={};performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:r}=e;super.performPrevStatsCleanup({...e,cleanupCallback:()=>{delete this.#n[t],"function"==typeof r&&r()}})}processData(e){const t=[],{id:r}=e.connection,i=this.getLastProcessedStats(r)?.video.inbound;return e.video.inbound.forEach((e=>{const{decoderImplementation:s,ssrc:n}=e,o=i?.find((e=>e.ssrc===n));if(o)if(s===this.UNKNOWN_DECODER){if(!this.hadLastDecoderWithIssue(r,n)){this.setLastDecoderWithIssue(r,n,this.UNKNOWN_DECODER);const i={mimeType:e.mimeType,decoderImplementation:s};t.push({ssrc:n,statsSample:i,type:Bc.Stream,reason:Uc.UnknownVideoDecoderIssue,trackIdentifier:e.track.trackIdentifier})}}else this.setLastDecoderWithIssue(r,n,void 0)})),t}setLastDecoderWithIssue(e,t,r){const i=this.#n[e]??{};void 0===r?delete i[t]:i[t]=r,this.#n[e]=i}hadLastDecoderWithIssue(e,t){const r=this.#n[e];return(r&&r[t])===this.UNKNOWN_DECODER}}const ud=e=>"closed"===e.iceConnectionState||"closed"===e.connectionState,hd=(e,t,r)=>8*((e,t,r)=>{if(!t)return 0;const i=e[r],s=t[r];if(null==i||null==s)return 0;const n=Math.floor(e.timestamp)-Math.floor(t.timestamp);return 0===n?0:(Number(i)-Number(s))/n*1e3})(e,t,r);class fd{connections=[];statsParser;constructor(e){this.statsParser=e.statsParser}listConnections(){return[...this.connections]}addPeerConnection(e){this.connections.push({id:e.id??String(Date.now()+Math.random().toString(32)),pc:e.pc})}removePeerConnection(e){const t=this.connections.findIndex((({pc:t})=>t===e.pc));t>=0&&this.removeConnectionsByIndexes([t])}async parse(){const e=[],t=this.connections.map((async(t,r)=>{if(!ud(t.pc))return this.statsParser.parse(t);e.unshift(r)}));return e.length&&this.removeConnectionsByIndexes(e),(await Promise.all(t)).filter((e=>void 0!==e))}removeConnectionsByIndexes(e){e.forEach((e=>{this.connections.splice(e,1)}))}}class md{prevStats=new Map;allowedReportTypes=new Set(["candidate-pair","inbound-rtp","outbound-rtp","remote-outbound-rtp","remote-inbound-rtp","track","transport"]);ignoreSSRCList;logger;constructor(e){this.ignoreSSRCList=e.ignoreSSRCList??[],this.logger=e.logger}get previouslyParsedStatsConnectionsIds(){return[...this.prevStats.keys()]}async parse(e){if(!ud(e.pc))return this.getConnectionStats(e);this.logger.debug("Skip stats parsing. Connection is closed.",{connection:e})}async getConnectionStats(e){const{pc:t,id:r}=e;try{const i=Date.now(),s=t.getReceivers().filter((e=>e.track?.enabled)),n=t.getSenders().filter((e=>e.track?.enabled)),o=await Promise.all(s.map((e=>e.getStats()))),a=await Promise.all(n.map((e=>e.getStats())));return{id:r,stats:this.mapReportsStats([...o,...a],e),timeTaken:Date.now()-i}}catch(e){return void this.logger.error("Failed to get stats for PC",{id:r,pc:t,error:e})}}mapReportsStats(e,t){const r={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{},remote:{video:{inbound:[],outbound:[]},audio:{inbound:[],outbound:[]}}};e.forEach((e=>{e.forEach((t=>{this.allowedReportTypes.has(t.type)&&this.updateMappedStatsWithReportItemData(t,r,e)}))}));const{id:i}=t,s=this.prevStats.get(i);return s&&this.propagateStatsWithRateValues(r,s.stats),this.prevStats.set(i,{stats:r,ts:Date.now()}),td({taskId:i,delayMs:35e3,callback:()=>this.prevStats.delete(i)}),r}updateMappedStatsWithReportItemData(e,t,r){const i=e.type;if("candidate-pair"===i&&"succeeded"===e.state&&e.nominated)return void(t.connection=this.prepareConnectionStats(e,r));const s=this.getMediaType(e);if(!s)return;const n=e.ssrc;if(!n||!this.ignoreSSRCList.includes(n))if("outbound-rtp"!==i)if("inbound-rtp"!==i)"remote-outbound-rtp"!==i?"remote-inbound-rtp"===i&&(this.mapConnectionStatsIfNecessary(t,e,r),t.remote[s].inbound.push({...e})):t.remote[s].outbound.push({...e});else{const i=r.get(e.trackId)||r.get(e.mediaSourceId)||{};this.mapConnectionStatsIfNecessary(t,e,r);const n={...e,track:{...i}};t[s].inbound.push(n)}else{const i=r.get(e.trackId)||r.get(e.mediaSourceId)||{},n={...e,track:{...i}};t[s].outbound.push(n)}}getMediaType(e){const t=e.mediaType||e.kind;if(!["audio","video"].includes(t)){const{id:t}=e;if(!t)return;return String(t).includes("Video")?"video":String(t).includes("Audio")?"audio":void 0}return t}propagateStatsWithRateValues(e,t){e.audio.inbound.forEach((e=>{const r=t.audio.inbound.find((({id:t})=>t===e.id));e.bitrate=hd(e,r,"bytesReceived"),e.packetRate=hd(e,r,"packetsReceived")})),e.audio.outbound.forEach((e=>{const r=t.audio.outbound.find((({id:t})=>t===e.id));e.bitrate=hd(e,r,"bytesSent"),e.packetRate=hd(e,r,"packetsSent")})),e.video.inbound.forEach((e=>{const r=t.video.inbound.find((({id:t})=>t===e.id));e.bitrate=hd(e,r,"bytesReceived"),e.packetRate=hd(e,r,"packetsReceived")})),e.video.outbound.forEach((e=>{const r=t.video.outbound.find((({id:t})=>t===e.id));e.bitrate=hd(e,r,"bytesSent"),e.packetRate=hd(e,r,"packetsSent")}))}mapConnectionStatsIfNecessary(e,t,r){if(e.connection.id||!t.transportId)return;const i=r.get(t.transportId);if(i&&i.selectedCandidatePairId){const t=r.get(i.selectedCandidatePairId);e.connection=this.prepareConnectionStats(t,r)}}prepareConnectionStats(e,t){if(!e||!t)return{};const r={...e};if(r.remoteCandidateId){const e=t.get(r.remoteCandidateId);r.remote={...e}}if(r.localCandidateId){const e=t.get(r.localCandidateId);r.local={...e}}return r}}class gd{eventEmitter;#o=!1;detectors=[];networkScoresCalculator;statsReporter;compositeStatsParser;logger;constructor(e){this.logger=e.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.eventEmitter=e.issueEmitter??new Zc,e.onIssues&&this.eventEmitter.on(Nc.Issue,e.onIssues),e.onNetworkScoresUpdated&&this.eventEmitter.on(Nc.NetworkScoresUpdated,e.onNetworkScoresUpdated),this.detectors=e.detectors??[new ld,new nd,new od,new ad,new dd,new cd,new sd,new pd],this.networkScoresCalculator=e.networkScoresCalculator??new rd,this.compositeStatsParser=e.compositeStatsParser??new fd({statsParser:new md({ignoreSSRCList:e.ignoreSSRCList,logger:this.logger})}),this.statsReporter=e.statsReporter??new ed({compositeStatsParser:this.compositeStatsParser,getStatsInterval:e.getStatsInterval??5e3}),window.wid=this,this.wrapRTCPeerConnection(),this.statsReporter.on(ed.STATS_REPORT_READY_EVENT,(e=>{this.detectIssues({data:e.stats}),this.calculateNetworkScores(e.stats)})),this.statsReporter.on(ed.STATS_REPORTS_PARSED,(e=>{const t={timeTaken:e.timeTaken,ts:Date.now()};this.eventEmitter.emit(Nc.StatsParsingFinished,t)}))}watchNewPeerConnections(){this.#o?this.logger.warn("WebRTCIssueDetector is already started. Skip processing"):(this.logger.info("Start watching peer connections"),this.#o=!0,this.statsReporter.startReporting())}stopWatchingNewPeerConnections(){this.#o?(this.logger.info("Stop watching peer connections"),this.#o=!1,this.statsReporter.stopReporting()):this.logger.warn("WebRTCIssueDetector is already stopped. Skip processing")}handleNewPeerConnection(e){this.#o?(this.logger.debug("Handling new peer connection",e),this.compositeStatsParser.addPeerConnection({pc:e})):this.logger.debug("Skip handling new peer connection. Detector is not running",e)}emitIssues(e){this.eventEmitter.emit(Nc.Issue,e)}detectIssues({data:e}){const t=this.detectors.reduce(((t,r)=>[...t,...r.detect(e)]),[]);t.length>0&&this.emitIssues(t)}calculateNetworkScores(e){const t=this.networkScoresCalculator.calculate(e);this.eventEmitter.emit(Nc.NetworkScoresUpdated,t)}wrapRTCPeerConnection(){if(!window.RTCPeerConnection)return void this.logger.warn("No RTCPeerConnection found in browser window. Skipping");const e=window.RTCPeerConnection,t=e=>this.handleNewPeerConnection(e);function r(r){const i=new e(r);return t(i),i}r.prototype=e.prototype,window.RTCPeerConnection=r}}Error;const vd=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0}],yd=({from:e,seen:t,to_:r,forceEnumerable:i})=>{const s=r||(Array.isArray(e)?[]:{});t.push(e);for(const[r,n]of Object.entries(e))"function"!=typeof n&&(n&&"object"==typeof n?t.includes(e[r])?s[r]="[Circular]":s[r]=yd({from:e[r],seen:t.slice(),forceEnumerable:i}):s[r]=n);for(const{property:t,enumerable:r}of vd)"string"==typeof e[t]&&Object.defineProperty(s,t,{value:e[t],enumerable:!!i||r,configurable:!0,writable:!0});return s};var bd=e=>"object"==typeof e&&null!==e?yd({from:e,seen:[],forceEnumerable:!0}):"function"==typeof e?`[Function: ${e.name||"anonymous"}]`:e;class wd{constructor(e){var t;this.preferRelay=!1;const{socketClient:r,loadBalancerApiClient:i,onLogMessage:s}=e;this.socket=r,this.loadBalancerClient=i,this.eventEmitter=null!==(t=e.eventEmitter)&&void 0!==t?t:new n,this.logger=new Ge({namespace:"Network",logLevel:e.logLevel,onLogMessage:s})}removeEventListeners(){const{sendTransport:e,receiveTransport:t}=this;if(e){["connect","produce","connectionstatechange"].forEach((t=>e.removeAllListeners(t)))}if(t){["connect","produce","connectionstatechange"].forEach((e=>t.removeAllListeners(e)))}}reset(){return r(this,void 0,void 0,(function*(){this.stopRestartIceAtempts(),this.removeEventListeners()}))}closeRemoteProducer(e){return r(this,void 0,void 0,(function*(){yield this.socket.request(oe,{peerId:this.socket.id,producerId:e})}))}closeSendTransport(){var e;return r(this,void 0,void 0,(function*(){this.sendTransport?((null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&(yield this.closeTransport(this.sendTransport)),this.sendTransport.close(),this.sendTransport=void 0):this.logger.warn("closeSendTransport()",{message:"No available send transport"})}))}closeReceiveTransport(){var e;return r(this,void 0,void 0,(function*(){this.receiveTransport?((null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&(yield this.closeTransport(this.receiveTransport)),this.receiveTransport.close(),this.receiveTransport=void 0):this.logger.warn("closeReceiveTransport()",{message:"No available receive transport"})}))}closeTransport(e){return r(this,void 0,void 0,(function*(){try{const{success:t}=yield this.socket.request(Ce,{transportId:e.id});return this.logger.debug("closeTransport()",{transport:e}),Boolean(t)}catch(e){return this.logger.error("closeTransport()",{error:e}),!1}}))}createSendTransport(e){return r(this,void 0,void 0,(function*(){if(this.sendTransport)return void this.logger.warn("createSendTransport()",{message:"Send transport already exists"});const t=yield this.socket.request(ke,{sctpCapabilities:e.sctpCapabilities,localDirection:"send"}),i=e.createSendTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));this.logger.debug("createSendTransport()",{transport:i}),i.on("connect",(({dtlsParameters:e},s,n)=>r(this,void 0,void 0,(function*(){try{yield this.socket.request(Pe,{transportId:i.id,dtlsParameters:e}),s(),this.logger.debug("sendTransport.connect()",{transportId:i.id,dtlsRole:e.role}),setTimeout((()=>this.logTransportDetails(i)),1500)}catch(r){this.logger.error("sendTransport.on(`connect`)",{dtlsParameters:e,sendTransportOptions:t,error:r}),n(r)}})))),i.on("produce",((e,t,s)=>r(this,void 0,void 0,(function*(){try{const{id:r}=yield this.socket.request(Te,{transportId:i.id,kind:e.kind,rtpParameters:e.rtpParameters,appData:e.appData});t({id:r}),this.logger.debug("sendTransport.produce()",{producerId:r,transportId:i.id,kind:e.kind})}catch(t){this.logger.error("sendTransport.produce()",{error:t,transportId:i.id,kind:e.kind}),s(t)}})))),i.on("connectionstatechange",(e=>{if(this.logger.info("sendTransport.state",{state:e}),["closed","connected"].includes(e))return this.sendTransportRestartIceInterval&&(this.logger.debug("Stop sendTransport.restartIce() retries",{sendTransportId:i.id}),clearInterval(this.sendTransportRestartIceInterval),this.sendTransportRestartIceInterval=void 0),void("connected"===e&&setTimeout((()=>this.logTransportDetails(i)),1500));if(["disconnected","failed"].includes(e)){if(this.sendTransportRestartIceInterval)return;"failed"===e&&(this.logger.debug("sendTransport.restartIce()",{sendTransportId:i.id}),this.restartIce(i)),this.sendTransportRestartIceInterval=setInterval((()=>{this.restartIce(i),this.logger.debug("sendTransport.restartIce() attempt",{sendTransportId:i.id})}),5e3)}})),this.sendTransport=i}))}createRecvTransport(e){return r(this,void 0,void 0,(function*(){if(this.receiveTransport)return void this.logger.warn("createReceiveTransport()",{message:"Receive transport already exists"});const t=yield this.socket.request(ke,{localDirection:"receive"}),i=e.createRecvTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));this.logger.debug("createReceiveTransport()",{transport:i}),i.on("connect",(({dtlsParameters:e},t,s)=>r(this,void 0,void 0,(function*(){try{yield this.socket.request(Pe,{transportId:i.id,dtlsParameters:e}),t(),this.logger.debug("receiveTransport.connect()",{transportId:i.id,dtlsRole:e.role}),setTimeout((()=>this.logTransportDetails(i)),1500)}catch(e){this.logger.error("receiveTransport.on(`connect`)",{error:e}),s(e)}})))),i.on("connectionstatechange",(e=>{if(this.logger.info("receiveTransport.state",{state:e}),["closed","connected"].includes(e))return this.recvTransportRestartIceInterval&&(this.logger.debug("Stop receiveTransport.restartIce() retries",{recvTransportId:i.id}),clearInterval(this.recvTransportRestartIceInterval),this.recvTransportRestartIceInterval=void 0),void("connected"===e&&setTimeout((()=>this.logTransportDetails(i)),1500));if(["disconnected","failed"].includes(e)){if(this.recvTransportRestartIceInterval)return;"failed"===e&&(this.logger.debug("receiveTransport.restartIce()",{recvTransportId:i.id}),this.restartIce(i)),this.recvTransportRestartIceInterval=setInterval((()=>{this.restartIce(i),this.logger.debug("receiveTransport.restartIce() attempt",{recvTransportId:i.id})}),5e3)}})),this.receiveTransport=i}))}getIceParameters(e){return r(this,void 0,void 0,(function*(){const t=yield this.socket.request(De,{transportId:e.id}),{error:r}=t;if(r)throw new Error(r);const{iceParameters:i}=t;return this.logger.debug("getIceParameters()",{iceParameters:i}),i}))}restartIce(e){return r(this,void 0,void 0,(function*(){try{const t=yield this.getIceParameters(e);yield e.restartIce({iceParameters:t}),this.logger.info("restartIce completed",{iceParameters:t})}catch(e){this.logger.error("restartIce error",{error:e})}}))}createConsumer({producerId:e,rtpCapabilities:t,appId:i,channelId:s,producerPeerId:n}){return r(this,void 0,void 0,(function*(){const r=this.receiveTransport;if(!r)throw this.logger.error("createConsumer()",{reason:"missing receive transport"}),new Error("Failed to create consumer");this.logger.debug("createConsumer()",{producerId:e});const o=yield this.socket.request(me,{producerId:e,transportId:r.id,rtpCapabilities:t,appData:{peerId:this.socket.id,appId:i,channelId:s},producerPeerId:n}),a=yield r.consume(o),{producerPaused:c}=o;return this.logger.debug("Consumer created",{consumer:a,isProducerPaused:c}),{consumer:a,isProducerPaused:c}}))}createDataConsumer({producerId:e,appId:t,channelId:i,ordered:s}){return r(this,void 0,void 0,(function*(){const r=this.receiveTransport;if(!r)throw this.logger.error("createDataConsumer()",{reason:"missing receive transport"}),new Error("Failed to create consumer");this.logger.debug("createDataConsumer()",{producerId:e});const n=yield this.socket.request(ge,{ordered:s,dataProducerId:e,transportId:r.id,appData:{peerId:this.socket.id,producerId:e,appId:t,channelId:i}}),o=yield r.consumeData(n);return this.logger.debug("Data consumer created",{consumer:o}),o}))}closeRemoteConsumer(e){return r(this,void 0,void 0,(function*(){return this.socket.request(ve,{peerId:this.socket.id,consumerId:e})}))}resumeRemoteConsumer(e){return r(this,void 0,void 0,(function*(){return this.socket.request(be,{consumerId:e})}))}pauseRemoteConsumer(e){return r(this,void 0,void 0,(function*(){return this.socket.request(ye,{consumerId:e})}))}updatePeerAppData({peerId:e,appData:t}){return r(this,void 0,void 0,(function*(){return this.socket.request(_,{peerId:e,appData:t})}))}getAudioObserverProducer(){return r(this,void 0,void 0,(function*(){return this.socket.request(T)}))}getGeneralDataProducer(){return r(this,void 0,void 0,(function*(){return this.socket.request(E)}))}getChannelStateSyncDataProducer(){return r(this,void 0,void 0,(function*(){return this.socket.request(D)}))}getTransportsStateInfo(){return r(this,void 0,void 0,(function*(){const[e,t]=yield Promise.all([this.getParsedTransportStats(this.receiveTransport),this.getParsedTransportStats(this.sendTransport)]);return{receive:e,send:t}}))}setPreferRelay(e){this.preferRelay=e}getPreferRelay(){return this.preferRelay}getParsedTransportStats(e){return r(this,void 0,void 0,(function*(){if(e)try{const t=Array.from((yield e.getStats()).values()),r=t.find((e=>"local-candidate"===e.type)),i=t.find((e=>"remote-candidate"===e.type)),s=t.find((e=>"transport"===e.type));return{dtlsState:null==s?void 0:s.dtlsState,iceState:null==s?void 0:s.iceState,dtlsRole:null==s?void 0:s.dtlsRole,iceRole:null==s?void 0:s.iceRole,selectedCandidatePairChanges:null==s?void 0:s.selectedCandidatePairChanges,tlsVersion:null==s?void 0:s.tlsVersion,localCandidateState:{ip:null==r?void 0:r.ip,address:null==r?void 0:r.address,port:null==r?void 0:r.port,protocol:null==r?void 0:r.protocol,candidateType:null==r?void 0:r.candidateType},remoteCandidateState:{ip:null==i?void 0:i.ip,address:null==i?void 0:i.address,port:null==i?void 0:i.port,protocol:null==i?void 0:i.protocol,candidateType:null==i?void 0:i.candidateType}}}catch(e){return void this.logger.warn("getParsedTransportStats()",{error:e})}else this.logger.debug("getParsedTransportStats()",{message:"Transport is missing"})}))}logTransportDetails(e){var t,i;return r(this,void 0,void 0,(function*(){let r;try{r=yield e.getStats()}catch(t){return void this.logger.error("Failed to log detailed WebRTC transport stats",{error:bd(t),transportId:e.id,reason:"failed to parse getStats"})}try{const s=[...r],[,n]=null!==(t=s.find((([,e])=>"transport"===(null==e?void 0:e.type))))&&void 0!==t?t:[],[,o]=null!==(i=s.find((([,e])=>"candidate-pair"===e.type&&"succeeded"===e.state&&e.nominated)))&&void 0!==i?i:[],a=r.get(String((null==o?void 0:o.localCandidateId)||"-")),c=r.get(String((null==o?void 0:o.remoteCandidateId)||"-")),d={hasNominatedPair:!!o,transportId:e.id,iceRole:null==n?void 0:n.iceRole,iceState:null==n?void 0:n.iceState,dtlsRole:null==n?void 0:n.dtlsRole,dtlsState:null==n?void 0:n.dtlsState,local:{address:null==a?void 0:a.address,candidateType:null==a?void 0:a.candidateType,foundation:null==a?void 0:a.foundation,networkType:null==a?void 0:a.networkType,isRemote:null==a?void 0:a.isRemote,port:null==a?void 0:a.port,protocol:null==a?void 0:a.protocol,relatedAddress:null==a?void 0:a.relatedAddress,relatedPort:null==a?void 0:a.relatedPort,transportId:null==a?void 0:a.transportId,relayProtocol:null==a?void 0:a.relayProtocol,url:null==a?void 0:a.url},remote:{address:null==c?void 0:c.address,candidateType:null==c?void 0:c.candidateType,foundation:null==c?void 0:c.foundation,isRemote:null==c?void 0:c.isRemote,port:null==c?void 0:c.port,protocol:null==c?void 0:c.protocol,transportId:null==c?void 0:c.transportId}};(null==o?void 0:o.totalRoundTripTime)&&(null==o?void 0:o.responsesReceived)&&(d.pairRoundTripTime=Math.round(o.totalRoundTripTime/o.responsesReceived*1e3)),this.logger.info("Detailed WebRTC transport stats",d)}catch(t){this.logger.error("Failed to log detailed WebRTC transport stats",{error:bd(t),transportId:e.id,reason:"-"})}}))}stopRestartIceAtempts(){clearInterval(this.sendTransportRestartIceInterval),clearInterval(this.recvTransportRestartIceInterval)}}const Sd=e=>![h.NotFoundError,h.NotAllowedError,h.DeviceIsBusy].includes(e);class _d{constructor(e){this.isEnableVideoDevicesLock=!1,this.isEnableAudioDevicesLock=!1,this.isDevicesDetected=!1,this.availableVideoDevices=[],this.availableAudioDevices=[];const{clientEventEmitter:t,logLevel:r,onLogMessage:i}=e;this.clientEventEmitter=t,this.logger=new Ge({namespace:"System",logLevel:r,onLogMessage:i}),this.deviceChangeHandler=this.deviceChangeHandler.bind(this),this.listenDevices()}setIsEnableVideoDevicesLock(e){this.isEnableVideoDevicesLock=e}setIsEnableAudioDevicesLock(e){this.isEnableAudioDevicesLock=e}setAvailableVideoDevices(e){this.availableVideoDevices=e}setAvailableAudioDevices(e){this.availableAudioDevices=e}requestMediaDevicesAccess(e={video:!0,audio:!0}){return r(this,void 0,void 0,(function*(){try{return(yield navigator.mediaDevices.getUserMedia(e)).getTracks()}catch(t){if(this.logger.error("getUserMedia()",{error:t,constraints:e}),"NotAllowedError"===t.name)throw new Error(h.NotAllowedError);if("NotReadableError"===t.name)throw new Error(h.DeviceIsBusy);if("NotFoundError"===t.name)throw new Error(h.NotFoundError);throw new Error(h.RequestDevicesUnknownError)}}))}refreshAvailableMediaDevicesList(){return r(this,void 0,void 0,(function*(){const e=yield navigator.mediaDevices.enumerateDevices(),t=[],r=[];e.forEach((e=>{""!==e.deviceId&&("videoinput"===e.kind&&t.push(e),"audioinput"===e.kind&&r.push(e))})),this.setAvailableVideoDevices(t),this.setAvailableAudioDevices(r);const i=({label:e,kind:t})=>({label:e,kind:t});return this.logger.debug("Devices list updated",{videoDevices:t.map(i),audioDevices:r.map(i)}),e}))}detectDevices(){return r(this,void 0,void 0,(function*(){let e=[];if(this.isDevicesDetected)return;try{e=yield this.requestMediaDevicesAccess()}catch(e){if(Sd(e.message))throw e;e.message!==h.DeviceIsBusy&&(yield this.assertHasAccessToMediaDevices({audio:!0}),yield this.assertHasAccessToMediaDevices({video:!0}))}this.isDevicesDetected=!0;const t=yield this.refreshAvailableMediaDevicesList();e.forEach((e=>e.stop()));const r=t.some((e=>"audioinput"===e.kind)),i=t.some((e=>"videoinput"===e.kind));if(!r&&!i)throw new Error(h.NoDevices)}))}deviceChangeHandler(){return r(this,void 0,void 0,(function*(){this.isDevicesDetected&&(yield this.refreshAvailableMediaDevicesList(),this.clientEventEmitter.safeEmit(F,{audio:this.availableAudioDevices,video:this.availableVideoDevices}))}))}listenDevices(){navigator.mediaDevices.addEventListener("devicechange",this.deviceChangeHandler)}assertHasAccessToMediaDevices(e={video:!0,audio:!0}){return r(this,void 0,void 0,(function*(){try{(yield this.requestMediaDevicesAccess(e)).forEach((e=>e.stop()))}catch(e){if(Sd(e.message))throw e}}))}}class Rd{constructor(e){const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new Ge({logLevel:t.logLevel,namespace:"ChannelEvents",onLogMessage:r})}handleDataChannelEvent(e){try{const{event:t,data:r}=JSON.parse(e);this.doHandleDataChannelEvent(t,r)}catch(t){this.logger.error("Failed to handle data channel event",{error:t,payload:e})}}doHandleDataChannelEvent(e,t){e===_&&this.handlePeerAppDataUpdate(t)}subscribeToEvents(){const{connection:e}=this.engine.network.socket;if(!e)throw this.logger.error("subscribeToEvents()",{error:"Socket connection not initialized"}),new Error("Socket connection not initialized");e.on(y,(e=>{this.engine.clientEventEmitter.safeEmit(M,e),this.logger.debug("New channel event",{event:e})})),e.on(b,(e=>{const t=this.engine.setPeer(e);this.engine.clientEventEmitter.safeEmit(x,t),this.logger.debug("Peer joined to the channel",{peer:t})})),e.on(S,(e=>{this.engine.removePeer(e),this.engine.clientEventEmitter.safeEmit(L,e),this.logger.debug("Peer left the channel",{peerId:e})})),e.on(C,(e=>{this.engine.clientEventEmitter.safeEmit(I,e),this.logger.info("Notify the channel that activity confirmation is required",e)})),e.on(P,(e=>{this.engine.clientEventEmitter.safeEmit(A,e),this.logger.info("Notify the channel that it has disconnected due to the activity confirmation expiring",e)})),e.on(k,(e=>{this.engine.clientEventEmitter.safeEmit(O,e),this.logger.info("Notify the channel that the activity has been acquired.",e)}))}removeEventListeners(){const{connection:e}=this.engine.network.socket;if(!e)return;[y,b,S,C,P,k,_].forEach((t=>e.removeAllListeners(t)))}handlePeerAppDataUpdate({peerId:e,appData:t}){const r=this.engine.peers.find((({id:t})=>t===e));r&&r.observer.emit(_,t)}reset(){this.removeEventListeners()}}class kd{constructor(e){this.queue=new Pa;const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new Ge({logLevel:t.logLevel,namespace:"MediasoupEvents",onLogMessage:r})}subscribeToEvents(){const{connection:e}=this.engine.network.socket;if(!e)throw this.logger.error("subscribeToEvents()",{error:"Socket connection not initialized"}),new Error("Socket connection not initialized");e.on(oe,(e=>{const t=this.engine.peers.find((t=>t.id===e.peerId));t&&t.observer.safeEmit(oe,e)})),e.on(ne,(e=>{const t=this.engine.peers.find((t=>t.id===e.peerId));t&&t.observer.safeEmit(ne,e)})),e.on(ve,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&r.observer.safeEmit(ve,e)})),e.on(be,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&!r.isMe&&r.observer.safeEmit(be,e)})),e.on(ye,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&!r.isMe&&r.observer.safeEmit(ye,e)})),e.on(Se,(({peerId:e,spatialLayer:t,temporalLayer:r,consumerId:i})=>{const s=this.engine.peers.find((t=>t.id===e));s&&!s.isMe&&s.observer.safeEmit(Se,{consumerId:i,spatialLayer:t,temporalLayer:r})})),e.on(we,(e=>{const{consumerPeerId:t}=e,r=this.engine.peers.find((e=>e.id===t));if(!r||r.isMe)return;r.observer.safeEmit(we,e);const i=this.engine.peers.find((e=>e.isMe));i&&i.observer.safeEmit(we,e)})),e.on(ue,(e=>{const t=this.engine.peers.find((e=>e.isMe));t&&t.observer.safeEmit(ue,e)})),e.on(fe,(({producerId:e,spatialLayer:t})=>r(this,void 0,void 0,(function*(){yield this.queue.push((()=>r(this,void 0,void 0,(function*(){yield this.handleProducerSetMaxSpatialLayer({producerId:e,spatialLayer:t})}))),fe)})))),e.on(he,(({peerId:e,producerId:t,spatialLayer:i})=>r(this,void 0,void 0,(function*(){const r=this.engine.peers.find((t=>t.id===e));r&&!r.isMe&&r.observer.safeEmit(he,{peerId:e,producerId:t,spatialLayer:i})})))),e.on(Ee,(({reason:e,transportId:t,direction:i,timeout:s})=>r(this,void 0,void 0,(function*(){const r=[this.engine.network.receiveTransport,this.engine.network.sendTransport].find((e=>(null==e?void 0:e.id)===t));r&&"connected"!==r.connectionState&&(this.logger.warn(Ee,{reason:e,transportId:t,direction:i,timeout:s}),this.engine.clientEventEmitter.emit(N,{direction:i,reason:e}))})))),e.on(de,(({peerId:e,producerId:t})=>{const r=this.engine.peers.find((t=>t.id===e)),i=null==r?void 0:r.producers.get(t);r&&i&&(i.paused=!0,r.observer.safeEmit(Q,{producerId:i.id,kind:i.kind,label:i.label,paused:i.paused}))})),e.on(le,(({peerId:e,producerId:t})=>{const r=this.engine.peers.find((t=>t.id===e)),i=null==r?void 0:r.producers.get(t);r&&i&&(i.paused=!1,r.observer.safeEmit(X,{producerId:i.id,kind:i.kind,label:i.label,paused:i.paused}))})),e.on(pe,(({label:e})=>r(this,void 0,void 0,(function*(){const t=this.engine.media.getTrack(e);t&&(t.stopMediaStreamTrack(),this.engine.clientEventEmitter.safeEmit(G,t),this.engine.clientEventEmitter.emit(B,{label:e}),yield this.engine.media.deleteTrack(t))}))))}removeEventListeners(){const{connection:e}=this.engine.network.socket;if(!e)return;[oe,ne,ve,be,ye,Se,we,ue,fe,he,Ee,de,le,pe].forEach((t=>e.removeAllListeners(t)))}reset(){this.removeEventListeners()}handleProducerSetMaxSpatialLayer({producerId:e,spatialLayer:t}){return r(this,void 0,void 0,(function*(){const r=this.engine.media.getAllTracks().find((t=>{var r;return(null===(r=t.getProducer())||void 0===r?void 0:r.id)===e}));if(!r)return void this.logger.warn("producerRequestMaxSpatialLayer()",{message:"Producer not found"});if(!(r instanceof Ic))return void this.logger.warn("producerRequestMaxSpatialLayer()",{message:"Wrong producer kind"});const i=r.getMaxSpatialLayer();i!==t?(yield r.setMaxSpatialLayer(t),yield this.engine.network.socket.request(he,{producerId:e,maxSpatialLayer:t})):this.logger.debug("producerRequestMaxSpatialLayer()",{message:"Skip set max spatial layer",requestedSpatialLayer:t,currentMaxSpatialLayer:i})}))}}const Cd=Object.create(null);Cd.open="0",Cd.close="1",Cd.ping="2",Cd.pong="3",Cd.message="4",Cd.upgrade="5",Cd.noop="6";const Pd=Object.create(null);Object.keys(Cd).forEach((e=>{Pd[Cd[e]]=e}));const Td={type:"error",data:"parser error"},Ed="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Dd="function"==typeof ArrayBuffer,Md=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,xd=({type:e,data:t},r,i)=>Ed&&t instanceof Blob?r?i(t):Ld(t,i):Dd&&(t instanceof ArrayBuffer||Md(t))?r?i(t):Ld(new Blob([t]),i):i(Cd[e]+(t||"")),Ld=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function Id(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Od;const Ad="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",jd="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<Ad.length;e++)jd[Ad.charCodeAt(e)]=e;const Fd="function"==typeof ArrayBuffer,Nd=(e,t)=>{if("string"!=typeof e)return{type:"message",data:Ud(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:Bd(e.substring(1),t)};return Pd[r]?e.length>1?{type:Pd[r],data:e.substring(1)}:{type:Pd[r]}:Td},Bd=(e,t)=>{if(Fd){const r=(e=>{let t,r,i,s,n,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const d=new ArrayBuffer(o),l=new Uint8Array(d);for(t=0;t<a;t+=4)r=jd[e.charCodeAt(t)],i=jd[e.charCodeAt(t+1)],s=jd[e.charCodeAt(t+2)],n=jd[e.charCodeAt(t+3)],l[c++]=r<<2|i>>4,l[c++]=(15&i)<<4|s>>2,l[c++]=(3&s)<<6|63&n;return d})(e);return Ud(r,t)}return{base64:!0,data:e}},Ud=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,qd=String.fromCharCode(30);function Wd(){return new TransformStream({transform(e,t){!function(e,t){Ed&&e.data instanceof Blob?e.data.arrayBuffer().then(Id).then(t):Dd&&(e.data instanceof ArrayBuffer||Md(e.data))?t(Id(e.data)):xd(e,!1,(e=>{Od||(Od=new TextEncoder),t(Od.encode(e))}))}(e,(r=>{const i=r.length;let s;if(i<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,i);else if(i<65536){s=new Uint8Array(3);const e=new DataView(s.buffer);e.setUint8(0,126),e.setUint16(1,i)}else{s=new Uint8Array(9);const e=new DataView(s.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(s[0]|=128),t.enqueue(s),t.enqueue(r)}))}})}let Vd;function zd(e){return e.reduce(((e,t)=>e+t.length),0)}function $d(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let i=0;for(let s=0;s<t;s++)r[s]=e[0][i++],i===e[0].length&&(e.shift(),i=0);return e.length&&i<e[0].length&&(e[0]=e[0].slice(i)),r}function Gd(e){if(e)return function(e){for(var t in Gd.prototype)e[t]=Gd.prototype[t];return e}(e)}Gd.prototype.on=Gd.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},Gd.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},Gd.prototype.off=Gd.prototype.removeListener=Gd.prototype.removeAllListeners=Gd.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,i=this._callbacks["$"+e];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var s=0;s<i.length;s++)if((r=i[s])===t||r.fn===t){i.splice(s,1);break}return 0===i.length&&delete this._callbacks["$"+e],this},Gd.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(r){i=0;for(var s=(r=r.slice(0)).length;i<s;++i)r[i].apply(this,t)}return this},Gd.prototype.emitReserved=Gd.prototype.emit,Gd.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},Gd.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Hd="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Jd(e,...t){return t.reduce(((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t)),{})}const Kd=Hd.setTimeout,Qd=Hd.clearTimeout;function Xd(e,t){t.useNativeTimers?(e.setTimeoutFn=Kd.bind(Hd),e.clearTimeoutFn=Qd.bind(Hd)):(e.setTimeoutFn=Hd.setTimeout.bind(Hd),e.clearTimeoutFn=Hd.clearTimeout.bind(Hd))}class Yd extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class Zd extends Gd{constructor(e){super(),this.writable=!1,Xd(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new Yd(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=Nd(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}(e);return t.length?"?"+t:""}}const el="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),tl={};let rl,il=0,sl=0;function nl(e){let t="";do{t=el[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function ol(){const e=nl(+new Date);return e!==rl?(il=0,rl=e):e+"."+nl(il++)}for(;sl<64;sl++)tl[el[sl]]=sl;let al=!1;try{al="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(fm){}const cl=al;function dl(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||cl))return new XMLHttpRequest}catch(e){}if(!t)try{return new(Hd[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function ll(){}const pl=null!=new dl({xdomain:!1}).responseType;class ul extends Gd{constructor(e,t){super(),Xd(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var e;const t=Jd(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd;const r=this.xhr=new dl(t);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{r.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var e;3===r.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(r)),4===r.readyState&&(200===r.status||1223===r.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof r.status?r.status:0)}),0))},r.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=ul.requestsCount++,ul.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=ll,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete ul.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(ul.requestsCount=0,ul.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",hl);else if("function"==typeof addEventListener){addEventListener("onpagehide"in Hd?"pagehide":"unload",hl,!1)}function hl(){for(let e in ul.requests)ul.requests.hasOwnProperty(e)&&ul.requests[e].abort()}const fl="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),ml=Hd.WebSocket||Hd.MozWebSocket,gl="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const vl={websocket:class extends Zd{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,r=gl?{}:Jd(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=gl?new ml(e,t,r):t?new ml(e,t):new ml(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;xd(r,this.supportsBinary,(e=>{try{this.ws.send(e)}catch(e){}i&&fl((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=ol()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!ml}},webtransport:class extends Zd{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then((()=>{this.onClose()})).catch((e=>{this.onError("webtransport error",e)})),this.transport.ready.then((()=>{this.transport.createBidirectionalStream().then((e=>{const t=function(e,t){Vd||(Vd=new TextDecoder);const r=[];let i=0,s=-1,n=!1;return new TransformStream({transform(o,a){for(r.push(o);;){if(0===i){if(zd(r)<1)break;const e=$d(r,1);n=128==(128&e[0]),s=127&e[0],i=s<126?3:126===s?1:2}else if(1===i){if(zd(r)<2)break;const e=$d(r,2);s=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(zd(r)<8)break;const e=$d(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),n=t.getUint32(0);if(n>Math.pow(2,21)-1){a.enqueue(Td);break}s=n*Math.pow(2,32)+t.getUint32(4),i=3}else{if(zd(r)<s)break;const e=$d(r,s);a.enqueue(Nd(n?e:Vd.decode(e),t)),i=0}if(0===s||s>e){a.enqueue(Td);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),i=Wd();i.readable.pipeTo(e.writable),this.writer=i.writable.getWriter();const s=()=>{r.read().then((({done:e,value:t})=>{e||(this.onPacket(t),s())})).catch((e=>{}))};s();const n={type:"open"};this.query.sid&&(n.data=`{"sid":"${this.query.sid}"}`),this.writer.write(n).then((()=>this.onOpen()))}))})))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;this.writer.write(r).then((()=>{i&&fl((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends Zd{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}const t=e&&e.forceBase64;this.supportsBinary=pl&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",(function(){--e||t()}))),this.writable||(e++,this.once("drain",(function(){--e||t()})))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const r=e.split(qd),i=[];for(let e=0;e<r.length;e++){const s=Nd(r[e],t);if(i.push(s),"error"===s.type)break}return i})(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const r=e.length,i=new Array(r);let s=0;e.forEach(((e,n)=>{xd(e,!1,(e=>{i[n]=e,++s===r&&t(i.join(qd))}))}))})(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=ol()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new ul(this.uri(),e)}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",((e,t)=>{this.onError("xhr post error",e,t)}))}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",((e,t)=>{this.onError("xhr poll error",e,t)})),this.pollXhr=e}}},yl=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,bl=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function wl(e){const t=e,r=e.indexOf("["),i=e.indexOf("]");-1!=r&&-1!=i&&(e=e.substring(0,r)+e.substring(r,i).replace(/:/g,";")+e.substring(i,e.length));let s=yl.exec(e||""),n={},o=14;for(;o--;)n[bl[o]]=s[o]||"";return-1!=r&&-1!=i&&(n.source=t,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=function(e,t){const r=/\/{2,9}/g,i=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||i.splice(0,1);"/"==t.slice(-1)&&i.splice(i.length-1,1);return i}(0,n.path),n.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,i){t&&(r[t]=i)})),r}(0,n.query),n}class Sl extends Gd{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=wl(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=wl(t.host).host),Xd(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let e=0,i=r.length;e<i;e++){let i=r[e].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new vl[e](r)}open(){let e;if(this.opts.rememberUpgrade&&Sl.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(e=>this.onClose("transport close",e)))}probe(e){let t=this.createTransport(e),r=!1;Sl.priorWebsocketSuccess=!1;const i=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",(e=>{if(!r)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Sl.priorWebsocketSuccess="websocket"===t.name,this.transport.pause((()=>{r||"closed"!==this.readyState&&(d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())}))}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}})))};function s(){r||(r=!0,d(),t.close(),t=null)}const n=e=>{const r=new Error("probe error: "+e);r.transport=t.name,s(),this.emitReserved("upgradeError",r)};function o(){n("transport closed")}function a(){n("socket closed")}function c(e){t&&e.name!==t.name&&s()}const d=()=>{t.removeListener("open",i),t.removeListener("error",n),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",i),t.once("error",n),t.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn((()=>{r||t.open()}),200):t.open()}onOpen(){if(this.readyState="open",Sl.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let r=0;r<this.writeBuffer.length;r++){const i=this.writeBuffer[r].data;if(i&&(e+="string"==typeof(t=i)?function(e){let t=0,r=0;for(let i=0,s=e.length;i<s;i++)t=e.charCodeAt(i),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(i++,r+=4);return r}(t):Math.ceil(1.33*(t.byteLength||t.size))),r>0&&e>this.maxPayload)return this.writeBuffer.slice(0,r);e+=2}var t;return this.writeBuffer}write(e,t,r){return this.sendPacket("message",e,t,r),this}send(e,t,r){return this.sendPacket("message",e,t,r),this}sendPacket(e,t,r,i){if("function"==typeof t&&(i=t,t=void 0),"function"==typeof r&&(i=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const s={type:e,data:t,options:r};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?r():e()})):this.upgrading?r():e()),this}onError(e){Sl.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let r=0;const i=e.length;for(;r<i;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}Sl.protocol=4;const _l="function"==typeof ArrayBuffer,Rl=Object.prototype.toString,kl="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Rl.call(Blob),Cl="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Rl.call(File);function Pl(e){return _l&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||kl&&e instanceof Blob||Cl&&e instanceof File}function Tl(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Tl(e[t]))return!0;return!1}if(Pl(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Tl(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Tl(e[t]))return!0;return!1}function El(e){const t=[],r=e.data,i=e;return i.data=Dl(r,t),i.attachments=t.length,{packet:i,buffers:t}}function Dl(e,t){if(!e)return e;if(Pl(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let i=0;i<e.length;i++)r[i]=Dl(e[i],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Dl(e[i],t));return r}return e}function Ml(e,t){return e.data=xl(e.data,t),delete e.attachments,e}function xl(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=xl(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=xl(e[r],t));return e}const Ll=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Il;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(Il||(Il={}));function Ol(e){return"[object Object]"===Object.prototype.toString.call(e)}class Al extends Gd{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===Il.BINARY_EVENT;r||t.type===Il.BINARY_ACK?(t.type=r?Il.EVENT:Il.ACK,this.reconstructor=new jl(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Pl(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===Il[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Il.BINARY_EVENT||r.type===Il.BINARY_ACK){const i=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const s=e.substring(i,t);if(s!=Number(s)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(s)}if("/"===e.charAt(t+1)){const i=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(i,t)}else r.nsp="/";const i=e.charAt(t+1);if(""!==i&&Number(i)==i){const i=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(!Al.isPayloadValid(r.type,i))throw new Error("invalid payload");r.data=i}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case Il.CONNECT:return Ol(t);case Il.DISCONNECT:return void 0===t;case Il.CONNECT_ERROR:return"string"==typeof t||Ol(t);case Il.EVENT:case Il.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Ll.indexOf(t[0]));case Il.ACK:case Il.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class jl{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Ml(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var Fl=Object.freeze({__proto__:null,protocol:5,get PacketType(){return Il},Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Il.EVENT&&e.type!==Il.ACK||!Tl(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Il.EVENT?Il.BINARY_EVENT:Il.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Il.BINARY_EVENT&&e.type!==Il.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=El(e),r=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(r),i}},Decoder:Al});function Nl(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const Bl=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Ul extends Gd{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[Nl(e,"open",this.onopen.bind(this)),Nl(e,"packet",this.onpacket.bind(this)),Nl(e,"error",this.onerror.bind(this)),Nl(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(Bl.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const r={type:Il.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,i=t.pop();this._registerAckCallback(e,i),r.id=e}const i=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!i||!this.connected)||(this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var r;const i=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===i)return void(this.acks[e]=t);const s=this.io.setTimeoutFn((()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))}),i);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(s),t.apply(this,[null,...e])}}emitWithAck(e,...t){const r=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((i,s)=>{t.push(((e,t)=>r?e?s(e):i(t):i(e))),this.emit(e,...t)}))}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push(((e,...i)=>{if(r!==this._queue[0])return;return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...i)),r.pending=!1,this._drainQueue()})),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Il.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Il.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Il.EVENT:case Il.BINARY_EVENT:this.onevent(e);break;case Il.ACK:case Il.BINARY_ACK:this.onack(e);break;case Il.DISCONNECT:this.ondisconnect();break;case Il.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...i){r||(r=!0,t.packet({type:Il.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((e=>{this.notifyOutgoingListeners(e),this.packet(e)})),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((e=>e())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Il.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function ql(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}ql.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-r:e+r}return 0|Math.min(e,this.max)},ql.prototype.reset=function(){this.attempts=0},ql.prototype.setMin=function(e){this.ms=e},ql.prototype.setMax=function(e){this.max=e},ql.prototype.setJitter=function(e){this.jitter=e};class Wl extends Gd{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,Xd(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new ql({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||Fl;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Sl(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=Nl(t,"open",(function(){r.onopen(),e&&e()})),s=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},n=Nl(t,"error",s);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn((()=>{i(),s(new Error("timeout")),t.close()}),e);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}return this.subs.push(i),this.subs.push(n),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(Nl(e,"ping",this.onping.bind(this)),Nl(e,"data",this.ondata.bind(this)),Nl(e,"error",this.onerror.bind(this)),Nl(e,"close",this.onclose.bind(this)),Nl(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){fl((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new Ul(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn((()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()})))}),t);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Vl={};function zl(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let i=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),i=wl(e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const s=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+s+":"+i.port+t,i.href=i.protocol+"://"+s+(r&&r.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),i=r.source,s=r.id,n=r.path,o=Vl[s]&&n in Vl[s].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new Wl(i,t):(Vl[s]||(Vl[s]=new Wl(i,t)),a=Vl[s]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(zl,{Manager:Wl,Socket:Ul,io:zl,connect:zl});class $l{constructor(e){this.reconnectingAttempt=0,this.isConnected=!1,this._observer=new n,this.knownDisconnectReasonsCodes={"io server disconnect":"server.disconnect","io client disconnect":"client.disconnect","ping timeout":"ping.timeout","transport close":"transport.close","transport error":"transport.error"},this.logger=new Ge({namespace:"Socket",logLevel:e.logLevel,onLogMessage:e.onLogMessage})}get observer(){return this._observer}get id(){var e;return null===(e=this.connection)||void 0===e?void 0:e.id}connect(e,t){const r=zl(e,{transports:["polling","websocket"],upgrade:!0,rememberUpgrade:!1,auth:{token:t,apiVersion:2}});this.connection=r,this.serverUrl=e,r.on(Ha.Connect,(()=>{const e=this.reconnectingAttempt?Ha.Reconnected:Ha.Connected;this.isConnected=!0,this.setReconnectingAttempt(0),this.logger.debug(`connection.on('${Ha.Connect}')`,{connectionId:r.id}),this.observer.safeEmit(Ha.State,{state:e})})),r.on(Ha.ConnectError,(e=>{this.connectionError=e,this.logger.error(`connection.on('${Ha.ConnectError}')`,{error:e}),this.observer.safeEmit(Ha.State,{state:Ha.Error,error:e})})),r.on(Ha.Disconnect,(e=>{this.isConnected=!1,this.setReconnectingAttempt(0),this.disconnectReason=e,this.logger.warn(`connection.on('${Ha.Disconnect}')`,{reason:e}),this.observer.safeEmit(Ha.State,{state:Ha.Disconnected,code:this.getDisconnectReasonCode(e)})})),r.io.on(Ha.ReconnectAttempt,(e=>{this.setReconnectingAttempt(e),this.logger.warn(`connection.on('${Ha.ReconnectAttempt}')`,{attempt:e}),this.observer.safeEmit(Ha.State,{state:Ha.Reconnecting})})),r.io.on(Ha.Reconnect,(()=>{this.logger.debug(`connection.on('${Ha.Reconnect}')`,{connectionId:r.id}),this.observer.safeEmit(Ha.State,{state:Ha.Reconnect})}))}disconnect(){this.connection&&(this.connection.offAny(),this.connection.volatile.offAny(),this.connection.disconnect(),this.connection.io.removeAllListeners(),this.setReconnectingAttempt(0))}request(e,t={}){return new Promise(((r,i)=>{if(!this.connection)return this.logger.error("request()",{type:e,data:t}),void i(new Error("Socket request: Socket connection is not initialized"));this.connection.emit(e,t,(s=>{s.error?(this.logger.error("request()",{event:e,payload:t,response:s}),i(s.error)):r(s)}))}))}getServerUrl(){return this.serverUrl}getDisconnectReasonCode(e){const t=String(e).toLowerCase();return this.knownDisconnectReasonsCodes[t]||t}setReconnectingAttempt(e){this.reconnectingAttempt=e}}var Gl={exports:{}},Hl=function(e,t){return function(){for(var r=new Array(arguments.length),i=0;i<r.length;i++)r[i]=arguments[i];return e.apply(t,r)}},Jl=Hl,Kl=Object.prototype.toString;function Ql(e){return"[object Array]"===Kl.call(e)}function Xl(e){return void 0===e}function Yl(e){return null!==e&&"object"==typeof e}function Zl(e){if("[object Object]"!==Kl.call(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}function ep(e){return"[object Function]"===Kl.call(e)}function tp(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),Ql(e))for(var r=0,i=e.length;r<i;r++)t.call(null,e[r],r,e);else for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.call(null,e[s],s,e)}var rp={isArray:Ql,isArrayBuffer:function(e){return"[object ArrayBuffer]"===Kl.call(e)},isBuffer:function(e){return null!==e&&!Xl(e)&&null!==e.constructor&&!Xl(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){return"undefined"!=typeof FormData&&e instanceof FormData},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:Yl,isPlainObject:Zl,isUndefined:Xl,isDate:function(e){return"[object Date]"===Kl.call(e)},isFile:function(e){return"[object File]"===Kl.call(e)},isBlob:function(e){return"[object Blob]"===Kl.call(e)},isFunction:ep,isStream:function(e){return Yl(e)&&ep(e.pipe)},isURLSearchParams:function(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)},forEach:tp,merge:function e(){var t={};function r(r,i){Zl(t[i])&&Zl(r)?t[i]=e(t[i],r):Zl(r)?t[i]=e({},r):Ql(r)?t[i]=r.slice():t[i]=r}for(var i=0,s=arguments.length;i<s;i++)tp(arguments[i],r);return t},extend:function(e,t,r){return tp(t,(function(t,i){e[i]=r&&"function"==typeof t?Jl(t,r):t})),e},trim:function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e}},ip=rp;function sp(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var np=function(e,t,r){if(!t)return e;var i;if(r)i=r(t);else if(ip.isURLSearchParams(t))i=t.toString();else{var s=[];ip.forEach(t,(function(e,t){null!=e&&(ip.isArray(e)?t+="[]":e=[e],ip.forEach(e,(function(e){ip.isDate(e)?e=e.toISOString():ip.isObject(e)&&(e=JSON.stringify(e)),s.push(sp(t)+"="+sp(e))})))})),i=s.join("&")}if(i){var n=e.indexOf("#");-1!==n&&(e=e.slice(0,n)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e},op=rp;function ap(){this.handlers=[]}ap.prototype.use=function(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1},ap.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},ap.prototype.forEach=function(e){op.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var cp=ap,dp=rp,lp=function(e,t,r,i,s){return e.config=t,r&&(e.code=r),e.request=i,e.response=s,e.isAxiosError=!0,e.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code}},e},pp=lp,up=function(e,t,r,i,s){var n=new Error(e);return pp(n,t,r,i,s)},hp=up,fp=rp,mp=fp.isStandardBrowserEnv()?{write:function(e,t,r,i,s,n){var o=[];o.push(e+"="+encodeURIComponent(t)),fp.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),fp.isString(i)&&o.push("path="+i),fp.isString(s)&&o.push("domain="+s),!0===n&&o.push("secure"),document.cookie=o.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}},gp=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)},vp=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},yp=rp,bp=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"],wp=rp,Sp=wp.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");function i(e){var i=e;return t&&(r.setAttribute("href",i),i=r.href),r.setAttribute("href",i),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:"/"===r.pathname.charAt(0)?r.pathname:"/"+r.pathname}}return e=i(window.location.href),function(t){var r=wp.isString(t)?i(t):t;return r.protocol===e.protocol&&r.host===e.host}}():function(){return!0},_p=rp,Rp=function(e,t,r){var i=r.config.validateStatus;r.status&&i&&!i(r.status)?t(hp("Request failed with status code "+r.status,r.config,null,r.request,r)):e(r)},kp=mp,Cp=np,Pp=function(e,t){return e&&!gp(t)?vp(e,t):t},Tp=function(e){var t,r,i,s={};return e?(yp.forEach(e.split("\n"),(function(e){if(i=e.indexOf(":"),t=yp.trim(e.substr(0,i)).toLowerCase(),r=yp.trim(e.substr(i+1)),t){if(s[t]&&bp.indexOf(t)>=0)return;s[t]="set-cookie"===t?(s[t]?s[t]:[]).concat([r]):s[t]?s[t]+", "+r:r}})),s):s},Ep=Sp,Dp=up,Mp=function(e){return new Promise((function(t,r){var i=e.data,s=e.headers,n=e.responseType;_p.isFormData(i)&&delete s["Content-Type"];var o=new XMLHttpRequest;if(e.auth){var a=e.auth.username||"",c=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";s.Authorization="Basic "+btoa(a+":"+c)}var d=Pp(e.baseURL,e.url);function l(){if(o){var i="getAllResponseHeaders"in o?Tp(o.getAllResponseHeaders()):null,s={data:n&&"text"!==n&&"json"!==n?o.response:o.responseText,status:o.status,statusText:o.statusText,headers:i,config:e,request:o};Rp(t,r,s),o=null}}if(o.open(e.method.toUpperCase(),Cp(d,e.params,e.paramsSerializer),!0),o.timeout=e.timeout,"onloadend"in o?o.onloadend=l:o.onreadystatechange=function(){o&&4===o.readyState&&(0!==o.status||o.responseURL&&0===o.responseURL.indexOf("file:"))&&setTimeout(l)},o.onabort=function(){o&&(r(Dp("Request aborted",e,"ECONNABORTED",o)),o=null)},o.onerror=function(){r(Dp("Network Error",e,null,o)),o=null},o.ontimeout=function(){var t="timeout of "+e.timeout+"ms exceeded";e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),r(Dp(t,e,e.transitional&&e.transitional.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",o)),o=null},_p.isStandardBrowserEnv()){var p=(e.withCredentials||Ep(d))&&e.xsrfCookieName?kp.read(e.xsrfCookieName):void 0;p&&(s[e.xsrfHeaderName]=p)}"setRequestHeader"in o&&_p.forEach(s,(function(e,t){void 0===i&&"content-type"===t.toLowerCase()?delete s[t]:o.setRequestHeader(t,e)})),_p.isUndefined(e.withCredentials)||(o.withCredentials=!!e.withCredentials),n&&"json"!==n&&(o.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&o.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&o.upload&&o.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then((function(e){o&&(o.abort(),r(e),o=null)})),i||(i=null),o.send(i)}))},xp=rp,Lp=function(e,t){dp.forEach(e,(function(r,i){i!==t&&i.toUpperCase()===t.toUpperCase()&&(e[t]=r,delete e[i])}))},Ip=lp,Op={"Content-Type":"application/x-www-form-urlencoded"};function Ap(e,t){!xp.isUndefined(e)&&xp.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var jp,Fp={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:(("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(jp=Mp),jp),transformRequest:[function(e,t){return Lp(t,"Accept"),Lp(t,"Content-Type"),xp.isFormData(e)||xp.isArrayBuffer(e)||xp.isBuffer(e)||xp.isStream(e)||xp.isFile(e)||xp.isBlob(e)?e:xp.isArrayBufferView(e)?e.buffer:xp.isURLSearchParams(e)?(Ap(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):xp.isObject(e)||t&&"application/json"===t["Content-Type"]?(Ap(t,"application/json"),function(e,t,r){if(xp.isString(e))try{return(t||JSON.parse)(e),xp.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional,r=t&&t.silentJSONParsing,i=t&&t.forcedJSONParsing,s=!r&&"json"===this.responseType;if(s||i&&xp.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(s){if("SyntaxError"===e.name)throw Ip(e,this,"E_JSON_PARSE");throw e}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(e){return e>=200&&e<300}};Fp.headers={common:{Accept:"application/json, text/plain, */*"}},xp.forEach(["delete","get","head"],(function(e){Fp.headers[e]={}})),xp.forEach(["post","put","patch"],(function(e){Fp.headers[e]=xp.merge(Op)}));var Np=Fp,Bp=rp,Up=Np,qp=function(e){return!(!e||!e.__CANCEL__)},Wp=rp,Vp=function(e,t,r){var i=this||Up;return Bp.forEach(r,(function(r){e=r.call(i,e,t)})),e},zp=qp,$p=Np;function Gp(e){e.cancelToken&&e.cancelToken.throwIfRequested()}var Hp=rp,Jp=function(e,t){t=t||{};var r={},i=["url","method","data"],s=["headers","auth","proxy","params"],n=["baseURL","transformRequest","transformResponse","paramsSerializer","timeout","timeoutMessage","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","decompress","maxContentLength","maxBodyLength","maxRedirects","transport","httpAgent","httpsAgent","cancelToken","socketPath","responseEncoding"],o=["validateStatus"];function a(e,t){return Hp.isPlainObject(e)&&Hp.isPlainObject(t)?Hp.merge(e,t):Hp.isPlainObject(t)?Hp.merge({},t):Hp.isArray(t)?t.slice():t}function c(i){Hp.isUndefined(t[i])?Hp.isUndefined(e[i])||(r[i]=a(void 0,e[i])):r[i]=a(e[i],t[i])}Hp.forEach(i,(function(e){Hp.isUndefined(t[e])||(r[e]=a(void 0,t[e]))})),Hp.forEach(s,c),Hp.forEach(n,(function(i){Hp.isUndefined(t[i])?Hp.isUndefined(e[i])||(r[i]=a(void 0,e[i])):r[i]=a(void 0,t[i])})),Hp.forEach(o,(function(i){i in t?r[i]=a(e[i],t[i]):i in e&&(r[i]=a(void 0,e[i]))}));var d=i.concat(s).concat(n).concat(o),l=Object.keys(e).concat(Object.keys(t)).filter((function(e){return-1===d.indexOf(e)}));return Hp.forEach(l,c),r},Kp={name:"axios",version:"0.21.4",description:"Promise based HTTP client for the browser and node.js",main:"index.js",scripts:{test:"grunt test",start:"node ./sandbox/server.js",build:"NODE_ENV=production grunt build",preversion:"npm test",version:"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json",postversion:"git push && git push --tags",examples:"node ./examples/server.js",coveralls:"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",fix:"eslint --fix lib/**/*.js"},repository:{type:"git",url:"https://github.com/axios/axios.git"},keywords:["xhr","http","ajax","promise","node"],author:"Matt Zabriskie",license:"MIT",bugs:{url:"https://github.com/axios/axios/issues"},homepage:"https://axios-http.com",devDependencies:{coveralls:"^3.0.0","es6-promise":"^4.2.4",grunt:"^1.3.0","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.1.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^23.0.0","grunt-karma":"^4.0.0","grunt-mocha-test":"^0.13.3","grunt-ts":"^6.0.0-beta.19","grunt-webpack":"^4.0.2","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1",karma:"^6.3.2","karma-chrome-launcher":"^3.1.0","karma-firefox-launcher":"^2.1.0","karma-jasmine":"^1.1.1","karma-jasmine-ajax":"^0.1.13","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^4.3.6","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.8","karma-webpack":"^4.0.2","load-grunt-tasks":"^3.5.2",minimist:"^1.2.0",mocha:"^8.2.1",sinon:"^4.5.0","terser-webpack-plugin":"^4.2.3",typescript:"^4.0.5","url-search-params":"^0.10.0",webpack:"^4.44.2","webpack-dev-server":"^3.11.0"},browser:{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},jsdelivr:"dist/axios.min.js",unpkg:"dist/axios.min.js",typings:"./index.d.ts",dependencies:{"follow-redirects":"^1.14.0"},bundlesize:[{path:"./dist/axios.min.js",threshold:"5kB"}]},Qp={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){Qp[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));var Xp={},Yp=Kp.version.split(".");function Zp(e,t){for(var r=t?t.split("."):Yp,i=e.split("."),s=0;s<3;s++){if(r[s]>i[s])return!0;if(r[s]<i[s])return!1}return!1}Qp.transitional=function(e,t,r){var i=t&&Zp(t);function s(e,t){return"[Axios v"+Kp.version+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return function(r,n,o){if(!1===e)throw new Error(s(n," has been removed in "+t));return i&&!Xp[n]&&(Xp[n]=!0,console.warn(s(n," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,n,o)}};var eu={isOlderVersion:Zp,assertOptions:function(e,t,r){if("object"!=typeof e)throw new TypeError("options must be an object");for(var i=Object.keys(e),s=i.length;s-- >0;){var n=i[s],o=t[n];if(o){var a=e[n],c=void 0===a||o(a,n,e);if(!0!==c)throw new TypeError("option "+n+" must be "+c)}else if(!0!==r)throw Error("Unknown option "+n)}},validators:Qp},tu=rp,ru=np,iu=cp,su=function(e){return Gp(e),e.headers=e.headers||{},e.data=Vp.call(e,e.data,e.headers,e.transformRequest),e.headers=Wp.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),Wp.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||$p.adapter)(e).then((function(t){return Gp(e),t.data=Vp.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return zp(t)||(Gp(e),t&&t.response&&(t.response.data=Vp.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},nu=Jp,ou=eu,au=ou.validators;function cu(e){this.defaults=e,this.interceptors={request:new iu,response:new iu}}cu.prototype.request=function(e){"string"==typeof e?(e=arguments[1]||{}).url=arguments[0]:e=e||{},(e=nu(this.defaults,e)).method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var t=e.transitional;void 0!==t&&ou.assertOptions(t,{silentJSONParsing:au.transitional(au.boolean,"1.0.0"),forcedJSONParsing:au.transitional(au.boolean,"1.0.0"),clarifyTimeoutError:au.transitional(au.boolean,"1.0.0")},!1);var r=[],i=!0;this.interceptors.request.forEach((function(t){"function"==typeof t.runWhen&&!1===t.runWhen(e)||(i=i&&t.synchronous,r.unshift(t.fulfilled,t.rejected))}));var s,n=[];if(this.interceptors.response.forEach((function(e){n.push(e.fulfilled,e.rejected)})),!i){var o=[su,void 0];for(Array.prototype.unshift.apply(o,r),o=o.concat(n),s=Promise.resolve(e);o.length;)s=s.then(o.shift(),o.shift());return s}for(var a=e;r.length;){var c=r.shift(),d=r.shift();try{a=c(a)}catch(e){d(e);break}}try{s=su(a)}catch(e){return Promise.reject(e)}for(;n.length;)s=s.then(n.shift(),n.shift());return s},cu.prototype.getUri=function(e){return e=nu(this.defaults,e),ru(e.url,e.params,e.paramsSerializer).replace(/^\?/,"")},tu.forEach(["delete","get","head","options"],(function(e){cu.prototype[e]=function(t,r){return this.request(nu(r||{},{method:e,url:t,data:(r||{}).data}))}})),tu.forEach(["post","put","patch"],(function(e){cu.prototype[e]=function(t,r,i){return this.request(nu(i||{},{method:e,url:t,data:r}))}}));var du=cu;function lu(e){this.message=e}lu.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},lu.prototype.__CANCEL__=!0;var pu=lu,uu=pu;function hu(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var r=this;e((function(e){r.reason||(r.reason=new uu(e),t(r.reason))}))}hu.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},hu.source=function(){var e,t=new hu((function(t){e=t}));return{token:t,cancel:e}};var fu=hu,mu=rp,gu=Hl,vu=du,yu=Jp;function bu(e){var t=new vu(e),r=gu(vu.prototype.request,t);return mu.extend(r,vu.prototype,t),mu.extend(r,t),r}var wu=bu(Np);wu.Axios=vu,wu.create=function(e){return bu(yu(wu.defaults,e))},wu.Cancel=pu,wu.CancelToken=fu,wu.isCancel=qp,wu.all=function(e){return Promise.all(e)},wu.spread=function(e){return function(t){return e.apply(null,t)}},wu.isAxiosError=function(e){return"object"==typeof e&&!0===e.isAxiosError},Gl.exports=wu,Gl.exports.default=wu;var Su=Gl.exports,_u="undefined"!=typeof Symbol&&Symbol,Ru=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var i=Object.getOwnPropertySymbols(e);if(1!==i.length||i[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var s=Object.getOwnPropertyDescriptor(e,t);if(42!==s.value||!0!==s.enumerable)return!1}return!0},ku="Function.prototype.bind called on incompatible ",Cu=Array.prototype.slice,Pu=Object.prototype.toString,Tu=function(e){var t=this;if("function"!=typeof t||"[object Function]"!==Pu.call(t))throw new TypeError(ku+t);for(var r,i=Cu.call(arguments,1),s=function(){if(this instanceof r){var s=t.apply(this,i.concat(Cu.call(arguments)));return Object(s)===s?s:this}return t.apply(e,i.concat(Cu.call(arguments)))},n=Math.max(0,t.length-i.length),o=[],a=0;a<n;a++)o.push("$"+a);if(r=Function("binder","return function ("+o.join(",")+"){ return binder.apply(this,arguments); }")(s),t.prototype){var c=function(){};c.prototype=t.prototype,r.prototype=new c,c.prototype=null}return r},Eu=Function.prototype.bind||Tu,Du=Eu.call(Function.call,Object.prototype.hasOwnProperty),Mu=SyntaxError,xu=Function,Lu=TypeError,Iu=function(e){try{return xu('"use strict"; return ('+e+").constructor;")()}catch(e){}},Ou=Object.getOwnPropertyDescriptor;if(Ou)try{Ou({},"")}catch(Bc){Ou=null}var Au=function(){throw new Lu},ju=Ou?function(){try{return Au}catch(e){try{return Ou(arguments,"callee").get}catch(e){return Au}}}():Au,Fu="function"==typeof _u&&"function"==typeof Symbol&&"symbol"==typeof _u("foo")&&"symbol"==typeof Symbol("bar")&&Ru(),Nu=Object.getPrototypeOf||function(e){return e.__proto__},Bu={},Uu="undefined"==typeof Uint8Array?undefined:Nu(Uint8Array),qu={"%AggregateError%":"undefined"==typeof AggregateError?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":Fu?Nu([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":Bu,"%AsyncGenerator%":Bu,"%AsyncGeneratorFunction%":Bu,"%AsyncIteratorPrototype%":Bu,"%Atomics%":"undefined"==typeof Atomics?undefined:Atomics,"%BigInt%":"undefined"==typeof BigInt?undefined:BigInt,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?undefined:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?undefined:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?undefined:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?undefined:FinalizationRegistry,"%Function%":xu,"%GeneratorFunction%":Bu,"%Int8Array%":"undefined"==typeof Int8Array?undefined:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?undefined:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":Fu?Nu(Nu([][Symbol.iterator]())):undefined,"%JSON%":"object"==typeof JSON?JSON:undefined,"%Map%":"undefined"==typeof Map?undefined:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&Fu?Nu((new Map)[Symbol.iterator]()):undefined,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?undefined:Promise,"%Proxy%":"undefined"==typeof Proxy?undefined:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?undefined:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?undefined:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&Fu?Nu((new Set)[Symbol.iterator]()):undefined,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":Fu?Nu(""[Symbol.iterator]()):undefined,"%Symbol%":Fu?Symbol:undefined,"%SyntaxError%":Mu,"%ThrowTypeError%":ju,"%TypedArray%":Uu,"%TypeError%":Lu,"%Uint8Array%":"undefined"==typeof Uint8Array?undefined:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?undefined:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?undefined:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?undefined:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?undefined:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?undefined:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?undefined:WeakSet},Wu=function e(t){var r;if("%AsyncFunction%"===t)r=Iu("async function () {}");else if("%GeneratorFunction%"===t)r=Iu("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=Iu("async function* () {}");else if("%AsyncGenerator%"===t){var i=e("%AsyncGeneratorFunction%");i&&(r=i.prototype)}else if("%AsyncIteratorPrototype%"===t){var s=e("%AsyncGenerator%");s&&(r=Nu(s.prototype))}return qu[t]=r,r},Vu={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},zu=Eu,$u=Du,Gu=zu.call(Function.call,Array.prototype.concat),Hu=zu.call(Function.apply,Array.prototype.splice),Ju=zu.call(Function.call,String.prototype.replace),Ku=zu.call(Function.call,String.prototype.slice),Qu=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Xu=/\\(\\)?/g,Yu=function(e){var t=Ku(e,0,1),r=Ku(e,-1);if("%"===t&&"%"!==r)throw new Mu("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new Mu("invalid intrinsic syntax, expected opening `%`");var i=[];return Ju(e,Qu,(function(e,t,r,s){i[i.length]=r?Ju(s,Xu,"$1"):t||e})),i},Zu=function(e,t){var r,i=e;if($u(Vu,i)&&(i="%"+(r=Vu[i])[0]+"%"),$u(qu,i)){var s=qu[i];if(s===Bu&&(s=Wu(i)),void 0===s&&!t)throw new Lu("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:i,value:s}}throw new Mu("intrinsic "+e+" does not exist!")},eh=function(e,t){if("string"!=typeof e||0===e.length)throw new Lu("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new Lu('"allowMissing" argument must be a boolean');var r=Yu(e),i=r.length>0?r[0]:"",s=Zu("%"+i+"%",t),n=s.name,o=s.value,a=!1,c=s.alias;c&&(i=c[0],Hu(r,Gu([0,1],c)));for(var d=1,l=!0;d<r.length;d+=1){var p=r[d],u=Ku(p,0,1),h=Ku(p,-1);if(('"'===u||"'"===u||"`"===u||'"'===h||"'"===h||"`"===h)&&u!==h)throw new Mu("property names with quotes must have matching quotes");if("constructor"!==p&&l||(a=!0),$u(qu,n="%"+(i+="."+p)+"%"))o=qu[n];else if(null!=o){if(!(p in o)){if(!t)throw new Lu("base intrinsic for "+e+" exists, but the property is not available.");return}if(Ou&&d+1>=r.length){var f=Ou(o,p);o=(l=!!f)&&"get"in f&&!("originalValue"in f.get)?f.get:o[p]}else l=$u(o,p),o=o[p];l&&!a&&(qu[n]=o)}}return o},th={exports:{}};!function(e){var t=Eu,r=eh,i=r("%Function.prototype.apply%"),s=r("%Function.prototype.call%"),n=r("%Reflect.apply%",!0)||t.call(s,i),o=r("%Object.getOwnPropertyDescriptor%",!0),a=r("%Object.defineProperty%",!0),c=r("%Math.max%");if(a)try{a({},"a",{value:1})}catch(e){a=null}e.exports=function(e){var r=n(t,s,arguments);if(o&&a){var i=o(r,"length");i.configurable&&a(r,"length",{value:1+c(0,e.length-(arguments.length-1))})}return r};var d=function(){return n(t,i,arguments)};a?a(e.exports,"apply",{value:d}):e.exports.apply=d}(th);var rh=eh,ih=th.exports,sh=ih(rh("String.prototype.indexOf")),nh=c(Object.freeze({__proto__:null,default:{}})),oh="function"==typeof Map&&Map.prototype,ah=Object.getOwnPropertyDescriptor&&oh?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,ch=oh&&ah&&"function"==typeof ah.get?ah.get:null,dh=oh&&Map.prototype.forEach,lh="function"==typeof Set&&Set.prototype,ph=Object.getOwnPropertyDescriptor&&lh?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,uh=lh&&ph&&"function"==typeof ph.get?ph.get:null,hh=lh&&Set.prototype.forEach,fh="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,mh="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,gh="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,vh=Boolean.prototype.valueOf,yh=Object.prototype.toString,bh=Function.prototype.toString,wh=String.prototype.match,Sh="function"==typeof BigInt?BigInt.prototype.valueOf:null,_h=Object.getOwnPropertySymbols,Rh="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,kh="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Ch=Object.prototype.propertyIsEnumerable,Ph=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null),Th=nh.custom,Eh=Th&&Ih(Th)?Th:null,Dh="function"==typeof Symbol&&void 0!==Symbol.toStringTag?Symbol.toStringTag:null;function Mh(e,t,r){var i="double"===(r.quoteStyle||t)?'"':"'";return i+e+i}function xh(e){return String(e).replace(/"/g,"&quot;")}function Lh(e){return!("[object Array]"!==jh(e)||Dh&&"object"==typeof e&&Dh in e)}function Ih(e){if(kh)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Rh)return!1;try{return Rh.call(e),!0}catch(e){}return!1}var Oh=Object.prototype.hasOwnProperty||function(e){return e in this};function Ah(e,t){return Oh.call(e,t)}function jh(e){return yh.call(e)}function Fh(e,t){if(e.indexOf)return e.indexOf(t);for(var r=0,i=e.length;r<i;r++)if(e[r]===t)return r;return-1}function Nh(e,t){if(e.length>t.maxStringLength){var r=e.length-t.maxStringLength,i="... "+r+" more character"+(r>1?"s":"");return Nh(e.slice(0,t.maxStringLength),t)+i}return Mh(e.replace(/(['\\])/g,"\\$1").replace(/[\x00-\x1f]/g,Bh),"single",t)}function Bh(e){var t=e.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return r?"\\"+r:"\\x"+(t<16?"0":"")+t.toString(16).toUpperCase()}function Uh(e){return"Object("+e+")"}function qh(e){return e+" { ? }"}function Wh(e,t,r,i){return e+" ("+t+") {"+(i?Vh(r,i):r.join(", "))+"}"}function Vh(e,t){if(0===e.length)return"";var r="\n"+t.prev+t.base;return r+e.join(","+r)+"\n"+t.prev}function zh(e,t){var r=Lh(e),i=[];if(r){i.length=e.length;for(var s=0;s<e.length;s++)i[s]=Ah(e,s)?t(e[s],e):""}var n,o="function"==typeof _h?_h(e):[];if(kh){n={};for(var a=0;a<o.length;a++)n["$"+o[a]]=o[a]}for(var c in e)Ah(e,c)&&(r&&String(Number(c))===c&&c<e.length||kh&&n["$"+c]instanceof Symbol||(/[^\w$]/.test(c)?i.push(t(c,e)+": "+t(e[c],e)):i.push(c+": "+t(e[c],e))));if("function"==typeof _h)for(var d=0;d<o.length;d++)Ch.call(e,o[d])&&i.push("["+t(o[d])+"]: "+t(e[o[d]],e));return i}var $h,Gh=eh,Hh=function(e,t){var r=rh(e,!!t);return"function"==typeof r&&sh(e,".prototype.")>-1?ih(r):r},Jh=function e(t,r,i,s){var n=r||{};if(Ah(n,"quoteStyle")&&"single"!==n.quoteStyle&&"double"!==n.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Ah(n,"maxStringLength")&&("number"==typeof n.maxStringLength?n.maxStringLength<0&&n.maxStringLength!==1/0:null!==n.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var o=!Ah(n,"customInspect")||n.customInspect;if("boolean"!=typeof o&&"symbol"!==o)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Ah(n,"indent")&&null!==n.indent&&"\t"!==n.indent&&!(parseInt(n.indent,10)===n.indent&&n.indent>0))throw new TypeError('options "indent" must be "\\t", an integer > 0, or `null`');if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return Nh(t,n);if("number"==typeof t)return 0===t?1/0/t>0?"0":"-0":String(t);if("bigint"==typeof t)return String(t)+"n";var a=void 0===n.depth?5:n.depth;if(void 0===i&&(i=0),i>=a&&a>0&&"object"==typeof t)return Lh(t)?"[Array]":"[Object]";var c=function(e,t){var r;if("\t"===e.indent)r="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;r=Array(e.indent+1).join(" ")}return{base:r,prev:Array(t+1).join(r)}}(n,i);if(void 0===s)s=[];else if(Fh(s,t)>=0)return"[Circular]";function d(t,r,o){if(r&&(s=s.slice()).push(r),o){var a={depth:n.depth};return Ah(n,"quoteStyle")&&(a.quoteStyle=n.quoteStyle),e(t,a,i+1,s)}return e(t,n,i+1,s)}if("function"==typeof t){var l=function(e){if(e.name)return e.name;var t=wh.call(bh.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),p=zh(t,d);return"[Function"+(l?": "+l:" (anonymous)")+"]"+(p.length>0?" { "+p.join(", ")+" }":"")}if(Ih(t)){var u=kh?String(t).replace(/^(Symbol\(.*\))_[^)]*$/,"$1"):Rh.call(t);return"object"!=typeof t||kh?u:Uh(u)}if(function(e){if(!e||"object"!=typeof e)return!1;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return!0;return"string"==typeof e.nodeName&&"function"==typeof e.getAttribute}(t)){for(var h="<"+String(t.nodeName).toLowerCase(),f=t.attributes||[],m=0;m<f.length;m++)h+=" "+f[m].name+"="+Mh(xh(f[m].value),"double",n);return h+=">",t.childNodes&&t.childNodes.length&&(h+="..."),h+="</"+String(t.nodeName).toLowerCase()+">"}if(Lh(t)){if(0===t.length)return"[]";var g=zh(t,d);return c&&!function(e){for(var t=0;t<e.length;t++)if(Fh(e[t],"\n")>=0)return!1;return!0}(g)?"["+Vh(g,c)+"]":"[ "+g.join(", ")+" ]"}if(function(e){return!("[object Error]"!==jh(e)||Dh&&"object"==typeof e&&Dh in e)}(t)){var v=zh(t,d);return 0===v.length?"["+String(t)+"]":"{ ["+String(t)+"] "+v.join(", ")+" }"}if("object"==typeof t&&o){if(Eh&&"function"==typeof t[Eh])return t[Eh]();if("symbol"!==o&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!ch||!e||"object"!=typeof e)return!1;try{ch.call(e);try{uh.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var y=[];return dh.call(t,(function(e,r){y.push(d(r,t,!0)+" => "+d(e,t))})),Wh("Map",ch.call(t),y,c)}if(function(e){if(!uh||!e||"object"!=typeof e)return!1;try{uh.call(e);try{ch.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var b=[];return hh.call(t,(function(e){b.push(d(e,t))})),Wh("Set",uh.call(t),b,c)}if(function(e){if(!fh||!e||"object"!=typeof e)return!1;try{fh.call(e,fh);try{mh.call(e,mh)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return qh("WeakMap");if(function(e){if(!mh||!e||"object"!=typeof e)return!1;try{mh.call(e,mh);try{fh.call(e,fh)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return qh("WeakSet");if(function(e){if(!gh||!e||"object"!=typeof e)return!1;try{return gh.call(e),!0}catch(e){}return!1}(t))return qh("WeakRef");if(function(e){return!("[object Number]"!==jh(e)||Dh&&"object"==typeof e&&Dh in e)}(t))return Uh(d(Number(t)));if(function(e){if(!e||"object"!=typeof e||!Sh)return!1;try{return Sh.call(e),!0}catch(e){}return!1}(t))return Uh(d(Sh.call(t)));if(function(e){return!("[object Boolean]"!==jh(e)||Dh&&"object"==typeof e&&Dh in e)}(t))return Uh(vh.call(t));if(function(e){return!("[object String]"!==jh(e)||Dh&&"object"==typeof e&&Dh in e)}(t))return Uh(d(String(t)));if(!function(e){return!("[object Date]"!==jh(e)||Dh&&"object"==typeof e&&Dh in e)}(t)&&!function(e){return!("[object RegExp]"!==jh(e)||Dh&&"object"==typeof e&&Dh in e)}(t)){var w=zh(t,d),S=Ph?Ph(t)===Object.prototype:t instanceof Object||t.constructor===Object,_=t instanceof Object?"":"null prototype",R=!S&&Dh&&Object(t)===t&&Dh in t?jh(t).slice(8,-1):_?"Object":"",k=(S||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(R||_?"["+[].concat(R||[],_||[]).join(": ")+"] ":"");return 0===w.length?k+"{}":c?k+"{"+Vh(w,c)+"}":k+"{ "+w.join(", ")+" }"}return String(t)},Kh=Gh("%TypeError%"),Qh=Gh("%WeakMap%",!0),Xh=Gh("%Map%",!0),Yh=Hh("WeakMap.prototype.get",!0),Zh=Hh("WeakMap.prototype.set",!0),ef=Hh("WeakMap.prototype.has",!0),tf=Hh("Map.prototype.get",!0),rf=Hh("Map.prototype.set",!0),sf=Hh("Map.prototype.has",!0),nf=function(e,t){for(var r,i=e;null!==(r=i.next);i=r)if(r.key===t)return i.next=r.next,r.next=e.next,e.next=r,r},of=String.prototype.replace,af=/%20/g,cf="RFC3986",df={default:cf,formatters:{RFC1738:function(e){return of.call(e,af,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:cf},lf=df,pf=Object.prototype.hasOwnProperty,uf=Array.isArray,hf=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),ff=function(e,t){for(var r=t&&t.plainObjects?Object.create(null):{},i=0;i<e.length;++i)void 0!==e[i]&&(r[i]=e[i]);return r},mf={arrayToObject:ff,assign:function(e,t){return Object.keys(t).reduce((function(e,r){return e[r]=t[r],e}),e)},combine:function(e,t){return[].concat(e,t)},compact:function(e){for(var t=[{obj:{o:e},prop:"o"}],r=[],i=0;i<t.length;++i)for(var s=t[i],n=s.obj[s.prop],o=Object.keys(n),a=0;a<o.length;++a){var c=o[a],d=n[c];"object"==typeof d&&null!==d&&-1===r.indexOf(d)&&(t.push({obj:n,prop:c}),r.push(d))}return function(e){for(;e.length>1;){var t=e.pop(),r=t.obj[t.prop];if(uf(r)){for(var i=[],s=0;s<r.length;++s)void 0!==r[s]&&i.push(r[s]);t.obj[t.prop]=i}}}(t),e},decode:function(e,t,r){var i=e.replace(/\+/g," ");if("iso-8859-1"===r)return i.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(i)}catch(e){return i}},encode:function(e,t,r,i,s){if(0===e.length)return e;var n=e;if("symbol"==typeof e?n=Symbol.prototype.toString.call(e):"string"!=typeof e&&(n=String(e)),"iso-8859-1"===r)return escape(n).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));for(var o="",a=0;a<n.length;++a){var c=n.charCodeAt(a);45===c||46===c||95===c||126===c||c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||s===lf.RFC1738&&(40===c||41===c)?o+=n.charAt(a):c<128?o+=hf[c]:c<2048?o+=hf[192|c>>6]+hf[128|63&c]:c<55296||c>=57344?o+=hf[224|c>>12]+hf[128|c>>6&63]+hf[128|63&c]:(a+=1,c=65536+((1023&c)<<10|1023&n.charCodeAt(a)),o+=hf[240|c>>18]+hf[128|c>>12&63]+hf[128|c>>6&63]+hf[128|63&c])}return o},isBuffer:function(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},maybeMap:function(e,t){if(uf(e)){for(var r=[],i=0;i<e.length;i+=1)r.push(t(e[i]));return r}return t(e)},merge:function e(t,r,i){if(!r)return t;if("object"!=typeof r){if(uf(t))t.push(r);else{if(!t||"object"!=typeof t)return[t,r];(i&&(i.plainObjects||i.allowPrototypes)||!pf.call(Object.prototype,r))&&(t[r]=!0)}return t}if(!t||"object"!=typeof t)return[t].concat(r);var s=t;return uf(t)&&!uf(r)&&(s=ff(t,i)),uf(t)&&uf(r)?(r.forEach((function(r,s){if(pf.call(t,s)){var n=t[s];n&&"object"==typeof n&&r&&"object"==typeof r?t[s]=e(n,r,i):t.push(r)}else t[s]=r})),t):Object.keys(r).reduce((function(t,s){var n=r[s];return pf.call(t,s)?t[s]=e(t[s],n,i):t[s]=n,t}),s)}},gf=function(){var e,t,r,i={assert:function(e){if(!i.has(e))throw new Kh("Side channel does not contain "+Jh(e))},get:function(i){if(Qh&&i&&("object"==typeof i||"function"==typeof i)){if(e)return Yh(e,i)}else if(Xh){if(t)return tf(t,i)}else if(r)return function(e,t){var r=nf(e,t);return r&&r.value}(r,i)},has:function(i){if(Qh&&i&&("object"==typeof i||"function"==typeof i)){if(e)return ef(e,i)}else if(Xh){if(t)return sf(t,i)}else if(r)return function(e,t){return!!nf(e,t)}(r,i);return!1},set:function(i,s){Qh&&i&&("object"==typeof i||"function"==typeof i)?(e||(e=new Qh),Zh(e,i,s)):Xh?(t||(t=new Xh),rf(t,i,s)):(r||(r={key:{},next:null}),function(e,t,r){var i=nf(e,t);i?i.value=r:e.next={key:t,next:e.next,value:r}}(r,i,s))}};return i},vf=mf,yf=df,bf=Object.prototype.hasOwnProperty,wf={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},Sf=Array.isArray,_f=String.prototype.split,Rf=Array.prototype.push,kf=function(e,t){Rf.apply(e,Sf(t)?t:[t])},Cf=Date.prototype.toISOString,Pf=yf.default,Tf={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:vf.encode,encodeValuesOnly:!1,format:Pf,formatter:yf.formatters[Pf],indices:!1,serializeDate:function(e){return Cf.call(e)},skipNulls:!1,strictNullHandling:!1},Ef={},Df=function e(t,r,i,s,n,o,a,c,d,l,p,u,h,f,m,g){for(var v=t,y=g,b=0,w=!1;void 0!==(y=y.get(Ef))&&!w;){var S=y.get(t);if(b+=1,void 0!==S){if(S===b)throw new RangeError("Cyclic object value");w=!0}void 0===y.get(Ef)&&(b=0)}if("function"==typeof c?v=c(r,v):v instanceof Date?v=p(v):"comma"===i&&Sf(v)&&(v=vf.maybeMap(v,(function(e){return e instanceof Date?p(e):e}))),null===v){if(n)return a&&!f?a(r,Tf.encoder,m,"key",u):r;v=""}if(function(e){return"string"==typeof e||"number"==typeof e||"boolean"==typeof e||"symbol"==typeof e||"bigint"==typeof e}(v)||vf.isBuffer(v)){if(a){var _=f?r:a(r,Tf.encoder,m,"key",u);if("comma"===i&&f){for(var R=_f.call(String(v),","),k="",C=0;C<R.length;++C)k+=(0===C?"":",")+h(a(R[C],Tf.encoder,m,"value",u));return[h(_)+(s&&Sf(v)&&1===R.length?"[]":"")+"="+k]}return[h(_)+"="+h(a(v,Tf.encoder,m,"value",u))]}return[h(r)+"="+h(String(v))]}var P,T=[];if(void 0===v)return T;if("comma"===i&&Sf(v))P=[{value:v.length>0?v.join(",")||null:void 0}];else if(Sf(c))P=c;else{var E=Object.keys(v);P=d?E.sort(d):E}for(var D=s&&Sf(v)&&1===v.length?r+"[]":r,M=0;M<P.length;++M){var x=P[M],L="object"==typeof x&&void 0!==x.value?x.value:v[x];if(!o||null!==L){var I=Sf(v)?"function"==typeof i?i(D,x):D:D+(l?"."+x:"["+x+"]");g.set(t,b);var O=gf();O.set(Ef,g),kf(T,e(L,I,i,s,n,o,a,c,d,l,p,u,h,f,m,O))}}return T},Mf=mf,xf=Object.prototype.hasOwnProperty,Lf=Array.isArray,If={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:Mf.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},Of=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},Af=function(e,t){return e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1?e.split(","):e},jf=function(e,t,r,i){if(e){var s=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,n=/(\[[^[\]]*])/g,o=r.depth>0&&/(\[[^[\]]*])/.exec(s),a=o?s.slice(0,o.index):s,c=[];if(a){if(!r.plainObjects&&xf.call(Object.prototype,a)&&!r.allowPrototypes)return;c.push(a)}for(var d=0;r.depth>0&&null!==(o=n.exec(s))&&d<r.depth;){if(d+=1,!r.plainObjects&&xf.call(Object.prototype,o[1].slice(1,-1))&&!r.allowPrototypes)return;c.push(o[1])}return o&&c.push("["+s.slice(o.index)+"]"),function(e,t,r,i){for(var s=i?t:Af(t,r),n=e.length-1;n>=0;--n){var o,a=e[n];if("[]"===a&&r.parseArrays)o=[].concat(s);else{o=r.plainObjects?Object.create(null):{};var c="["===a.charAt(0)&&"]"===a.charAt(a.length-1)?a.slice(1,-1):a,d=parseInt(c,10);r.parseArrays||""!==c?!isNaN(d)&&a!==c&&String(d)===c&&d>=0&&r.parseArrays&&d<=r.arrayLimit?(o=[])[d]=s:"__proto__"!==c&&(o[c]=s):o={0:s}}s=o}return s}(c,t,r,i)}},Ff=function(e,t){var r,i=e,s=function(e){if(!e)return Tf;if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var t=e.charset||Tf.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var r=yf.default;if(void 0!==e.format){if(!bf.call(yf.formatters,e.format))throw new TypeError("Unknown format option provided.");r=e.format}var i=yf.formatters[r],s=Tf.filter;return("function"==typeof e.filter||Sf(e.filter))&&(s=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Tf.addQueryPrefix,allowDots:void 0===e.allowDots?Tf.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Tf.charsetSentinel,delimiter:void 0===e.delimiter?Tf.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Tf.encode,encoder:"function"==typeof e.encoder?e.encoder:Tf.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Tf.encodeValuesOnly,filter:s,format:r,formatter:i,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Tf.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Tf.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Tf.strictNullHandling}}(t);"function"==typeof s.filter?i=(0,s.filter)("",i):Sf(s.filter)&&(r=s.filter);var n,o=[];if("object"!=typeof i||null===i)return"";n=t&&t.arrayFormat in wf?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var a=wf[n];if(t&&"commaRoundTrip"in t&&"boolean"!=typeof t.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var c="comma"===a&&t&&t.commaRoundTrip;r||(r=Object.keys(i)),s.sort&&r.sort(s.sort);for(var d=gf(),l=0;l<r.length;++l){var p=r[l];s.skipNulls&&null===i[p]||kf(o,Df(i[p],p,a,c,s.strictNullHandling,s.skipNulls,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,d))}var u=o.join(s.delimiter),h=!0===s.addQueryPrefix?"?":"";return s.charsetSentinel&&("iso-8859-1"===s.charset?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),u.length>0?h+u:""},Nf=function(e,t){var r=function(e){if(!e)return If;if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?If.charset:e.charset;return{allowDots:void 0===e.allowDots?If.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:If.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:If.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:If.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:If.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:If.comma,decoder:"function"==typeof e.decoder?e.decoder:If.decoder,delimiter:"string"==typeof e.delimiter||Mf.isRegExp(e.delimiter)?e.delimiter:If.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:If.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:If.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:If.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:If.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:If.strictNullHandling}}(t);if(""===e||null==e)return r.plainObjects?Object.create(null):{};for(var i="string"==typeof e?function(e,t){var r,i={},s=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,n=t.parameterLimit===1/0?void 0:t.parameterLimit,o=s.split(t.delimiter,n),a=-1,c=t.charset;if(t.charsetSentinel)for(r=0;r<o.length;++r)0===o[r].indexOf("utf8=")&&("utf8=%E2%9C%93"===o[r]?c="utf-8":"utf8=%26%2310003%3B"===o[r]&&(c="iso-8859-1"),a=r,r=o.length);for(r=0;r<o.length;++r)if(r!==a){var d,l,p=o[r],u=p.indexOf("]="),h=-1===u?p.indexOf("="):u+1;-1===h?(d=t.decoder(p,If.decoder,c,"key"),l=t.strictNullHandling?null:""):(d=t.decoder(p.slice(0,h),If.decoder,c,"key"),l=Mf.maybeMap(Af(p.slice(h+1),t),(function(e){return t.decoder(e,If.decoder,c,"value")}))),l&&t.interpretNumericEntities&&"iso-8859-1"===c&&(l=Of(l)),p.indexOf("[]=")>-1&&(l=Lf(l)?[l]:l),xf.call(i,d)?i[d]=Mf.combine(i[d],l):i[d]=l}return i}(e,r):e,s=r.plainObjects?Object.create(null):{},n=Object.keys(i),o=0;o<n.length;++o){var a=n[o],c=jf(a,i[a],r,"string"==typeof e);s=Mf.merge(s,c,r)}return!0===r.allowSparse?s:Mf.compact(s)},Bf={formats:df,parse:Nf,stringify:Ff};class Uf{constructor(e){const{baseURL:t,timeout:r,customNode:i}=e;this.api=Su.create({baseURL:t||"https://lb.livedigital.space/v1",timeout:r||5e3,withCredentials:!1,paramsSerializer:e=>Bf.stringify(e)}),this.customNode=i}getNode(e){return r(this,void 0,void 0,(function*(){if(this.customNode)return this.customNode;const{data:t}=yield this.api.get("/nodes/best",{params:e});return t}))}}class qf extends g{constructor(e,t){super(e,null!=t?t:"invalid_payload")}}!function(e){e.DominantSpeaker="dominant-speaker",e.PeersVolumes="peers-volumes",e.Silence="silence"}($h||($h={}));class Wf{constructor(e){const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new Ge({logLevel:t.logLevel,namespace:"ChannelAudioObserverEventHandler",onLogMessage:r})}handle(e){try{const t=JSON.parse(e);switch(Wf.validateEventPayload(t),t.event){case $h.DominantSpeaker:this.handleDominantSpeaker(t);break;case $h.PeersVolumes:this.handlePeerVolumes(t);break;case $h.Silence:this.handleSilence()}}catch(t){this.logger.warn("Failed to handle audio observer event",{error:bd(t),eventData:e})}}handleDominantSpeaker(e){const{peerId:t}=e.data,r=this.engine.getPeerById(t);this.engine.setActiveSpeakerPeer(r)}handlePeerVolumes(e){e.volumes.forEach((e=>{var t;const{peerId:r,trackLabel:i,value:s}=e,n=null===(t=this.engine.getPeerById(r))||void 0===t?void 0:t.tracks.get(i);n&&n.setVolume(s)}))}handleSilence(){this.engine.peers.flatMap((e=>Array.from(e.tracks.values()))).forEach((e=>e.setVolume(0))),this.engine.setActiveSpeakerPeer(void 0)}static validateEventPayload(e){switch(e.event){case $h.Silence:break;case $h.DominantSpeaker:{e.data||Wf.throwInvalidPayload();const{peerId:t,producerId:r,trackLabel:i}=e.data;"string"==typeof t&&"string"==typeof r&&i===u.Microphone||Wf.throwInvalidPayload();break}case $h.PeersVolumes:Array.isArray(e.volumes)||Wf.throwInvalidPayload(),e.volumes.forEach((e=>{const{peerId:t,producerId:r,value:i,trackLabel:s}=e;"string"==typeof t&&"string"==typeof r&&"number"==typeof i&&s===u.Microphone||Wf.throwInvalidPayload()}));break;default:Wf.throwInvalidPayload()}}static throwInvalidPayload(){throw new qf("Invalid channel audio observer event handler payload")}}var Vf=Uint8Array,zf=Uint16Array,$f=Int32Array,Gf=new Vf([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Hf=new Vf([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Jf=new Vf([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Kf=function(e,t){for(var r=new zf(31),i=0;i<31;++i)r[i]=t+=1<<e[i-1];var s=new $f(r[30]);for(i=1;i<30;++i)for(var n=r[i];n<r[i+1];++n)s[n]=n-r[i]<<5|i;return{b:r,r:s}},Qf=Kf(Gf,2),Xf=Qf.b,Yf=Qf.r;Xf[28]=258,Yf[258]=28;for(var Zf=Kf(Hf,0).b,em=new zf(32768),tm=0;tm<32768;++tm){var rm=(43690&tm)>>1|(21845&tm)<<1;rm=(61680&(rm=(52428&rm)>>2|(13107&rm)<<2))>>4|(3855&rm)<<4,em[tm]=((65280&rm)>>8|(255&rm)<<8)>>1}var im=function(e,t,r){for(var i=e.length,s=0,n=new zf(t);s<i;++s)e[s]&&++n[e[s]-1];var o,a=new zf(t);for(s=1;s<t;++s)a[s]=a[s-1]+n[s-1]<<1;if(r){o=new zf(1<<t);var c=15-t;for(s=0;s<i;++s)if(e[s])for(var d=s<<4|e[s],l=t-e[s],p=a[e[s]-1]++<<l,u=p|(1<<l)-1;p<=u;++p)o[em[p]>>c]=d}else for(o=new zf(i),s=0;s<i;++s)e[s]&&(o[s]=em[a[e[s]-1]++]>>15-e[s]);return o},sm=new Vf(288);for(tm=0;tm<144;++tm)sm[tm]=8;for(tm=144;tm<256;++tm)sm[tm]=9;for(tm=256;tm<280;++tm)sm[tm]=7;for(tm=280;tm<288;++tm)sm[tm]=8;var nm=new Vf(32);for(tm=0;tm<32;++tm)nm[tm]=5;var om=im(sm,9,1),am=im(nm,5,1),cm=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},dm=function(e,t,r){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(7&t)&r},lm=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},pm=function(e){return(e+7)/8|0},um=function(e,t,r){return(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length),new Vf(e.subarray(t,r))},hm=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],fm=function(e,t,r){var i=new Error(t||hm[e]);if(i.code=e,Error.captureStackTrace&&Error.captureStackTrace(i,fm),!r)throw i;return i},mm=function(e,t,r,i){var s=e.length,n=i?i.length:0;if(!s||t.f&&!t.l)return r||new Vf(0);var o=!r,a=o||2!=t.i,c=t.i;o&&(r=new Vf(3*s));var d=function(e){var t=r.length;if(e>t){var i=new Vf(Math.max(2*t,e));i.set(r),r=i}},l=t.f||0,p=t.p||0,u=t.b||0,h=t.l,f=t.d,m=t.m,g=t.n,v=8*s;do{if(!h){l=dm(e,p,1);var y=dm(e,p+1,3);if(p+=3,!y){var b=e[(M=pm(p)+4)-4]|e[M-3]<<8,w=M+b;if(w>s){c&&fm(0);break}a&&d(u+b),r.set(e.subarray(M,w),u),t.b=u+=b,t.p=p=8*w,t.f=l;continue}if(1==y)h=om,f=am,m=9,g=5;else if(2==y){var S=dm(e,p,31)+257,_=dm(e,p+10,15)+4,R=S+dm(e,p+5,31)+1;p+=14;for(var k=new Vf(R),C=new Vf(19),P=0;P<_;++P)C[Jf[P]]=dm(e,p+3*P,7);p+=3*_;var T=cm(C),E=(1<<T)-1,D=im(C,T,1);for(P=0;P<R;){var M,x=D[dm(e,p,E)];if(p+=15&x,(M=x>>4)<16)k[P++]=M;else{var L=0,I=0;for(16==M?(I=3+dm(e,p,3),p+=2,L=k[P-1]):17==M?(I=3+dm(e,p,7),p+=3):18==M&&(I=11+dm(e,p,127),p+=7);I--;)k[P++]=L}}var O=k.subarray(0,S),A=k.subarray(S);m=cm(O),g=cm(A),h=im(O,m,1),f=im(A,g,1)}else fm(1);if(p>v){c&&fm(0);break}}a&&d(u+131072);for(var j=(1<<m)-1,F=(1<<g)-1,N=p;;N=p){var B=(L=h[lm(e,p)&j])>>4;if((p+=15&L)>v){c&&fm(0);break}if(L||fm(2),B<256)r[u++]=B;else{if(256==B){N=p,h=null;break}var U=B-254;if(B>264){var q=Gf[P=B-257];U=dm(e,p,(1<<q)-1)+Xf[P],p+=q}var W=f[lm(e,p)&F],V=W>>4;W||fm(3),p+=15&W;A=Zf[V];if(V>3){q=Hf[V];A+=lm(e,p)&(1<<q)-1,p+=q}if(p>v){c&&fm(0);break}a&&d(u+131072);var z=u+U;if(u<A){var $=n-A,G=Math.min(A,z);for($+u<0&&fm(3);u<G;++u)r[u]=i[$+u]}for(;u<z;++u)r[u]=r[u-A]}}t.l=h,t.p=N,t.b=u,t.f=l,h&&(l=1,t.m=m,t.d=f,t.n=g)}while(!l);return u!=r.length&&o?um(r,0,u):r.subarray(0,u)},gm=new Vf(0);function vm(e,t){var r=function(e){31==e[0]&&139==e[1]&&8==e[2]||fm(6,"invalid gzip data");var t=e[3],r=10;4&t&&(r+=2+(e[10]|e[11]<<8));for(var i=(t>>3&1)+(t>>4&1);i>0;i-=!e[r++]);return r+(2&t)}(e);return r+8>e.length&&fm(6,"invalid gzip data"),mm(e.subarray(r,-8),{i:2},t&&t.out||new Vf(function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}(e)),t&&t.dictionary)}function ym(e,t){return mm(e.subarray(function(e,t){return(8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31)&&fm(6,"invalid zlib data"),(e[1]>>5&1)==+!t&&fm(6,"invalid zlib data: "+(32&e[1]?"need":"unexpected")+" dictionary"),2+(e[1]>>3&4)}(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function bm(e,t){return 31==e[0]&&139==e[1]&&8==e[2]?vm(e,t):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?function(e,t){return mm(e,{i:2},t&&t.out,t&&t.dictionary)}(e,t):ym(e,t)}var wm="undefined"!=typeof TextDecoder&&new TextDecoder;try{wm.decode(gm,{stream:!0}),1}catch(Bc){}var Sm,_m,Rm,km;function Cm(e,t){if(t){for(var r="",i=0;i<e.length;i+=16384)r+=String.fromCharCode.apply(null,e.subarray(i,i+16384));return r}if(wm)return wm.decode(e);var s=function(e){for(var t="",r=0;;){var i=e[r++],s=(i>127)+(i>223)+(i>239);if(r+s>e.length)return{s:t,r:um(e,r-1)};s?3==s?(i=((15&i)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,t+=String.fromCharCode(55296|i>>10,56320|1023&i)):t+=1&s?String.fromCharCode((31&i)<<6|63&e[r++]):String.fromCharCode((15&i)<<12|(63&e[r++])<<6|63&e[r++]):t+=String.fromCharCode(i)}}(e),n=s.s;return(r=s.r).length&&fm(8),n}class Pm{constructor(e){Sm.set(this,[]),_m.set(this,[]),Rm.set(this,[]),km.set(this,[]);const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new Ge({logLevel:t.logLevel,namespace:"ChannelStateSyncEventHandler",onLogMessage:r})}handle(e){try{const{event:t,data:r}=this.parseChannelStateSyncEventPayload(e);"channel-state"===t&&this.handleChannelStateEvent(r)}catch(e){this.logger.error("handleChannelStateSyncEvent()",{error:bd(e)})}}handleChannelStateEvent(e){const t=this.getLocalState();this.processStateInconsistency(t,e)}processStateInconsistency(e,t){this.notifyIfHasConfirmedInconsistency(e,t),this.prepareProbableInconsistencyStats(e,t)}notifyIfHasConfirmedInconsistency(e,t){t.peers.forEach((t=>{const r=e.peers.find((e=>e.id===t.id));r?(this.resetPeerInconsistency(t.id),t.producers.forEach((e=>{const t=r.producers.find((t=>t.id===e.id));if(!t)return void this.notifyIfConfirmedProducerInconsistency(e.id);this.resetProducerInconsistency(t.id);t.paused!==e.paused?this.notifyIfConfirmedProducerStateInconsistency(t.id,{localPaused:t.paused,remotePaused:e.paused}):this.resetProducerStateInconsistency(t.id)}))):this.notifyIfConfirmedPeerInconsistency(t.id)}))}prepareProbableInconsistencyStats(e,t){const r=[],n=[],o=[];this.getIsConnectionActive()?(t.peers.forEach((t=>{if(i(this,Sm,"f").includes(t.id))return;const s=e.peers.find((e=>e.id===t.id));s||r.push(t.id),s&&t.producers.forEach((e=>{if(i(this,_m,"f").includes(e.id))return;const t=s.producers.find((t=>t.id===e.id));if(t||n.push(e.id),!t)return;if(i(this,Rm,"f").includes(e.id))return;t.paused!==e.paused&&o.push(e.id)}))})),2===i(this,km,"f").length&&i(this,km,"f").shift(),i(this,km,"f").push({probablyMissingPeers:r,probablyMissingProducers:n,probablyProducersWithInconsistentState:o})):s(this,km,[],"f")}isReachedMaxCheckRetries(e,t){let r=0;return i(this,km,"f").forEach((i=>{i[e].includes(t)&&(r+=1)})),r>=2}isAlreadyAlertedAbout(e,t){return e.includes(t)}notifyIfConfirmedPeerInconsistency(e){const t=this.isReachedMaxCheckRetries("probablyMissingPeers",e),r=this.isAlreadyAlertedAbout(i(this,Sm,"f"),e);t&&!r&&(i(this,Sm,"f").push(e),this.logger.warn("Peer is missing",{case:"channel-state-sync",missingPeerId:e}))}resetPeerInconsistency(e){const t=i(this,Sm,"f").indexOf(e);t>-1&&delete i(this,Sm,"f")[t]}notifyIfConfirmedProducerInconsistency(e){const t=this.isReachedMaxCheckRetries("probablyMissingProducers",e),r=this.isAlreadyAlertedAbout(i(this,_m,"f"),e);t&&!r&&(i(this,_m,"f").push(e),this.logger.warn("Producer is missing",{case:"channel-state-sync",missingProducerId:e}))}resetProducerInconsistency(e){const t=i(this,_m,"f").indexOf(e);t>-1&&delete i(this,_m,"f")[t]}notifyIfConfirmedProducerStateInconsistency(e,t){const r=this.isReachedMaxCheckRetries("probablyProducersWithInconsistentState",e),s=this.isAlreadyAlertedAbout(i(this,Rm,"f"),e);r&&!s&&(i(this,Rm,"f").push(e),this.logger.warn("Producer is in inconsistent state",Object.assign({case:"channel-state-sync",producerId:e},t)))}resetProducerStateInconsistency(e){const t=i(this,Rm,"f").indexOf(e);t>-1&&delete i(this,Rm,"f")[t]}parseChannelStateSyncEventPayload(e){const t=bm(new Uint8Array(e));return JSON.parse(Cm(t))}getLocalState(){const{hostPeers:e}=this.engine;return{peers:e.map((e=>({id:e.id,producers:e.getProducers().map((e=>({id:e.id,paused:e.paused})))})))}}getIsConnectionActive(){try{return this.engine.checkConnectionActivity(),!0}catch(e){return!1}}}Sm=new WeakMap,_m=new WeakMap,Rm=new WeakMap,km=new WeakMap;class Tm{createSystem(e){return new _d(e)}createMedia(e){return new Ja(e)}createNetwork(e){const{loadbalancer:t,logLevel:r,onLogMessage:i}=e,s=new $l({logLevel:r,onLogMessage:i}),n=new Uf(t);return new wd({logLevel:r,socketClient:s,loadBalancerApiClient:n,onLogMessage:i})}createChannelEventHandler(e){return new Rd(e)}createMediaSoupEventHandler(e){return new kd(e)}createAudioObserverEventHandler(e){return new Wf(e)}createChannelStateSyncEventHandler(e){return new Pm(e)}createIssueDetector(e){var t,r;const i=null!==(t=e.logger)&&void 0!==t?t:console,s=new fd({statsParser:new md({ignoreSSRCList:e.ignoreSSRCList,logger:null!==(r=e.logger)&&void 0!==r?r:console})});return new gd({issueEmitter:new Zc,networkScoresCalculator:new rd,detectors:[new ld,new nd,new od,new ad,new dd,new cd,new sd,new pd],statsReporter:new ed({compositeStatsParser:s,getStatsInterval:5e3}),onIssues:e.onIssues,onNetworkScoresUpdated:e.onNetworkScoresUpdated,ignoreSSRCList:e.ignoreSSRCList,compositeStatsParser:s,logger:i})}}class Em extends AudioWorkletNode{constructor(e){super(e.context,"rnnoise",{channelCountMode:"explicit",channelCount:1,channelInterpretation:"speakers",numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{module:e.noiseSuppressor.module}}),this.port.onmessage=({data:e})=>{const t=Object.assign(new Event("status"),e);this.dispatchEvent(t)}}update(e){this.port.postMessage(e)}static register(e){return r(this,void 0,void 0,(function*(){yield e.audioWorklet.addModule(`${window.location.origin}/noiseSuppressionWorklet.js`)}))}}var Dm,Mm,xm,Lm,Im,Om;class Am{constructor(e){Dm.set(this,void 0),Mm.set(this,void 0),xm.set(this,void 0),Lm.set(this,void 0),Im.set(this,void 0),Om.set(this,!0),s(this,Dm,e.noiseSuppressor.instance.exports,"f"),s(this,Mm,e.context,"f"),s(this,xm,new Float32Array(i(this,Dm,"f").memory.buffer),"f"),s(this,Lm,i(this,Dm,"f").newState(),"f"),s(this,Im,i(this,Mm,"f").createScriptProcessor(),"f"),this.setOnAudioProcess()}get noiseSuppressionScriptProcessorNode(){return i(this,Im,"f")}update(e){e||(s(this,Om,!1,"f"),i(this,Dm,"f").deleteState(i(this,Lm,"f")));const t=Object.assign(new Event("status"),{vadProb:i(this,Dm,"f").getVadProb(i(this,Lm,"f"))});i(this,Im,"f").dispatchEvent(t)}setOnAudioProcess(){i(this,Im,"f").addEventListener("audioprocess",(({inputBuffer:e,outputBuffer:t})=>{if(!i(this,Om,"f"))return;i(this,xm,"f").set(e.getChannelData(0),i(this,Dm,"f").getInput(i(this,Lm,"f"))/4);const r=t.getChannelData(0),s=i(this,Dm,"f").pipe(i(this,Lm,"f"),r.length)/4;s&&r.set(i(this,xm,"f").subarray(s,s+r.length))}))}}Dm=new WeakMap,Mm=new WeakMap,xm=new WeakMap,Lm=new WeakMap,Im=new WeakMap,Om=new WeakMap;var jm,Fm,Nm,Bm,Um,qm,Wm,Vm,zm,$m;class Gm{constructor({context:e,noiseSuppressor:t}){jm.set(this,void 0),Fm.set(this,void 0),Nm.set(this,void 0),s(this,jm,e,"f"),s(this,Fm,t,"f")}createNoiseSuppressionNode(){return r(this,void 0,void 0,(function*(){return/apple/i.test(navigator.vendor)?this.createScriptProcessorNode():this.createAudioWorkletNode()}))}stop(){var e;null===(e=i(this,Nm,"f"))||void 0===e||e.update(!1)}createAudioWorkletNode(){return r(this,void 0,void 0,(function*(){return yield Em.register(i(this,jm,"f")),s(this,Nm,new Em({context:i(this,jm,"f"),noiseSuppressor:i(this,Fm,"f")}),"f"),i(this,Nm,"f")}))}createScriptProcessorNode(){return s(this,Nm,new Am({context:i(this,jm,"f"),noiseSuppressor:i(this,Fm,"f")}),"f"),i(this,Nm,"f").noiseSuppressionScriptProcessorNode}}jm=new WeakMap,Fm=new WeakMap,Nm=new WeakMap;class Hm{constructor(e){Bm.set(this,void 0),Um.set(this,void 0),qm.set(this,void 0),Wm.set(this,void 0),s(this,Bm,e.noiseSuppressor,"f"),s(this,qm,new Ge({namespace:"TrackProcessor",logLevel:e.logLevel}),"f")}get isProcessing(){return!!i(this,Wm,"f")}processTrack(e){return r(this,void 0,void 0,(function*(){const t=(e=>{const t=window.AudioContext||window.webkitAudioContext||!1;return t?new t(e):null})();if(!t)throw new Error("AudioContext is not available");const r=new MediaStreamAudioDestinationNode(t,{channelCountMode:"explicit",channelCount:1,channelInterpretation:"speakers"});yield Em.register(t);const n=t.createMediaStreamSource(new MediaStream([e])),o=new Gm({context:t,noiseSuppressor:i(this,Bm,"f")}),a=yield o.createNoiseSuppressionNode();a.connect(r),n.connect(a);const[c]=r.stream.getTracks();return s(this,Um,{audioContext:t,streamDestination:r,noiseSuppressionNode:a,noiseSuppressionProvider:o},"f"),s(this,Wm,c,"f"),i(this,qm,"f").info("processTrack()",{track:e}),c}))}stopProcessing(){var e;return r(this,void 0,void 0,(function*(){if(this.isProcessing)if(i(this,Um,"f"))try{i(this,Um,"f").noiseSuppressionProvider.stop(),i(this,Um,"f").noiseSuppressionNode.disconnect(),i(this,Um,"f").streamDestination.disconnect(),yield i(this,Um,"f").audioContext.close(),null===(e=i(this,Wm,"f"))||void 0===e||e.stop(),s(this,Wm,void 0,"f"),i(this,qm,"f").info("stopProcessing()",{success:!0})}catch(e){i(this,qm,"f").error("stopProcessing()",{success:!1,error:e})}else i(this,qm,"f").warn("stopProcessing()",{success:!1,description:"Processing context is not available"});else i(this,qm,"f").debug("stopProcessing()",{description:"Track is not processed"})}))}}Bm=new WeakMap,Um=new WeakMap,qm=new WeakMap,Wm=new WeakMap;class Jm extends cc{constructor(e){super(e),Vm.set(this,void 0),zm.set(this,void 0),$m.set(this,void 0),e.noiseSuppressor&&s(this,Vm,new Hm({noiseSuppressor:e.noiseSuppressor,logLevel:e.logLevel}),"f"),s(this,$m,new Ge({namespace:"AudioTrack",logLevel:e.logLevel}),"f")}get isEffectsProcessing(){var e;return!!(null===(e=i(this,Vm,"f"))||void 0===e?void 0:e.isProcessing)}getEncoderConfig(){return this.encoderConfig}getEncodings(){var e;return null!==(e=this.getEncoderConfig().encodings)&&void 0!==e?e:Oa}getCodecOptions(){var e,t;return{opusFec:null===(e=this.getEncoderConfig().enableFec)||void 0===e||e,opusDtx:null===(t=this.getEncoderConfig().enableDtx)||void 0===t||t}}getPreferredCodec(){const{preferredCodec:e}=this.getEncoderConfig();return e||"opus"}enableNoiseSuppression(){var e;return r(this,void 0,void 0,(function*(){if(i(this,Vm,"f"))try{const t=yield null===(e=i(this,Vm,"f"))||void 0===e?void 0:e.processTrack(this.mediaStreamTrack);s(this,zm,this.mediaStreamTrack,"f"),yield this.replaceTrack(t)}catch(e){throw this.logger.warn("enableNoiseSuppression()",{description:"Can not enable noise suppression",track:this,error:e}),new Error("Can not enable noise suppression")}else this.logger.warn("enableNoiseSuppression()",{description:"Track suppressor is not defined"})}))}disableNoiseSuppression(){var e,t;return r(this,void 0,void 0,(function*(){try{if(!(null===(e=i(this,Vm,"f"))||void 0===e?void 0:e.isProcessing))return void i(this,$m,"f").debug("stopProcessing()",{description:"Track is not processed"});if(!i(this,zm,"f"))return void this.logger.warn("disableNoiseSuppression()",{description:"Original track missing"});this.isPublished&&(yield this.replaceTrack(i(this,zm,"f"))),yield null===(t=i(this,Vm,"f"))||void 0===t?void 0:t.stopProcessing()}catch(e){throw this.logger.warn("disableNoiseSuppression()",{description:"Can not disable noise suppression",track:this,error:e}),new Error("Can not disable noise suppression")}}))}publish(){return r(this,void 0,void 0,(function*(){yield this.produce({encodings:this.getEncodings(),preferredCodec:this.getPreferredCodec(),codecOptions:this.getCodecOptions()}),this.clientEventEmitter.emit(W,this)}))}}Vm=new WeakMap,zm=new WeakMap,$m=new WeakMap;class Km{createAudioTrack(e){return new Jm(e)}createVideoTrack(e){return new Ic(e)}}class Qm{constructor(e){var t,r;const{observer:i,network:s,onLogMessage:o,onIssues:a,onNetworkScoresUpdated:c,logLevel:d,disableWid:l}=e;this._observer=null!=i?i:new n;const p=new Tm,u=new Km;this.engine=new Fc({dependenciesFactory:p,clientEventEmitter:this.observer,media:{mediaTracksFactory:u},network:{loadbalancer:{baseURL:null===(t=null==s?void 0:s.loadbalancer)||void 0===t?void 0:t.baseURL,customNode:null===(r=null==s?void 0:s.loadbalancer)||void 0===r?void 0:r.customNode}},logLevel:d,onLogMessage:o,onIssues:a,onNetworkScoresUpdated:c,disableWid:l})}get observer(){return this._observer}get id(){return this.engine.mySocketId}get peers(){return this.engine.peers}get availableVideoDevices(){return this.engine.system.availableVideoDevices}get availableAudioDevices(){return this.engine.system.availableAudioDevices}get canUseNoiseSuppression(){return this.engine.canUseNoiseSuppression}detectDevices(){return r(this,void 0,void 0,(function*(){return yield this.engine.system.detectDevices(),{video:this.engine.system.availableVideoDevices,audio:this.engine.system.availableAudioDevices}}))}join(e){return this.engine.join(e)}leave(){return this.engine.release()}confirmActivity(){return this.engine.confirmActivity()}createCameraVideoTrack(e){return this.engine.createCameraVideoTrack(e)}createMicrophoneAudioTrack(e){return this.engine.createMicrophoneAudioTrack(e)}createScreenMediaTracks(e){return this.engine.createScreenMediaTracks(e)}deleteTrack(e){return this.engine.deleteTrack(e)}loadPeers(e){return this.engine.loadPeers(e)}updateAppData(e){return this.engine.updateAppData(e)}getTransportsInfo(){return r(this,void 0,void 0,(function*(){return this.engine.network.getTransportsStateInfo()}))}getNodeActiveStreamsStat(){return this.engine.getNodeActiveStreamsStat()}setPreferRelay(e){this.engine.network.setPreferRelay(e)}getPreferRelay(){return this.engine.network.getPreferRelay()}}export{Qm as default};
241
+ `,{width:c,height:d}=n,l=c/d,p=lc(e,e.VERTEX_SHADER,o),u=lc(e,e.FRAGMENT_SHADER,a),h=hc(e,p,u,t,r),f=e.getUniformLocation(h,"u_backgroundScale"),m=e.getUniformLocation(h,"u_backgroundOffset"),g=e.getUniformLocation(h,"u_inputFrame"),v=e.getUniformLocation(h,"u_personMask"),y=e.getUniformLocation(h,"u_background"),b=e.getUniformLocation(h,"u_coverage"),w=e.getUniformLocation(h,"u_lightWrapping"),S=e.getUniformLocation(h,"u_blendMode");e.useProgram(h),e.uniform2f(f,1,1),e.uniform2f(m,0,0),e.uniform1i(g,0),e.uniform1i(v,1),e.uniform2f(b,0,1),e.uniform1f(w,0),e.uniform1f(S,0);let _=null;function R(t){_=pc(e,e.RGBA8,t.naturalWidth,t.naturalHeight,e.LINEAR,e.LINEAR),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.naturalWidth,t.naturalHeight,e.RGBA,e.UNSIGNED_BYTE,t);let r=0,i=0,s=t.naturalWidth,n=t.naturalHeight;s/n<l?(n=s/l,i=(t.naturalHeight-n)/2):(s=n*l,r=(t.naturalWidth-s)/2);const o=s/t.naturalWidth,a=n/t.naturalHeight;r/=t.naturalWidth,i/=t.naturalHeight,e.uniform2f(f,o,a),e.uniform2f(m,r,i)}return(null==s?void 0:s.complete)?R(s):s&&(s.onload=()=>{R(s)}),{render:function(){e.viewport(0,0,c,d),e.useProgram(h),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,i),null!==_&&(e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,_),e.uniform1i(y,2)),e.bindFramebuffer(e.FRAMEBUFFER,null),e.drawArrays(e.TRIANGLE_STRIP,0,4)},updateCoverage:function(t){e.useProgram(h),e.uniform2f(b,t[0],t[1])},updateLightWrapping:function(t){e.useProgram(h),e.uniform1f(w,t)},updateBlendMode:function(t){e.useProgram(h),e.uniform1f(S,"screen"===t?0:1)},cleanUp:function(){e.deleteTexture(_),e.deleteProgram(h),e.deleteShader(u),e.deleteShader(p)}}}(u,m,g,b,t,n);return{render:function(){return r(this,void 0,void 0,(function*(){u.activeTexture(u.TEXTURE0),u.bindTexture(u.TEXTURE_2D,v),u.texImage2D(u.TEXTURE_2D,0,u.RGBA,u.RGBA,u.UNSIGNED_BYTE,e.htmlElement),u.bindVertexArray(f),yield w.render(),o._runInference(),S.render(),_.render(),R.render()}))},updatePostProcessingConfig:function(e){if(_.updateSigmaSpace(e.jointBilateralFilter.sigmaSpace),_.updateSigmaColor(e.jointBilateralFilter.sigmaColor),"image"===i.type){const t=R;t.updateCoverage(e.coverage),t.updateLightWrapping(e.lightWrapping),t.updateBlendMode(e.blendMode)}else if("blur"===i.type){R.updateCoverage(e.coverage)}else{const e=R;e.updateCoverage([0,.9999]),e.updateLightWrapping(0)}},cleanUp:function(){R.cleanUp(),_.cleanUp(),S.cleanUp(),w.cleanUp(),u.deleteTexture(b),u.deleteTexture(y),u.deleteTexture(v),u.deleteBuffer(g),u.deleteBuffer(m),u.deleteVertexArray(f),u.deleteShader(h)}}}var wc,Sc,_c,Rc,kc,Cc,Pc,Tc,Ec,Dc;class Mc{constructor(e){wc.set(this,!1),Sc.set(this,void 0),_c.set(this,void 0),Rc.set(this,void 0),s(this,Rc,new Ge({logLevel:e,namespace:"TensorFlowLoader"}),"f")}get isLoaded(){return i(this,wc,"f")}get tfliteModule(){return i(this,Sc,"f")||i(this,_c,"f")}loadTFLite(){return r(this,void 0,void 0,(function*(){yield Promise.all([this.loadTFLiteRegular(),this.loadTFLiteSIMD()]),this.tfliteModule&&s(this,wc,!0,"f")}))}loadTFLiteModel(e){return r(this,void 0,void 0,(function*(){if(this.tfliteModule)try{const t=Mc.getTFLiteModelFileName(e);i(this,Rc,"f").info("loading model",{modelFileName:t});const r=yield fetch(`${window.location.origin}/tflite/models/${t}.tflite`),s=yield r.arrayBuffer(),n=this.tfliteModule._getModelBufferMemoryOffset();this.tfliteModule.HEAPU8.set(new Uint8Array(s),n);const o=this.tfliteModule._loadModel(s.byteLength);i(this,Rc,"f").info("loading model result",{result:o})}catch(e){i(this,Rc,"f").warn("loadTFLiteModel()",{error:e})}else i(this,Rc,"f").warn("loadTFLiteModel()",{description:"TFLite module is not loaded"})}))}loadTFLiteRegular(){return r(this,void 0,void 0,(function*(){try{s(this,Sc,yield createTFLiteModule(),"f")}catch(e){i(this,Rc,"f").error("Failed to create TFLite WebAssembly module.",{error:e})}}))}loadTFLiteSIMD(){return r(this,void 0,void 0,(function*(){try{s(this,_c,yield createTFLiteSIMDModule(),"f")}catch(e){i(this,Rc,"f").error("Failed to create TFLite SIMD WebAssembly module.",{error:e})}}))}static getTFLiteModelFileName({model:e,inputResolution:t}){switch(e){case"meet":return"256x144"===t?"segm_full_v679":"segm_lite_v681";case"mlkit":return"selfiesegmentation_mlkit-256x256-2021_01_19-v1215.f16";default:throw new Error(`No TFLite file for this segmentation model: ${e}`)}}}function xc({sourcePlayback:e,backgroundConfig:t,segmentationConfig:i,canvas:s,tflite:n}){const o=s.getContext("2d");o.scale(1.031,1.031),o.translate(-11,-11);const[a,c]=mc[i.inputResolution],d=a*c,l=new ImageData(a,c),p=document.createElement("canvas");p.width=a,p.height=c;const u=p.getContext("2d"),h=n._getInputMemoryOffset()/4,f=n._getOutputMemoryOffset()/4;let m;return{render:function(){return r(this,void 0,void 0,(function*(){"none"!==t.type&&(function(){if(u.drawImage(e.htmlElement,0,0,e.width,e.height,0,0,a,c),"meet"===i.model||"mlkit"===i.model){const e=u.getImageData(0,0,a,c);for(let t=0;t<d;t+=1)n.HEAPF32[h+3*t]=e.data[4*t]/255,n.HEAPF32[h+3*t+1]=e.data[4*t+1]/255,n.HEAPF32[h+3*t+2]=e.data[4*t+2]/255}}(),function(){n._runInference();for(let e=0;e<d;e+=1)if("meet"===i.model){const t=n.HEAPF32[f+2*e],r=n.HEAPF32[f+2*e+1],i=Math.max(t,r),s=Math.exp(t-i),o=Math.exp(r-i);l.data[4*e+3]=255*o/(s+o)}else if("mlkit"===i.model){const t=n.HEAPF32[f+e];l.data[4*e+3]=255*t}u.putImageData(l,0,0)}()),o.globalCompositeOperation="copy",o.filter="none",(null==m?void 0:m.smoothSegmentationMask)&&("blur"===t.type||"image"===t.type)&&(o.filter="blur(8px)"),"none"!==t.type&&(o.drawImage(p,0,0,a,c,0,0,e.width,e.height),o.globalCompositeOperation="source-in",o.filter="none"),o.drawImage(e.htmlElement,0,0),"blur"===t.type&&(o.globalCompositeOperation="destination-over",o.filter="blur(8px)",o.drawImage(e.htmlElement,0,0))}))},updatePostProcessingConfig:function(e){m=e},cleanUp:function(){}}}wc=new WeakMap,Sc=new WeakMap,_c=new WeakMap,Rc=new WeakMap;class Lc{constructor(e){kc.set(this,void 0),Cc.set(this,void 0),Pc.set(this,!1),Tc.set(this,void 0),s(this,kc,new Mc(e.logLevel),"f"),s(this,Tc,new Ge({namespace:"VideoTrackProcessor",logLevel:e.logLevel}),"f")}get isProcessing(){return i(this,Pc,"f")}processTrack(e){return r(this,void 0,void 0,(function*(){const{track:t,pipelineConfig:n}=e;i(this,Pc,"f")&&this.stopProcessing();try{i(this,kc,"f").isLoaded||(yield i(this,kc,"f").loadTFLite(),yield i(this,kc,"f").loadTFLiteModel(n.segmentationConfig));const{tfliteModule:o}=i(this,kc,"f");if(!o)throw new Error("TensorFlow model is not available");const{targetFps:a}=n.segmentationConfig,c=yield Lc.buildSourcePlayback(t),d=document.createElement("canvas");d.width=c.width,d.height=c.height;const l=function(){const e=new Map,t=new Worker(`${window.location.origin}/timerWorker.js`);t.onmessage=t=>{const r=e.get(t.data.callbackId);r&&(e.delete(t.data.callbackId),r())};let r=1;return{setTimeout:function(i,s){return r+=1,e.set(r,i),t.postMessage({callbackId:r,timeoutMs:s}),r},clearTimeout:function(r){e.has(r)&&(t.postMessage({callbackId:r}),e.delete(r))},terminate:function(){e.clear(),t.terminate()}}}(),p={config:n,sourcePlayback:c,destinationPlayback:d,tflite:o},u="canvas2dCpu"===e.pipelineConfig.segmentationConfig.pipeline?Lc.buildCanvas2dPipeline(p):Lc.buildWebGL2Pipeline(p),h=()=>r(this,void 0,void 0,(function*(){const e=performance.now();return yield u.render(),l.setTimeout(h,performance.now()-e)})),f=yield h();u.updatePostProcessingConfig(n.postprocessingConfig);const m=d.captureStream(a),[g]=m.getVideoTracks();return s(this,Cc,{pipeline:u,destination:d,source:c.htmlElement,track:g,timerWorker:l,timerId:f},"f"),s(this,Pc,!0,"f"),g}catch(e){throw i(this,Tc,"f").error("processTrack()",{error:e,track:t}),new Error("Can not process this track")}}))}stopProcessing(){if(this.isProcessing)if(i(this,Cc,"f"))try{i(this,Cc,"f").pipeline.cleanUp(),i(this,Cc,"f").source.remove(),i(this,Cc,"f").destination.remove(),i(this,Cc,"f").timerWorker.clearTimeout(i(this,Cc,"f").timerId),i(this,Cc,"f").timerWorker.terminate(),i(this,Cc,"f").destination.remove(),i(this,Cc,"f").track.stop(),s(this,Cc,void 0,"f"),s(this,Pc,!1,"f")}catch(e){i(this,Tc,"f").error("cleanUp()",{error:e})}else i(this,Tc,"f").warn("cleanUp()",{description:"This track is not processing"});else i(this,Tc,"f").debug("stopProcessing()",{description:"Track is not processed"})}static buildWebGL2Pipeline(e){return bc({backgroundImage:e.config.backgroundConfig.imageSource,sourcePlayback:e.sourcePlayback,backgroundConfig:e.config.backgroundConfig,segmentationConfig:e.config.segmentationConfig,canvas:e.destinationPlayback,tflite:e.tflite})}static buildCanvas2dPipeline(e){return xc({sourcePlayback:e.sourcePlayback,backgroundConfig:e.config.backgroundConfig,segmentationConfig:e.config.segmentationConfig,canvas:e.destinationPlayback,tflite:e.tflite})}static buildSourcePlayback(e){return r(this,void 0,void 0,(function*(){const t=document.createElement("video");return t.srcObject=new MediaStream([e]),t.autoplay=!0,yield t.play(),{htmlElement:t,width:t.videoWidth,height:t.videoHeight}}))}}kc=new WeakMap,Cc=new WeakMap,Pc=new WeakMap,Tc=new WeakMap;class Ic extends cc{constructor(e){super(e),Ec.set(this,void 0),Dc.set(this,void 0),this.transformParams={},s(this,Ec,new Lc({logLevel:e.logLevel}),"f"),this.watchOrientation(),this.watchDocumentVisibility()}get isEffectsProcessing(){return i(this,Ec,"f").isProcessing}getEncoderConfig(){return this.encoderConfig}getCodecOptions(){return{videoGoogleStartBitrate:this.getEncoderConfig().videoGoogleStartBitrate||1e3}}getPreferredCodec(){const{preferredCodec:e}=this.getEncoderConfig();return e||(this.getLabel()===u.ScreenVideo?"vp8":"h264")}getEncodings(){return this.getEncoderConfig().encodings||La}setTransformParams(e){this.transformParams=e}setMaxSpatialLayer(e){return r(this,void 0,void 0,(function*(){const t=this.getProducer();t?(yield t.setMaxSpatialLayer(e),this.logger.debug("setMaxSpatialLayer()",{label:this.getLabel(),spatialLayer:e})):this.logger.warn("setMaxSpatialLayer()",{message:"Not produced yet"})}))}getMaxSpatialLayer(){const e=this.getProducer();if(e)return e.maxSpatialLayer;this.logger.warn("getMaxSpatialLayer()",{message:"Not produced yet"})}enableBlur(){return r(this,void 0,void 0,(function*(){try{s(this,Dc,this.mediaStreamTrack.clone(),"f");const e=yield i(this,Ec,"f").processTrack({track:this.mediaStreamTrack,pipelineConfig:document.hidden?vc:gc});yield this.replaceTrack(e),this.logger.info("enableBlur()",{track:this})}catch(e){throw this.logger.warn("enableBlur()",{track:this,error:e}),new Error("Can not enable virtual background")}}))}disableBlur(){return r(this,void 0,void 0,(function*(){try{if(!i(this,Ec,"f").isProcessing)return void this.logger.debug("disableBlur()",{description:"Track is not processed"});if(!i(this,Dc,"f"))return void this.logger.warn("disableBlur()",{description:"Original track missing"});this.isPublished&&(yield this.replaceTrack(i(this,Dc,"f"))),i(this,Ec,"f").stopProcessing(),this.logger.info("disableBlur()",{track:this})}catch(e){throw this.logger.warn("disableBlur()",{track:this,error:e}),new Error("Can not disable virtual background")}}))}publish(e={}){var t;return r(this,void 0,void 0,(function*(){yield this.produce({encodings:this.getEncodings(),preferredCodec:this.getPreferredCodec(),transformParams:this.transformParams,codecOptions:this.getCodecOptions(),keyFrameRequestDelay:null!==(t=e.keyFrameRequestDelay)&&void 0!==t?t:0}),this.clientEventEmitter.emit(W,this)}))}watchOrientation(){window.screen.orientation&&(this.logger.debug("watchOrientation()",{description:"Watching started"}),window.screen.orientation.addEventListener("change",(()=>r(this,void 0,void 0,(function*(){if(this.isEffectsProcessing)try{this.mediaStreamTrack.enabled=!1;const e=yield i(this,Ec,"f").processTrack({track:this.mediaStreamTrack,pipelineConfig:document.hidden?vc:gc});yield this.replaceTrack(e)}catch(e){this.logger.warn("watchOrientation()",{description:"Restart blur error after orientation change",error:e})}})))))}watchDocumentVisibility(){this.logger.debug("watchDocumentVisibility()",{description:"Watching started"}),window.addEventListener("visibilitychange",(()=>r(this,void 0,void 0,(function*(){if(this.isEffectsProcessing)try{yield this.disableBlur(),yield this.enableBlur()}catch(e){this.logger.warn("watchDocumentVisibility()",{description:"Restart blur error after change document visibility",error:e})}}))))}}Ec=new WeakMap,Dc=new WeakMap;const Oc=new class{sleepMs(e){return r(this,void 0,void 0,(function*(){return new Promise((t=>setTimeout(t,e)))}))}now(){return new Date(Date.now())}},Ac=(e,t={})=>r(void 0,void 0,void 0,(function*(){var r;const i=t.maxRetries||2,s=t.minBackoffDelayMs||50;let n,o=0;for(;o<i;){o+=1;try{return yield e()}catch(e){if(n=e,t.logger&&t.logger.info("Action retry failed",{currentAttempt:o,actionName:t.actionName,error:e}),t.abortOnError&&t.abortOnError(e))throw n;if(o<i){const e=Math.pow(2,o-1)*s;yield Oc.sleepMs(Math.min(e,null!==(r=t.maxBackoffDelayMs)&&void 0!==r?r:e))}}}throw n}));class jc extends g{constructor(e,t){super(e,null!=t?t:"need_join_first")}}class Fc{constructor(e){this.initialized=!1,this.isJoined=!1,this.isChannelJoining=!1,this.rejoinRequested=!1,this.isReleasing=!1;const{clientEventEmitter:t,network:i,media:s,dependenciesFactory:n,logLevel:o}=e;this.logLevel=o||Be,this.system=n.createSystem({logLevel:this.logLevel,clientEventEmitter:t,onLogMessage:e.onLogMessage}),this.media=n.createMedia({logLevel:this.logLevel,engine:this,clientEventEmitter:t,mediaTracksFactory:s.mediaTracksFactory,onLogMessage:e.onLogMessage}),this.network=n.createNetwork({logLevel:this.logLevel,loadbalancer:i.loadbalancer,onLogMessage:e.onLogMessage}),this.peersRepository=new Map,this.clientEventEmitter=t,this.channelEventsHandler=n.createChannelEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.mediaSoupEventsHandler=n.createMediaSoupEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.channelAudioObserverEventHandler=n.createAudioObserverEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.channelStateSyncEventHandler=n.createChannelStateSyncEventHandler({engine:this,onLogMessage:e.onLogMessage}),this.handleChannelAudioObserverEvent=e=>{this.channelAudioObserverEventHandler.handle(e)},this.handleDataChannelEvent=e=>{this.channelEventsHandler.handleDataChannelEvent(e)},this.handleChannelStateSyncEvent=e=>r(this,void 0,void 0,(function*(){yield this.channelStateSyncEventHandler.handle(e)})),this.logger=new Ge({logLevel:this.logLevel,namespace:"Engine",onLogMessage:e.onLogMessage}),this.webRtcIssueDetector=e.disableWid?void 0:n.createIssueDetector({onIssues:e.onIssues,onNetworkScoresUpdated:e.onNetworkScoresUpdated,ignoreSSRCList:[1234],logger:new Ge({logLevel:this.logLevel,namespace:"WID"})}),this.watchSocketState()}initialize(){var e,t,i;return r(this,void 0,void 0,(function*(){try{const{rtpCapabilities:r}=yield this.network.socket.request("router.getRtpCapabilities");yield this.media.createNoiseSuppressor(),yield this.media.loadDevice(r),this.logger.info("Supported capabilities",{codecs:Ba(this.media.mediasoupDevice)}),null===(e=this.webRtcIssueDetector)||void 0===e||e.watchNewPeerConnections(),yield Promise.all([this.network.createSendTransport(this.media.mediasoupDevice),this.network.createRecvTransport(this.media.mediasoupDevice)]),this.initialized=!0,this.logger.debug("initialize()",{sendTransportId:null===(t=this.network.sendTransport)||void 0===t?void 0:t.id,recvTransportId:null===(i=this.network.receiveTransport)||void 0===i?void 0:i.id})}catch(e){this.logger.error("initialize()",{error:e});const t=e instanceof f&&"device not supported"===e.message,r=e instanceof Error&&"RTCPeerConnection is not defined"===e.message;if(t||r)throw new v("Device not supported",v.UNSUPPORTED_DEVICE_CODE);throw new Error("Error initialize engine")}}))}release(){var e,t,i,s,n,o,a;return r(this,void 0,void 0,(function*(){if(!this.isReleasing){this.isReleasing=!0;try{this.initialized=!1,this.isJoined=!1,this.app=void 0,this.channel=void 0,null===(e=this.webRtcIssueDetector)||void 0===e||e.stopWatchingNewPeerConnections(),this.peersRepository.forEach((e=>e.reset())),this.peersRepository.clear(),yield this.network.closeSendTransport(),yield this.network.closeReceiveTransport(),yield this.media.clearTracks(),null===(t=this.audioObserver)||void 0===t||t.removeListener("message",this.handleChannelAudioObserverEvent),null===(i=this.audioObserver)||void 0===i||i.close(),null===(s=this.generalDataConsumer)||void 0===s||s.removeListener("message",this.handleDataChannelEvent),null===(n=this.generalDataConsumer)||void 0===n||n.close(),null===(o=this.channelStateSyncDataConsumer)||void 0===o||o.removeListener("message",this.handleChannelStateSyncEvent),null===(a=this.channelStateSyncDataConsumer)||void 0===a||a.close(),this.channelEventsHandler.reset(),this.mediaSoupEventsHandler.reset(),this.removeClientEventEmitterListeners(),yield this.network.reset(),this.network.socket.disconnect(),this.logger.debug("release()",{socketId:this.mySocketId})}catch(e){throw this.logger.error("release()",{error:e}),new Error("Error release engine")}finally{this.isReleasing=!1}}}))}removeClientEventEmitterListeners(){[W,V,z,$,G,H].forEach((e=>this.clientEventEmitter.removeAllListeners(e)))}watchSocketState(){this.network.socket.observer.on(Ha.State,(e=>{var t;if(this.isReleasing)return;const{state:r,code:i,error:s}=e;this.clientEventEmitter.emit(r,{code:i,error:s});const n="unauthorized"===(null===(t=null==s?void 0:s.data)||void 0===t?void 0:t.errorCode);r===Ha.Error&&this.isJoined&&n?this.triggerRejoinEventIfAppropriate("unauthorized error"):r===Ha.Reconnected&&this.triggerRejoinEventIfAppropriate("reconnected socket")}))}get activeSpeaker(){return this.activeSpeakerPeer}get peers(){return Array.from(this.peersRepository.values())}get hostPeers(){return this.peers.filter((e=>"host"===e.role))}get audiencePeers(){return this.peers.filter((e=>"audience"===e.role))}get mySocketId(){return this.network.socket.id}getPeerById(e){return this.peersRepository.get(e)}checkConnectionActivity(){var e;return r(this,void 0,void 0,(function*(){if(!this.channel||this.isChannelJoining)throw new Error("Connect to the channel first");if(!(null===(e=this.network.socket.connection)||void 0===e?void 0:e.active))throw new Error("Socket is inactive")}))}confirmActivity(){return r(this,void 0,void 0,(function*(){this.checkConnectionActivity(),yield this.network.socket.request(R)}))}join(e){return r(this,void 0,void 0,(function*(){try{this.logger.debug("join()",{params:e}),this.isChannelJoining=!0,this.watchClientEvents(),yield this.connectToSocketServerWithRetry(e),yield this.performJoin({appData:e.appData})}catch(e){throw this.logger.error("join()",{error:e}),e}finally{this.isChannelJoining=!1,this.rejoinRequested=!1}}))}loadPeers(e){return r(this,void 0,void 0,(function*(){const{peers:t}=yield this.network.socket.request(w,{role:e});t.filter((e=>!this.peersRepository.has(e.id))).forEach((e=>this.setPeer(e)))}))}setPeer(e){const t=this.peersRepository.get(e.id);if(t)return t;const r=new Ma(Object.assign(Object.assign({},e),{engine:this,loginDate:new Date}));return this.peersRepository.set(r.id,r),r}removePeer(e){const t=this.peersRepository.get(e);t&&(t.tracks.forEach((e=>e.close())),t.reset(),this.peersRepository.delete(e))}updateAppData(e){return r(this,void 0,void 0,(function*(){const{myPeer:t}=this;if(!t)throw new Error("Need join to channel first");try{Ea(e),yield this.network.updatePeerAppData({peerId:t.id,appData:e})}catch(e){throw this.logger.error("updateAppData()",{error:e}),new Error("Can not update peer appData")}}))}createCameraVideoTrack(e){return r(this,void 0,void 0,(function*(){const t=Ja.getCameraVideoTrackParams(e);try{const[r]=yield this.media.createUserMediaTracks({audio:!1,video:t.videoTrackOptions});if(r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof Ic&&(r.setLabel(u.Camera),r.setEncoderConfig(t.encoderConfig),r.setTransformParams(Ja.getVideoTrackTransformParams(r.mediaStreamTrack)),null==e?void 0:e.blur))try{yield r.enableBlur()}catch(e){this.logger.warn("Failed to start virtual background, featured original track",{track:this})}return this.media.setTrack(r),this.logger.debug("createCameraVideoTrack()",{trackParams:t,track:r}),r}catch(e){throw this.logger.error("createCameraVideoTrack()",{error:e,trackParams:t}),new Error(`Can not create camera track: ${e.message}`)}}))}createMicrophoneAudioTrack(e){return r(this,void 0,void 0,(function*(){try{const[t]=yield this.media.createUserMediaTracks({video:!1,audio:null==e?void 0:e.audio});if(t.setLabel(u.Microphone),t.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),(null==e?void 0:e.encoderConfig)&&t.setEncoderConfig(e.encoderConfig),"audio"===t.kind&&(null==e?void 0:e.noiseSuppression))try{yield t.enableNoiseSuppression()}catch(e){this.logger.warn("Failed to start noise suppression, featured original track",{track:this})}return this.media.setTrack(t),this.logger.debug("createMicrophoneAudioTrack()",{options:e,track:t}),t}catch(t){throw this.logger.error("createMicrophoneAudioTrack()",{error:t,options:e}),new Error(`Can not create microphone track: ${t.message}`)}}))}createScreenMediaTracks(e){return r(this,void 0,void 0,(function*(){const t=Ja.getScreenVideoTrackParams(e);try{const r=yield this.media.createDisplayMediaTracks({audio:null==e?void 0:e.audio,video:null==e?void 0:e.video});return r.forEach((r=>{if(r.mediaStreamTrack.addEventListener("ended",(()=>{r.unpublish()}),{once:!0}),r.setStopTrackOnPause(Boolean(null==e?void 0:e.stopTrackOnPause)),r instanceof Ic){r.setLabel(u.ScreenVideo),r.setEncoderConfig(t.encoderConfig);const e=Ja.getVideoTrackTransformParams(r.mediaStreamTrack);return r.setTransformParams(e),this.media.setTrack(r),void this.logger.debug("createScreenMediaTrack()",{trackParams:t,transformParams:e,track:r})}r.setLabel(u.ScreenAudio),(null==e?void 0:e.audioEncoderConfig)&&r.setEncoderConfig(e.audioEncoderConfig),this.media.setTrack(r),this.logger.debug("createScreenMediaTrack()",{trackParams:null==e?void 0:e.audio,encoderConfig:null==e?void 0:e.audioEncoderConfig,track:r})})),r}catch(e){throw this.logger.error("createScreenMediaTrack()",{error:e,trackParams:t}),new Error(`Can not create screen media tracks: ${e.message}`)}}))}deleteTrack(e){return this.media.deleteTrack(e)}get channelId(){return this.channel}get appId(){return this.app}get canUseNoiseSuppression(){return this.media.isNoiseSuppressorLoaded}setActiveSpeakerPeer(e){this.activeSpeaker!==e&&(this.activeSpeakerPeer=e,this.clientEventEmitter.safeEmit(U,{peer:e}))}getNodeActiveStreamsStat(){var e;const t=this.network.socket.getServerUrl(),r=this.hostPeers.filter((e=>{var t;return e.id!==(null===(t=this.myPeer)||void 0===t?void 0:t.id)})).reduce(((e,t)=>e+t.getActiveTracksCount()),0);return{node:t,inboundActiveStreams:r,outboundActiveStreams:(null===(e=this.myPeer)||void 0===e?void 0:e.getActivePublishersCount())||0}}connectToSocketServerWithRetry(e){return r(this,void 0,void 0,(function*(){return Ac((()=>r(this,void 0,void 0,(function*(){return this.connectToSocketServer(e)}))),{maxRetries:15,minBackoffDelayMs:150,maxBackoffDelayMs:5e3,actionName:"connectToSocketServer",logger:new Ge({namespace:"RetrySocketConnect",logLevel:this.logLevel}),abortOnError:e=>{var t;return"unauthorized"===(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.errorCode)}})}))}connectToSocketServer(e){return r(this,void 0,void 0,(function*(){const{webSocketUrl:t}=yield this.getAvailableNode({channelId:e.channelId,role:e.role});this.network.socket.connect(t,e.token);try{yield this.waitForSocketConnection()}catch(r){throw this.logger.error("Failed to connect to socket server",{error:r,role:e.role,channelId:e.channelId,webSocketUrl:t}),this.network.socket.disconnect(),r}}))}getAvailableNode(e){return r(this,void 0,void 0,(function*(){try{return{webSocketUrl:(yield this.network.loadBalancerClient.getNode(e)).webSocketUrl}}catch(e){throw this.logger.error("getAvailableNode()",{error:"No available nodes"}),e}}))}waitForSocketConnection(){return new Promise(((e,t)=>{const i=s=>r(this,void 0,void 0,(function*(){const{error:r,state:n}=s,o=()=>this.network.socket.observer.removeListener(Ha.State,i),a=[Ha.Disconnected,Ha.Reconnecting].includes(n);return r?(o(),void t(r)):this.isChannelJoining&&a?(o(),void t(new Error(`Not expected socket state for new connection: ${n}`))):void(this.isChannelJoining&&[Ha.Connected,Ha.Reconnected].includes(n)&&(o(),e()))}));this.network.socket.observer.on(Ha.State,i)}))}performJoin(e){return r(this,void 0,void 0,(function*(){try{const{appId:t,channelId:r}=yield this.sendJoinChannelRequestWithRetry(e);this.app=t,this.channel=r,yield this.initialize(),this.channelEventsHandler.subscribeToEvents(),this.mediaSoupEventsHandler.subscribeToEvents(),this.isJoined=!0,this.logger.debug("Successfully joined channel",{channelId:r}),yield Promise.all([this.createAudioObserver(),this.createGeneralDataConsumer(),this.createChannelStateSyncDataConsumer()])}catch(e){throw this.logger.error("performJoin()",{error:e}),e}}))}sendJoinChannelRequestWithRetry(e){return r(this,void 0,void 0,(function*(){return Ac((()=>r(this,void 0,void 0,(function*(){return this.sendJoinChannelRequest(e)}))),{maxRetries:3,minBackoffDelayMs:300,actionName:"sendJoinChannelRequest",logger:new Ge({namespace:"RetryJoin",logLevel:this.logLevel})})}))}sendJoinChannelRequest(e){return r(this,void 0,void 0,(function*(){return this.network.socket.request(b,e)}))}get cahPublish(){var e;return"host"===(null===(e=this.peers.find((e=>e.isMe)))||void 0===e?void 0:e.role)}get myPeer(){return this.peers.find((e=>e.isMe))}watchClientEvents(){this.clientEventEmitter.on(W,(e=>r(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)})))),this.clientEventEmitter.on(V,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.close(),this.media.deleteTrack(e)})),this.clientEventEmitter.on(z,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.pause()})),this.clientEventEmitter.on($,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.resume()})),this.clientEventEmitter.on(G,(e=>{var t;const r=null===(t=this.myPeer)||void 0===t?void 0:t.tracks.get(e.getLabel());null==r||r.close()})),this.clientEventEmitter.on(H,(e=>r(this,void 0,void 0,(function*(){yield this.createSelfPeerTrack(e)}))))}createSelfPeerTrack(e){var t;return r(this,void 0,void 0,(function*(){const r=this.peersRepository.get(this.mySocketId);if(!r)return;yield null===(t=r.tracks.get(e.getLabel()))||void 0===t?void 0:t.close();const i=new Ta({mediaStreamTrack:e.mediaStreamTrack,label:e.getLabel(),engine:this,muted:!1,paused:e.isPaused,peerEventEmitter:r.observer});r.tracks.set(i.label,i)}))}createAudioObserver(){var e;return r(this,void 0,void 0,(function*(){if(!this.isJoined)throw new jc("Need to join first");const t={channelId:this.channelId,appId:this.appId,peerId:null===(e=this.myPeer)||void 0===e?void 0:e.id};try{const{producerId:e}=yield this.network.getAudioObserverProducer(),r=yield this.network.createDataConsumer({producerId:e,appId:this.appId,channelId:this.channelId});r.on("message",this.handleChannelAudioObserverEvent),this.audioObserver=r,this.logger.debug("Successfully create audio observer",t)}catch(e){this.logger.error("Failed to create audio observer",t)}}))}createGeneralDataConsumer(){var e;return r(this,void 0,void 0,(function*(){if(!this.isJoined)throw new jc("Need to join first");const t={channelId:this.channelId,appId:this.appId,peerId:null===(e=this.myPeer)||void 0===e?void 0:e.id};try{const{producerId:e}=yield this.network.getGeneralDataProducer();this.generalDataConsumer=yield this.network.createDataConsumer({producerId:e,appId:this.appId,channelId:this.channelId,ordered:!0}),this.generalDataConsumer.on("message",this.handleDataChannelEvent),this.logger.debug("Successfully created general data consumer",Object.assign(Object.assign({},t),{producerId:e}))}catch(e){this.logger.error("Failed to create general data consumer",Object.assign(Object.assign({},t),{error:e}))}}))}createChannelStateSyncDataConsumer(){var e;return r(this,void 0,void 0,(function*(){if(!this.isJoined)throw new jc("Need to join first");const t={channelId:this.channelId,appId:this.appId,peerId:null===(e=this.myPeer)||void 0===e?void 0:e.id};try{const{producerId:e}=yield this.network.getChannelStateSyncDataProducer();this.channelStateSyncDataConsumer=yield this.network.createDataConsumer({producerId:e,appId:this.appId,channelId:this.channelId}),this.channelStateSyncDataConsumer.on("message",this.handleChannelStateSyncEvent),this.logger.debug("Successfully created ChannelStateSyncDataConsumer",t)}catch(e){this.logger.error("Failed to create ChannelStateSyncDataConsumer",Object.assign(Object.assign({},t),{error:e}))}}))}triggerRejoinEventIfAppropriate(e){this.rejoinRequested&&!this.isChannelJoining||(this.logger.debug("Triggering channel rejoin required event",{reason:e}),this.rejoinRequested=!0,this.clientEventEmitter.emit(j))}}var Nc,Bc,Uc;function qc(){}function Wc(){Wc.init.call(this)}function Vc(e){return void 0===e._maxListeners?Wc.defaultMaxListeners:e._maxListeners}function zc(e,t,r){if(t)e.call(r);else for(var i=e.length,s=Yc(e,i),n=0;n<i;++n)s[n].call(r)}function $c(e,t,r,i){if(t)e.call(r,i);else for(var s=e.length,n=Yc(e,s),o=0;o<s;++o)n[o].call(r,i)}function Gc(e,t,r,i,s){if(t)e.call(r,i,s);else for(var n=e.length,o=Yc(e,n),a=0;a<n;++a)o[a].call(r,i,s)}function Hc(e,t,r,i,s,n){if(t)e.call(r,i,s,n);else for(var o=e.length,a=Yc(e,o),c=0;c<o;++c)a[c].call(r,i,s,n)}function Jc(e,t,r,i){if(t)e.apply(r,i);else for(var s=e.length,n=Yc(e,s),o=0;o<s;++o)n[o].apply(r,i)}function Kc(e,t,r,i){var s,n,o,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((n=e._events)?(n.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),n=e._events),o=n[t]):(n=e._events=new qc,e._eventsCount=0),o){if("function"==typeof o?o=n[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),!o.warned&&(s=Vc(e))&&s>0&&o.length>s){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,"function"==typeof console.warn?console.warn(a):console.log(a)}}else o=n[t]=r,++e._eventsCount;return e}function Qc(e,t,r){var i=!1;function s(){e.removeListener(t,s),i||(i=!0,r.apply(e,arguments))}return s.listener=r,s}function Xc(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Yc(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}qc.prototype=Object.create(null),Wc.EventEmitter=Wc,Wc.usingDomains=!1,Wc.prototype.domain=void 0,Wc.prototype._events=void 0,Wc.prototype._maxListeners=void 0,Wc.defaultMaxListeners=10,Wc.init=function(){this.domain=null,Wc.usingDomains&&(void 0).active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new qc,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Wc.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},Wc.prototype.getMaxListeners=function(){return Vc(this)},Wc.prototype.emit=function(e){var t,r,i,s,n,o,a,c="error"===e;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var d=new Error('Uncaught, unspecified "error" event. ('+t+")");throw d.context=t,d}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=o[e]))return!1;var l="function"==typeof r;switch(i=arguments.length){case 1:zc(r,l,this);break;case 2:$c(r,l,this,arguments[1]);break;case 3:Gc(r,l,this,arguments[1],arguments[2]);break;case 4:Hc(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(i-1),n=1;n<i;n++)s[n-1]=arguments[n];Jc(r,l,this,s)}return!0},Wc.prototype.addListener=function(e,t){return Kc(this,e,t,!1)},Wc.prototype.on=Wc.prototype.addListener,Wc.prototype.prependListener=function(e,t){return Kc(this,e,t,!0)},Wc.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,Qc(this,e,t)),this},Wc.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,Qc(this,e,t)),this},Wc.prototype.removeListener=function(e,t){var r,i,s,n,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(r=i[e]))return this;if(r===t||r.listener&&r.listener===t)0==--this._eventsCount?this._events=new qc:(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(s=-1,n=r.length;n-- >0;)if(r[n]===t||r[n].listener&&r[n].listener===t){o=r[n].listener,s=n;break}if(s<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new qc,this;delete i[e]}else!function(e,t){for(var r=t,i=r+1,s=e.length;i<s;r+=1,i+=1)e[r]=e[i];e.pop()}(r,s);i.removeListener&&this.emit("removeListener",e,o||t)}return this},Wc.prototype.off=function(e,t){return this.removeListener(e,t)},Wc.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new qc,this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=new qc:delete r[e]),this;if(0===arguments.length){for(var i,s=Object.keys(r),n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=new qc,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},Wc.prototype.listeners=function(e){var t,r=this._events;return r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[]},Wc.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Xc.call(e,t)},Wc.prototype.listenerCount=Xc,Wc.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class Zc extends Wc{}!function(e){e.Issue="issue",e.NetworkScoresUpdated="network-scores-updated",e.StatsParsingFinished="stats-parsing-finished"}(Nc||(Nc={})),function(e){e.Network="network",e.CPU="cpu",e.Server="server",e.Stream="stream"}(Bc||(Bc={})),function(e){e.OutboundNetworkQuality="outbound-network-quality",e.InboundNetworkQuality="inbound-network-quality",e.OutboundNetworkMediaLatency="outbound-network-media-latency",e.InboundNetworkMediaLatency="inbound-network-media-latency",e.NetworkMediaSyncFailure="network-media-sync-failure",e.OutboundNetworkThroughput="outbound-network-throughput",e.InboundNetworkThroughput="inbound-network-throughput",e.EncoderCPUThrottling="encoder-cpu-throttling",e.DecoderCPUThrottling="decoder-cpu-throttling",e.ServerIssue="server-issue",e.UnknownVideoDecoderIssue="unknown-video-decoder",e.LowInboundMOS="low-inbound-mean-opinion-score",e.LowOutboundMOS="low-outbound-mean-opinion-score"}(Uc||(Uc={}));class ed extends Wc{static STATS_REPORT_READY_EVENT="stats-report-ready";static STATS_REPORTS_PARSED="stats-reports-parsed";isStopped=!1;reportTimer;getStatsInterval;compositeStatsParser;constructor(e){super(),this.compositeStatsParser=e.compositeStatsParser,this.getStatsInterval=e.getStatsInterval??1e4}get isRunning(){return!!this.reportTimer&&!this.isStopped}startReporting(){if(this.reportTimer)return;const e=()=>setTimeout((()=>{this.isStopped?this.reportTimer=void 0:this.parseReports().finally((()=>{this.reportTimer=e()}))}),this.getStatsInterval);this.isStopped=!1,this.reportTimer=e()}stopReporting(){this.isStopped=!0,this.reportTimer&&(clearTimeout(this.reportTimer),this.reportTimer=void 0)}async parseReports(){const e=Date.now(),t=await this.compositeStatsParser.parse(),r=Date.now()-e;this.emit(ed.STATS_REPORTS_PARSED,{timeTaken:r}),t.forEach((e=>{this.emit(ed.STATS_REPORT_READY_EVENT,e)}))}}const td=(()=>{const e=new Map;return t=>{const{taskId:r,delayMs:i,maxJitterMs:s,callback:n}=t,o=Math.ceil(Math.random()*(s||0)),a=e.get(r);a&&clearTimeout(a);const c=setTimeout((()=>{n(),e.delete(r)}),i+o);e.set(r,c)}})();class rd{#e={};calculate(e){const{connection:{id:t}}=e,{mos:r,stats:i}=this.calculateOutboundScore(e)||{},{mos:s,stats:n}=this.calculateInboundScore(e)||{};return this.#e[t]=e,td({taskId:t,delayMs:35e3,callback:()=>delete this.#e[t]}),{outbound:r,inbound:s,statsSamples:{inboundStatsSample:n,outboundStatsSample:i}}}calculateOutboundScore(e){const t=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!t.length)return;const r=this.#e[e.connection.id];if(!r)return;const i=[...r.remote?.audio.inbound||[],...r.remote?.video.inbound||[]],{packetsSent:s}=e.connection,n=r.connection.packetsSent,o=t.reduce(((e,t)=>{const r=i.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=c/t.length,l=s-n,p=o.packetsLost-o.lastPacketsLost,u=l&&p?Math.round(100*p/(l+p)):0;return{mos:this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:u}),stats:{avgJitter:d,rtt:a,packetsLoss:u}}}calculateInboundScore(e){const t=[...e.audio?.inbound,...e.video?.inbound];if(!t.length)return;const r=this.#e[e.connection.id];if(!r)return;const i=[...r.video?.inbound,...r.audio?.inbound],{packetsReceived:s}=e.connection,n=r.connection.packetsReceived,o=t.reduce(((e,t)=>{const r=i.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,d=c/t.length,l=s-n,p=o.packetsLost-o.lastPacketsLost,u=l&&p?Math.round(100*p/(l+p)):0;return{mos:this.calculateMOS({avgJitter:d,rtt:a,packetsLoss:u}),stats:{avgJitter:d,rtt:a,packetsLoss:u}}}calculateMOS({avgJitter:e,rtt:t,packetsLoss:r}){const i=t+2*e+10;let s=i<160?93.2-i/40:93.2-i/120-10;return s-=2.5*r,1+.035*s+7e-6*s*(s-60)*(100-s)}}class id{#e;#t;constructor(e={}){this.#e=new Map,this.#t=e.statsCleanupTtlMs??35e3}detect(e){const t=this.performDetection(e);return this.performPrevStatsCleanup({connectionId:e.connection.id}),t}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:r}=e;this.#e.has(t)&&td({taskId:t,delayMs:this.#t,callback:()=>{this.deleteLastProcessedStats(t),"function"==typeof r&&r()}})}setLastProcessedStats(e,t){this.#e.set(e,t)}getLastProcessedStats(e){return this.#e.get(e)}deleteLastProcessedStats(e){this.#e.delete(e)}}class sd extends id{#r;constructor(e={}){super(e),this.#r=e.availableOutgoingBitrateThreshold??1e5}performDetection(e){const t=[],{availableOutgoingBitrate:r}=e.connection;if(void 0===r)return t;const i=e.audio.outbound.reduce(((e,t)=>e+t.targetBitrate),0),s=e.video.outbound.reduce(((e,t)=>e+t.bitrate),0);if(!i&&!s)return t;const n={availableOutgoingBitrate:r,videoStreamsTotalBitrate:s,audioStreamsTotalTargetBitrate:i};return i>r||s>0&&r<this.#r?(t.push({statsSample:n,type:Bc.Network,reason:Uc.OutboundNetworkThroughput}),t):t}}class nd extends id{#i;constructor(e={}){super(e),this.#i=e.framesDroppedThreshold??.5}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=e.video.inbound.filter((e=>e.framesDropped>0)),r=[],i=this.getLastProcessedStats(e.connection.id)?.video.inbound;return i?(t.forEach((e=>{const t=i.find((t=>t.ssrc===e.ssrc));if(!t)return;if(e.framesDropped===t.framesDropped)return;const s=e.framesReceived-t.framesReceived,n=e.framesDecoded-t.framesDecoded,o=e.framesDropped-t.framesDropped,a=o/s;if(0===s||0===n)return;const c={deltaFramesDropped:o,deltaFramesReceived:s,deltaFramesDecoded:n,framesDroppedPct:Math.round(100*a)};a>=this.#i&&r.push({statsSample:c,type:Bc.CPU,reason:Uc.DecoderCPUThrottling,ssrc:e.ssrc})})),r):r}}class od extends id{#s;constructor(e={}){super(e),this.#s=e.missedFramesThreshold??.15}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=e.video.outbound.filter((e=>e.framesEncoded>0)),r=[],i=this.getLastProcessedStats(e.connection.id)?.video.outbound;return i?(t.forEach((e=>{const t=i.find((t=>t.ssrc===e.ssrc));if(!t)return;if(e.framesEncoded===t.framesEncoded)return;const s=e.framesEncoded-t.framesEncoded,n=e.framesSent-t.framesSent,o=1-n/s;if(0===s)return;if(s===n)return;const a={deltaFramesSent:n,deltaFramesEncoded:s,missedFramesPct:Math.round(100*o)};o>=this.#s&&r.push({statsSample:a,type:Bc.Network,reason:Uc.OutboundNetworkThroughput,ssrc:e.ssrc})})),r):r}}class ad extends id{highPacketLossThresholdPct;highJitterThreshold;highJitterBufferDelayThresholdMs;highRttThresholdMs;constructor(e={}){super(),this.highPacketLossThresholdPct=e.highPacketLossThresholdPct??5,this.highJitterThreshold=e.highJitterThreshold??200,this.highJitterBufferDelayThresholdMs=e.highJitterBufferDelayThresholdMs??500,this.highRttThresholdMs=e.highRttThresholdMs??250}performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=[],r=[...e.audio?.inbound,...e.video?.inbound];if(!r.length)return t;const i=this.getLastProcessedStats(e.connection.id);if(!i)return t;const s=[...i.video?.inbound,...i.audio?.inbound],{packetsReceived:n}=e.connection,o=i.connection.packetsReceived,a=r.reduce(((e,t)=>{const r=s.find((e=>e.ssrc===t.ssrc)),i=r?.jitterBufferDelay||0,n=r?.jitterBufferEmittedCount||0,o=t.jitterBufferDelay-i,a=t.jitterBufferEmittedCount-n,c=o&&a?1e3*o/a:0;return{sumJitter:e.sumJitter+t.jitter,sumJitterBufferDelayMs:e.sumJitterBufferDelayMs+c,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,sumJitterBufferDelayMs:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:d,sumJitterBufferDelayMs:l}=a,p=d/r.length,u=l/r.length,h=n-o,f=a.packetsLost-a.lastPacketsLost,m=h&&f?Math.round(100*f/(h+f)):0,g=m>this.highPacketLossThresholdPct,v=p>=this.highJitterThreshold,y=c>=this.highRttThresholdMs,b=u>this.highJitterBufferDelayThresholdMs,w=y&&!v&&!g,S=g&&v,_=v&&b,R={rtt:c,packetLossPct:m,avgJitter:p,avgJitterBufferDelay:u};return(v||g)&&t.push({statsSample:R,type:Bc.Network,reason:Uc.InboundNetworkQuality,iceCandidate:e.connection.local.id}),w&&t.push({statsSample:R,type:Bc.Server,reason:Uc.ServerIssue,iceCandidate:e.connection.remote.id}),S&&t.push({statsSample:R,type:Bc.Network,reason:Uc.InboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),_&&t.push({statsSample:R,type:Bc.Network,reason:Uc.NetworkMediaSyncFailure,iceCandidate:e.connection.local.id}),t}}class cd extends id{performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=e.audio.inbound,r=[],i=this.getLastProcessedStats(e.connection.id)?.audio.inbound;return i?(t.forEach((e=>{const t=i.find((t=>t.ssrc===e.ssrc));if(!t)return;const s=e.track.insertedSamplesForDeceleration+e.track.removedSamplesForAcceleration,n=t.track.insertedSamplesForDeceleration+t.track.removedSamplesForAcceleration;if(s===n)return;const o=e.track.totalSamplesReceived-t.track.totalSamplesReceived,a=s-n,c=Math.round(100*a/o),d={correctedSamplesPct:c};c>5&&r.push({statsSample:d,type:Bc.Network,reason:Uc.NetworkMediaSyncFailure,ssrc:e.ssrc})})),r):r}}class dd extends id{performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=[],r=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!r.length)return t;const i=this.getLastProcessedStats(e.connection.id);if(!i)return t;const s=[...i.remote?.audio.inbound||[],...i.remote?.video.inbound||[]],{packetsSent:n}=e.connection,o=i.connection.packetsSent,a=r.reduce(((e,t)=>{const r=s.find((e=>e.ssrc===t.ssrc));return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(r?.packetsLost||0)}}),{sumJitter:0,packetsLost:0,lastPacketsLost:0}),c=1e3*e.connection.currentRoundTripTime||0,{sumJitter:d}=a,l=d/r.length,p=n-o,u=a.packetsLost-a.lastPacketsLost,h=p&&u?Math.round(100*u/(p+u)):0,f=h>5,m=l>=200,g=!f&&m||m||f,v={rtt:c,avgJitter:l,packetLossPct:h};return f&&m&&t.push({statsSample:v,type:Bc.Network,reason:Uc.OutboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),g&&t.push({statsSample:v,type:Bc.Network,reason:Uc.OutboundNetworkQuality,iceCandidate:e.connection.local.id}),t}}class ld extends id{performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}processData(e){const t=e.video.outbound.filter((e=>"none"!==e.qualityLimitationReason)),r=[],i=this.getLastProcessedStats(e.connection.id)?.video.outbound;return i?(t.forEach((e=>{const t=i.find((t=>t.ssrc===e.ssrc));if(!t)return;const s={qualityLimitationReason:e.qualityLimitationReason};e.framesSent>t.framesSent||("cpu"===e.qualityLimitationReason&&r.push({statsSample:s,type:Bc.CPU,reason:Uc.EncoderCPUThrottling,ssrc:e.ssrc}),"bandwidth"===e.qualityLimitationReason&&r.push({statsSample:s,type:Bc.Network,reason:Uc.OutboundNetworkThroughput,ssrc:e.ssrc}))})),r):r}}class pd extends id{UNKNOWN_DECODER="unknown";#n={};performDetection(e){const{connection:{id:t}}=e,r=this.processData(e);return this.setLastProcessedStats(t,e),r}performPrevStatsCleanup(e){const{connectionId:t,cleanupCallback:r}=e;super.performPrevStatsCleanup({...e,cleanupCallback:()=>{delete this.#n[t],"function"==typeof r&&r()}})}processData(e){const t=[],{id:r}=e.connection,i=this.getLastProcessedStats(r)?.video.inbound;return e.video.inbound.forEach((e=>{const{decoderImplementation:s,ssrc:n}=e,o=i?.find((e=>e.ssrc===n));if(o)if(s===this.UNKNOWN_DECODER){if(!this.hadLastDecoderWithIssue(r,n)){this.setLastDecoderWithIssue(r,n,this.UNKNOWN_DECODER);const i={mimeType:e.mimeType,decoderImplementation:s};t.push({ssrc:n,statsSample:i,type:Bc.Stream,reason:Uc.UnknownVideoDecoderIssue,trackIdentifier:e.track.trackIdentifier})}}else this.setLastDecoderWithIssue(r,n,void 0)})),t}setLastDecoderWithIssue(e,t,r){const i=this.#n[e]??{};void 0===r?delete i[t]:i[t]=r,this.#n[e]=i}hadLastDecoderWithIssue(e,t){const r=this.#n[e];return(r&&r[t])===this.UNKNOWN_DECODER}}const ud=e=>"closed"===e.iceConnectionState||"closed"===e.connectionState,hd=(e,t,r)=>8*((e,t,r)=>{if(!t)return 0;const i=e[r],s=t[r];if(null==i||null==s)return 0;const n=Math.floor(e.timestamp)-Math.floor(t.timestamp);return 0===n?0:(Number(i)-Number(s))/n*1e3})(e,t,r);class fd{connections=[];statsParser;constructor(e){this.statsParser=e.statsParser}listConnections(){return[...this.connections]}addPeerConnection(e){this.connections.push({id:e.id??String(Date.now()+Math.random().toString(32)),pc:e.pc})}removePeerConnection(e){const t=this.connections.findIndex((({pc:t})=>t===e.pc));t>=0&&this.removeConnectionsByIndexes([t])}async parse(){const e=[],t=this.connections.map((async(t,r)=>{if(!ud(t.pc))return this.statsParser.parse(t);e.unshift(r)}));return e.length&&this.removeConnectionsByIndexes(e),(await Promise.all(t)).filter((e=>void 0!==e))}removeConnectionsByIndexes(e){e.forEach((e=>{this.connections.splice(e,1)}))}}class md{prevStats=new Map;allowedReportTypes=new Set(["candidate-pair","inbound-rtp","outbound-rtp","remote-outbound-rtp","remote-inbound-rtp","track","transport"]);ignoreSSRCList;logger;constructor(e){this.ignoreSSRCList=e.ignoreSSRCList??[],this.logger=e.logger}get previouslyParsedStatsConnectionsIds(){return[...this.prevStats.keys()]}async parse(e){if(!ud(e.pc))return this.getConnectionStats(e);this.logger.debug("Skip stats parsing. Connection is closed.",{connection:e})}async getConnectionStats(e){const{pc:t,id:r}=e;try{const i=Date.now(),s=t.getReceivers().filter((e=>e.track?.enabled)),n=t.getSenders().filter((e=>e.track?.enabled)),o=await Promise.all(s.map((e=>e.getStats()))),a=await Promise.all(n.map((e=>e.getStats())));return{id:r,stats:this.mapReportsStats([...o,...a],e),timeTaken:Date.now()-i}}catch(e){return void this.logger.error("Failed to get stats for PC",{id:r,pc:t,error:e})}}mapReportsStats(e,t){const r={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{},remote:{video:{inbound:[],outbound:[]},audio:{inbound:[],outbound:[]}}};e.forEach((e=>{e.forEach((t=>{this.allowedReportTypes.has(t.type)&&this.updateMappedStatsWithReportItemData(t,r,e)}))}));const{id:i}=t,s=this.prevStats.get(i);return s&&this.propagateStatsWithRateValues(r,s.stats),this.prevStats.set(i,{stats:r,ts:Date.now()}),td({taskId:i,delayMs:35e3,callback:()=>this.prevStats.delete(i)}),r}updateMappedStatsWithReportItemData(e,t,r){const i=e.type;if("candidate-pair"===i&&"succeeded"===e.state&&e.nominated)return void(t.connection=this.prepareConnectionStats(e,r));const s=this.getMediaType(e);if(!s)return;const n=e.ssrc;if(!n||!this.ignoreSSRCList.includes(n))if("outbound-rtp"!==i)if("inbound-rtp"!==i)"remote-outbound-rtp"!==i?"remote-inbound-rtp"===i&&(this.mapConnectionStatsIfNecessary(t,e,r),t.remote[s].inbound.push({...e})):t.remote[s].outbound.push({...e});else{const i=r.get(e.trackId)||r.get(e.mediaSourceId)||{};this.mapConnectionStatsIfNecessary(t,e,r);const n={...e,track:{...i}};t[s].inbound.push(n)}else{const i=r.get(e.trackId)||r.get(e.mediaSourceId)||{},n={...e,track:{...i}};t[s].outbound.push(n)}}getMediaType(e){const t=e.mediaType||e.kind;if(!["audio","video"].includes(t)){const{id:t}=e;if(!t)return;return String(t).includes("Video")?"video":String(t).includes("Audio")?"audio":void 0}return t}propagateStatsWithRateValues(e,t){e.audio.inbound.forEach((e=>{const r=t.audio.inbound.find((({id:t})=>t===e.id));e.bitrate=hd(e,r,"bytesReceived"),e.packetRate=hd(e,r,"packetsReceived")})),e.audio.outbound.forEach((e=>{const r=t.audio.outbound.find((({id:t})=>t===e.id));e.bitrate=hd(e,r,"bytesSent"),e.packetRate=hd(e,r,"packetsSent")})),e.video.inbound.forEach((e=>{const r=t.video.inbound.find((({id:t})=>t===e.id));e.bitrate=hd(e,r,"bytesReceived"),e.packetRate=hd(e,r,"packetsReceived")})),e.video.outbound.forEach((e=>{const r=t.video.outbound.find((({id:t})=>t===e.id));e.bitrate=hd(e,r,"bytesSent"),e.packetRate=hd(e,r,"packetsSent")}))}mapConnectionStatsIfNecessary(e,t,r){if(e.connection.id||!t.transportId)return;const i=r.get(t.transportId);if(i&&i.selectedCandidatePairId){const t=r.get(i.selectedCandidatePairId);e.connection=this.prepareConnectionStats(t,r)}}prepareConnectionStats(e,t){if(!e||!t)return{};const r={...e};if(r.remoteCandidateId){const e=t.get(r.remoteCandidateId);r.remote={...e}}if(r.localCandidateId){const e=t.get(r.localCandidateId);r.local={...e}}return r}}class gd{eventEmitter;#o=!1;detectors=[];networkScoresCalculator;statsReporter;compositeStatsParser;logger;constructor(e){this.logger=e.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.eventEmitter=e.issueEmitter??new Zc,e.onIssues&&this.eventEmitter.on(Nc.Issue,e.onIssues),e.onNetworkScoresUpdated&&this.eventEmitter.on(Nc.NetworkScoresUpdated,e.onNetworkScoresUpdated),this.detectors=e.detectors??[new ld,new nd,new od,new ad,new dd,new cd,new sd,new pd],this.networkScoresCalculator=e.networkScoresCalculator??new rd,this.compositeStatsParser=e.compositeStatsParser??new fd({statsParser:new md({ignoreSSRCList:e.ignoreSSRCList,logger:this.logger})}),this.statsReporter=e.statsReporter??new ed({compositeStatsParser:this.compositeStatsParser,getStatsInterval:e.getStatsInterval??5e3}),window.wid=this,this.wrapRTCPeerConnection(),this.statsReporter.on(ed.STATS_REPORT_READY_EVENT,(e=>{this.detectIssues({data:e.stats}),this.calculateNetworkScores(e.stats)})),this.statsReporter.on(ed.STATS_REPORTS_PARSED,(e=>{const t={timeTaken:e.timeTaken,ts:Date.now()};this.eventEmitter.emit(Nc.StatsParsingFinished,t)}))}watchNewPeerConnections(){this.#o?this.logger.warn("WebRTCIssueDetector is already started. Skip processing"):(this.logger.info("Start watching peer connections"),this.#o=!0,this.statsReporter.startReporting())}stopWatchingNewPeerConnections(){this.#o?(this.logger.info("Stop watching peer connections"),this.#o=!1,this.statsReporter.stopReporting()):this.logger.warn("WebRTCIssueDetector is already stopped. Skip processing")}handleNewPeerConnection(e){this.#o?(this.logger.debug("Handling new peer connection",e),this.compositeStatsParser.addPeerConnection({pc:e})):this.logger.debug("Skip handling new peer connection. Detector is not running",e)}emitIssues(e){this.eventEmitter.emit(Nc.Issue,e)}detectIssues({data:e}){const t=this.detectors.reduce(((t,r)=>[...t,...r.detect(e)]),[]);t.length>0&&this.emitIssues(t)}calculateNetworkScores(e){const t=this.networkScoresCalculator.calculate(e);this.eventEmitter.emit(Nc.NetworkScoresUpdated,t)}wrapRTCPeerConnection(){if(!window.RTCPeerConnection)return void this.logger.warn("No RTCPeerConnection found in browser window. Skipping");const e=window.RTCPeerConnection,t=e=>this.handleNewPeerConnection(e);function r(r){const i=new e(r);return t(i),i}r.prototype=e.prototype,window.RTCPeerConnection=r}}Error;const vd=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0}],yd=({from:e,seen:t,to_:r,forceEnumerable:i})=>{const s=r||(Array.isArray(e)?[]:{});t.push(e);for(const[r,n]of Object.entries(e))"function"!=typeof n&&(n&&"object"==typeof n?t.includes(e[r])?s[r]="[Circular]":s[r]=yd({from:e[r],seen:t.slice(),forceEnumerable:i}):s[r]=n);for(const{property:t,enumerable:r}of vd)"string"==typeof e[t]&&Object.defineProperty(s,t,{value:e[t],enumerable:!!i||r,configurable:!0,writable:!0});return s};var bd=e=>"object"==typeof e&&null!==e?yd({from:e,seen:[],forceEnumerable:!0}):"function"==typeof e?`[Function: ${e.name||"anonymous"}]`:e;class wd{constructor(e){var t;this.preferRelay=!1;const{socketClient:r,loadBalancerApiClient:i,onLogMessage:s}=e;this.socket=r,this.loadBalancerClient=i,this.eventEmitter=null!==(t=e.eventEmitter)&&void 0!==t?t:new n,this.logger=new Ge({namespace:"Network",logLevel:e.logLevel,onLogMessage:s})}removeEventListeners(){const{sendTransport:e,receiveTransport:t}=this;if(e){["connect","produce","connectionstatechange"].forEach((t=>e.removeAllListeners(t)))}if(t){["connect","produce","connectionstatechange"].forEach((e=>t.removeAllListeners(e)))}}reset(){return r(this,void 0,void 0,(function*(){this.stopRestartIceAtempts(),this.removeEventListeners()}))}closeRemoteProducer(e){return r(this,void 0,void 0,(function*(){yield this.socket.request(oe,{peerId:this.socket.id,producerId:e})}))}closeSendTransport(){var e;return r(this,void 0,void 0,(function*(){this.sendTransport?((null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&(yield this.closeTransport(this.sendTransport)),this.sendTransport.close(),this.sendTransport=void 0):this.logger.warn("closeSendTransport()",{message:"No available send transport"})}))}closeReceiveTransport(){var e;return r(this,void 0,void 0,(function*(){this.receiveTransport?((null===(e=this.socket.connection)||void 0===e?void 0:e.connected)&&(yield this.closeTransport(this.receiveTransport)),this.receiveTransport.close(),this.receiveTransport=void 0):this.logger.warn("closeReceiveTransport()",{message:"No available receive transport"})}))}closeTransport(e){return r(this,void 0,void 0,(function*(){try{const{success:t}=yield this.socket.request(Ce,{transportId:e.id});return this.logger.debug("closeTransport()",{transport:e}),Boolean(t)}catch(e){return this.logger.error("closeTransport()",{error:e}),!1}}))}createSendTransport(e){return r(this,void 0,void 0,(function*(){if(this.sendTransport)return void this.logger.warn("createSendTransport()",{message:"Send transport already exists"});const t=yield this.socket.request(ke,{sctpCapabilities:e.sctpCapabilities,localDirection:"send"}),i=e.createSendTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));this.logger.debug("createSendTransport()",{transport:i}),i.on("connect",(({dtlsParameters:e},s,n)=>r(this,void 0,void 0,(function*(){try{yield this.socket.request(Pe,{transportId:i.id,dtlsParameters:e}),s(),this.logger.debug("sendTransport.connect()",{transportId:i.id,dtlsRole:e.role}),setTimeout((()=>this.logTransportDetails(i)),1500)}catch(r){this.logger.error("sendTransport.on(`connect`)",{dtlsParameters:e,sendTransportOptions:t,error:r}),n(r)}})))),i.on("produce",((e,t,s)=>r(this,void 0,void 0,(function*(){try{const{id:r}=yield this.socket.request(Te,{transportId:i.id,kind:e.kind,rtpParameters:e.rtpParameters,appData:e.appData});t({id:r}),this.logger.debug("sendTransport.produce()",{producerId:r,transportId:i.id,kind:e.kind})}catch(t){this.logger.error("sendTransport.produce()",{error:t,transportId:i.id,kind:e.kind}),s(t)}})))),i.on("connectionstatechange",(e=>{if(this.logger.info("sendTransport.state",{state:e}),["closed","connected"].includes(e))return this.sendTransportRestartIceInterval&&(this.logger.debug("Stop sendTransport.restartIce() retries",{sendTransportId:i.id}),clearInterval(this.sendTransportRestartIceInterval),this.sendTransportRestartIceInterval=void 0),void("connected"===e&&setTimeout((()=>this.logTransportDetails(i)),1500));if(["disconnected","failed"].includes(e)){if(this.sendTransportRestartIceInterval)return;"failed"===e&&(this.logger.debug("sendTransport.restartIce()",{sendTransportId:i.id}),this.restartIce(i)),this.sendTransportRestartIceInterval=setInterval((()=>{this.restartIce(i),this.logger.debug("sendTransport.restartIce() attempt",{sendTransportId:i.id})}),5e3)}})),this.sendTransport=i}))}createRecvTransport(e){return r(this,void 0,void 0,(function*(){if(this.receiveTransport)return void this.logger.warn("createReceiveTransport()",{message:"Receive transport already exists"});const t=yield this.socket.request(ke,{localDirection:"receive"}),i=e.createRecvTransport(Object.assign(Object.assign({},t),{iceTransportPolicy:this.preferRelay?"relay":t.iceTransportPolicy}));this.logger.debug("createReceiveTransport()",{transport:i}),i.on("connect",(({dtlsParameters:e},t,s)=>r(this,void 0,void 0,(function*(){try{yield this.socket.request(Pe,{transportId:i.id,dtlsParameters:e}),t(),this.logger.debug("receiveTransport.connect()",{transportId:i.id,dtlsRole:e.role}),setTimeout((()=>this.logTransportDetails(i)),1500)}catch(e){this.logger.error("receiveTransport.on(`connect`)",{error:e}),s(e)}})))),i.on("connectionstatechange",(e=>{if(this.logger.info("receiveTransport.state",{state:e}),["closed","connected"].includes(e))return this.recvTransportRestartIceInterval&&(this.logger.debug("Stop receiveTransport.restartIce() retries",{recvTransportId:i.id}),clearInterval(this.recvTransportRestartIceInterval),this.recvTransportRestartIceInterval=void 0),void("connected"===e&&setTimeout((()=>this.logTransportDetails(i)),1500));if(["disconnected","failed"].includes(e)){if(this.recvTransportRestartIceInterval)return;"failed"===e&&(this.logger.debug("receiveTransport.restartIce()",{recvTransportId:i.id}),this.restartIce(i)),this.recvTransportRestartIceInterval=setInterval((()=>{this.restartIce(i),this.logger.debug("receiveTransport.restartIce() attempt",{recvTransportId:i.id})}),5e3)}})),this.receiveTransport=i}))}getIceParameters(e){return r(this,void 0,void 0,(function*(){const t=yield this.socket.request(De,{transportId:e.id}),{error:r}=t;if(r)throw new Error(r);const{iceParameters:i}=t;return this.logger.debug("getIceParameters()",{iceParameters:i}),i}))}restartIce(e){return r(this,void 0,void 0,(function*(){try{const t=yield this.getIceParameters(e);yield e.restartIce({iceParameters:t}),this.logger.info("restartIce completed",{iceParameters:t})}catch(e){this.logger.error("restartIce error",{error:e})}}))}createConsumer({producerId:e,rtpCapabilities:t,appId:i,channelId:s,producerPeerId:n}){return r(this,void 0,void 0,(function*(){const r=this.receiveTransport;if(!r)throw this.logger.error("createConsumer()",{reason:"missing receive transport"}),new Error("Failed to create consumer");this.logger.debug("createConsumer()",{producerId:e});const o=yield this.socket.request(me,{producerId:e,transportId:r.id,rtpCapabilities:t,appData:{peerId:this.socket.id,appId:i,channelId:s},producerPeerId:n}),a=yield r.consume(o),{producerPaused:c}=o;return this.logger.debug("Consumer created",{consumer:a,isProducerPaused:c}),{consumer:a,isProducerPaused:c}}))}createDataConsumer({producerId:e,appId:t,channelId:i,ordered:s}){return r(this,void 0,void 0,(function*(){const r=this.receiveTransport;if(!r)throw this.logger.error("createDataConsumer()",{reason:"missing receive transport"}),new Error("Failed to create consumer");this.logger.debug("createDataConsumer()",{producerId:e});const n=yield this.socket.request(ge,{ordered:s,dataProducerId:e,transportId:r.id,appData:{peerId:this.socket.id,producerId:e,appId:t,channelId:i}}),o=yield r.consumeData(n);return this.logger.debug("Data consumer created",{consumer:o}),o}))}closeRemoteConsumer(e){return r(this,void 0,void 0,(function*(){return this.socket.request(ve,{peerId:this.socket.id,consumerId:e})}))}resumeRemoteConsumer(e){return r(this,void 0,void 0,(function*(){return this.socket.request(be,{consumerId:e})}))}pauseRemoteConsumer(e){return r(this,void 0,void 0,(function*(){return this.socket.request(ye,{consumerId:e})}))}updatePeerAppData({peerId:e,appData:t}){return r(this,void 0,void 0,(function*(){return this.socket.request(_,{peerId:e,appData:t})}))}getAudioObserverProducer(){return r(this,void 0,void 0,(function*(){return this.socket.request(T)}))}getGeneralDataProducer(){return r(this,void 0,void 0,(function*(){return this.socket.request(E)}))}getChannelStateSyncDataProducer(){return r(this,void 0,void 0,(function*(){return this.socket.request(D)}))}getTransportsStateInfo(){return r(this,void 0,void 0,(function*(){const[e,t]=yield Promise.all([this.getParsedTransportStats(this.receiveTransport),this.getParsedTransportStats(this.sendTransport)]);return{receive:e,send:t}}))}setPreferRelay(e){this.preferRelay=e}getPreferRelay(){return this.preferRelay}getParsedTransportStats(e){return r(this,void 0,void 0,(function*(){if(e)try{const t=Array.from((yield e.getStats()).values()),r=t.find((e=>"local-candidate"===e.type)),i=t.find((e=>"remote-candidate"===e.type)),s=t.find((e=>"transport"===e.type));return{dtlsState:null==s?void 0:s.dtlsState,iceState:null==s?void 0:s.iceState,dtlsRole:null==s?void 0:s.dtlsRole,iceRole:null==s?void 0:s.iceRole,selectedCandidatePairChanges:null==s?void 0:s.selectedCandidatePairChanges,tlsVersion:null==s?void 0:s.tlsVersion,localCandidateState:{ip:null==r?void 0:r.ip,address:null==r?void 0:r.address,port:null==r?void 0:r.port,protocol:null==r?void 0:r.protocol,candidateType:null==r?void 0:r.candidateType},remoteCandidateState:{ip:null==i?void 0:i.ip,address:null==i?void 0:i.address,port:null==i?void 0:i.port,protocol:null==i?void 0:i.protocol,candidateType:null==i?void 0:i.candidateType}}}catch(e){return void this.logger.warn("getParsedTransportStats()",{error:e})}else this.logger.debug("getParsedTransportStats()",{message:"Transport is missing"})}))}logTransportDetails(e){var t,i;return r(this,void 0,void 0,(function*(){let r;try{r=yield e.getStats()}catch(t){return void this.logger.error("Failed to log detailed WebRTC transport stats",{error:bd(t),transportId:e.id,reason:"failed to parse getStats"})}try{const s=[...r],[,n]=null!==(t=s.find((([,e])=>"transport"===(null==e?void 0:e.type))))&&void 0!==t?t:[],[,o]=null!==(i=s.find((([,e])=>"candidate-pair"===e.type&&"succeeded"===e.state&&e.nominated)))&&void 0!==i?i:[],a=r.get(String((null==o?void 0:o.localCandidateId)||"-")),c=r.get(String((null==o?void 0:o.remoteCandidateId)||"-")),d={hasNominatedPair:!!o,transportId:e.id,iceRole:null==n?void 0:n.iceRole,iceState:null==n?void 0:n.iceState,dtlsRole:null==n?void 0:n.dtlsRole,dtlsState:null==n?void 0:n.dtlsState,local:{address:null==a?void 0:a.address,candidateType:null==a?void 0:a.candidateType,foundation:null==a?void 0:a.foundation,networkType:null==a?void 0:a.networkType,isRemote:null==a?void 0:a.isRemote,port:null==a?void 0:a.port,protocol:null==a?void 0:a.protocol,relatedAddress:null==a?void 0:a.relatedAddress,relatedPort:null==a?void 0:a.relatedPort,transportId:null==a?void 0:a.transportId,relayProtocol:null==a?void 0:a.relayProtocol,url:null==a?void 0:a.url},remote:{address:null==c?void 0:c.address,candidateType:null==c?void 0:c.candidateType,foundation:null==c?void 0:c.foundation,isRemote:null==c?void 0:c.isRemote,port:null==c?void 0:c.port,protocol:null==c?void 0:c.protocol,transportId:null==c?void 0:c.transportId}};(null==o?void 0:o.totalRoundTripTime)&&(null==o?void 0:o.responsesReceived)&&(d.pairRoundTripTime=Math.round(o.totalRoundTripTime/o.responsesReceived*1e3)),this.logger.info("Detailed WebRTC transport stats",d)}catch(t){this.logger.error("Failed to log detailed WebRTC transport stats",{error:bd(t),transportId:e.id,reason:"-"})}}))}stopRestartIceAtempts(){clearInterval(this.sendTransportRestartIceInterval),clearInterval(this.recvTransportRestartIceInterval)}}const Sd=e=>![h.NotFoundError,h.NotAllowedError,h.DeviceIsBusy].includes(e);class _d{constructor(e){this.isEnableVideoDevicesLock=!1,this.isEnableAudioDevicesLock=!1,this.isDevicesDetected=!1,this.availableVideoDevices=[],this.availableAudioDevices=[];const{clientEventEmitter:t,logLevel:r,onLogMessage:i}=e;this.clientEventEmitter=t,this.logger=new Ge({namespace:"System",logLevel:r,onLogMessage:i}),this.deviceChangeHandler=this.deviceChangeHandler.bind(this),this.listenDevices()}setIsEnableVideoDevicesLock(e){this.isEnableVideoDevicesLock=e}setIsEnableAudioDevicesLock(e){this.isEnableAudioDevicesLock=e}setAvailableVideoDevices(e){this.availableVideoDevices=e}setAvailableAudioDevices(e){this.availableAudioDevices=e}requestMediaDevicesAccess(e={video:!0,audio:!0}){return r(this,void 0,void 0,(function*(){try{return(yield navigator.mediaDevices.getUserMedia(e)).getTracks()}catch(t){if(this.logger.error("getUserMedia()",{error:t,constraints:e}),"NotAllowedError"===t.name)throw new Error(h.NotAllowedError);if("NotReadableError"===t.name)throw new Error(h.DeviceIsBusy);if("NotFoundError"===t.name)throw new Error(h.NotFoundError);throw new Error(h.RequestDevicesUnknownError)}}))}refreshAvailableMediaDevicesList(){return r(this,void 0,void 0,(function*(){const e=yield navigator.mediaDevices.enumerateDevices(),t=[],r=[];e.forEach((e=>{""!==e.deviceId&&("videoinput"===e.kind&&t.push(e),"audioinput"===e.kind&&r.push(e))})),this.setAvailableVideoDevices(t),this.setAvailableAudioDevices(r);const i=({label:e,kind:t})=>({label:e,kind:t});return this.logger.debug("Devices list updated",{videoDevices:t.map(i),audioDevices:r.map(i)}),e}))}detectDevices(){return r(this,void 0,void 0,(function*(){let e=[];if(this.isDevicesDetected)return;try{e=yield this.requestMediaDevicesAccess()}catch(e){if(Sd(e.message))throw e;e.message!==h.DeviceIsBusy&&(yield this.assertHasAccessToMediaDevices({audio:!0}),yield this.assertHasAccessToMediaDevices({video:!0}))}this.isDevicesDetected=!0;const t=yield this.refreshAvailableMediaDevicesList();e.forEach((e=>e.stop()));const r=t.some((e=>"audioinput"===e.kind)),i=t.some((e=>"videoinput"===e.kind));if(!r&&!i)throw new Error(h.NoDevices)}))}deviceChangeHandler(){return r(this,void 0,void 0,(function*(){this.isDevicesDetected&&(yield this.refreshAvailableMediaDevicesList(),this.clientEventEmitter.safeEmit(F,{audio:this.availableAudioDevices,video:this.availableVideoDevices}))}))}listenDevices(){navigator.mediaDevices.addEventListener("devicechange",this.deviceChangeHandler)}assertHasAccessToMediaDevices(e={video:!0,audio:!0}){return r(this,void 0,void 0,(function*(){try{(yield this.requestMediaDevicesAccess(e)).forEach((e=>e.stop()))}catch(e){if(Sd(e.message))throw e}}))}}class Rd{constructor(e){const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new Ge({logLevel:t.logLevel,namespace:"ChannelEvents",onLogMessage:r})}handleDataChannelEvent(e){try{const{event:t,data:r}=JSON.parse(e);this.doHandleDataChannelEvent(t,r)}catch(t){this.logger.error("Failed to handle data channel event",{error:t,payload:e})}}doHandleDataChannelEvent(e,t){e===_&&this.handlePeerAppDataUpdate(t)}subscribeToEvents(){const{connection:e}=this.engine.network.socket;if(!e)throw this.logger.error("subscribeToEvents()",{error:"Socket connection not initialized"}),new Error("Socket connection not initialized");e.on(y,(e=>{this.engine.clientEventEmitter.safeEmit(M,e),this.logger.debug("New channel event",{event:e})})),e.on(b,(e=>{const t=this.engine.setPeer(e);this.engine.clientEventEmitter.safeEmit(x,t),this.logger.debug("Peer joined to the channel",{peer:t})})),e.on(S,(e=>{this.engine.removePeer(e),this.engine.clientEventEmitter.safeEmit(L,e),this.logger.debug("Peer left the channel",{peerId:e})})),e.on(C,(e=>{this.engine.clientEventEmitter.safeEmit(I,e),this.logger.info("Notify the channel that activity confirmation is required",e)})),e.on(P,(e=>{this.engine.clientEventEmitter.safeEmit(A,e),this.logger.info("Notify the channel that it has disconnected due to the activity confirmation expiring",e)})),e.on(k,(e=>{this.engine.clientEventEmitter.safeEmit(O,e),this.logger.info("Notify the channel that the activity has been acquired.",e)}))}removeEventListeners(){const{connection:e}=this.engine.network.socket;if(!e)return;[y,b,S,C,P,k,_].forEach((t=>e.removeAllListeners(t)))}handlePeerAppDataUpdate({peerId:e,appData:t}){const r=this.engine.peers.find((({id:t})=>t===e));r&&r.observer.emit(_,t)}reset(){this.removeEventListeners()}}class kd{constructor(e){this.queue=new Pa;const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new Ge({logLevel:t.logLevel,namespace:"MediasoupEvents",onLogMessage:r})}subscribeToEvents(){const{connection:e}=this.engine.network.socket;if(!e)throw this.logger.error("subscribeToEvents()",{error:"Socket connection not initialized"}),new Error("Socket connection not initialized");e.on(oe,(e=>{const t=this.engine.peers.find((t=>t.id===e.peerId));t&&t.observer.safeEmit(oe,e)})),e.on(ne,(e=>{const t=this.engine.peers.find((t=>t.id===e.peerId));t&&t.observer.safeEmit(ne,e)})),e.on(ve,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&r.observer.safeEmit(ve,e)})),e.on(be,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&!r.isMe&&r.observer.safeEmit(be,e)})),e.on(ye,((e,t)=>{const r=this.engine.peers.find((e=>e.id===t));r&&!r.isMe&&r.observer.safeEmit(ye,e)})),e.on(Se,(({peerId:e,spatialLayer:t,temporalLayer:r,consumerId:i})=>{const s=this.engine.peers.find((t=>t.id===e));s&&!s.isMe&&s.observer.safeEmit(Se,{consumerId:i,spatialLayer:t,temporalLayer:r})})),e.on(we,(e=>{const{consumerPeerId:t}=e,r=this.engine.peers.find((e=>e.id===t));if(!r||r.isMe)return;r.observer.safeEmit(we,e);const i=this.engine.peers.find((e=>e.isMe));i&&i.observer.safeEmit(we,e)})),e.on(ue,(e=>{const t=this.engine.peers.find((e=>e.isMe));t&&t.observer.safeEmit(ue,e)})),e.on(fe,(({producerId:e,spatialLayer:t})=>r(this,void 0,void 0,(function*(){yield this.queue.push((()=>r(this,void 0,void 0,(function*(){yield this.handleProducerSetMaxSpatialLayer({producerId:e,spatialLayer:t})}))),fe)})))),e.on(he,(({peerId:e,producerId:t,spatialLayer:i})=>r(this,void 0,void 0,(function*(){const r=this.engine.peers.find((t=>t.id===e));r&&!r.isMe&&r.observer.safeEmit(he,{peerId:e,producerId:t,spatialLayer:i})})))),e.on(Ee,(({reason:e,transportId:t,direction:i,timeout:s})=>r(this,void 0,void 0,(function*(){const r=[this.engine.network.receiveTransport,this.engine.network.sendTransport].find((e=>(null==e?void 0:e.id)===t));r&&"connected"!==r.connectionState&&(this.logger.warn(Ee,{reason:e,transportId:t,direction:i,timeout:s}),this.engine.clientEventEmitter.emit(N,{direction:i,reason:e}))})))),e.on(de,(({peerId:e,producerId:t})=>{const r=this.engine.peers.find((t=>t.id===e)),i=null==r?void 0:r.producers.get(t);r&&i&&(i.paused=!0,r.observer.safeEmit(Q,{producerId:i.id,kind:i.kind,label:i.label,paused:i.paused}))})),e.on(le,(({peerId:e,producerId:t})=>{const r=this.engine.peers.find((t=>t.id===e)),i=null==r?void 0:r.producers.get(t);r&&i&&(i.paused=!1,r.observer.safeEmit(X,{producerId:i.id,kind:i.kind,label:i.label,paused:i.paused}))})),e.on(pe,(({label:e})=>r(this,void 0,void 0,(function*(){const t=this.engine.media.getTrack(e);t&&(t.stopMediaStreamTrack(),this.engine.clientEventEmitter.safeEmit(G,t),this.engine.clientEventEmitter.emit(B,{label:e}),yield this.engine.media.deleteTrack(t))}))))}removeEventListeners(){const{connection:e}=this.engine.network.socket;if(!e)return;[oe,ne,ve,be,ye,Se,we,ue,fe,he,Ee,de,le,pe].forEach((t=>e.removeAllListeners(t)))}reset(){this.removeEventListeners()}handleProducerSetMaxSpatialLayer({producerId:e,spatialLayer:t}){return r(this,void 0,void 0,(function*(){const r=this.engine.media.getAllTracks().find((t=>{var r;return(null===(r=t.getProducer())||void 0===r?void 0:r.id)===e}));if(!r)return void this.logger.warn("producerRequestMaxSpatialLayer()",{message:"Producer not found"});if(!(r instanceof Ic))return void this.logger.warn("producerRequestMaxSpatialLayer()",{message:"Wrong producer kind"});const i=r.getMaxSpatialLayer();i!==t?(yield r.setMaxSpatialLayer(t),yield this.engine.network.socket.request(he,{producerId:e,maxSpatialLayer:t})):this.logger.debug("producerRequestMaxSpatialLayer()",{message:"Skip set max spatial layer",requestedSpatialLayer:t,currentMaxSpatialLayer:i})}))}}const Cd=Object.create(null);Cd.open="0",Cd.close="1",Cd.ping="2",Cd.pong="3",Cd.message="4",Cd.upgrade="5",Cd.noop="6";const Pd=Object.create(null);Object.keys(Cd).forEach((e=>{Pd[Cd[e]]=e}));const Td={type:"error",data:"parser error"},Ed="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Dd="function"==typeof ArrayBuffer,Md=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,xd=({type:e,data:t},r,i)=>Ed&&t instanceof Blob?r?i(t):Ld(t,i):Dd&&(t instanceof ArrayBuffer||Md(t))?r?i(t):Ld(new Blob([t]),i):i(Cd[e]+(t||"")),Ld=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function Id(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Od;const Ad="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",jd="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<Ad.length;e++)jd[Ad.charCodeAt(e)]=e;const Fd="function"==typeof ArrayBuffer,Nd=(e,t)=>{if("string"!=typeof e)return{type:"message",data:Ud(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:Bd(e.substring(1),t)};return Pd[r]?e.length>1?{type:Pd[r],data:e.substring(1)}:{type:Pd[r]}:Td},Bd=(e,t)=>{if(Fd){const r=(e=>{let t,r,i,s,n,o=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);const d=new ArrayBuffer(o),l=new Uint8Array(d);for(t=0;t<a;t+=4)r=jd[e.charCodeAt(t)],i=jd[e.charCodeAt(t+1)],s=jd[e.charCodeAt(t+2)],n=jd[e.charCodeAt(t+3)],l[c++]=r<<2|i>>4,l[c++]=(15&i)<<4|s>>2,l[c++]=(3&s)<<6|63&n;return d})(e);return Ud(r,t)}return{base64:!0,data:e}},Ud=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,qd=String.fromCharCode(30);function Wd(){return new TransformStream({transform(e,t){!function(e,t){Ed&&e.data instanceof Blob?e.data.arrayBuffer().then(Id).then(t):Dd&&(e.data instanceof ArrayBuffer||Md(e.data))?t(Id(e.data)):xd(e,!1,(e=>{Od||(Od=new TextEncoder),t(Od.encode(e))}))}(e,(r=>{const i=r.length;let s;if(i<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,i);else if(i<65536){s=new Uint8Array(3);const e=new DataView(s.buffer);e.setUint8(0,126),e.setUint16(1,i)}else{s=new Uint8Array(9);const e=new DataView(s.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(s[0]|=128),t.enqueue(s),t.enqueue(r)}))}})}let Vd;function zd(e){return e.reduce(((e,t)=>e+t.length),0)}function $d(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let i=0;for(let s=0;s<t;s++)r[s]=e[0][i++],i===e[0].length&&(e.shift(),i=0);return e.length&&i<e[0].length&&(e[0]=e[0].slice(i)),r}function Gd(e){if(e)return function(e){for(var t in Gd.prototype)e[t]=Gd.prototype[t];return e}(e)}Gd.prototype.on=Gd.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},Gd.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},Gd.prototype.off=Gd.prototype.removeListener=Gd.prototype.removeAllListeners=Gd.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,i=this._callbacks["$"+e];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var s=0;s<i.length;s++)if((r=i[s])===t||r.fn===t){i.splice(s,1);break}return 0===i.length&&delete this._callbacks["$"+e],this},Gd.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(r){i=0;for(var s=(r=r.slice(0)).length;i<s;++i)r[i].apply(this,t)}return this},Gd.prototype.emitReserved=Gd.prototype.emit,Gd.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},Gd.prototype.hasListeners=function(e){return!!this.listeners(e).length};const Hd="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Jd(e,...t){return t.reduce(((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t)),{})}const Kd=Hd.setTimeout,Qd=Hd.clearTimeout;function Xd(e,t){t.useNativeTimers?(e.setTimeoutFn=Kd.bind(Hd),e.clearTimeoutFn=Qd.bind(Hd)):(e.setTimeoutFn=Hd.setTimeout.bind(Hd),e.clearTimeoutFn=Hd.clearTimeout.bind(Hd))}class Yd extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class Zd extends Gd{constructor(e){super(),this.writable=!1,Xd(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,t,r){return super.emitReserved("error",new Yd(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=Nd(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}(e);return t.length?"?"+t:""}}const el="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),tl={};let rl,il=0,sl=0;function nl(e){let t="";do{t=el[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function ol(){const e=nl(+new Date);return e!==rl?(il=0,rl=e):e+"."+nl(il++)}for(;sl<64;sl++)tl[el[sl]]=sl;let al=!1;try{al="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(fm){}const cl=al;function dl(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||cl))return new XMLHttpRequest}catch(e){}if(!t)try{return new(Hd[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function ll(){}const pl=null!=new dl({xdomain:!1}).responseType;class ul extends Gd{constructor(e,t){super(),Xd(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.data=void 0!==t.data?t.data:null,this.create()}create(){var e;const t=Jd(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this.opts.xd;const r=this.xhr=new dl(t);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&r.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{r.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var e;3===r.readyState&&(null===(e=this.opts.cookieJar)||void 0===e||e.parseCookies(r)),4===r.readyState&&(200===r.status||1223===r.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof r.status?r.status:0)}),0))},r.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=ul.requestsCount++,ul.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=ll,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete ul.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(ul.requestsCount=0,ul.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",hl);else if("function"==typeof addEventListener){addEventListener("onpagehide"in Hd?"pagehide":"unload",hl,!1)}function hl(){for(let e in ul.requests)ul.requests.hasOwnProperty(e)&&ul.requests[e].abort()}const fl="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),ml=Hd.WebSocket||Hd.MozWebSocket,gl="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const vl={websocket:class extends Zd{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,r=gl?{}:Jd(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=gl?new ml(e,t,r):t?new ml(e,t):new ml(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;xd(r,this.supportsBinary,(e=>{try{this.ws.send(e)}catch(e){}i&&fl((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=ol()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}check(){return!!ml}},webtransport:class extends Zd{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then((()=>{this.onClose()})).catch((e=>{this.onError("webtransport error",e)})),this.transport.ready.then((()=>{this.transport.createBidirectionalStream().then((e=>{const t=function(e,t){Vd||(Vd=new TextDecoder);const r=[];let i=0,s=-1,n=!1;return new TransformStream({transform(o,a){for(r.push(o);;){if(0===i){if(zd(r)<1)break;const e=$d(r,1);n=128==(128&e[0]),s=127&e[0],i=s<126?3:126===s?1:2}else if(1===i){if(zd(r)<2)break;const e=$d(r,2);s=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(zd(r)<8)break;const e=$d(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),n=t.getUint32(0);if(n>Math.pow(2,21)-1){a.enqueue(Td);break}s=n*Math.pow(2,32)+t.getUint32(4),i=3}else{if(zd(r)<s)break;const e=$d(r,s);a.enqueue(Nd(n?e:Vd.decode(e),t)),i=0}if(0===s||s>e){a.enqueue(Td);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),i=Wd();i.readable.pipeTo(e.writable),this.writer=i.writable.getWriter();const s=()=>{r.read().then((({done:e,value:t})=>{e||(this.onPacket(t),s())})).catch((e=>{}))};s();const n={type:"open"};this.query.sid&&(n.data=`{"sid":"${this.query.sid}"}`),this.writer.write(n).then((()=>this.onOpen()))}))})))}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;this.writer.write(r).then((()=>{i&&fl((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var e;null===(e=this.transport)||void 0===e||e.close()}},polling:class extends Zd{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}const t=e&&e.forceBase64;this.supportsBinary=pl&&!t,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",(function(){--e||t()}))),this.writable||(e++,this.once("drain",(function(){--e||t()})))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const r=e.split(qd),i=[];for(let e=0;e<r.length;e++){const s=Nd(r[e],t);if(i.push(s),"error"===s.type)break}return i})(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const r=e.length,i=new Array(r);let s=0;e.forEach(((e,n)=>{xd(e,!1,(e=>{i[n]=e,++s===r&&t(i.join(qd))}))}))})(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=ol()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new ul(this.uri(),e)}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",((e,t)=>{this.onError("xhr post error",e,t)}))}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",((e,t)=>{this.onError("xhr poll error",e,t)})),this.pollXhr=e}}},yl=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,bl=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function wl(e){const t=e,r=e.indexOf("["),i=e.indexOf("]");-1!=r&&-1!=i&&(e=e.substring(0,r)+e.substring(r,i).replace(/:/g,";")+e.substring(i,e.length));let s=yl.exec(e||""),n={},o=14;for(;o--;)n[bl[o]]=s[o]||"";return-1!=r&&-1!=i&&(n.source=t,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.pathNames=function(e,t){const r=/\/{2,9}/g,i=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||i.splice(0,1);"/"==t.slice(-1)&&i.splice(i.length-1,1);return i}(0,n.path),n.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,i){t&&(r[t]=i)})),r}(0,n.query),n}class Sl extends Gd{constructor(e,t={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=wl(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=wl(t.host).host),Xd(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let e=0,i=r.length;e<i;e++){let i=r[e].split("=");t[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new vl[e](r)}open(){let e;if(this.opts.rememberUpgrade&&Sl.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(e=>this.onClose("transport close",e)))}probe(e){let t=this.createTransport(e),r=!1;Sl.priorWebsocketSuccess=!1;const i=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",(e=>{if(!r)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Sl.priorWebsocketSuccess="websocket"===t.name,this.transport.pause((()=>{r||"closed"!==this.readyState&&(d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())}))}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}})))};function s(){r||(r=!0,d(),t.close(),t=null)}const n=e=>{const r=new Error("probe error: "+e);r.transport=t.name,s(),this.emitReserved("upgradeError",r)};function o(){n("transport closed")}function a(){n("socket closed")}function c(e){t&&e.name!==t.name&&s()}const d=()=>{t.removeListener("open",i),t.removeListener("error",n),t.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};t.once("open",i),t.once("error",n),t.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn((()=>{r||t.open()}),200):t.open()}onOpen(){if(this.readyState="open",Sl.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let r=0;r<this.writeBuffer.length;r++){const i=this.writeBuffer[r].data;if(i&&(e+="string"==typeof(t=i)?function(e){let t=0,r=0;for(let i=0,s=e.length;i<s;i++)t=e.charCodeAt(i),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(i++,r+=4);return r}(t):Math.ceil(1.33*(t.byteLength||t.size))),r>0&&e>this.maxPayload)return this.writeBuffer.slice(0,r);e+=2}var t;return this.writeBuffer}write(e,t,r){return this.sendPacket("message",e,t,r),this}send(e,t,r){return this.sendPacket("message",e,t,r),this}sendPacket(e,t,r,i){if("function"==typeof t&&(i=t,t=void 0),"function"==typeof r&&(i=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const s={type:e,data:t,options:r};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?r():e()})):this.upgrading?r():e()),this}onError(e){Sl.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let r=0;const i=e.length;for(;r<i;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}Sl.protocol=4;const _l="function"==typeof ArrayBuffer,Rl=Object.prototype.toString,kl="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Rl.call(Blob),Cl="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Rl.call(File);function Pl(e){return _l&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||kl&&e instanceof Blob||Cl&&e instanceof File}function Tl(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Tl(e[t]))return!0;return!1}if(Pl(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Tl(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Tl(e[t]))return!0;return!1}function El(e){const t=[],r=e.data,i=e;return i.data=Dl(r,t),i.attachments=t.length,{packet:i,buffers:t}}function Dl(e,t){if(!e)return e;if(Pl(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let i=0;i<e.length;i++)r[i]=Dl(e[i],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=Dl(e[i],t));return r}return e}function Ml(e,t){return e.data=xl(e.data,t),delete e.attachments,e}function xl(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=xl(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=xl(e[r],t));return e}const Ll=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Il;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(Il||(Il={}));function Ol(e){return"[object Object]"===Object.prototype.toString.call(e)}class Al extends Gd{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===Il.BINARY_EVENT;r||t.type===Il.BINARY_ACK?(t.type=r?Il.EVENT:Il.ACK,this.reconstructor=new jl(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Pl(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===Il[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Il.BINARY_EVENT||r.type===Il.BINARY_ACK){const i=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const s=e.substring(i,t);if(s!=Number(s)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(s)}if("/"===e.charAt(t+1)){const i=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(i,t)}else r.nsp="/";const i=e.charAt(t+1);if(""!==i&&Number(i)==i){const i=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(!Al.isPayloadValid(r.type,i))throw new Error("invalid payload");r.data=i}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case Il.CONNECT:return Ol(t);case Il.DISCONNECT:return void 0===t;case Il.CONNECT_ERROR:return"string"==typeof t||Ol(t);case Il.EVENT:case Il.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Ll.indexOf(t[0]));case Il.ACK:case Il.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class jl{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Ml(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var Fl=Object.freeze({__proto__:null,protocol:5,get PacketType(){return Il},Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Il.EVENT&&e.type!==Il.ACK||!Tl(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Il.EVENT?Il.BINARY_EVENT:Il.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Il.BINARY_EVENT&&e.type!==Il.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=El(e),r=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(r),i}},Decoder:Al});function Nl(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const Bl=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Ul extends Gd{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[Nl(e,"open",this.onopen.bind(this)),Nl(e,"packet",this.onpacket.bind(this)),Nl(e,"error",this.onerror.bind(this)),Nl(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(Bl.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const r={type:Il.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,i=t.pop();this._registerAckCallback(e,i),r.id=e}const i=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!i||!this.connected)||(this.connected?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var r;const i=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===i)return void(this.acks[e]=t);const s=this.io.setTimeoutFn((()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))}),i);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(s),t.apply(this,[null,...e])}}emitWithAck(e,...t){const r=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((i,s)=>{t.push(((e,t)=>r?e?s(e):i(t):i(e))),this.emit(e,...t)}))}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push(((e,...i)=>{if(r!==this._queue[0])return;return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...i)),r.pending=!1,this._drainQueue()})),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Il.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Il.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Il.EVENT:case Il.BINARY_EVENT:this.onevent(e);break;case Il.ACK:case Il.BINARY_ACK:this.onack(e);break;case Il.DISCONNECT:this.ondisconnect();break;case Il.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...i){r||(r=!0,t.packet({type:Il.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((e=>{this.notifyOutgoingListeners(e),this.packet(e)})),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((e=>e())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Il.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function ql(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}ql.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-r:e+r}return 0|Math.min(e,this.max)},ql.prototype.reset=function(){this.attempts=0},ql.prototype.setMin=function(e){this.ms=e},ql.prototype.setMax=function(e){this.max=e},ql.prototype.setJitter=function(e){this.jitter=e};class Wl extends Gd{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,Xd(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new ql({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||Fl;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Sl(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=Nl(t,"open",(function(){r.onopen(),e&&e()})),s=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},n=Nl(t,"error",s);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn((()=>{i(),s(new Error("timeout")),t.close()}),e);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}return this.subs.push(i),this.subs.push(n),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(Nl(e,"ping",this.onping.bind(this)),Nl(e,"data",this.ondata.bind(this)),Nl(e,"error",this.onerror.bind(this)),Nl(e,"close",this.onclose.bind(this)),Nl(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){fl((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new Ul(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn((()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()})))}),t);this.opts.autoUnref&&r.unref(),this.subs.push((()=>{this.clearTimeoutFn(r)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Vl={};function zl(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let i=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),i=wl(e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const s=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+s+":"+i.port+t,i.href=i.protocol+"://"+s+(r&&r.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),i=r.source,s=r.id,n=r.path,o=Vl[s]&&n in Vl[s].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||o?a=new Wl(i,t):(Vl[s]||(Vl[s]=new Wl(i,t)),a=Vl[s]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(zl,{Manager:Wl,Socket:Ul,io:zl,connect:zl});class $l{constructor(e){this.reconnectingAttempt=0,this.isConnected=!1,this._observer=new n,this.knownDisconnectReasonsCodes={"io server disconnect":"server.disconnect","io client disconnect":"client.disconnect","ping timeout":"ping.timeout","transport close":"transport.close","transport error":"transport.error"},this.logger=new Ge({namespace:"Socket",logLevel:e.logLevel,onLogMessage:e.onLogMessage})}get observer(){return this._observer}get id(){var e;return null===(e=this.connection)||void 0===e?void 0:e.id}connect(e,t){const r=zl(e,{transports:["polling","websocket"],upgrade:!0,rememberUpgrade:!1,auth:{token:t,apiVersion:2}});this.connection=r,this.serverUrl=e,r.on(Ha.Connect,(()=>{const e=this.reconnectingAttempt?Ha.Reconnected:Ha.Connected;this.isConnected=!0,this.setReconnectingAttempt(0),this.logger.debug(`connection.on('${Ha.Connect}')`,{connectionId:r.id}),this.observer.safeEmit(Ha.State,{state:e})})),r.on(Ha.ConnectError,(e=>{this.connectionError=e,this.logger.error(`connection.on('${Ha.ConnectError}')`,{error:e}),this.observer.safeEmit(Ha.State,{state:Ha.Error,error:e})})),r.on(Ha.Disconnect,(e=>{this.isConnected=!1,this.setReconnectingAttempt(0),this.disconnectReason=e,this.logger.info(`connection.on('${Ha.Disconnect}')`,{reason:e}),this.observer.safeEmit(Ha.State,{state:Ha.Disconnected,code:this.getDisconnectReasonCode(e)})})),r.io.on(Ha.ReconnectAttempt,(e=>{this.setReconnectingAttempt(e),this.logger.info(`connection.on('${Ha.ReconnectAttempt}')`,{attempt:e}),this.observer.safeEmit(Ha.State,{state:Ha.Reconnecting})})),r.io.on(Ha.Reconnect,(()=>{this.logger.debug(`connection.on('${Ha.Reconnect}')`,{connectionId:r.id}),this.observer.safeEmit(Ha.State,{state:Ha.Reconnect})}))}disconnect(){this.connection&&(this.connection.offAny(),this.connection.volatile.offAny(),this.connection.disconnect(),this.connection.io.removeAllListeners(),this.setReconnectingAttempt(0))}request(e,t={}){return new Promise(((r,i)=>{if(!this.connection)return this.logger.error("request()",{type:e,data:t}),void i(new Error("Socket request: Socket connection is not initialized"));this.connection.emit(e,t,(s=>{s.error?(this.logger.error("request()",{event:e,payload:t,response:s}),i(s.error)):r(s)}))}))}getServerUrl(){return this.serverUrl}getDisconnectReasonCode(e){const t=String(e).toLowerCase();return this.knownDisconnectReasonsCodes[t]||t}setReconnectingAttempt(e){this.reconnectingAttempt=e}}var Gl={exports:{}},Hl=function(e,t){return function(){for(var r=new Array(arguments.length),i=0;i<r.length;i++)r[i]=arguments[i];return e.apply(t,r)}},Jl=Hl,Kl=Object.prototype.toString;function Ql(e){return"[object Array]"===Kl.call(e)}function Xl(e){return void 0===e}function Yl(e){return null!==e&&"object"==typeof e}function Zl(e){if("[object Object]"!==Kl.call(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}function ep(e){return"[object Function]"===Kl.call(e)}function tp(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),Ql(e))for(var r=0,i=e.length;r<i;r++)t.call(null,e[r],r,e);else for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.call(null,e[s],s,e)}var rp={isArray:Ql,isArrayBuffer:function(e){return"[object ArrayBuffer]"===Kl.call(e)},isBuffer:function(e){return null!==e&&!Xl(e)&&null!==e.constructor&&!Xl(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){return"undefined"!=typeof FormData&&e instanceof FormData},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e},isObject:Yl,isPlainObject:Zl,isUndefined:Xl,isDate:function(e){return"[object Date]"===Kl.call(e)},isFile:function(e){return"[object File]"===Kl.call(e)},isBlob:function(e){return"[object Blob]"===Kl.call(e)},isFunction:ep,isStream:function(e){return Yl(e)&&ep(e.pipe)},isURLSearchParams:function(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)},forEach:tp,merge:function e(){var t={};function r(r,i){Zl(t[i])&&Zl(r)?t[i]=e(t[i],r):Zl(r)?t[i]=e({},r):Ql(r)?t[i]=r.slice():t[i]=r}for(var i=0,s=arguments.length;i<s;i++)tp(arguments[i],r);return t},extend:function(e,t,r){return tp(t,(function(t,i){e[i]=r&&"function"==typeof t?Jl(t,r):t})),e},trim:function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e}},ip=rp;function sp(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var np=function(e,t,r){if(!t)return e;var i;if(r)i=r(t);else if(ip.isURLSearchParams(t))i=t.toString();else{var s=[];ip.forEach(t,(function(e,t){null!=e&&(ip.isArray(e)?t+="[]":e=[e],ip.forEach(e,(function(e){ip.isDate(e)?e=e.toISOString():ip.isObject(e)&&(e=JSON.stringify(e)),s.push(sp(t)+"="+sp(e))})))})),i=s.join("&")}if(i){var n=e.indexOf("#");-1!==n&&(e=e.slice(0,n)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e},op=rp;function ap(){this.handlers=[]}ap.prototype.use=function(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1},ap.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},ap.prototype.forEach=function(e){op.forEach(this.handlers,(function(t){null!==t&&e(t)}))};var cp=ap,dp=rp,lp=function(e,t,r,i,s){return e.config=t,r&&(e.code=r),e.request=i,e.response=s,e.isAxiosError=!0,e.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code}},e},pp=lp,up=function(e,t,r,i,s){var n=new Error(e);return pp(n,t,r,i,s)},hp=up,fp=rp,mp=fp.isStandardBrowserEnv()?{write:function(e,t,r,i,s,n){var o=[];o.push(e+"="+encodeURIComponent(t)),fp.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),fp.isString(i)&&o.push("path="+i),fp.isString(s)&&o.push("domain="+s),!0===n&&o.push("secure"),document.cookie=o.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}},gp=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)},vp=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e},yp=rp,bp=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"],wp=rp,Sp=wp.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");function i(e){var i=e;return t&&(r.setAttribute("href",i),i=r.href),r.setAttribute("href",i),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:"/"===r.pathname.charAt(0)?r.pathname:"/"+r.pathname}}return e=i(window.location.href),function(t){var r=wp.isString(t)?i(t):t;return r.protocol===e.protocol&&r.host===e.host}}():function(){return!0},_p=rp,Rp=function(e,t,r){var i=r.config.validateStatus;r.status&&i&&!i(r.status)?t(hp("Request failed with status code "+r.status,r.config,null,r.request,r)):e(r)},kp=mp,Cp=np,Pp=function(e,t){return e&&!gp(t)?vp(e,t):t},Tp=function(e){var t,r,i,s={};return e?(yp.forEach(e.split("\n"),(function(e){if(i=e.indexOf(":"),t=yp.trim(e.substr(0,i)).toLowerCase(),r=yp.trim(e.substr(i+1)),t){if(s[t]&&bp.indexOf(t)>=0)return;s[t]="set-cookie"===t?(s[t]?s[t]:[]).concat([r]):s[t]?s[t]+", "+r:r}})),s):s},Ep=Sp,Dp=up,Mp=function(e){return new Promise((function(t,r){var i=e.data,s=e.headers,n=e.responseType;_p.isFormData(i)&&delete s["Content-Type"];var o=new XMLHttpRequest;if(e.auth){var a=e.auth.username||"",c=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";s.Authorization="Basic "+btoa(a+":"+c)}var d=Pp(e.baseURL,e.url);function l(){if(o){var i="getAllResponseHeaders"in o?Tp(o.getAllResponseHeaders()):null,s={data:n&&"text"!==n&&"json"!==n?o.response:o.responseText,status:o.status,statusText:o.statusText,headers:i,config:e,request:o};Rp(t,r,s),o=null}}if(o.open(e.method.toUpperCase(),Cp(d,e.params,e.paramsSerializer),!0),o.timeout=e.timeout,"onloadend"in o?o.onloadend=l:o.onreadystatechange=function(){o&&4===o.readyState&&(0!==o.status||o.responseURL&&0===o.responseURL.indexOf("file:"))&&setTimeout(l)},o.onabort=function(){o&&(r(Dp("Request aborted",e,"ECONNABORTED",o)),o=null)},o.onerror=function(){r(Dp("Network Error",e,null,o)),o=null},o.ontimeout=function(){var t="timeout of "+e.timeout+"ms exceeded";e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),r(Dp(t,e,e.transitional&&e.transitional.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",o)),o=null},_p.isStandardBrowserEnv()){var p=(e.withCredentials||Ep(d))&&e.xsrfCookieName?kp.read(e.xsrfCookieName):void 0;p&&(s[e.xsrfHeaderName]=p)}"setRequestHeader"in o&&_p.forEach(s,(function(e,t){void 0===i&&"content-type"===t.toLowerCase()?delete s[t]:o.setRequestHeader(t,e)})),_p.isUndefined(e.withCredentials)||(o.withCredentials=!!e.withCredentials),n&&"json"!==n&&(o.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&o.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&o.upload&&o.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then((function(e){o&&(o.abort(),r(e),o=null)})),i||(i=null),o.send(i)}))},xp=rp,Lp=function(e,t){dp.forEach(e,(function(r,i){i!==t&&i.toUpperCase()===t.toUpperCase()&&(e[t]=r,delete e[i])}))},Ip=lp,Op={"Content-Type":"application/x-www-form-urlencoded"};function Ap(e,t){!xp.isUndefined(e)&&xp.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}var jp,Fp={transitional:{silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},adapter:(("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(jp=Mp),jp),transformRequest:[function(e,t){return Lp(t,"Accept"),Lp(t,"Content-Type"),xp.isFormData(e)||xp.isArrayBuffer(e)||xp.isBuffer(e)||xp.isStream(e)||xp.isFile(e)||xp.isBlob(e)?e:xp.isArrayBufferView(e)?e.buffer:xp.isURLSearchParams(e)?(Ap(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):xp.isObject(e)||t&&"application/json"===t["Content-Type"]?(Ap(t,"application/json"),function(e,t,r){if(xp.isString(e))try{return(t||JSON.parse)(e),xp.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){var t=this.transitional,r=t&&t.silentJSONParsing,i=t&&t.forcedJSONParsing,s=!r&&"json"===this.responseType;if(s||i&&xp.isString(e)&&e.length)try{return JSON.parse(e)}catch(e){if(s){if("SyntaxError"===e.name)throw Ip(e,this,"E_JSON_PARSE");throw e}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,validateStatus:function(e){return e>=200&&e<300}};Fp.headers={common:{Accept:"application/json, text/plain, */*"}},xp.forEach(["delete","get","head"],(function(e){Fp.headers[e]={}})),xp.forEach(["post","put","patch"],(function(e){Fp.headers[e]=xp.merge(Op)}));var Np=Fp,Bp=rp,Up=Np,qp=function(e){return!(!e||!e.__CANCEL__)},Wp=rp,Vp=function(e,t,r){var i=this||Up;return Bp.forEach(r,(function(r){e=r.call(i,e,t)})),e},zp=qp,$p=Np;function Gp(e){e.cancelToken&&e.cancelToken.throwIfRequested()}var Hp=rp,Jp=function(e,t){t=t||{};var r={},i=["url","method","data"],s=["headers","auth","proxy","params"],n=["baseURL","transformRequest","transformResponse","paramsSerializer","timeout","timeoutMessage","withCredentials","adapter","responseType","xsrfCookieName","xsrfHeaderName","onUploadProgress","onDownloadProgress","decompress","maxContentLength","maxBodyLength","maxRedirects","transport","httpAgent","httpsAgent","cancelToken","socketPath","responseEncoding"],o=["validateStatus"];function a(e,t){return Hp.isPlainObject(e)&&Hp.isPlainObject(t)?Hp.merge(e,t):Hp.isPlainObject(t)?Hp.merge({},t):Hp.isArray(t)?t.slice():t}function c(i){Hp.isUndefined(t[i])?Hp.isUndefined(e[i])||(r[i]=a(void 0,e[i])):r[i]=a(e[i],t[i])}Hp.forEach(i,(function(e){Hp.isUndefined(t[e])||(r[e]=a(void 0,t[e]))})),Hp.forEach(s,c),Hp.forEach(n,(function(i){Hp.isUndefined(t[i])?Hp.isUndefined(e[i])||(r[i]=a(void 0,e[i])):r[i]=a(void 0,t[i])})),Hp.forEach(o,(function(i){i in t?r[i]=a(e[i],t[i]):i in e&&(r[i]=a(void 0,e[i]))}));var d=i.concat(s).concat(n).concat(o),l=Object.keys(e).concat(Object.keys(t)).filter((function(e){return-1===d.indexOf(e)}));return Hp.forEach(l,c),r},Kp={name:"axios",version:"0.21.4",description:"Promise based HTTP client for the browser and node.js",main:"index.js",scripts:{test:"grunt test",start:"node ./sandbox/server.js",build:"NODE_ENV=production grunt build",preversion:"npm test",version:"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json",postversion:"git push && git push --tags",examples:"node ./examples/server.js",coveralls:"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",fix:"eslint --fix lib/**/*.js"},repository:{type:"git",url:"https://github.com/axios/axios.git"},keywords:["xhr","http","ajax","promise","node"],author:"Matt Zabriskie",license:"MIT",bugs:{url:"https://github.com/axios/axios/issues"},homepage:"https://axios-http.com",devDependencies:{coveralls:"^3.0.0","es6-promise":"^4.2.4",grunt:"^1.3.0","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.1.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^23.0.0","grunt-karma":"^4.0.0","grunt-mocha-test":"^0.13.3","grunt-ts":"^6.0.0-beta.19","grunt-webpack":"^4.0.2","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1",karma:"^6.3.2","karma-chrome-launcher":"^3.1.0","karma-firefox-launcher":"^2.1.0","karma-jasmine":"^1.1.1","karma-jasmine-ajax":"^0.1.13","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^4.3.6","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.8","karma-webpack":"^4.0.2","load-grunt-tasks":"^3.5.2",minimist:"^1.2.0",mocha:"^8.2.1",sinon:"^4.5.0","terser-webpack-plugin":"^4.2.3",typescript:"^4.0.5","url-search-params":"^0.10.0",webpack:"^4.44.2","webpack-dev-server":"^3.11.0"},browser:{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},jsdelivr:"dist/axios.min.js",unpkg:"dist/axios.min.js",typings:"./index.d.ts",dependencies:{"follow-redirects":"^1.14.0"},bundlesize:[{path:"./dist/axios.min.js",threshold:"5kB"}]},Qp={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){Qp[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));var Xp={},Yp=Kp.version.split(".");function Zp(e,t){for(var r=t?t.split("."):Yp,i=e.split("."),s=0;s<3;s++){if(r[s]>i[s])return!0;if(r[s]<i[s])return!1}return!1}Qp.transitional=function(e,t,r){var i=t&&Zp(t);function s(e,t){return"[Axios v"+Kp.version+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return function(r,n,o){if(!1===e)throw new Error(s(n," has been removed in "+t));return i&&!Xp[n]&&(Xp[n]=!0,console.warn(s(n," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,n,o)}};var eu={isOlderVersion:Zp,assertOptions:function(e,t,r){if("object"!=typeof e)throw new TypeError("options must be an object");for(var i=Object.keys(e),s=i.length;s-- >0;){var n=i[s],o=t[n];if(o){var a=e[n],c=void 0===a||o(a,n,e);if(!0!==c)throw new TypeError("option "+n+" must be "+c)}else if(!0!==r)throw Error("Unknown option "+n)}},validators:Qp},tu=rp,ru=np,iu=cp,su=function(e){return Gp(e),e.headers=e.headers||{},e.data=Vp.call(e,e.data,e.headers,e.transformRequest),e.headers=Wp.merge(e.headers.common||{},e.headers[e.method]||{},e.headers),Wp.forEach(["delete","get","head","post","put","patch","common"],(function(t){delete e.headers[t]})),(e.adapter||$p.adapter)(e).then((function(t){return Gp(e),t.data=Vp.call(e,t.data,t.headers,e.transformResponse),t}),(function(t){return zp(t)||(Gp(e),t&&t.response&&(t.response.data=Vp.call(e,t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)}))},nu=Jp,ou=eu,au=ou.validators;function cu(e){this.defaults=e,this.interceptors={request:new iu,response:new iu}}cu.prototype.request=function(e){"string"==typeof e?(e=arguments[1]||{}).url=arguments[0]:e=e||{},(e=nu(this.defaults,e)).method?e.method=e.method.toLowerCase():this.defaults.method?e.method=this.defaults.method.toLowerCase():e.method="get";var t=e.transitional;void 0!==t&&ou.assertOptions(t,{silentJSONParsing:au.transitional(au.boolean,"1.0.0"),forcedJSONParsing:au.transitional(au.boolean,"1.0.0"),clarifyTimeoutError:au.transitional(au.boolean,"1.0.0")},!1);var r=[],i=!0;this.interceptors.request.forEach((function(t){"function"==typeof t.runWhen&&!1===t.runWhen(e)||(i=i&&t.synchronous,r.unshift(t.fulfilled,t.rejected))}));var s,n=[];if(this.interceptors.response.forEach((function(e){n.push(e.fulfilled,e.rejected)})),!i){var o=[su,void 0];for(Array.prototype.unshift.apply(o,r),o=o.concat(n),s=Promise.resolve(e);o.length;)s=s.then(o.shift(),o.shift());return s}for(var a=e;r.length;){var c=r.shift(),d=r.shift();try{a=c(a)}catch(e){d(e);break}}try{s=su(a)}catch(e){return Promise.reject(e)}for(;n.length;)s=s.then(n.shift(),n.shift());return s},cu.prototype.getUri=function(e){return e=nu(this.defaults,e),ru(e.url,e.params,e.paramsSerializer).replace(/^\?/,"")},tu.forEach(["delete","get","head","options"],(function(e){cu.prototype[e]=function(t,r){return this.request(nu(r||{},{method:e,url:t,data:(r||{}).data}))}})),tu.forEach(["post","put","patch"],(function(e){cu.prototype[e]=function(t,r,i){return this.request(nu(i||{},{method:e,url:t,data:r}))}}));var du=cu;function lu(e){this.message=e}lu.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},lu.prototype.__CANCEL__=!0;var pu=lu,uu=pu;function hu(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var r=this;e((function(e){r.reason||(r.reason=new uu(e),t(r.reason))}))}hu.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},hu.source=function(){var e,t=new hu((function(t){e=t}));return{token:t,cancel:e}};var fu=hu,mu=rp,gu=Hl,vu=du,yu=Jp;function bu(e){var t=new vu(e),r=gu(vu.prototype.request,t);return mu.extend(r,vu.prototype,t),mu.extend(r,t),r}var wu=bu(Np);wu.Axios=vu,wu.create=function(e){return bu(yu(wu.defaults,e))},wu.Cancel=pu,wu.CancelToken=fu,wu.isCancel=qp,wu.all=function(e){return Promise.all(e)},wu.spread=function(e){return function(t){return e.apply(null,t)}},wu.isAxiosError=function(e){return"object"==typeof e&&!0===e.isAxiosError},Gl.exports=wu,Gl.exports.default=wu;var Su=Gl.exports,_u="undefined"!=typeof Symbol&&Symbol,Ru=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var i=Object.getOwnPropertySymbols(e);if(1!==i.length||i[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var s=Object.getOwnPropertyDescriptor(e,t);if(42!==s.value||!0!==s.enumerable)return!1}return!0},ku="Function.prototype.bind called on incompatible ",Cu=Array.prototype.slice,Pu=Object.prototype.toString,Tu=function(e){var t=this;if("function"!=typeof t||"[object Function]"!==Pu.call(t))throw new TypeError(ku+t);for(var r,i=Cu.call(arguments,1),s=function(){if(this instanceof r){var s=t.apply(this,i.concat(Cu.call(arguments)));return Object(s)===s?s:this}return t.apply(e,i.concat(Cu.call(arguments)))},n=Math.max(0,t.length-i.length),o=[],a=0;a<n;a++)o.push("$"+a);if(r=Function("binder","return function ("+o.join(",")+"){ return binder.apply(this,arguments); }")(s),t.prototype){var c=function(){};c.prototype=t.prototype,r.prototype=new c,c.prototype=null}return r},Eu=Function.prototype.bind||Tu,Du=Eu.call(Function.call,Object.prototype.hasOwnProperty),Mu=SyntaxError,xu=Function,Lu=TypeError,Iu=function(e){try{return xu('"use strict"; return ('+e+").constructor;")()}catch(e){}},Ou=Object.getOwnPropertyDescriptor;if(Ou)try{Ou({},"")}catch(Bc){Ou=null}var Au=function(){throw new Lu},ju=Ou?function(){try{return Au}catch(e){try{return Ou(arguments,"callee").get}catch(e){return Au}}}():Au,Fu="function"==typeof _u&&"function"==typeof Symbol&&"symbol"==typeof _u("foo")&&"symbol"==typeof Symbol("bar")&&Ru(),Nu=Object.getPrototypeOf||function(e){return e.__proto__},Bu={},Uu="undefined"==typeof Uint8Array?undefined:Nu(Uint8Array),qu={"%AggregateError%":"undefined"==typeof AggregateError?undefined:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?undefined:ArrayBuffer,"%ArrayIteratorPrototype%":Fu?Nu([][Symbol.iterator]()):undefined,"%AsyncFromSyncIteratorPrototype%":undefined,"%AsyncFunction%":Bu,"%AsyncGenerator%":Bu,"%AsyncGeneratorFunction%":Bu,"%AsyncIteratorPrototype%":Bu,"%Atomics%":"undefined"==typeof Atomics?undefined:Atomics,"%BigInt%":"undefined"==typeof BigInt?undefined:BigInt,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?undefined:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?undefined:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?undefined:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?undefined:FinalizationRegistry,"%Function%":xu,"%GeneratorFunction%":Bu,"%Int8Array%":"undefined"==typeof Int8Array?undefined:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?undefined:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?undefined:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":Fu?Nu(Nu([][Symbol.iterator]())):undefined,"%JSON%":"object"==typeof JSON?JSON:undefined,"%Map%":"undefined"==typeof Map?undefined:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&Fu?Nu((new Map)[Symbol.iterator]()):undefined,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?undefined:Promise,"%Proxy%":"undefined"==typeof Proxy?undefined:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?undefined:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?undefined:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&Fu?Nu((new Set)[Symbol.iterator]()):undefined,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?undefined:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":Fu?Nu(""[Symbol.iterator]()):undefined,"%Symbol%":Fu?Symbol:undefined,"%SyntaxError%":Mu,"%ThrowTypeError%":ju,"%TypedArray%":Uu,"%TypeError%":Lu,"%Uint8Array%":"undefined"==typeof Uint8Array?undefined:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?undefined:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?undefined:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?undefined:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?undefined:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?undefined:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?undefined:WeakSet},Wu=function e(t){var r;if("%AsyncFunction%"===t)r=Iu("async function () {}");else if("%GeneratorFunction%"===t)r=Iu("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=Iu("async function* () {}");else if("%AsyncGenerator%"===t){var i=e("%AsyncGeneratorFunction%");i&&(r=i.prototype)}else if("%AsyncIteratorPrototype%"===t){var s=e("%AsyncGenerator%");s&&(r=Nu(s.prototype))}return qu[t]=r,r},Vu={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},zu=Eu,$u=Du,Gu=zu.call(Function.call,Array.prototype.concat),Hu=zu.call(Function.apply,Array.prototype.splice),Ju=zu.call(Function.call,String.prototype.replace),Ku=zu.call(Function.call,String.prototype.slice),Qu=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Xu=/\\(\\)?/g,Yu=function(e){var t=Ku(e,0,1),r=Ku(e,-1);if("%"===t&&"%"!==r)throw new Mu("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new Mu("invalid intrinsic syntax, expected opening `%`");var i=[];return Ju(e,Qu,(function(e,t,r,s){i[i.length]=r?Ju(s,Xu,"$1"):t||e})),i},Zu=function(e,t){var r,i=e;if($u(Vu,i)&&(i="%"+(r=Vu[i])[0]+"%"),$u(qu,i)){var s=qu[i];if(s===Bu&&(s=Wu(i)),void 0===s&&!t)throw new Lu("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:i,value:s}}throw new Mu("intrinsic "+e+" does not exist!")},eh=function(e,t){if("string"!=typeof e||0===e.length)throw new Lu("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new Lu('"allowMissing" argument must be a boolean');var r=Yu(e),i=r.length>0?r[0]:"",s=Zu("%"+i+"%",t),n=s.name,o=s.value,a=!1,c=s.alias;c&&(i=c[0],Hu(r,Gu([0,1],c)));for(var d=1,l=!0;d<r.length;d+=1){var p=r[d],u=Ku(p,0,1),h=Ku(p,-1);if(('"'===u||"'"===u||"`"===u||'"'===h||"'"===h||"`"===h)&&u!==h)throw new Mu("property names with quotes must have matching quotes");if("constructor"!==p&&l||(a=!0),$u(qu,n="%"+(i+="."+p)+"%"))o=qu[n];else if(null!=o){if(!(p in o)){if(!t)throw new Lu("base intrinsic for "+e+" exists, but the property is not available.");return}if(Ou&&d+1>=r.length){var f=Ou(o,p);o=(l=!!f)&&"get"in f&&!("originalValue"in f.get)?f.get:o[p]}else l=$u(o,p),o=o[p];l&&!a&&(qu[n]=o)}}return o},th={exports:{}};!function(e){var t=Eu,r=eh,i=r("%Function.prototype.apply%"),s=r("%Function.prototype.call%"),n=r("%Reflect.apply%",!0)||t.call(s,i),o=r("%Object.getOwnPropertyDescriptor%",!0),a=r("%Object.defineProperty%",!0),c=r("%Math.max%");if(a)try{a({},"a",{value:1})}catch(e){a=null}e.exports=function(e){var r=n(t,s,arguments);if(o&&a){var i=o(r,"length");i.configurable&&a(r,"length",{value:1+c(0,e.length-(arguments.length-1))})}return r};var d=function(){return n(t,i,arguments)};a?a(e.exports,"apply",{value:d}):e.exports.apply=d}(th);var rh=eh,ih=th.exports,sh=ih(rh("String.prototype.indexOf")),nh=c(Object.freeze({__proto__:null,default:{}})),oh="function"==typeof Map&&Map.prototype,ah=Object.getOwnPropertyDescriptor&&oh?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,ch=oh&&ah&&"function"==typeof ah.get?ah.get:null,dh=oh&&Map.prototype.forEach,lh="function"==typeof Set&&Set.prototype,ph=Object.getOwnPropertyDescriptor&&lh?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,uh=lh&&ph&&"function"==typeof ph.get?ph.get:null,hh=lh&&Set.prototype.forEach,fh="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,mh="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,gh="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,vh=Boolean.prototype.valueOf,yh=Object.prototype.toString,bh=Function.prototype.toString,wh=String.prototype.match,Sh="function"==typeof BigInt?BigInt.prototype.valueOf:null,_h=Object.getOwnPropertySymbols,Rh="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,kh="function"==typeof Symbol&&"object"==typeof Symbol.iterator,Ch=Object.prototype.propertyIsEnumerable,Ph=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null),Th=nh.custom,Eh=Th&&Ih(Th)?Th:null,Dh="function"==typeof Symbol&&void 0!==Symbol.toStringTag?Symbol.toStringTag:null;function Mh(e,t,r){var i="double"===(r.quoteStyle||t)?'"':"'";return i+e+i}function xh(e){return String(e).replace(/"/g,"&quot;")}function Lh(e){return!("[object Array]"!==jh(e)||Dh&&"object"==typeof e&&Dh in e)}function Ih(e){if(kh)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!Rh)return!1;try{return Rh.call(e),!0}catch(e){}return!1}var Oh=Object.prototype.hasOwnProperty||function(e){return e in this};function Ah(e,t){return Oh.call(e,t)}function jh(e){return yh.call(e)}function Fh(e,t){if(e.indexOf)return e.indexOf(t);for(var r=0,i=e.length;r<i;r++)if(e[r]===t)return r;return-1}function Nh(e,t){if(e.length>t.maxStringLength){var r=e.length-t.maxStringLength,i="... "+r+" more character"+(r>1?"s":"");return Nh(e.slice(0,t.maxStringLength),t)+i}return Mh(e.replace(/(['\\])/g,"\\$1").replace(/[\x00-\x1f]/g,Bh),"single",t)}function Bh(e){var t=e.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return r?"\\"+r:"\\x"+(t<16?"0":"")+t.toString(16).toUpperCase()}function Uh(e){return"Object("+e+")"}function qh(e){return e+" { ? }"}function Wh(e,t,r,i){return e+" ("+t+") {"+(i?Vh(r,i):r.join(", "))+"}"}function Vh(e,t){if(0===e.length)return"";var r="\n"+t.prev+t.base;return r+e.join(","+r)+"\n"+t.prev}function zh(e,t){var r=Lh(e),i=[];if(r){i.length=e.length;for(var s=0;s<e.length;s++)i[s]=Ah(e,s)?t(e[s],e):""}var n,o="function"==typeof _h?_h(e):[];if(kh){n={};for(var a=0;a<o.length;a++)n["$"+o[a]]=o[a]}for(var c in e)Ah(e,c)&&(r&&String(Number(c))===c&&c<e.length||kh&&n["$"+c]instanceof Symbol||(/[^\w$]/.test(c)?i.push(t(c,e)+": "+t(e[c],e)):i.push(c+": "+t(e[c],e))));if("function"==typeof _h)for(var d=0;d<o.length;d++)Ch.call(e,o[d])&&i.push("["+t(o[d])+"]: "+t(e[o[d]],e));return i}var $h,Gh=eh,Hh=function(e,t){var r=rh(e,!!t);return"function"==typeof r&&sh(e,".prototype.")>-1?ih(r):r},Jh=function e(t,r,i,s){var n=r||{};if(Ah(n,"quoteStyle")&&"single"!==n.quoteStyle&&"double"!==n.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Ah(n,"maxStringLength")&&("number"==typeof n.maxStringLength?n.maxStringLength<0&&n.maxStringLength!==1/0:null!==n.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var o=!Ah(n,"customInspect")||n.customInspect;if("boolean"!=typeof o&&"symbol"!==o)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Ah(n,"indent")&&null!==n.indent&&"\t"!==n.indent&&!(parseInt(n.indent,10)===n.indent&&n.indent>0))throw new TypeError('options "indent" must be "\\t", an integer > 0, or `null`');if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return Nh(t,n);if("number"==typeof t)return 0===t?1/0/t>0?"0":"-0":String(t);if("bigint"==typeof t)return String(t)+"n";var a=void 0===n.depth?5:n.depth;if(void 0===i&&(i=0),i>=a&&a>0&&"object"==typeof t)return Lh(t)?"[Array]":"[Object]";var c=function(e,t){var r;if("\t"===e.indent)r="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;r=Array(e.indent+1).join(" ")}return{base:r,prev:Array(t+1).join(r)}}(n,i);if(void 0===s)s=[];else if(Fh(s,t)>=0)return"[Circular]";function d(t,r,o){if(r&&(s=s.slice()).push(r),o){var a={depth:n.depth};return Ah(n,"quoteStyle")&&(a.quoteStyle=n.quoteStyle),e(t,a,i+1,s)}return e(t,n,i+1,s)}if("function"==typeof t){var l=function(e){if(e.name)return e.name;var t=wh.call(bh.call(e),/^function\s*([\w$]+)/);if(t)return t[1];return null}(t),p=zh(t,d);return"[Function"+(l?": "+l:" (anonymous)")+"]"+(p.length>0?" { "+p.join(", ")+" }":"")}if(Ih(t)){var u=kh?String(t).replace(/^(Symbol\(.*\))_[^)]*$/,"$1"):Rh.call(t);return"object"!=typeof t||kh?u:Uh(u)}if(function(e){if(!e||"object"!=typeof e)return!1;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return!0;return"string"==typeof e.nodeName&&"function"==typeof e.getAttribute}(t)){for(var h="<"+String(t.nodeName).toLowerCase(),f=t.attributes||[],m=0;m<f.length;m++)h+=" "+f[m].name+"="+Mh(xh(f[m].value),"double",n);return h+=">",t.childNodes&&t.childNodes.length&&(h+="..."),h+="</"+String(t.nodeName).toLowerCase()+">"}if(Lh(t)){if(0===t.length)return"[]";var g=zh(t,d);return c&&!function(e){for(var t=0;t<e.length;t++)if(Fh(e[t],"\n")>=0)return!1;return!0}(g)?"["+Vh(g,c)+"]":"[ "+g.join(", ")+" ]"}if(function(e){return!("[object Error]"!==jh(e)||Dh&&"object"==typeof e&&Dh in e)}(t)){var v=zh(t,d);return 0===v.length?"["+String(t)+"]":"{ ["+String(t)+"] "+v.join(", ")+" }"}if("object"==typeof t&&o){if(Eh&&"function"==typeof t[Eh])return t[Eh]();if("symbol"!==o&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!ch||!e||"object"!=typeof e)return!1;try{ch.call(e);try{uh.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var y=[];return dh.call(t,(function(e,r){y.push(d(r,t,!0)+" => "+d(e,t))})),Wh("Map",ch.call(t),y,c)}if(function(e){if(!uh||!e||"object"!=typeof e)return!1;try{uh.call(e);try{ch.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var b=[];return hh.call(t,(function(e){b.push(d(e,t))})),Wh("Set",uh.call(t),b,c)}if(function(e){if(!fh||!e||"object"!=typeof e)return!1;try{fh.call(e,fh);try{mh.call(e,mh)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return qh("WeakMap");if(function(e){if(!mh||!e||"object"!=typeof e)return!1;try{mh.call(e,mh);try{fh.call(e,fh)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return qh("WeakSet");if(function(e){if(!gh||!e||"object"!=typeof e)return!1;try{return gh.call(e),!0}catch(e){}return!1}(t))return qh("WeakRef");if(function(e){return!("[object Number]"!==jh(e)||Dh&&"object"==typeof e&&Dh in e)}(t))return Uh(d(Number(t)));if(function(e){if(!e||"object"!=typeof e||!Sh)return!1;try{return Sh.call(e),!0}catch(e){}return!1}(t))return Uh(d(Sh.call(t)));if(function(e){return!("[object Boolean]"!==jh(e)||Dh&&"object"==typeof e&&Dh in e)}(t))return Uh(vh.call(t));if(function(e){return!("[object String]"!==jh(e)||Dh&&"object"==typeof e&&Dh in e)}(t))return Uh(d(String(t)));if(!function(e){return!("[object Date]"!==jh(e)||Dh&&"object"==typeof e&&Dh in e)}(t)&&!function(e){return!("[object RegExp]"!==jh(e)||Dh&&"object"==typeof e&&Dh in e)}(t)){var w=zh(t,d),S=Ph?Ph(t)===Object.prototype:t instanceof Object||t.constructor===Object,_=t instanceof Object?"":"null prototype",R=!S&&Dh&&Object(t)===t&&Dh in t?jh(t).slice(8,-1):_?"Object":"",k=(S||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(R||_?"["+[].concat(R||[],_||[]).join(": ")+"] ":"");return 0===w.length?k+"{}":c?k+"{"+Vh(w,c)+"}":k+"{ "+w.join(", ")+" }"}return String(t)},Kh=Gh("%TypeError%"),Qh=Gh("%WeakMap%",!0),Xh=Gh("%Map%",!0),Yh=Hh("WeakMap.prototype.get",!0),Zh=Hh("WeakMap.prototype.set",!0),ef=Hh("WeakMap.prototype.has",!0),tf=Hh("Map.prototype.get",!0),rf=Hh("Map.prototype.set",!0),sf=Hh("Map.prototype.has",!0),nf=function(e,t){for(var r,i=e;null!==(r=i.next);i=r)if(r.key===t)return i.next=r.next,r.next=e.next,e.next=r,r},of=String.prototype.replace,af=/%20/g,cf="RFC3986",df={default:cf,formatters:{RFC1738:function(e){return of.call(e,af,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:cf},lf=df,pf=Object.prototype.hasOwnProperty,uf=Array.isArray,hf=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),ff=function(e,t){for(var r=t&&t.plainObjects?Object.create(null):{},i=0;i<e.length;++i)void 0!==e[i]&&(r[i]=e[i]);return r},mf={arrayToObject:ff,assign:function(e,t){return Object.keys(t).reduce((function(e,r){return e[r]=t[r],e}),e)},combine:function(e,t){return[].concat(e,t)},compact:function(e){for(var t=[{obj:{o:e},prop:"o"}],r=[],i=0;i<t.length;++i)for(var s=t[i],n=s.obj[s.prop],o=Object.keys(n),a=0;a<o.length;++a){var c=o[a],d=n[c];"object"==typeof d&&null!==d&&-1===r.indexOf(d)&&(t.push({obj:n,prop:c}),r.push(d))}return function(e){for(;e.length>1;){var t=e.pop(),r=t.obj[t.prop];if(uf(r)){for(var i=[],s=0;s<r.length;++s)void 0!==r[s]&&i.push(r[s]);t.obj[t.prop]=i}}}(t),e},decode:function(e,t,r){var i=e.replace(/\+/g," ");if("iso-8859-1"===r)return i.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(i)}catch(e){return i}},encode:function(e,t,r,i,s){if(0===e.length)return e;var n=e;if("symbol"==typeof e?n=Symbol.prototype.toString.call(e):"string"!=typeof e&&(n=String(e)),"iso-8859-1"===r)return escape(n).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));for(var o="",a=0;a<n.length;++a){var c=n.charCodeAt(a);45===c||46===c||95===c||126===c||c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||s===lf.RFC1738&&(40===c||41===c)?o+=n.charAt(a):c<128?o+=hf[c]:c<2048?o+=hf[192|c>>6]+hf[128|63&c]:c<55296||c>=57344?o+=hf[224|c>>12]+hf[128|c>>6&63]+hf[128|63&c]:(a+=1,c=65536+((1023&c)<<10|1023&n.charCodeAt(a)),o+=hf[240|c>>18]+hf[128|c>>12&63]+hf[128|c>>6&63]+hf[128|63&c])}return o},isBuffer:function(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},maybeMap:function(e,t){if(uf(e)){for(var r=[],i=0;i<e.length;i+=1)r.push(t(e[i]));return r}return t(e)},merge:function e(t,r,i){if(!r)return t;if("object"!=typeof r){if(uf(t))t.push(r);else{if(!t||"object"!=typeof t)return[t,r];(i&&(i.plainObjects||i.allowPrototypes)||!pf.call(Object.prototype,r))&&(t[r]=!0)}return t}if(!t||"object"!=typeof t)return[t].concat(r);var s=t;return uf(t)&&!uf(r)&&(s=ff(t,i)),uf(t)&&uf(r)?(r.forEach((function(r,s){if(pf.call(t,s)){var n=t[s];n&&"object"==typeof n&&r&&"object"==typeof r?t[s]=e(n,r,i):t.push(r)}else t[s]=r})),t):Object.keys(r).reduce((function(t,s){var n=r[s];return pf.call(t,s)?t[s]=e(t[s],n,i):t[s]=n,t}),s)}},gf=function(){var e,t,r,i={assert:function(e){if(!i.has(e))throw new Kh("Side channel does not contain "+Jh(e))},get:function(i){if(Qh&&i&&("object"==typeof i||"function"==typeof i)){if(e)return Yh(e,i)}else if(Xh){if(t)return tf(t,i)}else if(r)return function(e,t){var r=nf(e,t);return r&&r.value}(r,i)},has:function(i){if(Qh&&i&&("object"==typeof i||"function"==typeof i)){if(e)return ef(e,i)}else if(Xh){if(t)return sf(t,i)}else if(r)return function(e,t){return!!nf(e,t)}(r,i);return!1},set:function(i,s){Qh&&i&&("object"==typeof i||"function"==typeof i)?(e||(e=new Qh),Zh(e,i,s)):Xh?(t||(t=new Xh),rf(t,i,s)):(r||(r={key:{},next:null}),function(e,t,r){var i=nf(e,t);i?i.value=r:e.next={key:t,next:e.next,value:r}}(r,i,s))}};return i},vf=mf,yf=df,bf=Object.prototype.hasOwnProperty,wf={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},Sf=Array.isArray,_f=String.prototype.split,Rf=Array.prototype.push,kf=function(e,t){Rf.apply(e,Sf(t)?t:[t])},Cf=Date.prototype.toISOString,Pf=yf.default,Tf={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:vf.encode,encodeValuesOnly:!1,format:Pf,formatter:yf.formatters[Pf],indices:!1,serializeDate:function(e){return Cf.call(e)},skipNulls:!1,strictNullHandling:!1},Ef={},Df=function e(t,r,i,s,n,o,a,c,d,l,p,u,h,f,m,g){for(var v=t,y=g,b=0,w=!1;void 0!==(y=y.get(Ef))&&!w;){var S=y.get(t);if(b+=1,void 0!==S){if(S===b)throw new RangeError("Cyclic object value");w=!0}void 0===y.get(Ef)&&(b=0)}if("function"==typeof c?v=c(r,v):v instanceof Date?v=p(v):"comma"===i&&Sf(v)&&(v=vf.maybeMap(v,(function(e){return e instanceof Date?p(e):e}))),null===v){if(n)return a&&!f?a(r,Tf.encoder,m,"key",u):r;v=""}if(function(e){return"string"==typeof e||"number"==typeof e||"boolean"==typeof e||"symbol"==typeof e||"bigint"==typeof e}(v)||vf.isBuffer(v)){if(a){var _=f?r:a(r,Tf.encoder,m,"key",u);if("comma"===i&&f){for(var R=_f.call(String(v),","),k="",C=0;C<R.length;++C)k+=(0===C?"":",")+h(a(R[C],Tf.encoder,m,"value",u));return[h(_)+(s&&Sf(v)&&1===R.length?"[]":"")+"="+k]}return[h(_)+"="+h(a(v,Tf.encoder,m,"value",u))]}return[h(r)+"="+h(String(v))]}var P,T=[];if(void 0===v)return T;if("comma"===i&&Sf(v))P=[{value:v.length>0?v.join(",")||null:void 0}];else if(Sf(c))P=c;else{var E=Object.keys(v);P=d?E.sort(d):E}for(var D=s&&Sf(v)&&1===v.length?r+"[]":r,M=0;M<P.length;++M){var x=P[M],L="object"==typeof x&&void 0!==x.value?x.value:v[x];if(!o||null!==L){var I=Sf(v)?"function"==typeof i?i(D,x):D:D+(l?"."+x:"["+x+"]");g.set(t,b);var O=gf();O.set(Ef,g),kf(T,e(L,I,i,s,n,o,a,c,d,l,p,u,h,f,m,O))}}return T},Mf=mf,xf=Object.prototype.hasOwnProperty,Lf=Array.isArray,If={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:Mf.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},Of=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},Af=function(e,t){return e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1?e.split(","):e},jf=function(e,t,r,i){if(e){var s=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,n=/(\[[^[\]]*])/g,o=r.depth>0&&/(\[[^[\]]*])/.exec(s),a=o?s.slice(0,o.index):s,c=[];if(a){if(!r.plainObjects&&xf.call(Object.prototype,a)&&!r.allowPrototypes)return;c.push(a)}for(var d=0;r.depth>0&&null!==(o=n.exec(s))&&d<r.depth;){if(d+=1,!r.plainObjects&&xf.call(Object.prototype,o[1].slice(1,-1))&&!r.allowPrototypes)return;c.push(o[1])}return o&&c.push("["+s.slice(o.index)+"]"),function(e,t,r,i){for(var s=i?t:Af(t,r),n=e.length-1;n>=0;--n){var o,a=e[n];if("[]"===a&&r.parseArrays)o=[].concat(s);else{o=r.plainObjects?Object.create(null):{};var c="["===a.charAt(0)&&"]"===a.charAt(a.length-1)?a.slice(1,-1):a,d=parseInt(c,10);r.parseArrays||""!==c?!isNaN(d)&&a!==c&&String(d)===c&&d>=0&&r.parseArrays&&d<=r.arrayLimit?(o=[])[d]=s:"__proto__"!==c&&(o[c]=s):o={0:s}}s=o}return s}(c,t,r,i)}},Ff=function(e,t){var r,i=e,s=function(e){if(!e)return Tf;if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var t=e.charset||Tf.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var r=yf.default;if(void 0!==e.format){if(!bf.call(yf.formatters,e.format))throw new TypeError("Unknown format option provided.");r=e.format}var i=yf.formatters[r],s=Tf.filter;return("function"==typeof e.filter||Sf(e.filter))&&(s=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:Tf.addQueryPrefix,allowDots:void 0===e.allowDots?Tf.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:Tf.charsetSentinel,delimiter:void 0===e.delimiter?Tf.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:Tf.encode,encoder:"function"==typeof e.encoder?e.encoder:Tf.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:Tf.encodeValuesOnly,filter:s,format:r,formatter:i,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:Tf.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:Tf.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:Tf.strictNullHandling}}(t);"function"==typeof s.filter?i=(0,s.filter)("",i):Sf(s.filter)&&(r=s.filter);var n,o=[];if("object"!=typeof i||null===i)return"";n=t&&t.arrayFormat in wf?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var a=wf[n];if(t&&"commaRoundTrip"in t&&"boolean"!=typeof t.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var c="comma"===a&&t&&t.commaRoundTrip;r||(r=Object.keys(i)),s.sort&&r.sort(s.sort);for(var d=gf(),l=0;l<r.length;++l){var p=r[l];s.skipNulls&&null===i[p]||kf(o,Df(i[p],p,a,c,s.strictNullHandling,s.skipNulls,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,d))}var u=o.join(s.delimiter),h=!0===s.addQueryPrefix?"?":"";return s.charsetSentinel&&("iso-8859-1"===s.charset?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),u.length>0?h+u:""},Nf=function(e,t){var r=function(e){if(!e)return If;if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?If.charset:e.charset;return{allowDots:void 0===e.allowDots?If.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:If.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:If.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:If.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:If.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:If.comma,decoder:"function"==typeof e.decoder?e.decoder:If.decoder,delimiter:"string"==typeof e.delimiter||Mf.isRegExp(e.delimiter)?e.delimiter:If.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:If.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:If.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:If.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:If.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:If.strictNullHandling}}(t);if(""===e||null==e)return r.plainObjects?Object.create(null):{};for(var i="string"==typeof e?function(e,t){var r,i={},s=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,n=t.parameterLimit===1/0?void 0:t.parameterLimit,o=s.split(t.delimiter,n),a=-1,c=t.charset;if(t.charsetSentinel)for(r=0;r<o.length;++r)0===o[r].indexOf("utf8=")&&("utf8=%E2%9C%93"===o[r]?c="utf-8":"utf8=%26%2310003%3B"===o[r]&&(c="iso-8859-1"),a=r,r=o.length);for(r=0;r<o.length;++r)if(r!==a){var d,l,p=o[r],u=p.indexOf("]="),h=-1===u?p.indexOf("="):u+1;-1===h?(d=t.decoder(p,If.decoder,c,"key"),l=t.strictNullHandling?null:""):(d=t.decoder(p.slice(0,h),If.decoder,c,"key"),l=Mf.maybeMap(Af(p.slice(h+1),t),(function(e){return t.decoder(e,If.decoder,c,"value")}))),l&&t.interpretNumericEntities&&"iso-8859-1"===c&&(l=Of(l)),p.indexOf("[]=")>-1&&(l=Lf(l)?[l]:l),xf.call(i,d)?i[d]=Mf.combine(i[d],l):i[d]=l}return i}(e,r):e,s=r.plainObjects?Object.create(null):{},n=Object.keys(i),o=0;o<n.length;++o){var a=n[o],c=jf(a,i[a],r,"string"==typeof e);s=Mf.merge(s,c,r)}return!0===r.allowSparse?s:Mf.compact(s)},Bf={formats:df,parse:Nf,stringify:Ff};class Uf{constructor(e){const{baseURL:t,timeout:r,customNode:i}=e;this.api=Su.create({baseURL:t||"https://lb.livedigital.space/v1",timeout:r||5e3,withCredentials:!1,paramsSerializer:e=>Bf.stringify(e)}),this.customNode=i}getNode(e){return r(this,void 0,void 0,(function*(){if(this.customNode)return this.customNode;const{data:t}=yield this.api.get("/nodes/best",{params:e});return t}))}}class qf extends g{constructor(e,t){super(e,null!=t?t:"invalid_payload")}}!function(e){e.DominantSpeaker="dominant-speaker",e.PeersVolumes="peers-volumes",e.Silence="silence"}($h||($h={}));class Wf{constructor(e){const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new Ge({logLevel:t.logLevel,namespace:"ChannelAudioObserverEventHandler",onLogMessage:r})}handle(e){try{const t=JSON.parse(e);switch(Wf.validateEventPayload(t),t.event){case $h.DominantSpeaker:this.handleDominantSpeaker(t);break;case $h.PeersVolumes:this.handlePeerVolumes(t);break;case $h.Silence:this.handleSilence()}}catch(t){this.logger.warn("Failed to handle audio observer event",{error:bd(t),eventData:e})}}handleDominantSpeaker(e){const{peerId:t}=e.data,r=this.engine.getPeerById(t);this.engine.setActiveSpeakerPeer(r)}handlePeerVolumes(e){e.volumes.forEach((e=>{var t;const{peerId:r,trackLabel:i,value:s}=e,n=null===(t=this.engine.getPeerById(r))||void 0===t?void 0:t.tracks.get(i);n&&n.setVolume(s)}))}handleSilence(){this.engine.peers.flatMap((e=>Array.from(e.tracks.values()))).forEach((e=>e.setVolume(0))),this.engine.setActiveSpeakerPeer(void 0)}static validateEventPayload(e){switch(e.event){case $h.Silence:break;case $h.DominantSpeaker:{e.data||Wf.throwInvalidPayload();const{peerId:t,producerId:r,trackLabel:i}=e.data;"string"==typeof t&&"string"==typeof r&&i===u.Microphone||Wf.throwInvalidPayload();break}case $h.PeersVolumes:Array.isArray(e.volumes)||Wf.throwInvalidPayload(),e.volumes.forEach((e=>{const{peerId:t,producerId:r,value:i,trackLabel:s}=e;"string"==typeof t&&"string"==typeof r&&"number"==typeof i&&s===u.Microphone||Wf.throwInvalidPayload()}));break;default:Wf.throwInvalidPayload()}}static throwInvalidPayload(){throw new qf("Invalid channel audio observer event handler payload")}}var Vf=Uint8Array,zf=Uint16Array,$f=Int32Array,Gf=new Vf([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Hf=new Vf([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Jf=new Vf([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Kf=function(e,t){for(var r=new zf(31),i=0;i<31;++i)r[i]=t+=1<<e[i-1];var s=new $f(r[30]);for(i=1;i<30;++i)for(var n=r[i];n<r[i+1];++n)s[n]=n-r[i]<<5|i;return{b:r,r:s}},Qf=Kf(Gf,2),Xf=Qf.b,Yf=Qf.r;Xf[28]=258,Yf[258]=28;for(var Zf=Kf(Hf,0).b,em=new zf(32768),tm=0;tm<32768;++tm){var rm=(43690&tm)>>1|(21845&tm)<<1;rm=(61680&(rm=(52428&rm)>>2|(13107&rm)<<2))>>4|(3855&rm)<<4,em[tm]=((65280&rm)>>8|(255&rm)<<8)>>1}var im=function(e,t,r){for(var i=e.length,s=0,n=new zf(t);s<i;++s)e[s]&&++n[e[s]-1];var o,a=new zf(t);for(s=1;s<t;++s)a[s]=a[s-1]+n[s-1]<<1;if(r){o=new zf(1<<t);var c=15-t;for(s=0;s<i;++s)if(e[s])for(var d=s<<4|e[s],l=t-e[s],p=a[e[s]-1]++<<l,u=p|(1<<l)-1;p<=u;++p)o[em[p]>>c]=d}else for(o=new zf(i),s=0;s<i;++s)e[s]&&(o[s]=em[a[e[s]-1]++]>>15-e[s]);return o},sm=new Vf(288);for(tm=0;tm<144;++tm)sm[tm]=8;for(tm=144;tm<256;++tm)sm[tm]=9;for(tm=256;tm<280;++tm)sm[tm]=7;for(tm=280;tm<288;++tm)sm[tm]=8;var nm=new Vf(32);for(tm=0;tm<32;++tm)nm[tm]=5;var om=im(sm,9,1),am=im(nm,5,1),cm=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},dm=function(e,t,r){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(7&t)&r},lm=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},pm=function(e){return(e+7)/8|0},um=function(e,t,r){return(null==t||t<0)&&(t=0),(null==r||r>e.length)&&(r=e.length),new Vf(e.subarray(t,r))},hm=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],fm=function(e,t,r){var i=new Error(t||hm[e]);if(i.code=e,Error.captureStackTrace&&Error.captureStackTrace(i,fm),!r)throw i;return i},mm=function(e,t,r,i){var s=e.length,n=i?i.length:0;if(!s||t.f&&!t.l)return r||new Vf(0);var o=!r,a=o||2!=t.i,c=t.i;o&&(r=new Vf(3*s));var d=function(e){var t=r.length;if(e>t){var i=new Vf(Math.max(2*t,e));i.set(r),r=i}},l=t.f||0,p=t.p||0,u=t.b||0,h=t.l,f=t.d,m=t.m,g=t.n,v=8*s;do{if(!h){l=dm(e,p,1);var y=dm(e,p+1,3);if(p+=3,!y){var b=e[(M=pm(p)+4)-4]|e[M-3]<<8,w=M+b;if(w>s){c&&fm(0);break}a&&d(u+b),r.set(e.subarray(M,w),u),t.b=u+=b,t.p=p=8*w,t.f=l;continue}if(1==y)h=om,f=am,m=9,g=5;else if(2==y){var S=dm(e,p,31)+257,_=dm(e,p+10,15)+4,R=S+dm(e,p+5,31)+1;p+=14;for(var k=new Vf(R),C=new Vf(19),P=0;P<_;++P)C[Jf[P]]=dm(e,p+3*P,7);p+=3*_;var T=cm(C),E=(1<<T)-1,D=im(C,T,1);for(P=0;P<R;){var M,x=D[dm(e,p,E)];if(p+=15&x,(M=x>>4)<16)k[P++]=M;else{var L=0,I=0;for(16==M?(I=3+dm(e,p,3),p+=2,L=k[P-1]):17==M?(I=3+dm(e,p,7),p+=3):18==M&&(I=11+dm(e,p,127),p+=7);I--;)k[P++]=L}}var O=k.subarray(0,S),A=k.subarray(S);m=cm(O),g=cm(A),h=im(O,m,1),f=im(A,g,1)}else fm(1);if(p>v){c&&fm(0);break}}a&&d(u+131072);for(var j=(1<<m)-1,F=(1<<g)-1,N=p;;N=p){var B=(L=h[lm(e,p)&j])>>4;if((p+=15&L)>v){c&&fm(0);break}if(L||fm(2),B<256)r[u++]=B;else{if(256==B){N=p,h=null;break}var U=B-254;if(B>264){var q=Gf[P=B-257];U=dm(e,p,(1<<q)-1)+Xf[P],p+=q}var W=f[lm(e,p)&F],V=W>>4;W||fm(3),p+=15&W;A=Zf[V];if(V>3){q=Hf[V];A+=lm(e,p)&(1<<q)-1,p+=q}if(p>v){c&&fm(0);break}a&&d(u+131072);var z=u+U;if(u<A){var $=n-A,G=Math.min(A,z);for($+u<0&&fm(3);u<G;++u)r[u]=i[$+u]}for(;u<z;++u)r[u]=r[u-A]}}t.l=h,t.p=N,t.b=u,t.f=l,h&&(l=1,t.m=m,t.d=f,t.n=g)}while(!l);return u!=r.length&&o?um(r,0,u):r.subarray(0,u)},gm=new Vf(0);function vm(e,t){var r=function(e){31==e[0]&&139==e[1]&&8==e[2]||fm(6,"invalid gzip data");var t=e[3],r=10;4&t&&(r+=2+(e[10]|e[11]<<8));for(var i=(t>>3&1)+(t>>4&1);i>0;i-=!e[r++]);return r+(2&t)}(e);return r+8>e.length&&fm(6,"invalid gzip data"),mm(e.subarray(r,-8),{i:2},t&&t.out||new Vf(function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}(e)),t&&t.dictionary)}function ym(e,t){return mm(e.subarray(function(e,t){return(8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31)&&fm(6,"invalid zlib data"),(e[1]>>5&1)==+!t&&fm(6,"invalid zlib data: "+(32&e[1]?"need":"unexpected")+" dictionary"),2+(e[1]>>3&4)}(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function bm(e,t){return 31==e[0]&&139==e[1]&&8==e[2]?vm(e,t):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?function(e,t){return mm(e,{i:2},t&&t.out,t&&t.dictionary)}(e,t):ym(e,t)}var wm="undefined"!=typeof TextDecoder&&new TextDecoder;try{wm.decode(gm,{stream:!0}),1}catch(Bc){}var Sm,_m,Rm,km;function Cm(e,t){if(t){for(var r="",i=0;i<e.length;i+=16384)r+=String.fromCharCode.apply(null,e.subarray(i,i+16384));return r}if(wm)return wm.decode(e);var s=function(e){for(var t="",r=0;;){var i=e[r++],s=(i>127)+(i>223)+(i>239);if(r+s>e.length)return{s:t,r:um(e,r-1)};s?3==s?(i=((15&i)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,t+=String.fromCharCode(55296|i>>10,56320|1023&i)):t+=1&s?String.fromCharCode((31&i)<<6|63&e[r++]):String.fromCharCode((15&i)<<12|(63&e[r++])<<6|63&e[r++]):t+=String.fromCharCode(i)}}(e),n=s.s;return(r=s.r).length&&fm(8),n}class Pm{constructor(e){Sm.set(this,[]),_m.set(this,[]),Rm.set(this,[]),km.set(this,[]);const{engine:t,onLogMessage:r}=e;this.engine=t,this.logger=new Ge({logLevel:t.logLevel,namespace:"ChannelStateSyncEventHandler",onLogMessage:r})}handle(e){return r(this,void 0,void 0,(function*(){try{const{event:t,data:r}=yield this.parseChannelStateSyncEventPayload(e);"channel-state"===t&&this.handleChannelStateEvent(r)}catch(e){this.logger.error("handleChannelStateSyncEvent()",{error:bd(e)})}}))}handleChannelStateEvent(e){const t=this.getLocalState();this.processStateInconsistency(t,e)}processStateInconsistency(e,t){this.notifyIfHasConfirmedInconsistency(e,t),this.prepareProbableInconsistencyStats(e,t)}notifyIfHasConfirmedInconsistency(e,t){t.peers.forEach((t=>{const r=e.peers.find((e=>e.id===t.id));r?(this.resetPeerInconsistency(t.id),t.producers.forEach((e=>{const t=r.producers.find((t=>t.id===e.id));if(!t)return void this.notifyIfConfirmedProducerInconsistency(e.id);this.resetProducerInconsistency(t.id);t.paused!==e.paused?this.notifyIfConfirmedProducerStateInconsistency(t.id,{localPaused:t.paused,remotePaused:e.paused}):this.resetProducerStateInconsistency(t.id)}))):this.notifyIfConfirmedPeerInconsistency(t.id)}))}prepareProbableInconsistencyStats(e,t){const r=[],n=[],o=[];this.getIsConnectionActive()?(t.peers.forEach((t=>{if(i(this,Sm,"f").includes(t.id))return;const s=e.peers.find((e=>e.id===t.id));s||r.push(t.id),s&&t.producers.forEach((e=>{if(i(this,_m,"f").includes(e.id))return;const t=s.producers.find((t=>t.id===e.id));if(t||n.push(e.id),!t)return;if(i(this,Rm,"f").includes(e.id))return;t.paused!==e.paused&&o.push(e.id)}))})),2===i(this,km,"f").length&&i(this,km,"f").shift(),i(this,km,"f").push({probablyMissingPeers:r,probablyMissingProducers:n,probablyProducersWithInconsistentState:o})):s(this,km,[],"f")}isReachedMaxCheckRetries(e,t){let r=0;return i(this,km,"f").forEach((i=>{i[e].includes(t)&&(r+=1)})),r>=2}isAlreadyAlertedAbout(e,t){return e.includes(t)}notifyIfConfirmedPeerInconsistency(e){const t=this.isReachedMaxCheckRetries("probablyMissingPeers",e),r=this.isAlreadyAlertedAbout(i(this,Sm,"f"),e);t&&!r&&(i(this,Sm,"f").push(e),this.logger.warn("Peer is missing",{case:"channel-state-sync",missingPeerId:e}))}resetPeerInconsistency(e){const t=i(this,Sm,"f").indexOf(e);t>-1&&delete i(this,Sm,"f")[t]}notifyIfConfirmedProducerInconsistency(e){const t=this.isReachedMaxCheckRetries("probablyMissingProducers",e),r=this.isAlreadyAlertedAbout(i(this,_m,"f"),e);t&&!r&&(i(this,_m,"f").push(e),this.logger.warn("Producer is missing",{case:"channel-state-sync",missingProducerId:e}))}resetProducerInconsistency(e){const t=i(this,_m,"f").indexOf(e);t>-1&&delete i(this,_m,"f")[t]}notifyIfConfirmedProducerStateInconsistency(e,t){const r=this.isReachedMaxCheckRetries("probablyProducersWithInconsistentState",e),s=this.isAlreadyAlertedAbout(i(this,Rm,"f"),e);r&&!s&&(i(this,Rm,"f").push(e),this.logger.warn("Producer is in inconsistent state",Object.assign({case:"channel-state-sync",producerId:e},t)))}resetProducerStateInconsistency(e){const t=i(this,Rm,"f").indexOf(e);t>-1&&delete i(this,Rm,"f")[t]}parseChannelStateSyncEventPayload(e){return r(this,void 0,void 0,(function*(){const t=bm("arrayBuffer"in e?new Uint8Array(yield e.arrayBuffer()):new Uint8Array(e));return JSON.parse(Cm(t))}))}getLocalState(){const{hostPeers:e}=this.engine;return{peers:e.map((e=>({id:e.id,producers:e.getProducers().map((e=>({id:e.id,paused:e.paused})))})))}}getIsConnectionActive(){try{return this.engine.checkConnectionActivity(),!0}catch(e){return!1}}}Sm=new WeakMap,_m=new WeakMap,Rm=new WeakMap,km=new WeakMap;class Tm{createSystem(e){return new _d(e)}createMedia(e){return new Ja(e)}createNetwork(e){const{loadbalancer:t,logLevel:r,onLogMessage:i}=e,s=new $l({logLevel:r,onLogMessage:i}),n=new Uf(t);return new wd({logLevel:r,socketClient:s,loadBalancerApiClient:n,onLogMessage:i})}createChannelEventHandler(e){return new Rd(e)}createMediaSoupEventHandler(e){return new kd(e)}createAudioObserverEventHandler(e){return new Wf(e)}createChannelStateSyncEventHandler(e){return new Pm(e)}createIssueDetector(e){var t,r;const i=null!==(t=e.logger)&&void 0!==t?t:console,s=new fd({statsParser:new md({ignoreSSRCList:e.ignoreSSRCList,logger:null!==(r=e.logger)&&void 0!==r?r:console})});return new gd({issueEmitter:new Zc,networkScoresCalculator:new rd,detectors:[new ld,new nd,new od,new ad,new dd,new cd,new sd,new pd],statsReporter:new ed({compositeStatsParser:s,getStatsInterval:5e3}),onIssues:e.onIssues,onNetworkScoresUpdated:e.onNetworkScoresUpdated,ignoreSSRCList:e.ignoreSSRCList,compositeStatsParser:s,logger:i})}}class Em extends AudioWorkletNode{constructor(e){super(e.context,"rnnoise",{channelCountMode:"explicit",channelCount:1,channelInterpretation:"speakers",numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{module:e.noiseSuppressor.module}}),this.port.onmessage=({data:e})=>{const t=Object.assign(new Event("status"),e);this.dispatchEvent(t)}}update(e){this.port.postMessage(e)}static register(e){return r(this,void 0,void 0,(function*(){yield e.audioWorklet.addModule(`${window.location.origin}/noiseSuppressionWorklet.js`)}))}}var Dm,Mm,xm,Lm,Im,Om;class Am{constructor(e){Dm.set(this,void 0),Mm.set(this,void 0),xm.set(this,void 0),Lm.set(this,void 0),Im.set(this,void 0),Om.set(this,!0),s(this,Dm,e.noiseSuppressor.instance.exports,"f"),s(this,Mm,e.context,"f"),s(this,xm,new Float32Array(i(this,Dm,"f").memory.buffer),"f"),s(this,Lm,i(this,Dm,"f").newState(),"f"),s(this,Im,i(this,Mm,"f").createScriptProcessor(),"f"),this.setOnAudioProcess()}get noiseSuppressionScriptProcessorNode(){return i(this,Im,"f")}update(e){e||(s(this,Om,!1,"f"),i(this,Dm,"f").deleteState(i(this,Lm,"f")));const t=Object.assign(new Event("status"),{vadProb:i(this,Dm,"f").getVadProb(i(this,Lm,"f"))});i(this,Im,"f").dispatchEvent(t)}setOnAudioProcess(){i(this,Im,"f").addEventListener("audioprocess",(({inputBuffer:e,outputBuffer:t})=>{if(!i(this,Om,"f"))return;i(this,xm,"f").set(e.getChannelData(0),i(this,Dm,"f").getInput(i(this,Lm,"f"))/4);const r=t.getChannelData(0),s=i(this,Dm,"f").pipe(i(this,Lm,"f"),r.length)/4;s&&r.set(i(this,xm,"f").subarray(s,s+r.length))}))}}Dm=new WeakMap,Mm=new WeakMap,xm=new WeakMap,Lm=new WeakMap,Im=new WeakMap,Om=new WeakMap;var jm,Fm,Nm,Bm,Um,qm,Wm,Vm,zm,$m;class Gm{constructor({context:e,noiseSuppressor:t}){jm.set(this,void 0),Fm.set(this,void 0),Nm.set(this,void 0),s(this,jm,e,"f"),s(this,Fm,t,"f")}createNoiseSuppressionNode(){return r(this,void 0,void 0,(function*(){return/apple/i.test(navigator.vendor)?this.createScriptProcessorNode():this.createAudioWorkletNode()}))}stop(){var e;null===(e=i(this,Nm,"f"))||void 0===e||e.update(!1)}createAudioWorkletNode(){return r(this,void 0,void 0,(function*(){return yield Em.register(i(this,jm,"f")),s(this,Nm,new Em({context:i(this,jm,"f"),noiseSuppressor:i(this,Fm,"f")}),"f"),i(this,Nm,"f")}))}createScriptProcessorNode(){return s(this,Nm,new Am({context:i(this,jm,"f"),noiseSuppressor:i(this,Fm,"f")}),"f"),i(this,Nm,"f").noiseSuppressionScriptProcessorNode}}jm=new WeakMap,Fm=new WeakMap,Nm=new WeakMap;class Hm{constructor(e){Bm.set(this,void 0),Um.set(this,void 0),qm.set(this,void 0),Wm.set(this,void 0),s(this,Bm,e.noiseSuppressor,"f"),s(this,qm,new Ge({namespace:"TrackProcessor",logLevel:e.logLevel}),"f")}get isProcessing(){return!!i(this,Wm,"f")}processTrack(e){return r(this,void 0,void 0,(function*(){const t=(e=>{const t=window.AudioContext||window.webkitAudioContext||!1;return t?new t(e):null})();if(!t)throw new Error("AudioContext is not available");const r=new MediaStreamAudioDestinationNode(t,{channelCountMode:"explicit",channelCount:1,channelInterpretation:"speakers"});yield Em.register(t);const n=t.createMediaStreamSource(new MediaStream([e])),o=new Gm({context:t,noiseSuppressor:i(this,Bm,"f")}),a=yield o.createNoiseSuppressionNode();a.connect(r),n.connect(a);const[c]=r.stream.getTracks();return s(this,Um,{audioContext:t,streamDestination:r,noiseSuppressionNode:a,noiseSuppressionProvider:o},"f"),s(this,Wm,c,"f"),i(this,qm,"f").info("processTrack()",{track:e}),c}))}stopProcessing(){var e;return r(this,void 0,void 0,(function*(){if(this.isProcessing)if(i(this,Um,"f"))try{i(this,Um,"f").noiseSuppressionProvider.stop(),i(this,Um,"f").noiseSuppressionNode.disconnect(),i(this,Um,"f").streamDestination.disconnect(),yield i(this,Um,"f").audioContext.close(),null===(e=i(this,Wm,"f"))||void 0===e||e.stop(),s(this,Wm,void 0,"f"),i(this,qm,"f").info("stopProcessing()",{success:!0})}catch(e){i(this,qm,"f").error("stopProcessing()",{success:!1,error:e})}else i(this,qm,"f").warn("stopProcessing()",{success:!1,description:"Processing context is not available"});else i(this,qm,"f").debug("stopProcessing()",{description:"Track is not processed"})}))}}Bm=new WeakMap,Um=new WeakMap,qm=new WeakMap,Wm=new WeakMap;class Jm extends cc{constructor(e){super(e),Vm.set(this,void 0),zm.set(this,void 0),$m.set(this,void 0),e.noiseSuppressor&&s(this,Vm,new Hm({noiseSuppressor:e.noiseSuppressor,logLevel:e.logLevel}),"f"),s(this,$m,new Ge({namespace:"AudioTrack",logLevel:e.logLevel}),"f")}get isEffectsProcessing(){var e;return!!(null===(e=i(this,Vm,"f"))||void 0===e?void 0:e.isProcessing)}getEncoderConfig(){return this.encoderConfig}getEncodings(){var e;return null!==(e=this.getEncoderConfig().encodings)&&void 0!==e?e:Oa}getCodecOptions(){var e,t;return{opusFec:null===(e=this.getEncoderConfig().enableFec)||void 0===e||e,opusDtx:null===(t=this.getEncoderConfig().enableDtx)||void 0===t||t}}getPreferredCodec(){const{preferredCodec:e}=this.getEncoderConfig();return e||"opus"}enableNoiseSuppression(){var e;return r(this,void 0,void 0,(function*(){if(i(this,Vm,"f"))try{const t=yield null===(e=i(this,Vm,"f"))||void 0===e?void 0:e.processTrack(this.mediaStreamTrack);s(this,zm,this.mediaStreamTrack,"f"),yield this.replaceTrack(t)}catch(e){throw this.logger.warn("enableNoiseSuppression()",{description:"Can not enable noise suppression",track:this,error:e}),new Error("Can not enable noise suppression")}else this.logger.warn("enableNoiseSuppression()",{description:"Track suppressor is not defined"})}))}disableNoiseSuppression(){var e,t;return r(this,void 0,void 0,(function*(){try{if(!(null===(e=i(this,Vm,"f"))||void 0===e?void 0:e.isProcessing))return void i(this,$m,"f").debug("stopProcessing()",{description:"Track is not processed"});if(!i(this,zm,"f"))return void this.logger.warn("disableNoiseSuppression()",{description:"Original track missing"});this.isPublished&&(yield this.replaceTrack(i(this,zm,"f"))),yield null===(t=i(this,Vm,"f"))||void 0===t?void 0:t.stopProcessing()}catch(e){throw this.logger.warn("disableNoiseSuppression()",{description:"Can not disable noise suppression",track:this,error:e}),new Error("Can not disable noise suppression")}}))}publish(){return r(this,void 0,void 0,(function*(){yield this.produce({encodings:this.getEncodings(),preferredCodec:this.getPreferredCodec(),codecOptions:this.getCodecOptions()}),this.clientEventEmitter.emit(W,this)}))}}Vm=new WeakMap,zm=new WeakMap,$m=new WeakMap;class Km{createAudioTrack(e){return new Jm(e)}createVideoTrack(e){return new Ic(e)}}class Qm{constructor(e){var t,r;const{observer:i,network:s,onLogMessage:o,onIssues:a,onNetworkScoresUpdated:c,logLevel:d,disableWid:l}=e;this._observer=null!=i?i:new n;const p=new Tm,u=new Km;this.engine=new Fc({dependenciesFactory:p,clientEventEmitter:this.observer,media:{mediaTracksFactory:u},network:{loadbalancer:{baseURL:null===(t=null==s?void 0:s.loadbalancer)||void 0===t?void 0:t.baseURL,customNode:null===(r=null==s?void 0:s.loadbalancer)||void 0===r?void 0:r.customNode}},logLevel:d,onLogMessage:o,onIssues:a,onNetworkScoresUpdated:c,disableWid:l})}get observer(){return this._observer}get id(){return this.engine.mySocketId}get peers(){return this.engine.peers}get availableVideoDevices(){return this.engine.system.availableVideoDevices}get availableAudioDevices(){return this.engine.system.availableAudioDevices}get canUseNoiseSuppression(){return this.engine.canUseNoiseSuppression}detectDevices(){return r(this,void 0,void 0,(function*(){return yield this.engine.system.detectDevices(),{video:this.engine.system.availableVideoDevices,audio:this.engine.system.availableAudioDevices}}))}join(e){return this.engine.join(e)}leave(){return this.engine.release()}confirmActivity(){return this.engine.confirmActivity()}createCameraVideoTrack(e){return this.engine.createCameraVideoTrack(e)}createMicrophoneAudioTrack(e){return this.engine.createMicrophoneAudioTrack(e)}createScreenMediaTracks(e){return this.engine.createScreenMediaTracks(e)}deleteTrack(e){return this.engine.deleteTrack(e)}loadPeers(e){return this.engine.loadPeers(e)}updateAppData(e){return this.engine.updateAppData(e)}getTransportsInfo(){return r(this,void 0,void 0,(function*(){return this.engine.network.getTransportsStateInfo()}))}getNodeActiveStreamsStat(){return this.engine.getNodeActiveStreamsStat()}setPreferRelay(e){this.engine.network.setPreferRelay(e)}getPreferRelay(){return this.engine.network.getPreferRelay()}}export{Qm as default};