@sanseng/livekit-ws-sdk 0.1.10 → 0.1.11

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.
@@ -1,4 +1,4 @@
1
- (function(D,B){typeof exports=="object"&&typeof module<"u"?B(exports):typeof define=="function"&&define.amd?define(["exports"],B):(D=typeof globalThis<"u"?globalThis:D||self,B(D.LivekitSDK={}))})(this,(function(D){"use strict";var B;(function(n){n.SDK_AUTH_TOKEN_FAILED="SDK_AUTH_TOKEN_FAILED",n.SDK_GET_LIVEKIT_CONFIG_FAILED="SDK_GET_LIVEKIT_CONFIG_FAILED",n.SDK_RECONNECT_FAILED="SDK_RECONNECT_FAILED",n.SDK_DISCONNECT_FAILED="SDK_DISCONNECT_FAILED",n.SDK_NOT_CONNECTED="SDK_NOT_CONNECTED",n.SDK_CONNECT_FAILED="SDK_CONNECT_FAILED",n.SDK_SWITCH_VIDEO_FAILED="SDK_SWITCH_VIDEO_FAILED",n.SDK_ERROR="SDK_ERROR",n.SDK_PRECONNECT_FAILED="SDK_PRECONNECT_FAILED",n.SDK_INTERRUPT_CONVERSATION_FAILED="SDK_INTERRUPT_CONVERSATION_FAILED",n.SDK_INITIALIZATION_FAILED="SDK_INITIALIZATION_FAILED",n.SDK_INVALID_STATE_TRANSITION="SDK_INVALID_STATE_TRANSITION",n.NO_AVATARNAME="NO_AVATARNAME",n.AUDIO_CAPTURE_START_FAILED="AUDIO_CAPTURE_START_FAILED",n.AUDIO_CAPTURE_FAILED="AUDIO_CAPTURE_FAILED",n.AUDIO_INVALID_SAMPLE_RATE="AUDIO_INVALID_SAMPLE_RATE",n.AUDIO_INVALID_CHANNEL="AUDIO_INVALID_CHANNEL",n.AUDIO_INVALID_HEADER_LENGTH="AUDIO_INVALID_HEADER_LENGTH",n.AUDIO_INVALID_TYPE="AUDIO_INVALID_TYPE",n.AUDIO_INVALID_RESERVED="AUDIO_INVALID_RESERVED",n.AUDIO_CONTROLLER_NOT_AVAILABLE="AUDIO_CONTROLLER_NOT_AVAILABLE",n.WS_CONNECT_FAILED="WS_CONNECT_FAILED",n.WS_TEXT_SEND_FAILED="WS_TEXT_SEND_FAILED",n.WS_PARSE_ERROR="WS_PARSE_ERROR",n.WS_NOT_CONNECTED="WS_NOT_CONNECTED",n.WS_CONNECT_ERROR="WS_CONNECT_ERROR",n.LIVEKIT_CONNECT_FAILED="LIVEKIT_CONNECT_FAILED",n.CONVERSATION_CONTROLLER_NOT_AVAILABLE="CONVERSATION_CONTROLLER_NOT_AVAILABLE",n.STATE_MACHINE_INVALID_STATE_TRANSITION="STATE_MACHINE_INVALID_STATE_TRANSITION",n.OBJECT_DISPOSED="OBJECT_DISPOSED"})(B||(B={}));class H extends Error{constructor(e,t="SDK_ERROR",i){super(e),this.name="SDKError",this.code=t,this.cause=i,Object.setPrototypeOf(this,H.prototype)}static fromError(e,t){return e instanceof H?e:e instanceof Error?new H(e.message,t||B.SDK_ERROR,e):typeof e=="string"?new H(e,t||B.SDK_ERROR):new H("Unknown error",t||B.SDK_ERROR,e)}}class G{constructor(){this._disposed=!1}get isDisposed(){return this._disposed}dispose(){this._disposed||(this.onDispose(),this._disposed=!0)}ensureNotDisposed(){if(this._disposed)throw new H("Object has been disposed",B.OBJECT_DISPOSED)}}D.LogLevel=void 0,(function(n){n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n[n.NONE=4]="NONE"})(D.LogLevel||(D.LogLevel={}));class m{static setLevel(e){this._level=e}static setPrefix(e){this._prefix=e}static debug(e,...t){this._level<=D.LogLevel.DEBUG&&console.debug(`${this._prefix} [DEBUG]`,e,...t)}static info(e,...t){this._level<=D.LogLevel.INFO&&console.info(`${this._prefix} [INFO]`,e,...t)}static warn(e,...t){this._level<=D.LogLevel.WARN&&console.warn(`${this._prefix} [WARN]`,e,...t)}static error(e,...t){this._level<=D.LogLevel.ERROR&&console.error(`${this._prefix} [ERROR]`,e,...t)}}m._level=D.LogLevel.ERROR,m._prefix="[SDK]";class ls extends G{constructor(){super(...arguments),this._listeners=new Map}on(e,t){this.ensureNotDisposed(),this._listeners.has(e)||this._listeners.set(e,new Set);const i=this._listeners.get(e);return i.add(t),m.debug(`Event listener added for: ${String(e)}`),()=>{i.delete(t),m.debug(`Event listener removed for: ${String(e)}`)}}once(e,t){this.ensureNotDisposed();const i=s=>{t(s),this.off(e,i)};return this.on(e,i)}off(e,t){this.ensureNotDisposed();const i=this._listeners.get(e);i&&i.delete(t)}emit(e,t){this.ensureNotDisposed();const i=this._listeners.get(e);i&&i.size>0&&(m.debug(`Emitting event: ${String(e)}`,t),i.forEach(s=>{try{s(t)}catch(r){m.error(`Error in event listener for ${String(e)}:`,r)}}))}removeAllListeners(){this._listeners.clear(),m.debug("All event listeners removed")}listenerCount(e){const t=this._listeners.get(e);return t?t.size:0}onDispose(){this.removeAllListeners()}}D.SessionStatus=void 0,(function(n){n.IDLE="idle",n.CONNECTING="connecting",n.CONNECTED="connected",n.PARTIAL="partial",n.DISCONNECTED="disconnected",n.RECONNECTING="reconnecting",n.DISCONNECTING="disconnecting",n.ERROR="error",n.DISPOSED="disposed"})(D.SessionStatus||(D.SessionStatus={}));function Da(n){switch(n){case"idle":return D.SessionStatus.IDLE;case"connecting":return D.SessionStatus.CONNECTING;case"connected":return D.SessionStatus.CONNECTED;case"partial":return D.SessionStatus.PARTIAL;case"disconnecting":return D.SessionStatus.DISCONNECTING;case"disconnected":case"error":return D.SessionStatus.DISCONNECTED;case"reconnecting:auto":case"reconnecting:manual":return D.SessionStatus.RECONNECTING;case"disposed":return D.SessionStatus.DISPOSED;default:return D.SessionStatus.DISCONNECTED}}class us{constructor(){this.status=D.SessionStatus.DISCONNECTED,this.state=D.SessionStatus.DISCONNECTED,this.isConnected=!1}reset(){this.status=D.SessionStatus.DISCONNECTED,this.state=D.SessionStatus.DISCONNECTED,this.isConnected=!1}}const It=3,Aa=5e3,Dt=1e3,Ni=10,Oa=1e4,Na=3e3,hs=3e4,xi=24e3,ps=16,xa=1,Ma=4096,At=0,La="https://api.newportai.com/s2/aigc/api/vih_dispatcher",Ua="wss://api.newportai.com/s2/livekit-lisbon",Fa="wss://api.newportai.com/s2/aigc/api/ws_dispatch/render/v1/stream",Ba=6e4;var ht;(function(n){n.NO_VIDEO_TRACK="NO_VIDEO_TRACK",n.TRACK_MUTED="TRACK_MUTED",n.TRACK_ENDED="TRACK_ENDED"})(ht||(ht={}));class Va{constructor(e){this.options=e,this._livekitUrl="",this._token="",this._wsUrl="",this.eventBus=new ls,this.sessionState=new us,e.debug&&m.setLevel(0),m.info("SDK Context initialized")}setLivekitConfig(e,t,i){this._livekitUrl=e||Ua,this._token=t,this._roomId=i}emitError(e,t){const i=H.fromError(e,t);return this.eventBus.emit("inner:sdk:error",{error:i}),i}setVideoOptions(e){this.options.video=Object.assign({},e,this.options.video||{})}setWsUrl(e){this._wsUrl=e}get wsUrl(){return this._wsUrl}get livekitUrl(){return this._livekitUrl}get token(){return this._token}get roomId(){return this._roomId}getLivekitConfig(){return{livekitUrl:this._livekitUrl,token:this._token}}dispose(){this.eventBus.dispose(),this.sessionState.reset(),m.info("SDK Context disposed")}}function ms(n){return{ws:{connected:!1},rtc:{connected:!1,hasVideoTrack:!1},overall:{state:n}}}function fs(n){return Object.freeze({ws:Object.freeze({...n.ws}),rtc:Object.freeze({...n.rtc}),overall:Object.freeze({...n.overall})})}class gs{constructor(){this._transitionMap=null}get transitionMap(){if(!this._transitionMap){const e=new Map;for(const t of this.transitionTable)e.set(t.from,new Set(t.to));this._transitionMap=e}return this._transitionMap}getCurrentState(){return this._currentState}transitionTo(e,t){const i=this._currentState;if(!this.canTransition(i,e)){const s=this.transitionMap.get(i),r=s?Array.from(s).join(", "):"none";throw t?.error??new H(`Invalid state transition: cannot transition from "${i}" to "${e}". Current state: "${i}". Allowed transitions: [${r}]`,B.STATE_MACHINE_INVALID_STATE_TRANSITION)}this._currentState=e}canTransition(e,t){return e===t?!1:this.transitionMap.get(e)?.has(t)??!1}reset(){throw new Error("Method not implemented.")}}class ja extends gs{constructor(){super(...arguments),this._currentState="idle",this.transitionTable=[{from:"idle",to:["connecting","disposed"]},{from:"connecting",to:["connected","partial","error","idle","disposed"]},{from:"connected",to:["disconnecting","partial","reconnecting:auto","reconnecting:manual","error","disposed"]},{from:"partial",to:["connected","disconnecting","reconnecting:auto","reconnecting:manual","error","disposed"]},{from:"reconnecting:auto",to:["connected","partial","error","idle","disposed"]},{from:"reconnecting:manual",to:["connected","partial","error","idle","disposed"]},{from:"disconnecting",to:["disconnected","error","disposed"]},{from:"disconnected",to:["reconnecting:manual","reconnecting:auto","idle","disposed"]},{from:"error",to:["reconnecting:manual","reconnecting:auto","idle","disposed"]},{from:"disposed",to:[]}]}reset(){this._currentState="idle"}}class qa extends G{constructor(e){super(),this._unsubscribes=[],this._context=e,this._fsm=new ja,this._snapshot=ms("idle")}start(){this.ensureNotDisposed();const e=this._context.eventBus,t=e.on("inner:rtc:connected",()=>{this._snapshot.rtc.connected=!0,this._context.eventBus.emit("inner:sdk:connected",{source:"livekit"}),this._onFactsChanged()}),i=e.on("inner:rtc:disconnected",c=>{this._snapshot.rtc.connected=!1,this._snapshot.rtc.hasVideoTrack=!1,this._context.eventBus.emit("inner:sdk:disconnected",{source:"livekit",reason:c?.reason}),this._onFactsChanged()}),s=e.on("inner:rtc:video:available",()=>{this._snapshot.rtc.hasVideoTrack=!0}),r=e.on("inner:rtc:video:unavailable",()=>{this._snapshot.rtc.hasVideoTrack=!1}),a=e.on("inner:ws:connected",()=>{this._snapshot.ws.connected=!0,this._context.eventBus.emit("inner:sdk:connected",{source:"ws"}),this._onFactsChanged()}),o=e.on("inner:ws:disconnected",c=>{this._snapshot.ws.connected=!1,this._context.eventBus.emit("inner:sdk:disconnected",{source:"ws",reason:c?.reason}),this._onFactsChanged()});this._unsubscribes=[t,i,s,r,a,o]}startConnecting(){this._transitionTo("connecting")}startDisconnecting(){this._transitionTo("disconnecting")}completeDisconnecting(){this._snapshot.ws.connected=!1,this._snapshot.rtc.connected=!1,this._snapshot.rtc.hasVideoTrack=!1,this._transitionTo("disconnected")}captureSnapshotAndStartReconnectingManual(){const e=this.getSnapshot();return this._transitionTo("reconnecting:manual"),e}transitionToIdle(){this._snapshot.ws.connected=!1,this._snapshot.rtc.connected=!1,this._snapshot.rtc.hasVideoTrack=!1,this._transitionTo("idle")}transitionToDisposed(){this._transitionTo("disposed")}getSnapshot(){return fs(this._snapshot)}getState(){return this._fsm.getCurrentState()}canStartReconnectingManual(){const e=this._fsm.getCurrentState();return e==="connected"||e==="partial"||e==="disconnected"||e==="error"}_onFactsChanged(){const e=this._fsm.getCurrentState();if(e==="connecting"||e==="reconnecting:auto"||e==="reconnecting:manual"){const t=this._snapshot.rtc.connected&&this._snapshot.ws.connected,i=this._snapshot.rtc.connected||this._snapshot.ws.connected;if(t){this._transitionTo("connected");return}if(i){this._transitionTo("partial");return}}if(e==="connected"||e==="partial"){const t=this._snapshot.rtc.connected&&this._snapshot.ws.connected;if(!(this._snapshot.rtc.connected||this._snapshot.ws.connected)){this._transitionTo("disconnected");return}if(!t){this._transitionTo("partial");return}if(t&&e==="partial"){this._transitionTo("connected");return}}}_transitionTo(e){this._fsm.canTransition(this._fsm.getCurrentState(),e)&&(this._fsm.transitionTo(e),this._snapshot.overall.state=this._fsm.getCurrentState(),this._syncSessionState())}_syncSessionState(){const e=this._fsm.getCurrentState();this._context.sessionState.status=Da(e),this._context.sessionState.state=this._context.sessionState.status,this._context.sessionState.isConnected=e==="connected"}onDispose(){this._unsubscribes.forEach(e=>e()),this._unsubscribes=[]}}class vs extends G{get trackId(){return this._trackId}get participantId(){return this._participantId}get track(){return this._track}constructor(){super(),this._trackId=null,this._participantId=null,this._track=null,this._stream=null,this._videoElement=document.createElement("video"),this._videoElement.autoplay=!0,this._videoElement.playsInline=!0,this._videoElement.muted=!0,this._videoElement.crossOrigin="anonymous",this._videoElement.style.display="none",m.info("Video Source initialized with internal video element")}getInternalElement(){return this._videoElement}setTrack(e,t,i){this.ensureNotDisposed(),this._track&&this._track.stop(),this._track=e,this._trackId=t,this._participantId=i,this._stream||(this._stream=new MediaStream);const s=this._stream.getTracks();for(const r of s)if(r!==e)try{this._stream.removeTrack(r)}catch(a){m.warn("Failed to remove track from stream",a)}if(!this._stream.getTracks().includes(e))try{this._stream.addTrack(e)}catch(r){m.error("Failed to add track to media stream:",r)}m.info("Video track ready")}clearTrack(){if(this._stream){const e=this._stream.getTracks();for(const t of e)try{this._stream.removeTrack(t)}catch(i){m.warn("Failed to remove track from stream",i)}}this._track&&(this._track.stop(),this._track=null),this._trackId=null,this._participantId=null,m.info("Video track cleared")}get hasTrack(){return this._track!==null&&this._track.readyState==="live"}onDispose(){this.clearTrack(),this._videoElement&&this._videoElement.parentElement&&this._videoElement.parentElement.removeChild(this._videoElement),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),m.info("Video Source disposed")}}class Wa extends G{constructor(){super(...arguments),this._renderer=null}getRenderer(){return this._renderer}setRenderer(e){this._renderer&&this._renderer.dispose(),this._renderer=e,m.debug("Raw render strategy renderer set")}getProcessors(){return[]}setProcessors(e){m.warn("Raw render strategy does not support processors")}attachToContainer(e){if(!this._renderer){m.warn("No renderer available to attach to container");return}if("getElement"in this._renderer&&typeof this._renderer.getElement=="function"){const t=this._renderer.getElement();t instanceof HTMLVideoElement&&(t.parentElement&&t.parentElement!==e&&t.parentElement.removeChild(t),t.parentElement!==e&&(e.appendChild(t),t.style.display="",m.debug("Video element attached to container in raw mode")))}}onDispose(){this._renderer&&(this._renderer.dispose(),this._renderer=null),m.info("Raw Render Strategy disposed")}}class Ka{create(){return new Wa}}class Mi extends G{constructor(e,t){if(super(),this._canvas=null,this._ctx=null,this._videoElement=null,this._parentElement=null,this._resizeObserver=null,this._animationFrameId=null,this._isRendering=!1,this._renderLoop=()=>{if(!(!this._isRendering||!this._videoElement||!this._canvas||!this._ctx)){try{this._syncCanvasSize(),this._ctx.drawImage(this._videoElement,0,0,this._canvas.width,this._canvas.height)}catch(i){m.error("Error rendering from video to canvas:",i)}this._animationFrameId=requestAnimationFrame(this._renderLoop)}},e){if(this._canvas=e,this._ctx=e.getContext("2d"),!this._ctx)throw new Error("Failed to get 2D context from canvas")}else if(t)this._videoElement=t,this._createCanvasFromVideo();else throw new Error("CanvasRenderer requires either canvas or videoElement");m.info("Canvas Renderer created")}_createCanvasFromVideo(){if(!this._videoElement)return;if(this._parentElement=this._videoElement.parentElement,!this._parentElement)throw new Error("Video element must have a parent element");if(window.getComputedStyle(this._parentElement).position==="static"&&(this._parentElement.style.position="relative"),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d"),!this._ctx)throw new Error("Failed to get 2D context from canvas");this._canvas.style.position="absolute",this._canvas.style.top="0",this._canvas.style.left="0",this._canvas.style.width="100%",this._canvas.style.height="100%",this._canvas.style.pointerEvents="none",this._parentElement.appendChild(this._canvas),this._syncCanvasSize(),this._setupResizeObserver()}_syncCanvasSize(){if(!this._canvas||!this._videoElement||!this._ctx)return;const e=this._videoElement.videoWidth,t=this._videoElement.videoHeight,i=this._videoElement.clientWidth,s=this._videoElement.clientHeight;if(e>0&&t>0&&i>0&&s>0){const r=e/t,a=i/s;let o,c;r>a?(o=i,c=i/r):(o=s*r,c=s),this._canvas.style.width=`${o}px`,this._canvas.style.height=`${c}px`;const d=(i-o)/2,l=(s-c)/2;this._canvas.style.left=`${d}px`,this._canvas.style.top=`${l}px`,this._canvas.width=e,this._canvas.height=t}}_setupResizeObserver(){!this._videoElement||typeof ResizeObserver>"u"||(this._resizeObserver=new ResizeObserver(()=>{this._syncCanvasSize()}),this._resizeObserver.observe(this._videoElement))}startRenderingFromVideo(){this._isRendering||!this._videoElement||!this._canvas||!this._ctx||(this._isRendering=!0,this._renderLoop())}stopRenderingFromVideo(){this._isRendering=!1,this._animationFrameId!==null&&(cancelAnimationFrame(this._animationFrameId),this._animationFrameId=null)}setFitMode(e){this._canvas&&(this._canvas.style.width="100%",this._canvas.style.height="100%",this._canvas.style.objectFit=e)}render(e){if(this.ensureNotDisposed(),!(!this._ctx||!this._canvas))try{const t=e.displayWidth,i=e.displayHeight;this._videoElement?this._syncCanvasSize():(this._canvas.width!==t||this._canvas.height!==i)&&(this._canvas.width=t,this._canvas.height=i);const s=e instanceof VideoFrame?e.displayWidth:e.videoWidth,r=e instanceof VideoFrame?e.displayHeight:e.videoHeight;s>0&&r>0&&(this._canvas.width!==s||this._canvas.height!==r)&&(this._canvas.width=s,this._canvas.height=r),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._ctx.drawImage(e,0,0,this._canvas.width,this._canvas.height)}catch(t){m.error("Error rendering video frame to canvas:",t)}}getCanvas(){return this._canvas}getContext(){return this._ctx}onDispose(){this.stopRenderingFromVideo(),this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),this._canvas&&this._parentElement&&this._canvas.parentElement===this._parentElement&&this._parentElement.removeChild(this._canvas),this._canvas=null,this._ctx=null,this._videoElement=null,this._parentElement=null,m.info("Canvas Renderer disposed")}}class bs extends G{constructor(e){super(),this._element=null,this._stream=null,this._track=null,this._element=e,m.info("Video Element Renderer created")}setTrack(e){if(this.ensureNotDisposed(),this._track=e,!this._element){m.warn("No video element available to set track");return}this._stream||(this._stream=new MediaStream,this._element.srcObject=this._stream);const t=this._stream.getTracks();for(const i of t)if(i!==e)try{this._stream.removeTrack(i)}catch(s){console.error(s)}if(!this._stream.getTracks().includes(e))try{this._stream.addTrack(e)}catch(i){m.error("Failed to add track to media stream:",i)}this._element.play().catch(i=>{m.error("Error playing video:",i)}),m.debug("Video track set to element (stream reused)")}setOpacity(e){this._element&&(this._element.style.opacity=String(e))}getElement(){return this._element}setFitMode(e){this._element&&(this._element.style.width="100%",this._element.style.height="100%",this._element.style.objectFit=e)}render(e){m.debug("Render called in direct mode (no-op)")}onDispose(){this._element&&(this._element.srcObject=null),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),this._track&&(this._track.stop(),this._track=null),m.info("Video Element Renderer disposed")}clearTrack(){if(this._stream){const e=this._stream.getTracks();for(const t of e)try{this._stream.removeTrack(t)}catch(i){console.error(i)}}this._track=null}}class Ga extends G{constructor(){super(...arguments),this._renderer=null,this._processors=[],this._videoElementRenderer=null,this._canvasRenderer=null,this._videoFrameCallbackId=null,this._animationFrameId=null,this._isProcessing=!1,this._processVideoFrame=()=>{if(!this._isProcessing||!this._videoElementRenderer||!this._canvasRenderer)return;const e=this._videoElementRenderer.getElement();if(!e||e.readyState<2){this._isProcessing&&e&&(this._videoFrameCallbackId=e.requestVideoFrameCallback(this._processVideoFrame));return}try{let t=new VideoFrame(e,{timestamp:performance.now()*1e3});for(const i of this._processors){const s=i.process(t);s&&s!==t&&(t instanceof VideoFrame&&t.close(),t=s)}t instanceof ImageData?this._renderImageData(t):this._canvasRenderer.render(t),t instanceof VideoFrame&&t.close()}catch(t){m.error("Error processing video frame:",t)}this._isProcessing&&e&&(this._videoFrameCallbackId=e.requestVideoFrameCallback(this._processVideoFrame))},this._processVideoFrameFallback=()=>{if(!this._isProcessing||!this._canvasRenderer||!this._videoElementRenderer)return;const e=this._videoElementRenderer.getElement();if(!e||e.readyState<2||e.paused){const a=this._canvasRenderer.getContext(),o=this._canvasRenderer.getCanvas();a&&o&&a.clearRect(0,0,o.width,o.height),this._animationFrameId=requestAnimationFrame(this._processVideoFrameFallback);return}const t=e.videoWidth,i=e.videoHeight,s=this._canvasRenderer.getCanvas();t>0&&s&&(s.width!==t||s.height!==i)&&(s.width=t,s.height=i);let r=new VideoFrame(e);try{for(const a of this._processors){const o=a.process(r);o&&o!==r&&(r instanceof VideoFrame&&r.close(),r=o)}r instanceof ImageData?this._renderImageData(r):this._canvasRenderer.render(r)}finally{r instanceof VideoFrame&&r.close()}this._isProcessing&&(this._animationFrameId=requestAnimationFrame(this._processVideoFrameFallback))}}getRenderer(){return this._renderer}setRenderer(e){if(this._renderer&&this._renderer.dispose(),this._renderer=e,e instanceof bs){if(this._videoElementRenderer=e,!this._canvasRenderer){const t=this._videoElementRenderer.getElement();if(t)try{t.parentElement&&(this._canvasRenderer=new Mi(void 0,t),this._renderer=this._canvasRenderer,m.debug("Canvas renderer created in setRenderer (processed mode)"))}catch(i){m.warn("Failed to create CanvasRenderer in setRenderer, will retry in attachToContainer:",i)}}this._setupProcessingPipeline()}else this._videoElementRenderer=null,this._stopProcessingPipeline();m.debug("Processed render strategy renderer set")}addProcessor(e,t){t!==void 0&&t>=0&&t<this._processors.length?this._processors.splice(t,0,e):this._processors.push(e),this._setupProcessingPipeline()}getProcessors(){return this._processors}setProcessors(e){this._processors.forEach(t=>t.dispose()),this._processors=e,this._setupProcessingPipeline(),m.debug("Processed render strategy processor set")}attachToContainer(e){if(this._canvasRenderer){const t=this._canvasRenderer.getCanvas();if(t&&(t.parentElement&&t.parentElement!==e&&t.parentElement.removeChild(t),t.parentElement!==e&&(e.appendChild(t),m.debug("Canvas element attached to container in processed mode"))),this._videoElementRenderer){const i=this._videoElementRenderer.getElement();i&&(i.parentElement&&i.parentElement.removeChild(i),i.style.display="none")}}else if(this._videoElementRenderer){const t=this._videoElementRenderer.getElement();if(t){const i=t.parentElement!==null;i||e.appendChild(t);try{this._canvasRenderer=new Mi(void 0,t),this._renderer=this._canvasRenderer,!i&&t.parentElement===e&&e.removeChild(t),t.style.display="none";const s=this._canvasRenderer.getCanvas();s&&s.parentElement!==e&&e.appendChild(s),this._startProcessingLoop(),m.debug("Canvas created and attached to container in processed mode")}catch(s){m.error("Failed to create CanvasRenderer in attachToContainer:",s),!i&&t.parentElement===e&&e.removeChild(t),t.parentElement!==e&&(e.appendChild(t),t.style.display="")}}}}_setupProcessingPipeline(){if(!this._videoElementRenderer)return;const e=this._videoElementRenderer.getElement();if(!e){m.warn("Video element not available for processing");return}if(e.parentElement&&e.parentElement.removeChild(e),e.style.display="none",e.readyState<2){const t=()=>{this._setupProcessingPipeline(),e.removeEventListener("loadedmetadata",t)};e.addEventListener("loadedmetadata",t);return}this._canvasRenderer&&(this._startProcessingLoop(),m.info("Processing pipeline setup completed"))}_stopProcessingPipeline(){this._stopProcessingLoop(),this._canvasRenderer&&(this._canvasRenderer.dispose(),this._canvasRenderer=null),this._videoElementRenderer&&(this._renderer=this._videoElementRenderer)}_startProcessingLoop(){this._isProcessing||!this._videoElementRenderer||!this._canvasRenderer||!this._videoElementRenderer.getElement()||(this._isProcessing=!0,"requestVideoFrameCallback"in HTMLVideoElement.prototype?this._processVideoFrame():this._processVideoFrameFallback())}_stopProcessingLoop(){this._isProcessing=!1;const e=this._videoElementRenderer?.getElement();this._videoFrameCallbackId!==null&&e&&"cancelVideoFrameCallback"in e&&(e.cancelVideoFrameCallback(this._videoFrameCallbackId),this._videoFrameCallbackId=null),this._animationFrameId!==null&&(cancelAnimationFrame(this._animationFrameId),this._animationFrameId=null)}_renderImageData(e){if(!this._canvasRenderer)return;const t=this._canvasRenderer.getContext(),i=this._canvasRenderer.getCanvas();t&&i&&((i.width!==e.width||i.height!==e.height)&&(i.width=e.width,i.height=e.height),t.clearRect(0,0,i.width,i.height),t.putImageData(e,0,0))}onDispose(){this._stopProcessingPipeline(),this._renderer&&(this._renderer.dispose(),this._renderer=null),this._processors.forEach(e=>e.dispose()),this._processors=[],this._videoElementRenderer=null,this._canvasRenderer=null,m.info("Processed Render Strategy disposed")}}class Ha{create(){return new Ga}}class ys{static getFactory(e){return e==="processed"?new Ha:new Ka}}class Ts extends G{constructor(e,t){super(),this._videoElementRenderer=null,this._containerElement=null,this._source=e;const i=t?.renderMode||"raw";this._containerElement=t?.containerElement||null,this._strategyFactory=ys.getFactory(i),this._strategy=this._strategyFactory.create();const s=this._source.getInternalElement(),r=new bs(s);this._videoElementRenderer=r,this._strategy.setRenderer(r),this._containerElement&&(this._strategy.attachToContainer(this._containerElement),m.info("Renderer elements attached to container via strategy")),m.info("Video Pipeline created")}setRenderMode(e){this.ensureNotDisposed();const t=ys.getFactory(e);if(this._strategyFactory.constructor===t.constructor)return;const i=this._strategy.getRenderer(),s=this._strategy.getProcessors();this._strategy.dispose(),this._strategyFactory=t,this._strategy=this._strategyFactory.create(),i&&this._strategy.setRenderer(i),s.length>0&&this._strategy.setProcessors(s),this._containerElement&&this._strategy.attachToContainer(this._containerElement),m.info(`Video render mode changed to: ${e}`)}setRenderFitMode(e){this.ensureNotDisposed(),this._strategy.getRenderer()?.setFitMode(e),m.info(`Video render fit mode changed to: ${e}`)}setProcessor(e){this.ensureNotDisposed(),this._strategy.setProcessors(e?[e]:[])}setRenderer(e){this.ensureNotDisposed(),this._strategy.setRenderer(e)}get strategy(){return this._strategy}get videoElementRenderer(){return this._videoElementRenderer}onDispose(){if(this._strategy.dispose(),this._videoElementRenderer){const e=this._videoElementRenderer.getElement();e&&e.parentElement&&e.parentElement.removeChild(e),this._videoElementRenderer.dispose(),this._videoElementRenderer=null}m.info("Video Pipeline disposed")}}class za extends G{onDispose(){}}class Li extends za{constructor(e){super(),this._program=null,this._texture=null,this._lastProcessedTimestamp=null,this._options=e,this._canvas=document.createElement("canvas");const t=this._canvas.getContext("webgl",{premultipliedAlpha:!1,preserveDrawingBuffer:!0});if(!t)throw new Error("WebGL not supported");this._gl=t,this._initGL(),m.info("WebGL Green Screen Processor initialized")}_initGL(){const e=this._gl,t=`
1
+ (function(D,B){typeof exports=="object"&&typeof module<"u"?B(exports):typeof define=="function"&&define.amd?define(["exports"],B):(D=typeof globalThis<"u"?globalThis:D||self,B(D.LivekitSDK={}))})(this,(function(D){"use strict";var B;(function(n){n.SDK_AUTH_TOKEN_FAILED="SDK_AUTH_TOKEN_FAILED",n.SDK_GET_LIVEKIT_CONFIG_FAILED="SDK_GET_LIVEKIT_CONFIG_FAILED",n.SDK_RECONNECT_FAILED="SDK_RECONNECT_FAILED",n.SDK_DISCONNECT_FAILED="SDK_DISCONNECT_FAILED",n.SDK_NOT_CONNECTED="SDK_NOT_CONNECTED",n.SDK_CONNECT_FAILED="SDK_CONNECT_FAILED",n.SDK_SWITCH_VIDEO_FAILED="SDK_SWITCH_VIDEO_FAILED",n.SDK_ERROR="SDK_ERROR",n.SDK_PRECONNECT_FAILED="SDK_PRECONNECT_FAILED",n.SDK_INTERRUPT_CONVERSATION_FAILED="SDK_INTERRUPT_CONVERSATION_FAILED",n.SDK_INITIALIZATION_FAILED="SDK_INITIALIZATION_FAILED",n.SDK_INVALID_STATE_TRANSITION="SDK_INVALID_STATE_TRANSITION",n.NO_AVATARNAME="NO_AVATARNAME",n.AUDIO_CAPTURE_START_FAILED="AUDIO_CAPTURE_START_FAILED",n.AUDIO_CAPTURE_FAILED="AUDIO_CAPTURE_FAILED",n.AUDIO_INVALID_SAMPLE_RATE="AUDIO_INVALID_SAMPLE_RATE",n.AUDIO_INVALID_CHANNEL="AUDIO_INVALID_CHANNEL",n.AUDIO_INVALID_HEADER_LENGTH="AUDIO_INVALID_HEADER_LENGTH",n.AUDIO_INVALID_TYPE="AUDIO_INVALID_TYPE",n.AUDIO_INVALID_RESERVED="AUDIO_INVALID_RESERVED",n.AUDIO_CONTROLLER_NOT_AVAILABLE="AUDIO_CONTROLLER_NOT_AVAILABLE",n.CAMERA_CONTROLLER_NOT_AVAILABLE="CAMERA_CONTROLLER_NOT_AVAILABLE",n.WS_CONNECT_FAILED="WS_CONNECT_FAILED",n.WS_TEXT_SEND_FAILED="WS_TEXT_SEND_FAILED",n.WS_PARSE_ERROR="WS_PARSE_ERROR",n.WS_NOT_CONNECTED="WS_NOT_CONNECTED",n.WS_CONNECT_ERROR="WS_CONNECT_ERROR",n.LIVEKIT_CONNECT_FAILED="LIVEKIT_CONNECT_FAILED",n.CONVERSATION_CONTROLLER_NOT_AVAILABLE="CONVERSATION_CONTROLLER_NOT_AVAILABLE",n.STATE_MACHINE_INVALID_STATE_TRANSITION="STATE_MACHINE_INVALID_STATE_TRANSITION",n.OBJECT_DISPOSED="OBJECT_DISPOSED"})(B||(B={}));class G extends Error{constructor(e,t="SDK_ERROR",i){super(e),this.name="SDKError",this.code=t,this.cause=i,Object.setPrototypeOf(this,G.prototype)}static fromError(e,t){return e instanceof G?e:e instanceof Error?new G(e.message,t||B.SDK_ERROR,e):typeof e=="string"?new G(e,t||B.SDK_ERROR):new G("Unknown error",t||B.SDK_ERROR,e)}}class j{constructor(){this._disposed=!1}get isDisposed(){return this._disposed}dispose(){this._disposed||(this.onDispose(),this._disposed=!0)}ensureNotDisposed(){if(this._disposed)throw new G("Object has been disposed",B.OBJECT_DISPOSED)}}D.LogLevel=void 0,(function(n){n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n[n.NONE=4]="NONE"})(D.LogLevel||(D.LogLevel={}));class m{static setLevel(e){this._level=e}static setPrefix(e){this._prefix=e}static debug(e,...t){this._level<=D.LogLevel.DEBUG&&console.debug(`${this._prefix} [DEBUG]`,e,...t)}static info(e,...t){this._level<=D.LogLevel.INFO&&console.info(`${this._prefix} [INFO]`,e,...t)}static warn(e,...t){this._level<=D.LogLevel.WARN&&console.warn(`${this._prefix} [WARN]`,e,...t)}static error(e,...t){this._level<=D.LogLevel.ERROR&&console.error(`${this._prefix} [ERROR]`,e,...t)}}m._level=D.LogLevel.ERROR,m._prefix="[SDK]";class ps extends j{constructor(){super(...arguments),this._listeners=new Map}on(e,t){this.ensureNotDisposed(),this._listeners.has(e)||this._listeners.set(e,new Set);const i=this._listeners.get(e);return i.add(t),m.debug(`Event listener added for: ${String(e)}`),()=>{i.delete(t),m.debug(`Event listener removed for: ${String(e)}`)}}once(e,t){this.ensureNotDisposed();const i=s=>{t(s),this.off(e,i)};return this.on(e,i)}off(e,t){this.ensureNotDisposed();const i=this._listeners.get(e);i&&i.delete(t)}emit(e,t){this.ensureNotDisposed();const i=this._listeners.get(e);i&&i.size>0&&(m.debug(`Emitting event: ${String(e)}`,t),i.forEach(s=>{try{s(t)}catch(r){m.error(`Error in event listener for ${String(e)}:`,r)}}))}removeAllListeners(){this._listeners.clear(),m.debug("All event listeners removed")}listenerCount(e){const t=this._listeners.get(e);return t?t.size:0}onDispose(){this.removeAllListeners()}}D.SessionStatus=void 0,(function(n){n.IDLE="idle",n.CONNECTING="connecting",n.CONNECTED="connected",n.PARTIAL="partial",n.DISCONNECTED="disconnected",n.RECONNECTING="reconnecting",n.DISCONNECTING="disconnecting",n.ERROR="error",n.DISPOSED="disposed"})(D.SessionStatus||(D.SessionStatus={}));function Fa(n){switch(n){case"idle":return D.SessionStatus.IDLE;case"connecting":return D.SessionStatus.CONNECTING;case"connected":return D.SessionStatus.CONNECTED;case"partial":return D.SessionStatus.PARTIAL;case"disconnecting":return D.SessionStatus.DISCONNECTING;case"disconnected":case"error":return D.SessionStatus.DISCONNECTED;case"reconnecting:auto":case"reconnecting:manual":return D.SessionStatus.RECONNECTING;case"disposed":return D.SessionStatus.DISPOSED;default:return D.SessionStatus.DISCONNECTED}}class ms{constructor(){this.status=D.SessionStatus.DISCONNECTED,this.state=D.SessionStatus.DISCONNECTED,this.isConnected=!1}reset(){this.status=D.SessionStatus.DISCONNECTED,this.state=D.SessionStatus.DISCONNECTED,this.isConnected=!1}}const It=3,Ba=5e3,Dt=1e3,Mi=10,Va=1e4,ja=3e3,fs=3e4,Li=24e3,gs=16,qa=1,Wa=4096,At=0,Ka="https://api.newportai.com/s2/aigc/api/vih_dispatcher",Ha="wss://api.newportai.com/s2/livekit-lisbon",Ga="wss://api.newportai.com/s2/aigc/api/ws_dispatch/render/v1/stream",za=6e4;var ht;(function(n){n.NO_VIDEO_TRACK="NO_VIDEO_TRACK",n.TRACK_MUTED="TRACK_MUTED",n.TRACK_ENDED="TRACK_ENDED"})(ht||(ht={}));const Ot=.7;class Ja{constructor(e){this.options=e,this._livekitUrl="",this._token="",this._wsUrl="",this.eventBus=new ps,this.sessionState=new ms,e.debug&&m.setLevel(0),m.info("SDK Context initialized")}setLivekitConfig(e,t,i){this._livekitUrl=e||Ha,this._token=t,this._roomId=i}emitError(e,t){const i=G.fromError(e,t);return this.eventBus.emit("inner:sdk:error",{error:i}),i}setVideoOptions(e){this.options.video=Object.assign({},e,this.options.video||{})}setWsUrl(e){this._wsUrl=e}get wsUrl(){return this._wsUrl}get livekitUrl(){return this._livekitUrl}get token(){return this._token}get roomId(){return this._roomId}getLivekitConfig(){return{livekitUrl:this._livekitUrl,token:this._token}}dispose(){this.eventBus.dispose(),this.sessionState.reset(),m.info("SDK Context disposed")}}function vs(n){return{ws:{connected:!1},rtc:{connected:!1,hasVideoTrack:!1},overall:{state:n}}}function bs(n){return Object.freeze({ws:Object.freeze({...n.ws}),rtc:Object.freeze({...n.rtc}),overall:Object.freeze({...n.overall})})}class ys{constructor(){this._transitionMap=null}get transitionMap(){if(!this._transitionMap){const e=new Map;for(const t of this.transitionTable)e.set(t.from,new Set(t.to));this._transitionMap=e}return this._transitionMap}getCurrentState(){return this._currentState}transitionTo(e,t){const i=this._currentState;if(!this.canTransition(i,e)){const s=this.transitionMap.get(i),r=s?Array.from(s).join(", "):"none";throw t?.error??new G(`Invalid state transition: cannot transition from "${i}" to "${e}". Current state: "${i}". Allowed transitions: [${r}]`,B.STATE_MACHINE_INVALID_STATE_TRANSITION)}this._currentState=e}canTransition(e,t){return e===t?!1:this.transitionMap.get(e)?.has(t)??!1}reset(){throw new Error("Method not implemented.")}}class $a extends ys{constructor(){super(...arguments),this._currentState="idle",this.transitionTable=[{from:"idle",to:["connecting","disposed"]},{from:"connecting",to:["connected","partial","error","idle","disposed"]},{from:"connected",to:["disconnecting","partial","reconnecting:auto","reconnecting:manual","error","disposed"]},{from:"partial",to:["connected","disconnecting","reconnecting:auto","reconnecting:manual","error","disposed"]},{from:"reconnecting:auto",to:["connected","partial","error","idle","disposed"]},{from:"reconnecting:manual",to:["connected","partial","error","idle","disposed"]},{from:"disconnecting",to:["disconnected","error","disposed"]},{from:"disconnected",to:["reconnecting:manual","reconnecting:auto","idle","disposed"]},{from:"error",to:["reconnecting:manual","reconnecting:auto","idle","disposed"]},{from:"disposed",to:[]}]}reset(){this._currentState="idle"}}class Qa extends j{constructor(e){super(),this._unsubscribes=[],this._context=e,this._fsm=new $a,this._snapshot=vs("idle")}start(){this.ensureNotDisposed();const e=this._context.eventBus,t=e.on("inner:rtc:connected",()=>{this._snapshot.rtc.connected=!0,this._context.eventBus.emit("inner:sdk:connected",{source:"livekit"}),this._onFactsChanged()}),i=e.on("inner:rtc:disconnected",c=>{this._snapshot.rtc.connected=!1,this._snapshot.rtc.hasVideoTrack=!1,this._context.eventBus.emit("inner:sdk:disconnected",{source:"livekit",reason:c?.reason}),this._onFactsChanged()}),s=e.on("inner:rtc:video:available",()=>{this._snapshot.rtc.hasVideoTrack=!0}),r=e.on("inner:rtc:video:unavailable",()=>{this._snapshot.rtc.hasVideoTrack=!1}),a=e.on("inner:ws:connected",()=>{this._snapshot.ws.connected=!0,this._context.eventBus.emit("inner:sdk:connected",{source:"ws"}),this._onFactsChanged()}),o=e.on("inner:ws:disconnected",c=>{this._snapshot.ws.connected=!1,this._context.eventBus.emit("inner:sdk:disconnected",{source:"ws",reason:c?.reason}),this._onFactsChanged()});this._unsubscribes=[t,i,s,r,a,o]}startConnecting(){this._transitionTo("connecting")}startDisconnecting(){this._transitionTo("disconnecting")}completeDisconnecting(){this._snapshot.ws.connected=!1,this._snapshot.rtc.connected=!1,this._snapshot.rtc.hasVideoTrack=!1,this._transitionTo("disconnected")}captureSnapshotAndStartReconnectingManual(){const e=this.getSnapshot();return this._transitionTo("reconnecting:manual"),e}transitionToIdle(){this._snapshot.ws.connected=!1,this._snapshot.rtc.connected=!1,this._snapshot.rtc.hasVideoTrack=!1,this._transitionTo("idle")}transitionToDisposed(){this._transitionTo("disposed")}getSnapshot(){return bs(this._snapshot)}getState(){return this._fsm.getCurrentState()}canStartReconnectingManual(){const e=this._fsm.getCurrentState();return e==="connected"||e==="partial"||e==="disconnected"||e==="error"}_onFactsChanged(){const e=this._fsm.getCurrentState();if(e==="connecting"||e==="reconnecting:auto"||e==="reconnecting:manual"){const t=this._snapshot.rtc.connected&&this._snapshot.ws.connected,i=this._snapshot.rtc.connected||this._snapshot.ws.connected;if(t){this._transitionTo("connected");return}if(i){this._transitionTo("partial");return}}if(e==="connected"||e==="partial"){const t=this._snapshot.rtc.connected&&this._snapshot.ws.connected;if(!(this._snapshot.rtc.connected||this._snapshot.ws.connected)){this._transitionTo("disconnected");return}if(!t){this._transitionTo("partial");return}if(t&&e==="partial"){this._transitionTo("connected");return}}}_transitionTo(e){this._fsm.canTransition(this._fsm.getCurrentState(),e)&&(this._fsm.transitionTo(e),this._snapshot.overall.state=this._fsm.getCurrentState(),this._syncSessionState())}_syncSessionState(){const e=this._fsm.getCurrentState();this._context.sessionState.status=Fa(e),this._context.sessionState.state=this._context.sessionState.status,this._context.sessionState.isConnected=e==="connected"}onDispose(){this._unsubscribes.forEach(e=>e()),this._unsubscribes=[]}}class _s extends j{get trackId(){return this._trackId}get participantId(){return this._participantId}get track(){return this._track}constructor(){super(),this._trackId=null,this._participantId=null,this._track=null,this._stream=null,this._videoElement=document.createElement("video"),this._videoElement.autoplay=!0,this._videoElement.playsInline=!0,this._videoElement.muted=!0,this._videoElement.crossOrigin="anonymous",this._videoElement.style.display="none",m.info("Video Source initialized with internal video element")}getInternalElement(){return this._videoElement}setTrack(e,t,i){this.ensureNotDisposed(),this._track&&this._track.stop(),this._track=e,this._trackId=t,this._participantId=i,this._stream||(this._stream=new MediaStream);const s=this._stream.getTracks();for(const r of s)if(r!==e)try{this._stream.removeTrack(r)}catch(a){m.warn("Failed to remove track from stream",a)}if(!this._stream.getTracks().includes(e))try{this._stream.addTrack(e)}catch(r){m.error("Failed to add track to media stream:",r)}m.info("Video track ready")}clearTrack(){if(this._stream){const e=this._stream.getTracks();for(const t of e)try{this._stream.removeTrack(t)}catch(i){m.warn("Failed to remove track from stream",i)}}this._track&&(this._track.stop(),this._track=null),this._trackId=null,this._participantId=null,m.info("Video track cleared")}get hasTrack(){return this._track!==null&&this._track.readyState==="live"}onDispose(){this.clearTrack(),this._videoElement&&this._videoElement.parentElement&&this._videoElement.parentElement.removeChild(this._videoElement),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),m.info("Video Source disposed")}}class Ya extends j{constructor(){super(...arguments),this._renderer=null}getRenderer(){return this._renderer}setRenderer(e){this._renderer&&this._renderer.dispose(),this._renderer=e,m.debug("Raw render strategy renderer set")}getProcessors(){return[]}setProcessors(e){m.warn("Raw render strategy does not support processors")}attachToContainer(e){if(!this._renderer){m.warn("No renderer available to attach to container");return}if("getElement"in this._renderer&&typeof this._renderer.getElement=="function"){const t=this._renderer.getElement();t instanceof HTMLVideoElement&&(t.parentElement&&t.parentElement!==e&&t.parentElement.removeChild(t),t.parentElement!==e&&(e.appendChild(t),t.style.display="",m.debug("Video element attached to container in raw mode")))}}onDispose(){this._renderer&&(this._renderer.dispose(),this._renderer=null),m.info("Raw Render Strategy disposed")}}class Xa{create(){return new Ya}}class Ui extends j{constructor(e,t){if(super(),this._canvas=null,this._ctx=null,this._videoElement=null,this._parentElement=null,this._resizeObserver=null,this._animationFrameId=null,this._isRendering=!1,this._renderLoop=()=>{if(!(!this._isRendering||!this._videoElement||!this._canvas||!this._ctx)){try{this._syncCanvasSize(),this._ctx.drawImage(this._videoElement,0,0,this._canvas.width,this._canvas.height)}catch(i){m.error("Error rendering from video to canvas:",i)}this._animationFrameId=requestAnimationFrame(this._renderLoop)}},e){if(this._canvas=e,this._ctx=e.getContext("2d"),!this._ctx)throw new Error("Failed to get 2D context from canvas")}else if(t)this._videoElement=t,this._createCanvasFromVideo();else throw new Error("CanvasRenderer requires either canvas or videoElement");m.info("Canvas Renderer created")}_createCanvasFromVideo(){if(!this._videoElement)return;if(this._parentElement=this._videoElement.parentElement,!this._parentElement)throw new Error("Video element must have a parent element");if(window.getComputedStyle(this._parentElement).position==="static"&&(this._parentElement.style.position="relative"),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d"),!this._ctx)throw new Error("Failed to get 2D context from canvas");this._canvas.style.position="absolute",this._canvas.style.top="0",this._canvas.style.left="0",this._canvas.style.width="100%",this._canvas.style.height="100%",this._canvas.style.pointerEvents="none",this._parentElement.appendChild(this._canvas),this._syncCanvasSize(),this._setupResizeObserver()}_syncCanvasSize(){if(!this._canvas||!this._videoElement||!this._ctx)return;const e=this._videoElement.videoWidth,t=this._videoElement.videoHeight,i=this._videoElement.clientWidth,s=this._videoElement.clientHeight;if(e>0&&t>0&&i>0&&s>0){const r=e/t,a=i/s;let o,c;r>a?(o=i,c=i/r):(o=s*r,c=s),this._canvas.style.width=`${o}px`,this._canvas.style.height=`${c}px`;const d=(i-o)/2,l=(s-c)/2;this._canvas.style.left=`${d}px`,this._canvas.style.top=`${l}px`,this._canvas.width=e,this._canvas.height=t}}_setupResizeObserver(){!this._videoElement||typeof ResizeObserver>"u"||(this._resizeObserver=new ResizeObserver(()=>{this._syncCanvasSize()}),this._resizeObserver.observe(this._videoElement))}startRenderingFromVideo(){this._isRendering||!this._videoElement||!this._canvas||!this._ctx||(this._isRendering=!0,this._renderLoop())}stopRenderingFromVideo(){this._isRendering=!1,this._animationFrameId!==null&&(cancelAnimationFrame(this._animationFrameId),this._animationFrameId=null)}setFitMode(e){this._canvas&&(this._canvas.style.width="100%",this._canvas.style.height="100%",this._canvas.style.objectFit=e)}render(e){if(this.ensureNotDisposed(),!(!this._ctx||!this._canvas))try{const t=e.displayWidth,i=e.displayHeight;this._videoElement?this._syncCanvasSize():(this._canvas.width!==t||this._canvas.height!==i)&&(this._canvas.width=t,this._canvas.height=i);const s=e instanceof VideoFrame?e.displayWidth:e.videoWidth,r=e instanceof VideoFrame?e.displayHeight:e.videoHeight;s>0&&r>0&&(this._canvas.width!==s||this._canvas.height!==r)&&(this._canvas.width=s,this._canvas.height=r),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._ctx.drawImage(e,0,0,this._canvas.width,this._canvas.height)}catch(t){m.error("Error rendering video frame to canvas:",t)}}getCanvas(){return this._canvas}getContext(){return this._ctx}onDispose(){this.stopRenderingFromVideo(),this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),this._canvas&&this._parentElement&&this._canvas.parentElement===this._parentElement&&this._parentElement.removeChild(this._canvas),this._canvas=null,this._ctx=null,this._videoElement=null,this._parentElement=null,m.info("Canvas Renderer disposed")}}class Ts extends j{constructor(e){super(),this._element=null,this._stream=null,this._track=null,this._element=e,m.info("Video Element Renderer created")}setTrack(e){if(this.ensureNotDisposed(),this._track=e,!this._element){m.warn("No video element available to set track");return}this._stream||(this._stream=new MediaStream,this._element.srcObject=this._stream);const t=this._stream.getTracks();for(const i of t)if(i!==e)try{this._stream.removeTrack(i)}catch(s){console.error(s)}if(!this._stream.getTracks().includes(e))try{this._stream.addTrack(e)}catch(i){m.error("Failed to add track to media stream:",i)}this._element.play().catch(i=>{m.error("Error playing video:",i)}),m.debug("Video track set to element (stream reused)")}setOpacity(e){this._element&&(this._element.style.opacity=String(e))}getElement(){return this._element}setFitMode(e){this._element&&(this._element.style.width="100%",this._element.style.height="100%",this._element.style.objectFit=e)}render(e){m.debug("Render called in direct mode (no-op)")}onDispose(){this._element&&(this._element.srcObject=null),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),this._track&&(this._track.stop(),this._track=null),m.info("Video Element Renderer disposed")}clearTrack(){if(this._stream){const e=this._stream.getTracks();for(const t of e)try{this._stream.removeTrack(t)}catch(i){console.error(i)}}this._track=null}}class Za extends j{constructor(){super(...arguments),this._renderer=null,this._processors=[],this._videoElementRenderer=null,this._canvasRenderer=null,this._videoFrameCallbackId=null,this._animationFrameId=null,this._isProcessing=!1,this._processVideoFrame=()=>{if(!this._isProcessing||!this._videoElementRenderer||!this._canvasRenderer)return;const e=this._videoElementRenderer.getElement();if(!e||e.readyState<2){this._isProcessing&&e&&(this._videoFrameCallbackId=e.requestVideoFrameCallback(this._processVideoFrame));return}try{let t=new VideoFrame(e,{timestamp:performance.now()*1e3});for(const i of this._processors){const s=i.process(t);s&&s!==t&&(t instanceof VideoFrame&&t.close(),t=s)}t instanceof ImageData?this._renderImageData(t):this._canvasRenderer.render(t),t instanceof VideoFrame&&t.close()}catch(t){m.error("Error processing video frame:",t)}this._isProcessing&&e&&(this._videoFrameCallbackId=e.requestVideoFrameCallback(this._processVideoFrame))},this._processVideoFrameFallback=()=>{if(!this._isProcessing||!this._canvasRenderer||!this._videoElementRenderer)return;const e=this._videoElementRenderer.getElement();if(!e||e.readyState<2||e.paused){const a=this._canvasRenderer.getContext(),o=this._canvasRenderer.getCanvas();a&&o&&a.clearRect(0,0,o.width,o.height),this._animationFrameId=requestAnimationFrame(this._processVideoFrameFallback);return}const t=e.videoWidth,i=e.videoHeight,s=this._canvasRenderer.getCanvas();t>0&&s&&(s.width!==t||s.height!==i)&&(s.width=t,s.height=i);let r=new VideoFrame(e);try{for(const a of this._processors){const o=a.process(r);o&&o!==r&&(r instanceof VideoFrame&&r.close(),r=o)}r instanceof ImageData?this._renderImageData(r):this._canvasRenderer.render(r)}finally{r instanceof VideoFrame&&r.close()}this._isProcessing&&(this._animationFrameId=requestAnimationFrame(this._processVideoFrameFallback))}}getRenderer(){return this._renderer}setRenderer(e){if(this._renderer&&this._renderer.dispose(),this._renderer=e,e instanceof Ts){if(this._videoElementRenderer=e,!this._canvasRenderer){const t=this._videoElementRenderer.getElement();if(t)try{t.parentElement&&(this._canvasRenderer=new Ui(void 0,t),this._renderer=this._canvasRenderer,m.debug("Canvas renderer created in setRenderer (processed mode)"))}catch(i){m.warn("Failed to create CanvasRenderer in setRenderer, will retry in attachToContainer:",i)}}this._setupProcessingPipeline()}else this._videoElementRenderer=null,this._stopProcessingPipeline();m.debug("Processed render strategy renderer set")}addProcessor(e,t){t!==void 0&&t>=0&&t<this._processors.length?this._processors.splice(t,0,e):this._processors.push(e),this._setupProcessingPipeline()}getProcessors(){return this._processors}setProcessors(e){this._processors.forEach(t=>t.dispose()),this._processors=e,this._setupProcessingPipeline(),m.debug("Processed render strategy processor set")}attachToContainer(e){if(this._canvasRenderer){const t=this._canvasRenderer.getCanvas();if(t&&(t.parentElement&&t.parentElement!==e&&t.parentElement.removeChild(t),t.parentElement!==e&&(e.appendChild(t),m.debug("Canvas element attached to container in processed mode"))),this._videoElementRenderer){const i=this._videoElementRenderer.getElement();i&&(i.parentElement&&i.parentElement.removeChild(i),i.style.display="none")}}else if(this._videoElementRenderer){const t=this._videoElementRenderer.getElement();if(t){const i=t.parentElement!==null;i||e.appendChild(t);try{this._canvasRenderer=new Ui(void 0,t),this._renderer=this._canvasRenderer,!i&&t.parentElement===e&&e.removeChild(t),t.style.display="none";const s=this._canvasRenderer.getCanvas();s&&s.parentElement!==e&&e.appendChild(s),this._startProcessingLoop(),m.debug("Canvas created and attached to container in processed mode")}catch(s){m.error("Failed to create CanvasRenderer in attachToContainer:",s),!i&&t.parentElement===e&&e.removeChild(t),t.parentElement!==e&&(e.appendChild(t),t.style.display="")}}}}_setupProcessingPipeline(){if(!this._videoElementRenderer)return;const e=this._videoElementRenderer.getElement();if(!e){m.warn("Video element not available for processing");return}if(e.parentElement&&e.parentElement.removeChild(e),e.style.display="none",e.readyState<2){const t=()=>{this._setupProcessingPipeline(),e.removeEventListener("loadedmetadata",t)};e.addEventListener("loadedmetadata",t);return}this._canvasRenderer&&(this._startProcessingLoop(),m.info("Processing pipeline setup completed"))}_stopProcessingPipeline(){this._stopProcessingLoop(),this._canvasRenderer&&(this._canvasRenderer.dispose(),this._canvasRenderer=null),this._videoElementRenderer&&(this._renderer=this._videoElementRenderer)}_startProcessingLoop(){this._isProcessing||!this._videoElementRenderer||!this._canvasRenderer||!this._videoElementRenderer.getElement()||(this._isProcessing=!0,"requestVideoFrameCallback"in HTMLVideoElement.prototype?this._processVideoFrame():this._processVideoFrameFallback())}_stopProcessingLoop(){this._isProcessing=!1;const e=this._videoElementRenderer?.getElement();this._videoFrameCallbackId!==null&&e&&"cancelVideoFrameCallback"in e&&(e.cancelVideoFrameCallback(this._videoFrameCallbackId),this._videoFrameCallbackId=null),this._animationFrameId!==null&&(cancelAnimationFrame(this._animationFrameId),this._animationFrameId=null)}_renderImageData(e){if(!this._canvasRenderer)return;const t=this._canvasRenderer.getContext(),i=this._canvasRenderer.getCanvas();t&&i&&((i.width!==e.width||i.height!==e.height)&&(i.width=e.width,i.height=e.height),t.clearRect(0,0,i.width,i.height),t.putImageData(e,0,0))}onDispose(){this._stopProcessingPipeline(),this._renderer&&(this._renderer.dispose(),this._renderer=null),this._processors.forEach(e=>e.dispose()),this._processors=[],this._videoElementRenderer=null,this._canvasRenderer=null,m.info("Processed Render Strategy disposed")}}class ec{create(){return new Za}}class ks{static getFactory(e){return e==="processed"?new ec:new Xa}}class Ss extends j{constructor(e,t){super(),this._videoElementRenderer=null,this._containerElement=null,this._source=e;const i=t?.renderMode||"raw";this._containerElement=t?.containerElement||null,this._strategyFactory=ks.getFactory(i),this._strategy=this._strategyFactory.create();const s=this._source.getInternalElement(),r=new Ts(s);this._videoElementRenderer=r,this._strategy.setRenderer(r),this._containerElement&&(this._strategy.attachToContainer(this._containerElement),m.info("Renderer elements attached to container via strategy")),m.info("Video Pipeline created")}setRenderMode(e){this.ensureNotDisposed();const t=ks.getFactory(e);if(this._strategyFactory.constructor===t.constructor)return;const i=this._strategy.getRenderer(),s=this._strategy.getProcessors();this._strategy.dispose(),this._strategyFactory=t,this._strategy=this._strategyFactory.create(),i&&this._strategy.setRenderer(i),s.length>0&&this._strategy.setProcessors(s),this._containerElement&&this._strategy.attachToContainer(this._containerElement),m.info(`Video render mode changed to: ${e}`)}setRenderFitMode(e){this.ensureNotDisposed(),this._strategy.getRenderer()?.setFitMode(e),m.info(`Video render fit mode changed to: ${e}`)}setProcessor(e){this.ensureNotDisposed(),this._strategy.setProcessors(e?[e]:[])}setRenderer(e){this.ensureNotDisposed(),this._strategy.setRenderer(e)}get strategy(){return this._strategy}get videoElementRenderer(){return this._videoElementRenderer}onDispose(){if(this._strategy.dispose(),this._videoElementRenderer){const e=this._videoElementRenderer.getElement();e&&e.parentElement&&e.parentElement.removeChild(e),this._videoElementRenderer.dispose(),this._videoElementRenderer=null}m.info("Video Pipeline disposed")}}class tc extends j{onDispose(){}}class Fi extends tc{constructor(e){super(),this._program=null,this._texture=null,this._lastProcessedTimestamp=null,this._options=e,this._canvas=document.createElement("canvas");const t=this._canvas.getContext("webgl",{premultipliedAlpha:!1,preserveDrawingBuffer:!0});if(!t)throw new Error("WebGL not supported");this._gl=t,this._initGL(),m.info("WebGL Green Screen Processor initialized")}_initGL(){const e=this._gl,t=`
2
2
  attribute vec2 aPosition;
3
3
  attribute vec2 aTexCoord;
4
4
  varying vec2 vTexCoord;
@@ -52,7 +52,7 @@
52
52
 
53
53
  gl_FragColor = vec4(rgb, alpha * color.a);
54
54
  }
55
- `;this._program=this._createProgram(t,i),this._texture=e.createTexture();const s=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),r=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,r),e.bufferData(e.ARRAY_BUFFER,s,e.STATIC_DRAW);const a=e.getAttribLocation(this._program,"aPosition"),o=e.getAttribLocation(this._program,"aTexCoord");e.enableVertexAttribArray(a),e.vertexAttribPointer(a,2,e.FLOAT,!1,16,0),e.enableVertexAttribArray(o),e.vertexAttribPointer(o,2,e.FLOAT,!1,16,8)}process(e){if(!this._options.enabled)return e;const{displayWidth:t,displayHeight:i,timestamp:s}=e;(this._canvas.width!==t||this._canvas.height!==i)&&(this._canvas.width=t,this._canvas.height=i,this._gl.viewport(0,0,t,i));const r=this._gl;r.useProgram(this._program),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this._texture),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,e),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR);const a=this._options.chromaKey||[0,255,0];r.uniform3f(r.getUniformLocation(this._program,"uChromaKey"),a[0]/255,a[1]/255,a[2]/255),r.uniform1f(r.getUniformLocation(this._program,"uSimilarity"),this._options.similarity??.3),r.uniform1f(r.getUniformLocation(this._program,"uSmoothness"),this._options.smoothness??.25),r.uniform1f(r.getUniformLocation(this._program,"uSpill"),this._options.despillStrength??1.15),r.drawArrays(r.TRIANGLE_STRIP,0,4);const o=new VideoFrame(this._canvas,{timestamp:s,duration:e.duration??void 0});return e.close(),o}_createProgram(e,t){const i=this._gl,s=(a,o)=>{const c=i.createShader(a);return i.shaderSource(c,o),i.compileShader(c),c},r=i.createProgram();return i.attachShader(r,s(i.VERTEX_SHADER,e)),i.attachShader(r,s(i.FRAGMENT_SHADER,t)),i.linkProgram(r),r}onDispose(){const e=this._gl;this._texture&&e.deleteTexture(this._texture),this._program&&e.deleteProgram(this._program),m.info("WebGL Green Screen Processor disposed")}updateOptions(e){this._options={...this._options,...e}}}class Ja extends G{constructor(e,t){if(super(),this._context=e,this._source=new vs,this._pipeline=new Ts(this._source,t),t?.renderMode==="processed"&&t?.greenScreen?.enabled){const i=new Li(t.greenScreen);this._pipeline.setProcessor(i),m.info("Green screen processor enabled")}this._pipeline.setRenderFitMode(t?.fitMode||"contain"),m.info("Video Controller created")}setTrack(e,t,i){this.ensureNotDisposed(),this._source.setTrack(e,t,i)}removeTrack(e){this.ensureNotDisposed(),this._source.trackId===e&&this._source.clearTrack()}setRenderMode(e){this.ensureNotDisposed(),this._pipeline.setRenderMode(e),this._context.eventBus.emit("inner:video:render:mode:changed",{mode:e})}setRenderFitMode(e){this.ensureNotDisposed(),this._pipeline.setRenderFitMode(e)}getSource(){return this.ensureNotDisposed(),this._source}onDispose(){this._source.dispose(),this._pipeline.dispose(),m.info("Video Controller disposed")}}class $a extends G{process(e,t){return this.ensureNotDisposed(),e}onDispose(){}}class Qa extends G{set onProcessedAudio(e){this._onProcessedAudio=e}constructor(e){super(),this._processors=[],this._processingStrategy=new $a,m.info("Input Audio Pipeline created")}setProcessingStrategy(e){this.ensureNotDisposed(),this._processingStrategy&&this._processingStrategy.dispose(),this._processingStrategy=e,m.debug("Audio processing strategy set")}get processingStrategy(){return this._processingStrategy}addProcessor(e){this.ensureNotDisposed(),this._processors.push(e),m.debug(`Audio processor added. Total: ${this._processors.length}`)}removeProcessor(e){this.ensureNotDisposed();const t=this._processors.indexOf(e);t>=0&&(this._processors.splice(t,1),m.debug(`Audio processor removed. Total: ${this._processors.length}`))}process(e,t){this.ensureNotDisposed();let i=e;try{i=this._processingStrategy.process(i,t)}catch(s){m.error("Error in audio processing strategy:",s)}for(const s of this._processors)try{i=s.process(i,t)}catch(r){m.error("Error in audio processor:",r);continue}this._onProcessedAudio&&this._onProcessedAudio(i,t)}onDispose(){if(this._processingStrategy)try{this._processingStrategy.dispose()}catch(e){m.error("Error disposing audio processing strategy:",e)}this._processors.forEach(e=>{try{e.dispose()}catch(t){m.error("Error disposing audio processor:",t)}}),this._processors.length=0,this._onProcessedAudio=void 0,m.info("Input Audio Pipeline disposed")}}class Ya extends G{constructor(){super(),this._audioElement=null,this._stream=null,this._track=null,this._volume=1,this._isMuted=!1,this._audioElement=document.createElement("audio"),this._audioElement.autoplay=!0,this._audioElement.volume=this._volume,this._audioElement.muted=this._isMuted,m.info("Output Audio Pipeline created")}getAudioElement(){if(!this._audioElement)throw new H("Audio element not found");return this._audioElement}setTrack(e){this.ensureNotDisposed(),this._track&&this._track!==e&&this._track.stop(),this._track=e,this._audioElement&&(this._stream&&(this._stream.getTracks().forEach(t=>t.stop()),this._stream=null),this._stream=new MediaStream([e]),this._audioElement.volume=this._volume,this._audioElement.muted=this._isMuted,m.debug("Audio track set to output pipeline"))}removeTrack(){this.ensureNotDisposed(),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),this._track&&(this._track.stop(),this._track=null),m.debug("Audio track removed from output pipeline")}setVolume(e){this.ensureNotDisposed(),this._volume=Math.max(0,Math.min(1,e)),this._audioElement&&(this._audioElement.volume=this._volume),m.debug(`Audio output volume set to: ${this._volume}`)}getVolume(){return this._volume}mute(){this.ensureNotDisposed(),this._isMuted=!0,this._audioElement&&(this._audioElement.muted=!0),m.debug("Audio output muted")}unmute(){this.ensureNotDisposed(),this._isMuted=!1,this._audioElement&&(this._audioElement.muted=!1),m.debug("Audio output unmuted")}isMuted(){return this._isMuted}onDispose(){this.removeTrack(),this._audioElement&&(this._audioElement=null),m.info("Output Audio Pipeline disposed")}}const Xa=1,Za=0,ec={0:0,1:1,2:2};function tc(n){return n<0?0:n>4095?4095:Math.floor(n)}function ic(n){if(n<0)return 0;const e=1048575;return n>e?n&e:Math.floor(n)}function nc(n){return n<0?0:n>4095?4095:Math.floor(n)}function sc(n){return n<0?0:n>65535?65535:Math.floor(n)}function rc(n){if(n!==0&&n!==1&&n!==2)throw new H(`Invalid sample rate encoding: ${n}. Must be 0 (16kHz), 1 (24kHz), or 2 (48kHz)`,B.AUDIO_INVALID_SAMPLE_RATE)}function oc(n){rc(n.sampleRate);const e=tc(n.sequenceNumber),t=ic(n.timestamp),i=nc(n.frameSize),s=sc(n.payloadLength);if(n.channel!==0&&n.channel!==1)throw new H(`Invalid channel value: ${n.channel}. Must be 0 (mono) or 1 (stereo)`,B.AUDIO_INVALID_CHANNEL);const r=new Uint8Array(9);let a=Xa<<6;a|=n.channel<<5,a|=(n.keyFrame?1:0)<<4,a|=e>>8&15,r[0]=a,r[1]=e&255,r[2]=t>>12&255,r[3]=t>>4&255;const o=ec[n.sampleRate];let c=(t&15)<<4;c|=o<<2,c|=i>>10&3,r[4]=c,r[5]=i>>2&255;let d=(i&3)<<6;return d|=Za&63,r[6]=d,r[7]=s>>8&255,r[8]=s&255,r}class ac{constructor(e){this.transport=e}sendBinary(e){this.transport.sendBinary(e)}isConnected(){return this.transport.isConnected}}class cc extends G{constructor(e,t){super(),this._wsSender=null,this._sequenceNumber=0,this._isKeyFrame=!0,this._audioStartTime=0,this._isSending=!1,this._audioFrameListener=null,this._audioBuffer=[],this._bufferedSampleCount=0,this._targetSampleRate=24e3,this._bitDepth=16,this._minSamplesToSend=0,this._context=e,this._options=t;const i=t?.input;this._targetSampleRate=i?.sampleRate||24e3,this._bitDepth=i?.bitDepth||16,this._minSamplesToSend=Math.floor(this._targetSampleRate/10),m.info(`Audio Frame Sender created: sampleRate=${this._targetSampleRate}Hz, bitDepth=${this._bitDepth}bit, minSamples=${this._minSamplesToSend}`)}setWebSocketSender(e){this._wsSender=e}setConversationTransport(e){this._wsSender=new ac(e)}start(){if(this.ensureNotDisposed(),this._isSending){m.warn("Audio frame sending already started");return}this._sequenceNumber=0,this._isKeyFrame=!0,this._audioStartTime=Date.now(),this._audioFrameListener=e=>{this._handleAudioFrame(e.data,e.sampleRate)},this._context.eventBus.on("inner:audio:frame:received",this._audioFrameListener),this._isSending=!0,m.info("Audio frame sending started")}stop(){this.ensureNotDisposed(),this._isSending&&(this._flushBuffer(),this._audioFrameListener&&(this._context.eventBus.off("inner:audio:frame:received",this._audioFrameListener),this._audioFrameListener=null),this._isSending=!1,m.info("Audio frame sending stopped"))}_handleAudioFrame(e,t){if(this._isSending)try{Math.abs(t-this._targetSampleRate)>1&&m.warn(`Sample rate mismatch: expected ${this._targetSampleRate}Hz, got ${t}Hz`),this._audioBuffer.push(new Float32Array(e)),this._bufferedSampleCount+=e.length,this._bufferedSampleCount>=this._minSamplesToSend&&this._flushBuffer()}catch(i){m.error("Error handling audio frame:",i)}}_flushBuffer(){if(!(this._audioBuffer.length===0||this._bufferedSampleCount===0))try{const e=this._bufferedSampleCount,t=new Float32Array(e);let i=0;for(const u of this._audioBuffer)t.set(u,i),i+=u.length;this._audioBuffer=[],this._bufferedSampleCount=0;const s=this._convertToPCM(t,this._bitDepth),r=Math.ceil(this._bitDepth/8),a=s.length*r,o=this._getSampleRateEncoding(this._targetSampleRate),c=Math.floor(Date.now()-this._audioStartTime),d={channel:(this._options?.input?.channels||1)===1?0:1,keyFrame:!!this._isKeyFrame,sequenceNumber:this._sequenceNumber,timestamp:c,sampleRate:o,frameSize:t.length,payloadLength:a},l=this._pcmToUint8Array(s,this._bitDepth);if(setTimeout(()=>{try{this._context.eventBus.emit("inner:audio:payload:send",{payload:l,sampleRate:this._targetSampleRate,channels:this._options?.input?.channels||1,sequenceNumber:d.sequenceNumber,timestamp:d.timestamp,keyFrame:d.keyFrame,frameSize:d.frameSize})}catch(u){m.error("Error emitting inner:audio:payload:send event:",u)}},0),this._wsSender&&this._wsSender.isConnected())try{const u=oc(d),h=new Uint8Array(u.length+l.length);h.set(u,0),h.set(l,u.length),this._wsSender.sendBinary(h),m.debug(`Audio frame sent via WS: seq=${d.sequenceNumber}, samples=${t.length}, size=${h.length} bytes`)}catch(u){m.error("Error sending audio frame via WebSocket:",u)}this._isKeyFrame=!1,this._sequenceNumber=(this._sequenceNumber+1)%4096}catch(e){m.error("Error flushing audio buffer:",e)}}_convertToPCM(e,t){if(t===16){const i=new Int16Array(e.length);for(let s=0;s<e.length;s++){const r=Math.max(-1,Math.min(1,e[s]));i[s]=r<0?r*32768:r*32767}return i}else if(t===32){const i=new Int32Array(e.length);for(let s=0;s<e.length;s++){const r=Math.max(-1,Math.min(1,e[s]));i[s]=r*2147483647}return i}else return m.warn(`Unsupported bit depth: ${t}, using 16-bit`),this._convertToPCM(e,16)}_pcmToUint8Array(e,t){const i=Math.ceil(t/8),s=new Uint8Array(e.length*i),r=new DataView(s.buffer);for(let a=0;a<e.length;a++)t===16?r.setInt16(a*2,e[a],!0):t===32&&r.setInt32(a*4,e[a],!0);return s}_getSampleRateEncoding(e){return e===16e3?0:e===24e3?1:e===48e3?2:(m.warn(`Unsupported sample rate: ${e}, defaulting to 48kHz`),1)}onDispose(){this.stop(),m.info("Audio Frame Sender disposed")}}class dc extends G{emitAudioData(e,t){if(this.onAudioData)try{this.onAudioData(e,t)}catch(i){m.error("Error in audio data callback:",i)}}}const lc=`
55
+ `;this._program=this._createProgram(t,i),this._texture=e.createTexture();const s=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),r=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,r),e.bufferData(e.ARRAY_BUFFER,s,e.STATIC_DRAW);const a=e.getAttribLocation(this._program,"aPosition"),o=e.getAttribLocation(this._program,"aTexCoord");e.enableVertexAttribArray(a),e.vertexAttribPointer(a,2,e.FLOAT,!1,16,0),e.enableVertexAttribArray(o),e.vertexAttribPointer(o,2,e.FLOAT,!1,16,8)}process(e){if(!this._options.enabled)return e;const{displayWidth:t,displayHeight:i,timestamp:s}=e;(this._canvas.width!==t||this._canvas.height!==i)&&(this._canvas.width=t,this._canvas.height=i,this._gl.viewport(0,0,t,i));const r=this._gl;r.useProgram(this._program),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this._texture),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,e),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR);const a=this._options.chromaKey||[0,255,0];r.uniform3f(r.getUniformLocation(this._program,"uChromaKey"),a[0]/255,a[1]/255,a[2]/255),r.uniform1f(r.getUniformLocation(this._program,"uSimilarity"),this._options.similarity??.3),r.uniform1f(r.getUniformLocation(this._program,"uSmoothness"),this._options.smoothness??.25),r.uniform1f(r.getUniformLocation(this._program,"uSpill"),this._options.despillStrength??1.15),r.drawArrays(r.TRIANGLE_STRIP,0,4);const o=new VideoFrame(this._canvas,{timestamp:s,duration:e.duration??void 0});return e.close(),o}_createProgram(e,t){const i=this._gl,s=(a,o)=>{const c=i.createShader(a);return i.shaderSource(c,o),i.compileShader(c),c},r=i.createProgram();return i.attachShader(r,s(i.VERTEX_SHADER,e)),i.attachShader(r,s(i.FRAGMENT_SHADER,t)),i.linkProgram(r),r}onDispose(){const e=this._gl;this._texture&&e.deleteTexture(this._texture),this._program&&e.deleteProgram(this._program),m.info("WebGL Green Screen Processor disposed")}updateOptions(e){this._options={...this._options,...e}}}class ic extends j{constructor(e,t){if(super(),this._context=e,this._source=new _s,this._pipeline=new Ss(this._source,t),t?.renderMode==="processed"&&t?.greenScreen?.enabled){const i=new Fi(t.greenScreen);this._pipeline.setProcessor(i),m.info("Green screen processor enabled")}this._pipeline.setRenderFitMode(t?.fitMode||"contain"),m.info("Video Controller created")}setTrack(e,t,i){this.ensureNotDisposed(),this._source.setTrack(e,t,i)}removeTrack(e){this.ensureNotDisposed(),this._source.trackId===e&&this._source.clearTrack()}setRenderMode(e){this.ensureNotDisposed(),this._pipeline.setRenderMode(e),this._context.eventBus.emit("inner:video:render:mode:changed",{mode:e})}setRenderFitMode(e){this.ensureNotDisposed(),this._pipeline.setRenderFitMode(e)}getSource(){return this.ensureNotDisposed(),this._source}onDispose(){this._source.dispose(),this._pipeline.dispose(),m.info("Video Controller disposed")}}class nc extends j{process(e,t){return this.ensureNotDisposed(),e}onDispose(){}}class sc extends j{set onProcessedAudio(e){this._onProcessedAudio=e}constructor(e){super(),this._processors=[],this._processingStrategy=new nc,m.info("Input Audio Pipeline created")}setProcessingStrategy(e){this.ensureNotDisposed(),this._processingStrategy&&this._processingStrategy.dispose(),this._processingStrategy=e,m.debug("Audio processing strategy set")}get processingStrategy(){return this._processingStrategy}addProcessor(e){this.ensureNotDisposed(),this._processors.push(e),m.debug(`Audio processor added. Total: ${this._processors.length}`)}removeProcessor(e){this.ensureNotDisposed();const t=this._processors.indexOf(e);t>=0&&(this._processors.splice(t,1),m.debug(`Audio processor removed. Total: ${this._processors.length}`))}process(e,t){this.ensureNotDisposed();let i=e;try{i=this._processingStrategy.process(i,t)}catch(s){m.error("Error in audio processing strategy:",s)}for(const s of this._processors)try{i=s.process(i,t)}catch(r){m.error("Error in audio processor:",r);continue}this._onProcessedAudio&&this._onProcessedAudio(i,t)}onDispose(){if(this._processingStrategy)try{this._processingStrategy.dispose()}catch(e){m.error("Error disposing audio processing strategy:",e)}this._processors.forEach(e=>{try{e.dispose()}catch(t){m.error("Error disposing audio processor:",t)}}),this._processors.length=0,this._onProcessedAudio=void 0,m.info("Input Audio Pipeline disposed")}}class rc extends j{constructor(){super(),this._audioElement=null,this._stream=null,this._track=null,this._volume=1,this._isMuted=!1,this._audioElement=document.createElement("audio"),this._audioElement.autoplay=!0,this._audioElement.volume=this._volume,this._audioElement.muted=this._isMuted,m.info("Output Audio Pipeline created")}getAudioElement(){if(!this._audioElement)throw new G("Audio element not found");return this._audioElement}setTrack(e){this.ensureNotDisposed(),this._track&&this._track!==e&&this._track.stop(),this._track=e,this._audioElement&&(this._stream&&(this._stream.getTracks().forEach(t=>t.stop()),this._stream=null),this._stream=new MediaStream([e]),this._audioElement.volume=this._volume,this._audioElement.muted=this._isMuted,m.debug("Audio track set to output pipeline"))}removeTrack(){this.ensureNotDisposed(),this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),this._track&&(this._track.stop(),this._track=null),m.debug("Audio track removed from output pipeline")}setVolume(e){this.ensureNotDisposed(),this._volume=Math.max(0,Math.min(1,e)),this._audioElement&&(this._audioElement.volume=this._volume),m.debug(`Audio output volume set to: ${this._volume}`)}getVolume(){return this._volume}mute(){this.ensureNotDisposed(),this._isMuted=!0,this._audioElement&&(this._audioElement.muted=!0),m.debug("Audio output muted")}unmute(){this.ensureNotDisposed(),this._isMuted=!1,this._audioElement&&(this._audioElement.muted=!1),m.debug("Audio output unmuted")}isMuted(){return this._isMuted}onDispose(){this.removeTrack(),this._audioElement&&(this._audioElement=null),m.info("Output Audio Pipeline disposed")}}const oc=1,ac=0,cc={0:0,1:1,2:2};function dc(n){return n<0?0:n>4095?4095:Math.floor(n)}function lc(n){if(n<0)return 0;const e=1048575;return n>e?n&e:Math.floor(n)}function uc(n){return n<0?0:n>4095?4095:Math.floor(n)}function hc(n){return n<0?0:n>65535?65535:Math.floor(n)}function pc(n){if(n!==0&&n!==1&&n!==2)throw new G(`Invalid sample rate encoding: ${n}. Must be 0 (16kHz), 1 (24kHz), or 2 (48kHz)`,B.AUDIO_INVALID_SAMPLE_RATE)}function mc(n){pc(n.sampleRate);const e=dc(n.sequenceNumber),t=lc(n.timestamp),i=uc(n.frameSize),s=hc(n.payloadLength);if(n.channel!==0&&n.channel!==1)throw new G(`Invalid channel value: ${n.channel}. Must be 0 (mono) or 1 (stereo)`,B.AUDIO_INVALID_CHANNEL);const r=new Uint8Array(9);let a=oc<<6;a|=n.channel<<5,a|=(n.keyFrame?1:0)<<4,a|=e>>8&15,r[0]=a,r[1]=e&255,r[2]=t>>12&255,r[3]=t>>4&255;const o=cc[n.sampleRate];let c=(t&15)<<4;c|=o<<2,c|=i>>10&3,r[4]=c,r[5]=i>>2&255;let d=(i&3)<<6;return d|=ac&63,r[6]=d,r[7]=s>>8&255,r[8]=s&255,r}class fc{constructor(e){this.transport=e}sendBinary(e){this.transport.sendBinary(e)}isConnected(){return this.transport.isConnected}}class gc extends j{constructor(e,t){super(),this._wsSender=null,this._sequenceNumber=0,this._isKeyFrame=!0,this._audioStartTime=0,this._isSending=!1,this._audioFrameListener=null,this._audioBuffer=[],this._bufferedSampleCount=0,this._targetSampleRate=24e3,this._bitDepth=16,this._minSamplesToSend=0,this._context=e,this._options=t;const i=t?.input;this._targetSampleRate=i?.sampleRate||24e3,this._bitDepth=i?.bitDepth||16,this._minSamplesToSend=Math.floor(this._targetSampleRate/10),m.info(`Audio Frame Sender created: sampleRate=${this._targetSampleRate}Hz, bitDepth=${this._bitDepth}bit, minSamples=${this._minSamplesToSend}`)}setWebSocketSender(e){this._wsSender=e}setConversationTransport(e){this._wsSender=new fc(e)}start(){if(this.ensureNotDisposed(),this._isSending){m.warn("Audio frame sending already started");return}this._sequenceNumber=0,this._isKeyFrame=!0,this._audioStartTime=Date.now(),this._audioFrameListener=e=>{this._handleAudioFrame(e.data,e.sampleRate)},this._context.eventBus.on("inner:audio:frame:received",this._audioFrameListener),this._isSending=!0,m.info("Audio frame sending started")}stop(){this.ensureNotDisposed(),this._isSending&&(this._flushBuffer(),this._audioFrameListener&&(this._context.eventBus.off("inner:audio:frame:received",this._audioFrameListener),this._audioFrameListener=null),this._isSending=!1,m.info("Audio frame sending stopped"))}_handleAudioFrame(e,t){if(this._isSending)try{Math.abs(t-this._targetSampleRate)>1&&m.warn(`Sample rate mismatch: expected ${this._targetSampleRate}Hz, got ${t}Hz`),this._audioBuffer.push(new Float32Array(e)),this._bufferedSampleCount+=e.length,this._bufferedSampleCount>=this._minSamplesToSend&&this._flushBuffer()}catch(i){m.error("Error handling audio frame:",i)}}_flushBuffer(){if(!(this._audioBuffer.length===0||this._bufferedSampleCount===0))try{const e=this._bufferedSampleCount,t=new Float32Array(e);let i=0;for(const u of this._audioBuffer)t.set(u,i),i+=u.length;this._audioBuffer=[],this._bufferedSampleCount=0;const s=this._convertToPCM(t,this._bitDepth),r=Math.ceil(this._bitDepth/8),a=s.length*r,o=this._getSampleRateEncoding(this._targetSampleRate),c=Math.floor(Date.now()-this._audioStartTime),d={channel:(this._options?.input?.channels||1)===1?0:1,keyFrame:!!this._isKeyFrame,sequenceNumber:this._sequenceNumber,timestamp:c,sampleRate:o,frameSize:t.length,payloadLength:a},l=this._pcmToUint8Array(s,this._bitDepth);if(setTimeout(()=>{try{this._context.eventBus.emit("inner:audio:payload:send",{payload:l,sampleRate:this._targetSampleRate,channels:this._options?.input?.channels||1,sequenceNumber:d.sequenceNumber,timestamp:d.timestamp,keyFrame:d.keyFrame,frameSize:d.frameSize})}catch(u){m.error("Error emitting inner:audio:payload:send event:",u)}},0),this._wsSender&&this._wsSender.isConnected())try{const u=mc(d),h=new Uint8Array(u.length+l.length);h.set(u,0),h.set(l,u.length),this._wsSender.sendBinary(h),m.debug(`Audio frame sent via WS: seq=${d.sequenceNumber}, samples=${t.length}, size=${h.length} bytes`)}catch(u){m.error("Error sending audio frame via WebSocket:",u)}this._isKeyFrame=!1,this._sequenceNumber=(this._sequenceNumber+1)%4096}catch(e){m.error("Error flushing audio buffer:",e)}}_convertToPCM(e,t){if(t===16){const i=new Int16Array(e.length);for(let s=0;s<e.length;s++){const r=Math.max(-1,Math.min(1,e[s]));i[s]=r<0?r*32768:r*32767}return i}else if(t===32){const i=new Int32Array(e.length);for(let s=0;s<e.length;s++){const r=Math.max(-1,Math.min(1,e[s]));i[s]=r*2147483647}return i}else return m.warn(`Unsupported bit depth: ${t}, using 16-bit`),this._convertToPCM(e,16)}_pcmToUint8Array(e,t){const i=Math.ceil(t/8),s=new Uint8Array(e.length*i),r=new DataView(s.buffer);for(let a=0;a<e.length;a++)t===16?r.setInt16(a*2,e[a],!0):t===32&&r.setInt32(a*4,e[a],!0);return s}_getSampleRateEncoding(e){return e===16e3?0:e===24e3?1:e===48e3?2:(m.warn(`Unsupported sample rate: ${e}, defaulting to 48kHz`),1)}onDispose(){this.stop(),m.info("Audio Frame Sender disposed")}}class vc extends j{emitAudioData(e,t){if(this.onAudioData)try{this.onAudioData(e,t)}catch(i){m.error("Error in audio data callback:",i)}}}const bc=`
56
56
  class AudioResamplerProcessor extends AudioWorkletProcessor {
57
57
  constructor(options) {
58
58
  super();
@@ -107,8 +107,8 @@ class AudioResamplerProcessor extends AudioWorkletProcessor {
107
107
  }
108
108
 
109
109
  registerProcessor('audio-resampler', AudioResamplerProcessor);
110
- `;function uc(){const n=new Blob([lc],{type:"text/javascript"});return URL.createObjectURL(n)}class hc extends dc{constructor(e){super(),this.options=e,this._stream=null,this._audioContext=null,this._sourceNode=null,this._workletNode=null,this._targetSampleRate=xi,this._bitDepth=ps,this._channels=1;const t=e?.input;this._targetSampleRate=t?.sampleRate||xi,this._bitDepth=t?.bitDepth||ps,this._channels=t?.channels||1}async start(){this.ensureNotDisposed();try{const t={audio:this.options?.input?.constraints||{channelCount:this._channels}};this._stream=await navigator.mediaDevices.getUserMedia(t);const r=this._stream.getAudioTracks()[0].getSettings().sampleRate||44100;this._audioContext=new AudioContext({sampleRate:r});const a=uc();await this._audioContext.audioWorklet.addModule(a),this._sourceNode=this._audioContext.createMediaStreamSource(this._stream),this._workletNode=new AudioWorkletNode(this._audioContext,"audio-resampler",{processorOptions:{targetSampleRate:this._targetSampleRate,bitDepth:this._bitDepth,channels:this._channels},numberOfInputs:1,numberOfOutputs:0}),this._workletNode.port.onmessage=o=>{const{type:c,data:d,sampleRate:l}=o.data;c==="audioData"&&d&&this.emitAudioData(d,l)},this._sourceNode.connect(this._workletNode),m.info(`Audio capture started: input=${r}Hz -> output=${this._targetSampleRate}Hz, ${this._bitDepth}bit`)}catch(e){throw H.fromError(e,B.AUDIO_CAPTURE_FAILED)}}stop(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),this._workletNode&&(this._workletNode.port.onmessage=null,this._workletNode.disconnect(),this._workletNode=null),this._sourceNode&&(this._sourceNode.disconnect(),this._sourceNode=null),this._audioContext&&(this._audioContext.close(),this._audioContext=null),m.info("Audio capture stopped")}onDispose(){this.stop()}}class pc{create(e){return new hc(e)}}class mc extends G{constructor(e,t,i){super(),this._source=null,this._isCapturing=!1,this._currentOutputTrackId=null,this._context=e,this._inputPipeline=new Qa(t),this._outputPipeline=new Ya,this._frameSender=new cc(e,t),this._sourceFactory=i||new pc,this._inputPipeline.onProcessedAudio=(s,r)=>{this._context.eventBus.emit("inner:audio:frame:received",{data:s,sampleRate:r})},m.info("Audio Controller created")}setWebSocketSender(e){this._frameSender.setWebSocketSender(e)}async startCapture(){if(this.ensureNotDisposed(),this._isCapturing){m.warn("Audio capture already started");return}try{this._source||(this._source=this._sourceFactory.create(this._context.options.audio),this._source.onAudioData=(e,t)=>{this._inputPipeline.process(e,t)}),await this._source.start(),this._isCapturing=!0,this._frameSender.start(),this._context.eventBus.emit("inner:audio:input:started",void 0),m.info("Audio capture started")}catch(e){throw this._context.emitError(e,B.AUDIO_CAPTURE_START_FAILED)}}stopCapture(){this.ensureNotDisposed(),this._isCapturing&&(this._source&&this._source.stop(),this._frameSender.stop(),this._isCapturing=!1,this._context.eventBus.emit("inner:audio:input:stopped",void 0),m.info("Audio capture stopped"))}get isCapturing(){return this._isCapturing}setOutputTrack(e,t,i){this.ensureNotDisposed(),this._outputPipeline.setTrack(e),this._currentOutputTrackId=t,this._context.eventBus.emit("inner:audio:track:added",{trackId:t,participantId:i}),m.info("Audio output track ready")}removeOutputTrack(e){this.ensureNotDisposed(),this._currentOutputTrackId===e&&(this._outputPipeline.removeTrack(),this._currentOutputTrackId=null,this._context.eventBus.emit("inner:audio:track:removed",{trackId:e}),m.info("Audio output track removed"))}setVolume(e){this.ensureNotDisposed(),this._outputPipeline.setVolume(e),this._context.eventBus.emit("inner:audio:volume:changed",{volume:e}),m.debug(`Audio volume set to: ${e}`)}getVolume(){return this._outputPipeline.getVolume()}mute(){this.ensureNotDisposed(),this._outputPipeline.mute(),this._context.eventBus.emit("inner:audio:muted",void 0),m.debug("Audio muted")}unmute(){this.ensureNotDisposed(),this._outputPipeline.unmute(),this._context.eventBus.emit("inner:audio:unmuted",void 0),m.debug("Audio unmuted")}getOutputElement(){return this._outputPipeline.getAudioElement()}isMuted(){return this._outputPipeline.isMuted()}onDispose(){this.stopCapture(),this._source&&(this._source.dispose(),this._source=null),this._inputPipeline.dispose(),this._outputPipeline.dispose(),this._frameSender.dispose(),m.info("Audio Controller disposed")}}D.ConversationStateType=void 0,(function(n){n.IDLE="idle",n.WAITING="waiting",n.STREAMING="streaming",n.COMPLETED="completed",n.ERROR="error"})(D.ConversationStateType||(D.ConversationStateType={}));class fc extends gs{constructor(){super(...arguments),this._currentState=D.ConversationStateType.IDLE,this.transitionTable=[{from:D.ConversationStateType.IDLE,to:[D.ConversationStateType.WAITING,D.ConversationStateType.ERROR]},{from:D.ConversationStateType.WAITING,to:[D.ConversationStateType.STREAMING,D.ConversationStateType.ERROR]},{from:D.ConversationStateType.STREAMING,to:[D.ConversationStateType.COMPLETED,D.ConversationStateType.ERROR]},{from:D.ConversationStateType.COMPLETED,to:[D.ConversationStateType.IDLE,D.ConversationStateType.WAITING,D.ConversationStateType.ERROR]},{from:D.ConversationStateType.ERROR,to:[D.ConversationStateType.IDLE]}]}reset(){this._currentState=D.ConversationStateType.IDLE}}class _s extends G{constructor(e,t){super(),this._currentQuestion=null,this._currentAnswer=null,this._sessionId=e,this._stateMachine=new fc,m.info(`Conversation session created: ${e}`)}get sessionId(){return this._sessionId}get state(){return this._stateMachine.getCurrentState()}_setQuestion(e){this._currentQuestion=e,this._stateMachine.transitionTo(D.ConversationStateType.WAITING),this._syncContextState()}get currentQuestion(){return this._currentQuestion}_startAnswer(e){this._currentAnswer={questionId:e,text:"",isComplete:!1,timestamp:Date.now()},this._stateMachine.transitionTo(D.ConversationStateType.STREAMING),this._syncContextState()}_appendAnswerChunk(e){this._currentAnswer&&(this._currentAnswer.text+=e)}_completeAnswer(){this._currentAnswer&&(this._currentAnswer.isComplete=!0,this._currentAnswer.completedAt=Date.now()),this._stateMachine.transitionTo(D.ConversationStateType.COMPLETED),this._syncContextState()}get currentAnswer(){return this._currentAnswer}_setError(e){this._stateMachine.transitionTo(D.ConversationStateType.ERROR),this._syncContextState()}_syncContextState(){}handleEvent(e){const t=this._stateMachine.getCurrentState();switch(e.type){case"QUESTION":if(t!==D.ConversationStateType.IDLE&&t!==D.ConversationStateType.COMPLETED){m.warn(`Ignoring QUESTION event in invalid state: ${t}`);return}this._setQuestion(e.payload);break;case"ANSWER_START":if(t!==D.ConversationStateType.WAITING){m.warn(`Ignoring ANSWER_START event in invalid state: ${t}. Expected: WAITING`);return}this._startAnswer(e.payload);break;case"ANSWER_CHUNK":if(t!==D.ConversationStateType.STREAMING){m.warn(`Ignoring ANSWER_CHUNK event in invalid state: ${t}. Expected: STREAMING`);return}this._appendAnswerChunk(e.payload&&e.payload.chunk||""),e.payload&&e.payload.isComplete&&this._completeAnswer();break;case"ANSWER_COMPLETE":if(t!==D.ConversationStateType.STREAMING){m.warn(`Ignoring ANSWER_COMPLETE event in invalid state: ${t}. Expected: STREAMING`);return}this._completeAnswer();break;case"ERROR":this._setError(e.payload);break;default:m.warn(`Unknown event type: ${e.type}`);break}}reset(){this._stateMachine.reset(),this._currentQuestion=null,this._currentAnswer=null}onDispose(){this.reset(),m.info(`Conversation session disposed: ${this._sessionId}`)}}class gc extends G{constructor(){super(...arguments),this._buffers=new Map}appendChunk(e,t){this.ensureNotDisposed();const s=(this._buffers.get(e)||"")+t;return this._buffers.set(e,s),m.debug(`Message chunk appended for question ${e}, length: ${s.length}`),s}getMessage(e){return this._buffers.get(e)||null}complete(e){const t=this.getMessage(e)||"";return this._buffers.delete(e),m.debug(`Message assembly completed for question ${e}, length: ${t.length}`),t}clear(e){this._buffers.delete(e)}onDispose(){this._buffers.clear(),m.info("Message Assembler disposed")}}class vc{generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}generateQuestionId(){return Math.random().toString(36).substring(2,6)}}class bc extends G{constructor(e,t){super(),this._transport=null,this._sessions=new Map,this._context=e,this._assembler=new gc,this._idService=new vc,m.info("Conversation Manager created")}setTransport(e){this._transport=e}async sendQuestion(e,t={speed:100,mood:0,vol:50}){this.ensureNotDisposed();const i=this._idService.generateQuestionId(),s={id:i,text:e,timestamp:Date.now(),inputMode:"text"},r=this._idService.generateSessionId(),a=new _s(r,this._context);if(a.handleEvent({type:"QUESTION",payload:s}),this._sessions.set(i,a),this._transport)try{this._transport.sendText(i,e,200,t)}catch(o){throw m.error("Error sending question via transport:",o),a.handleEvent({type:"ERROR",payload:"Failed to send question"}),this._context.eventBus.emit("inner:sdk:error",{error:o instanceof Error?o:new Error(String(o))}),o}else m.warn("Transport not set, question not sent");return this._context.eventBus.emit("inner:conversation:question:sent",{questionId:i,text:e}),this._context.eventBus.emit("inner:conversation:answer:waiting",{questionId:i}),m.info(`Question sent: ${i}`),i}handleServerPong(){this.ensureNotDisposed(),this._transport&&this._transport.handlePongReceived()}willDisconnect(){this.ensureNotDisposed(),this._transport?.willDisconnect()}handleTextInput(e){this.sendQuestion(e).catch(t=>{m.error("Error sending question:",t)})}handleAnswerChunk(e,t,i){this.ensureNotDisposed();const s=this._sessions.get(e);if(!s){m.warn(`No active session for answer chunk: ${e}`);return}if(s.state===D.ConversationStateType.WAITING&&s.handleEvent({type:"ANSWER_START",payload:e}),i){s.handleEvent({type:"ANSWER_COMPLETE"});const a=this._assembler.complete(e);this._context.eventBus.emit("inner:conversation:answer:completed",{questionId:e,fullAnswer:a});try{s.dispose()}catch(o){m.error("Error disposing session:",o)}this._sessions.delete(e)}else s.handleEvent({type:"ANSWER_CHUNK",payload:{uid:e,chunk:t,isComplete:i}}),this._assembler.appendChunk(e,t),this._context.eventBus.emit("inner:conversation:answer:chunk",{questionId:e,chunk:t,isComplete:i})}handleServerInitiatedMessage(e,t){this.ensureNotDisposed(),this._context.eventBus.emit("inner:conversation:server:message",{questionId:e,message:t,type:"text"})}handleAsrTextReceived(e,t){this.ensureNotDisposed();const i=this._idService.generateSessionId(),s=new _s(i,this._context);s.handleEvent({type:"QUESTION",payload:{id:e,text:t,timestamp:Date.now(),inputMode:"voice"}}),this._sessions.set(e,s),this._context.eventBus.emit("inner:conversation:asr:received",{questionId:e,text:t})}onDispose(){for(const e of this._sessions.values())try{e.dispose()}catch(t){m.error("Error disposing session:",t)}this._sessions.clear(),this._assembler.dispose(),m.info("Conversation Manager disposed")}}class yc extends G{constructor(e,t){super(),this._manager=new bc(e,t),m.info("Conversation Controller created")}get manager(){return this._manager}setTransport(e){this._manager.setTransport(e)}async sendQuestion(e,t){return this.ensureNotDisposed(),this._manager.sendQuestion(e,t)}onDispose(){this._manager.dispose(),m.info("Conversation Controller disposed")}}class Tc extends G{constructor(){super(...arguments),this._tracks=new Map,this._participants=new Map}register(e,t,i){this.ensureNotDisposed(),this._tracks.set(e,t),this._participants.has(i)||this._participants.set(i,new Set),this._participants.get(i).add(e),t.on("ended",()=>{m.debug(`Track ended: ${e}`),this.unregister(e)}),m.debug(`Track registered: ${e} from participant ${i}`)}unregister(e){const t=this._tracks.get(e);if(t){t.stop(),this._tracks.delete(e);for(const[i,s]of this._participants.entries())if(s.has(e)){s.delete(e),s.size===0&&this._participants.delete(i);break}m.debug(`Track unregistered: ${e}`)}}getTrack(e){return this._tracks.get(e)||null}getParticipantTracks(e){const t=this._participants.get(e);return t?Array.from(t):[]}getAllTrackIds(){return Array.from(this._tracks.keys())}getVideoAvailability(){let e=!1,t=!1,i=!1;for(const s of this._tracks.values()){const r=s.mediaStreamTrack;if(r.kind==="video"&&(e=!0,r.readyState==="live"&&(t=!0),r.enabled&&(i=!0),r.readyState==="live"&&r.enabled))return{available:!0}}return e?t?i?{available:!1,reason:ht.NO_VIDEO_TRACK}:{available:!1,reason:ht.TRACK_MUTED}:{available:!1,reason:ht.TRACK_ENDED}:{available:!1,reason:ht.NO_VIDEO_TRACK}}clear(){for(const e of this._tracks.values())e.stop();this._tracks.clear(),this._participants.clear(),m.info("All tracks cleared")}onDispose(){this.clear()}}class ks extends G{constructor(e,t){super(),this._videoController=null,this._room=null,this._context=e,this._trackRegistry=t,this._loosTrackTimer=null,m.info("Video Track Handler created")}setRoom(e){this._room=e}setVideoController(e){this._videoController=e}handleTrackSubscribed(e,t,i){this.ensureNotDisposed(),this._loosTrackTimer&&clearTimeout(this._loosTrackTimer),this._trackRegistry.register(t,e,i),this._videoController&&e.attach(this._videoController.getSource().getInternalElement()),e.on("videoPlaybackStarted",()=>{m.info("inner:rtc:video:available"),this._context.eventBus.emit("inner:rtc:video:available",void 0)}),this._context.eventBus.emit("inner:video:track:added",{trackId:t,participantId:i}),m.debug(`Video track subscribed: ${t}`)}handleTrackUnsubscribed(e,t,i){this.ensureNotDisposed(),this._videoController&&e.detach(this._videoController.getSource().getInternalElement()),e.removeAllListeners(),this._context.eventBus.emit("inner:video:track:removed",{trackId:t,participantId:i}),this._loosTrackTimer&&clearTimeout(this._loosTrackTimer),this._loosTrackTimer=setTimeout(()=>{this._context.eventBus.emit("inner:rtc:video:unavailable",void 0)},Aa),this._trackRegistry.unregister(t),m.debug(`Video track unsubscribed: ${t}`)}supports(e){return e.mediaStreamTrack.kind==="video"}onDispose(){this._loosTrackTimer&&(clearTimeout(this._loosTrackTimer),this._loosTrackTimer=null),m.info("Video Track Handler disposed")}}class Ss extends G{constructor(e,t){super(),this._audioController=null,this._room=null,this._context=e,this._trackRegistry=t,m.info("Audio Track Handler created")}setRoom(e){this._room=e}setAudioController(e){this._audioController=e}handleTrackSubscribed(e,t,i){this.ensureNotDisposed(),this._trackRegistry.register(t,e,i),this._audioController?e.attach(this._audioController.getOutputElement()):this._context.eventBus.emit("inner:audio:track:added",{trackId:t,participantId:i}),m.debug(`Audio track subscribed: ${t}`)}handleTrackUnsubscribed(e,t,i){this.ensureNotDisposed(),this._audioController?(this._audioController.removeOutputTrack(t),e.detach(this._audioController.getOutputElement())):this._context.eventBus.emit("inner:audio:track:removed",{trackId:t}),this._trackRegistry.unregister(t),m.debug(`Audio track unsubscribed: ${t}`)}supports(e){return e.mediaStreamTrack.kind==="audio"}onDispose(){m.info("Audio Track Handler disposed")}}class _c extends G{constructor(e,t){super(),this._room=null,this._context=e,this._trackRegistry=t,this._handlers=[new ks(e,t),new Ss(e,t)],m.info("LiveKit Event Adapter created")}setRoom(e){this._room=e,this._handlers.forEach(t=>{t.setRoom(e)}),console.log("LiveKit room set:",this._room)}setVideoController(e){const t=this._handlers.find(i=>i instanceof ks);t&&t.setVideoController(e)}setAudioController(e){const t=this._handlers.find(i=>i instanceof Ss);t&&t.setAudioController(e)}handleTrackSubscribed(e,t,i){this.ensureNotDisposed();const s=this._findHandler(e);s?s.handleTrackSubscribed(e,t,i):m.warn(`No handler found for track, trackId: ${t}`)}handleTrackUnsubscribed(e,t){this.ensureNotDisposed();const i=this._trackRegistry.getTrack(e);if(i){const s=this._findHandler(i);s?s.handleTrackUnsubscribed(i,e,t):(this._trackRegistry.unregister(e),m.warn(`No handler found for track, trackId: ${e}`))}}_findHandler(e){return this._handlers.find(t=>t.supports(e))||null}onDispose(){this._handlers.forEach(e=>{try{e.dispose()}catch(t){m.error("Error disposing track handler:",t)}}),this._handlers.length=0,m.info("LiveKit Event Adapter disposed")}}function kc(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(i!=="default"&&!(i in n)){var s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,s.get?s:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(n)}var Sc=Object.defineProperty,Cc=(n,e,t)=>e in n?Sc(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Cs=(n,e,t)=>Cc(n,typeof e!="symbol"?e+"":e,t);class he{constructor(){Cs(this,"_locking"),Cs(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(s=>e=()=>{this._locks-=1,s()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function ee(n,e){if(!n)throw new Error(e)}const Ec=34028234663852886e22,Rc=-34028234663852886e22,wc=4294967295,Pc=2147483647,Ic=-2147483648;function Qt(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>Pc||n<Ic)throw new Error("invalid int 32: "+n)}function Ui(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>wc||n<0)throw new Error("invalid uint 32: "+n)}function Es(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>Ec||n<Rc))throw new Error("invalid float 32: "+n)}const Rs=Symbol("@bufbuild/protobuf/enum-type");function Dc(n){const e=n[Rs];return ee(e,"missing enum type on enum object"),e}function ws(n,e,t,i){n[Rs]=Ps(e,t.map(s=>({no:s.no,name:s.name,localName:n[s.no]})))}function Ps(n,e,t){const i=Object.create(null),s=Object.create(null),r=[];for(const a of e){const o=Is(a);r.push(o),i[a.name]=o,s[a.no]=o}return{typeName:n,values:r,findName(a){return i[a]},findNumber(a){return s[a]}}}function Ac(n,e,t){const i={};for(const s of e){const r=Is(s);i[r.localName]=r.no,i[r.no]=r.localName}return ws(i,n,e),i}function Is(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class Fi{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType(),s=i.runtime.bin,r=s.makeReadOptions(t);return s.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const i=this.getType(),s=i.runtime.json,r=s.makeReadOptions(t);return s.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(s){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(s instanceof Error?s.message:String(s)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType(),i=t.runtime.bin,s=i.makeWriteOptions(e),r=s.writerFactory();return i.writeMessage(this,r,s),r.finish()}toJson(e){const t=this.getType(),i=t.runtime.json,s=i.makeWriteOptions(e);return i.writeMessage(this,s)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,(t=e?.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Oc(n,e,t,i){var s;const r=(s=i?.localName)!==null&&s!==void 0?s:e.substring(e.lastIndexOf(".")+1),a={[r]:function(o){n.util.initFields(this),n.util.initPartial(o,this)}}[r];return Object.setPrototypeOf(a.prototype,new Fi),Object.assign(a,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary(o,c){return new a().fromBinary(o,c)},fromJson(o,c){return new a().fromJson(o,c)},fromJsonString(o,c){return new a().fromJsonString(o,c)},equals(o,c){return n.util.equals(a,o,c)}}),a}function Nc(){let n=0,e=0;for(let i=0;i<28;i+=7){let s=this.buf[this.pos++];if(n|=(s&127)<<i,(s&128)==0)return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<i,(s&128)==0)return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function Bi(n,e,t){for(let r=0;r<28;r=r+7){const a=n>>>r,o=!(!(a>>>7)&&e==0),c=(o?a|128:a)&255;if(t.push(c),!o)return}const i=n>>>28&15|(e&7)<<4,s=e>>3!=0;if(t.push((s?i|128:i)&255),!!s){for(let r=3;r<31;r=r+7){const a=e>>>r,o=!!(a>>>7),c=(o?a|128:a)&255;if(t.push(c),!o)return}t.push(e>>>31&1)}}const Yt=4294967296;function Ds(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,s=0;function r(a,o){const c=Number(n.slice(a,o));s*=t,i=i*t+c,i>=Yt&&(s=s+(i/Yt|0),i=i%Yt)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?Os(i,s):Vi(i,s)}function xc(n,e){let t=Vi(n,e);const i=t.hi&2147483648;i&&(t=Os(t.lo,t.hi));const s=As(t.lo,t.hi);return i?"-"+s:s}function As(n,e){if({lo:n,hi:e}=Mc(n,e),e<=2097151)return String(Yt*e+n);const t=n&16777215,i=(n>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+i*6777216+s*6710656,a=i+s*8147497,o=s*2;const c=1e7;return r>=c&&(a+=Math.floor(r/c),r%=c),a>=c&&(o+=Math.floor(a/c),a%=c),o.toString()+Ns(a)+Ns(r)}function Mc(n,e){return{lo:n>>>0,hi:e>>>0}}function Vi(n,e){return{lo:n|0,hi:e|0}}function Os(n,e){return e=~e,n?n=~n+1:e+=1,Vi(n,e)}const Ns=n=>{const e=String(n);return"0000000".slice(e.length)+e};function xs(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function Lc(){let n=this.buf[this.pos++],e=n&127;if((n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,(n&128)==0)return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;(n&128)!==0&&t<10;t++)n=this.buf[this.pos++];if((n&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function Uc(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const s=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),a=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>r||d<s)throw new Error("int64 invalid: ".concat(c));return d},uParse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>o||d<a)throw new Error("uint64 invalid: ".concat(c));return d},enc(c){return n.setBigInt64(0,this.parse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(c){return n.setBigInt64(0,this.uParse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigInt64(0,!0)},uDec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigUint64(0,!0)}}}const t=s=>ee(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),i=s=>ee(/^[0-9]+$/.test(s),"uint64 invalid: ".concat(s));return{zero:"0",supported:!1,parse(s){return typeof s!="string"&&(s=s.toString()),t(s),s},uParse(s){return typeof s!="string"&&(s=s.toString()),i(s),s},enc(s){return typeof s!="string"&&(s=s.toString()),t(s),Ds(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),i(s),Ds(s)},dec(s,r){return xc(s,r)},uDec(s,r){return As(s,r)}}}const X=Uc();var k;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(k||(k={}));var Ge;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(Ge||(Ge={}));function He(n,e,t){if(e===t)return!0;if(n==k.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}switch(n){case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return e==t}return!1}function pt(n,e){switch(n){case k.BOOL:return!1;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return e==0?X.zero:"0";case k.DOUBLE:case k.FLOAT:return 0;case k.BYTES:return new Uint8Array(0);case k.STRING:return"";default:return 0}}function Ms(n,e){switch(n){case k.BOOL:return e===!1;case k.STRING:return e==="";case k.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var ne;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(ne||(ne={}));class Fc{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let s=0;s<this.chunks.length;s++)e+=this.chunks[s].length;let t=new Uint8Array(e),i=0;for(let s=0;s<this.chunks.length;s++)t.set(this.chunks[s],i),i+=this.chunks[s].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Ui(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Qt(e),xs(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Es(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Ui(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Qt(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Qt(e),e=(e<<1^e>>31)>>>0,xs(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=X.enc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=X.uEnc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=X.enc(e);return Bi(t.lo,t.hi,this.buf),this}sint64(e){let t=X.enc(e),i=t.hi>>31,s=t.lo<<1^i,r=(t.hi<<1|t.lo>>>31)^i;return Bi(s,r,this.buf),this}uint64(e){let t=X.uEnc(e);return Bi(t.lo,t.hi,this.buf),this}}class Bc{constructor(e,t){this.varint64=Nc,this.uint32=Lc,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case ne.Varint:for(;this.buf[this.pos++]&128;);break;case ne.Bit64:this.pos+=4;case ne.Bit32:this.pos+=4;break;case ne.LengthDelimited:let s=this.uint32();this.pos+=s;break;case ne.StartGroup:for(;;){const[r,a]=this.tag();if(a===ne.EndGroup){if(t!==void 0&&r!==t)throw new Error("invalid end group tag");break}this.skip(a,r)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return X.dec(...this.varint64())}uint64(){return X.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,X.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return X.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return X.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function Vc(n,e,t,i){let s;return{typeName:e,extendee:t,get field(){if(!s){const r=typeof i=="function"?i():i;r.name=e.split(".").pop(),r.jsonName="[".concat(e,"]"),s=n.util.newFieldList([r]).list()[0]}return s},runtime:n}}function Ls(n){const e=n.field.localName,t=Object.create(null);return t[e]=jc(n),[t,()=>t[e]]}function jc(n){const e=n.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return pt(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function qc(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=n.length-1;t>=0;--t)if(n[t].no==e.no)return[n[t]];return[]}return n.filter(t=>t.no===e.no)}let Fe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Xt=[];for(let n=0;n<Fe.length;n++)Xt[Fe[n].charCodeAt(0)]=n;Xt[45]=Fe.indexOf("+"),Xt[95]=Fe.indexOf("/");const Us={dec(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let t=new Uint8Array(e),i=0,s=0,r,a=0;for(let o=0;o<n.length;o++){if(r=Xt[n.charCodeAt(o)],r===void 0)switch(n[o]){case"=":s=0;case`
111
- `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:a=r,s=1;break;case 1:t[i++]=a<<2|(r&48)>>4,a=r,s=2;break;case 2:t[i++]=(a&15)<<4|(r&60)>>2,a=r,s=3;break;case 3:t[i++]=(a&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return t.subarray(0,i)},enc(n){let e="",t=0,i,s=0;for(let r=0;r<n.length;r++)switch(i=n[r],t){case 0:e+=Fe[i>>2],s=(i&3)<<4,t=1;break;case 1:e+=Fe[s|i>>4],s=(i&15)<<2,t=2;break;case 2:e+=Fe[s|i>>6],e+=Fe[i&63],t=0;break}return t&&(e+=Fe[s],e+="=",t==1&&(e+="=")),e}};function Wc(n,e,t){Bs(e,n);const i=e.runtime.bin.makeReadOptions(t),s=qc(n.getType().runtime.bin.listUnknownFields(n),e.field),[r,a]=Ls(e);for(const o of s)e.runtime.bin.readField(r,i.readerFactory(o.data),e.field,o.wireType,i);return a()}function Kc(n,e,t,i){Bs(e,n);const s=e.runtime.bin.makeReadOptions(i),r=e.runtime.bin.makeWriteOptions(i);if(Fs(n,e)){const d=n.getType().runtime.bin.listUnknownFields(n).filter(l=>l.no!=e.field.no);n.getType().runtime.bin.discardUnknownFields(n);for(const l of d)n.getType().runtime.bin.onUnknownField(n,l.no,l.wireType,l.data)}const a=r.writerFactory();let o=e.field;!o.opt&&!o.repeated&&(o.kind=="enum"||o.kind=="scalar")&&(o=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(o,t,a,r);const c=s.readerFactory(a.finish());for(;c.pos<c.len;){const[d,l]=c.tag(),u=c.skip(l,d);n.getType().runtime.bin.onUnknownField(n,d,l,u)}}function Fs(n,e){const t=n.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(n).find(i=>i.no==e.field.no)}function Bs(n,e){ee(n.extendee.typeName==e.getType().typeName,"extension ".concat(n.typeName," can only be applied to message ").concat(n.extendee.typeName))}function Vs(n,e){const t=n.localName;if(n.repeated)return e[t].length>0;if(n.oneof)return e[n.oneof.localName].case===t;switch(n.kind){case"enum":case"scalar":return n.opt||n.req?e[t]!==void 0:n.kind=="enum"?e[t]!==n.T.values[0].no:!Ms(n.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function js(n,e){const t=n.localName,i=!n.opt&&!n.req;if(n.repeated)e[t]=[];else if(n.oneof)e[n.oneof.localName]={case:void 0};else switch(n.kind){case"map":e[t]={};break;case"enum":e[t]=i?n.T.values[0].no:void 0;break;case"scalar":e[t]=i?pt(n.T,n.L):void 0;break;case"message":e[t]=void 0;break}}function Be(n,e){if(n===null||typeof n!="object"||!Object.getOwnPropertyNames(Fi.prototype).every(i=>i in n&&typeof n[i]=="function"))return!1;const t=n.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function qs(n,e){return Be(e)||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}k.DOUBLE,k.FLOAT,k.INT64,k.UINT64,k.INT32,k.UINT32,k.BOOL,k.STRING,k.BYTES;const Ws={ignoreUnknownFields:!1},Ks={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Gc(n){return n?Object.assign(Object.assign({},Ws),n):Ws}function Hc(n){return n?Object.assign(Object.assign({},Ks),n):Ks}const Zt=Symbol(),ei=Symbol();function zc(){return{makeReadOptions:Gc,makeWriteOptions:Hc,readMessage(n,e,t,i){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(n.typeName," from JSON: ").concat(Oe(e)));i=i??new n;const s=new Map,r=t.typeRegistry;for(const[a,o]of Object.entries(e)){const c=n.fields.findJsonName(a);if(c){if(c.oneof){if(o===null&&c.kind=="scalar")continue;const d=s.get(c.oneof);if(d!==void 0)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(d,'", "').concat(a,'"'));s.set(c.oneof,a)}Gs(i,o,c,t,n)}else{let d=!1;if(r?.findExtension&&a.startsWith("[")&&a.endsWith("]")){const l=r.findExtension(a.substring(1,a.length-1));if(l&&l.extendee.typeName==n.typeName){d=!0;const[u,h]=Ls(l);Gs(u,o,l.field,t,l),Kc(i,l,h(),t)}}if(!d&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: key "').concat(a,'" is unknown'))}}return i},writeMessage(n,e){const t=n.getType(),i={};let s;try{for(s of t.fields.byNumber()){if(!Vs(s,n)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!$c(s))continue}const a=s.oneof?n[s.oneof.localName].value:n[s.localName],o=Hs(s,a,e);o!==void 0&&(i[e.useProtoFieldName?s.name:s.jsonName]=o)}const r=e.typeRegistry;if(r?.findExtensionFor)for(const a of t.runtime.bin.listUnknownFields(n)){const o=r.findExtensionFor(t.typeName,a.no);if(o&&Fs(n,o)){const c=Wc(n,o,e),d=Hs(o.field,c,e);d!==void 0&&(i[o.field.jsonName]=d)}}}catch(r){const a=s?"cannot encode field ".concat(t.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),o=r instanceof Error?r.message:String(r);throw new Error(a+(o.length>0?": ".concat(o):""))}return i},readScalar(n,e,t){return Ot(n,e,t??Ge.BIGINT,!0)},writeScalar(n,e,t){if(e!==void 0&&(t||Ms(n,e)))return ti(n,e)},debug:Oe}}function Oe(n){if(n===null)return"null";switch(typeof n){case"object":return Array.isArray(n)?"array":"object";case"string":return n.length>100?"string":'"'.concat(n.split('"').join('\\"'),'"');default:return String(n)}}function Gs(n,e,t,i,s){let r=t.localName;if(t.repeated){if(ee(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Oe(e)));const a=n[r];for(const o of e){if(o===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Oe(o)));switch(t.kind){case"message":a.push(t.T.fromJson(o,i));break;case"enum":const c=ji(t.T,o,i.ignoreUnknownFields,!0);c!==ei&&a.push(c);break;case"scalar":try{a.push(Ot(t.T,o,t.L,!0))}catch(d){let l="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Oe(o));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Oe(e)));const a=n[r];for(const[o,c]of Object.entries(e)){if(c===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: map value null"));let d;try{d=Jc(t.K,o)}catch(l){let u="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Oe(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}switch(t.V.kind){case"message":a[d]=t.V.T.fromJson(c,i);break;case"enum":const l=ji(t.V.T,c,i.ignoreUnknownFields,!0);l!==ei&&(a[d]=l);break;case"scalar":try{a[d]=Ot(t.V.T,c,Ge.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Oe(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}}else switch(t.oneof&&(n=n[t.oneof.localName]={case:r},r="value"),t.kind){case"message":const a=t.T;if(e===null&&a.typeName!="google.protobuf.Value")return;let o=n[r];Be(o)?o.fromJson(e,i):(n[r]=o=a.fromJson(e,i),a.fieldWrapper&&!t.oneof&&(n[r]=a.fieldWrapper.unwrapField(o)));break;case"enum":const c=ji(t.T,e,i.ignoreUnknownFields,!1);switch(c){case Zt:js(t,n);break;case ei:break;default:n[r]=c;break}break;case"scalar":try{const d=Ot(t.T,e,t.L,!1);d===Zt?js(t,n):n[r]=d}catch(d){let l="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Oe(e));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}function Jc(n,e){if(n===k.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Ot(n,e,Ge.BIGINT,!0).toString()}function Ot(n,e,t,i){if(e===null)return i?pt(n,t):Zt;switch(n){case k.DOUBLE:case k.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const s=Number(e);if(Number.isNaN(s)||!Number.isFinite(s))break;return n==k.FLOAT&&Es(s),s;case k.INT32:case k.FIXED32:case k.SFIXED32:case k.SINT32:case k.UINT32:let r;if(typeof e=="number"?r=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(r=Number(e)),r===void 0)break;return n==k.UINT32||n==k.FIXED32?Ui(r):Qt(r),r;case k.INT64:case k.SFIXED64:case k.SINT64:if(typeof e!="number"&&typeof e!="string")break;const a=X.parse(e);return t?a.toString():a;case k.FIXED64:case k.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=X.uParse(e);return t?o.toString():o;case k.BOOL:if(typeof e!="boolean")break;return e;case k.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case k.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return Us.dec(e)}throw new Error}function ji(n,e,t,i){if(e===null)return n.typeName=="google.protobuf.NullValue"?0:i?n.values[0].no:Zt;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const s=n.findName(e);if(s!==void 0)return s.no;if(t)return ei;break}throw new Error("cannot decode enum ".concat(n.typeName," from JSON: ").concat(Oe(e)))}function $c(n){return n.repeated||n.kind=="map"?!0:!(n.oneof||n.kind=="message"||n.opt||n.req)}function Hs(n,e,t){if(n.kind=="map"){ee(typeof e=="object"&&e!=null);const i={},s=Object.entries(e);switch(n.V.kind){case"scalar":for(const[a,o]of s)i[a.toString()]=ti(n.V.T,o);break;case"message":for(const[a,o]of s)i[a.toString()]=o.toJson(t);break;case"enum":const r=n.V.T;for(const[a,o]of s)i[a.toString()]=qi(r,o,t.enumAsInteger);break}return t.emitDefaultValues||s.length>0?i:void 0}if(n.repeated){ee(Array.isArray(e));const i=[];switch(n.kind){case"scalar":for(let s=0;s<e.length;s++)i.push(ti(n.T,e[s]));break;case"enum":for(let s=0;s<e.length;s++)i.push(qi(n.T,e[s],t.enumAsInteger));break;case"message":for(let s=0;s<e.length;s++)i.push(e[s].toJson(t));break}return t.emitDefaultValues||i.length>0?i:void 0}switch(n.kind){case"scalar":return ti(n.T,e);case"enum":return qi(n.T,e,t.enumAsInteger);case"message":return qs(n.T,e).toJson(t)}}function qi(n,e,t){var i;if(ee(typeof e=="number"),n.typeName=="google.protobuf.NullValue")return null;if(t)return e;const s=n.findNumber(e);return(i=s?.name)!==null&&i!==void 0?i:e}function ti(n,e){switch(n){case k.INT32:case k.SFIXED32:case k.SINT32:case k.FIXED32:case k.UINT32:return ee(typeof e=="number"),e;case k.FLOAT:case k.DOUBLE:return ee(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case k.STRING:return ee(typeof e=="string"),e;case k.BOOL:return ee(typeof e=="boolean"),e;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return ee(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case k.BYTES:return ee(e instanceof Uint8Array),Us.enc(e)}}const mt=Symbol("@bufbuild/protobuf/unknown-fields"),zs={readUnknownFields:!0,readerFactory:n=>new Bc(n)},Js={writeUnknownFields:!0,writerFactory:()=>new Fc};function Qc(n){return n?Object.assign(Object.assign({},zs),n):zs}function Yc(n){return n?Object.assign(Object.assign({},Js),n):Js}function Xc(){return{makeReadOptions:Qc,makeWriteOptions:Yc,listUnknownFields(n){var e;return(e=n[mt])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[mt]},writeUnknownFields(n,e){const i=n[mt];if(i)for(const s of i)e.tag(s.no,s.wireType).raw(s.data)},onUnknownField(n,e,t,i){const s=n;Array.isArray(s[mt])||(s[mt]=[]),s[mt].push({no:e,wireType:t,data:i})},readMessage(n,e,t,i,s){const r=n.getType(),a=s?e.len:e.pos+t;let o,c;for(;e.pos<a&&([o,c]=e.tag(),!(s===!0&&c==ne.EndGroup));){const d=r.fields.find(o);if(!d){const l=e.skip(c,o);i.readUnknownFields&&this.onUnknownField(n,o,c,l);continue}$s(n,e,d,c,i)}if(s&&(c!=ne.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:$s,writeMessage(n,e,t){const i=n.getType();for(const s of i.fields.byNumber()){if(!Vs(s,n)){if(s.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(s.name," to binary: required field not set"));continue}const r=s.oneof?n[s.oneof.localName].value:n[s.localName];Qs(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(n,e),e},writeField(n,e,t,i){e!==void 0&&Qs(n,e,t,i)}}}function $s(n,e,t,i,s){let{repeated:r,localName:a}=t;switch(t.oneof&&(n=n[t.oneof.localName],n.case!=a&&delete n.value,n.case=a,a="value"),t.kind){case"scalar":case"enum":const o=t.kind=="enum"?k.INT32:t.T;let c=ni;if(t.kind=="scalar"&&t.L>0&&(c=ed),r){let h=n[a];if(i==ne.LengthDelimited&&o!=k.STRING&&o!=k.BYTES){let b=e.uint32()+e.pos;for(;e.pos<b;)h.push(c(e,o))}else h.push(c(e,o))}else n[a]=c(e,o);break;case"message":const d=t.T;r?n[a].push(ii(e,new d,s,t)):Be(n[a])?ii(e,n[a],s,t):(n[a]=ii(e,new d,s,t),d.fieldWrapper&&!t.oneof&&!t.repeated&&(n[a]=d.fieldWrapper.unwrapField(n[a])));break;case"map":let[l,u]=Zc(t,e,s);n[a][l]=u;break}}function ii(n,e,t,i){const s=e.getType().runtime.bin,r=i?.delimited;return s.readMessage(e,n,r?i.no:n.uint32(),t,r),e}function Zc(n,e,t){const i=e.uint32(),s=e.pos+i;let r,a;for(;e.pos<s;){const[o]=e.tag();switch(o){case 1:r=ni(e,n.K);break;case 2:switch(n.V.kind){case"scalar":a=ni(e,n.V.T);break;case"enum":a=e.int32();break;case"message":a=ii(e,new n.V.T,t,void 0);break}break}}if(r===void 0&&(r=pt(n.K,Ge.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),a===void 0)switch(n.V.kind){case"scalar":a=pt(n.V.T,Ge.BIGINT);break;case"enum":a=n.V.T.values[0].no;break;case"message":a=new n.V.T;break}return[r,a]}function ed(n,e){const t=ni(n,e);return typeof t=="bigint"?t.toString():t}function ni(n,e){switch(e){case k.STRING:return n.string();case k.BOOL:return n.bool();case k.DOUBLE:return n.double();case k.FLOAT:return n.float();case k.INT32:return n.int32();case k.INT64:return n.int64();case k.UINT64:return n.uint64();case k.FIXED64:return n.fixed64();case k.BYTES:return n.bytes();case k.FIXED32:return n.fixed32();case k.SFIXED32:return n.sfixed32();case k.SFIXED64:return n.sfixed64();case k.SINT64:return n.sint64();case k.UINT32:return n.uint32();case k.SINT32:return n.sint32()}}function Qs(n,e,t,i){ee(e!==void 0);const s=n.repeated;switch(n.kind){case"scalar":case"enum":let r=n.kind=="enum"?k.INT32:n.T;if(s)if(ee(Array.isArray(e)),n.packed)id(t,r,n.no,e);else for(const a of e)Nt(t,r,n.no,a);else Nt(t,r,n.no,e);break;case"message":if(s){ee(Array.isArray(e));for(const a of e)Ys(t,i,n,a)}else Ys(t,i,n,e);break;case"map":ee(typeof e=="object"&&e!=null);for(const[a,o]of Object.entries(e))td(t,i,n,a,o);break}}function td(n,e,t,i,s){n.tag(t.no,ne.LengthDelimited),n.fork();let r=i;switch(t.K){case k.INT32:case k.FIXED32:case k.UINT32:case k.SFIXED32:case k.SINT32:r=Number.parseInt(i);break;case k.BOOL:ee(i=="true"||i=="false"),r=i=="true";break}switch(Nt(n,t.K,1,r),t.V.kind){case"scalar":Nt(n,t.V.T,2,s);break;case"enum":Nt(n,k.INT32,2,s);break;case"message":ee(s!==void 0),n.tag(2,ne.LengthDelimited).bytes(s.toBinary(e));break}n.join()}function Ys(n,e,t,i){const s=qs(t.T,i);t.delimited?n.tag(t.no,ne.StartGroup).raw(s.toBinary(e)).tag(t.no,ne.EndGroup):n.tag(t.no,ne.LengthDelimited).bytes(s.toBinary(e))}function Nt(n,e,t,i){ee(i!==void 0);let[s,r]=Xs(e);n.tag(t,s)[r](i)}function id(n,e,t,i){if(!i.length)return;n.tag(t,ne.LengthDelimited).fork();let[,s]=Xs(e);for(let r=0;r<i.length;r++)n[s](i[r]);n.join()}function Xs(n){let e=ne.Varint;switch(n){case k.BYTES:case k.STRING:e=ne.LengthDelimited;break;case k.DOUBLE:case k.FIXED64:case k.SFIXED64:e=ne.Bit64;break;case k.FIXED32:case k.SFIXED32:case k.FLOAT:e=ne.Bit32;break}const t=k[n].toLowerCase();return[e,t]}function nd(){return{setEnumType:ws,initPartial(n,e){if(n===void 0)return;const t=e.getType();for(const i of t.fields.byMember()){const s=i.localName,r=e,a=n;if(a[s]!=null)switch(i.kind){case"oneof":const o=a[s].case;if(o===void 0)continue;const c=i.findField(o);let d=a[s].value;c&&c.kind=="message"&&!Be(d,c.T)?d=new c.T(d):c&&c.kind==="scalar"&&c.T===k.BYTES&&(d=xt(d)),r[s]={case:o,value:d};break;case"scalar":case"enum":let l=a[s];i.T===k.BYTES&&(l=i.repeated?l.map(xt):xt(l)),r[s]=l;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===k.BYTES)for(const[f,b]of Object.entries(a[s]))r[s][f]=xt(b);else Object.assign(r[s],a[s]);break;case"message":const h=i.V.T;for(const f of Object.keys(a[s])){let b=a[s][f];h.fieldWrapper||(b=new h(b)),r[s][f]=b}break}break;case"message":const u=i.T;if(i.repeated)r[s]=a[s].map(h=>Be(h,u)?h:new u(h));else{const h=a[s];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[s]=xt(h):r[s]=h:r[s]=Be(h,u)?h:new u(h)}break}}},equals(n,e,t){return e===t?!0:!e||!t?!1:n.fields.byMember().every(i=>{const s=e[i.localName],r=t[i.localName];if(i.repeated){if(s.length!==r.length)return!1;switch(i.kind){case"message":return s.every((a,o)=>i.T.equals(a,r[o]));case"scalar":return s.every((a,o)=>He(i.T,a,r[o]));case"enum":return s.every((a,o)=>He(k.INT32,a,r[o]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":let a=s,o=r;return i.T.fieldWrapper&&(a!==void 0&&!Be(a)&&(a=i.T.fieldWrapper.wrapField(a)),o!==void 0&&!Be(o)&&(o=i.T.fieldWrapper.wrapField(o))),i.T.equals(a,o);case"enum":return He(k.INT32,s,r);case"scalar":return He(i.T,s,r);case"oneof":if(s.case!==r.case)return!1;const c=i.findField(s.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(s.value,r.value);case"enum":return He(k.INT32,s.value,r.value);case"scalar":return He(c.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const d=Object.keys(s).concat(Object.keys(r));switch(i.V.kind){case"message":const l=i.V.T;return d.every(h=>l.equals(s[h],r[h]));case"enum":return d.every(h=>He(k.INT32,s[h],r[h]));case"scalar":const u=i.V.T;return d.every(h=>He(u,s[h],r[h]))}break}})},clone(n){const e=n.getType(),t=new e,i=t;for(const s of e.fields.byMember()){const r=n[s.localName];let a;if(s.repeated)a=r.map(si);else if(s.kind=="map"){a=i[s.localName];for(const[o,c]of Object.entries(r))a[o]=si(c)}else s.kind=="oneof"?a=s.findField(r.case)?{case:r.case,value:si(r.value)}:{case:void 0}:a=si(r);i[s.localName]=a}for(const s of e.runtime.bin.listUnknownFields(n))e.runtime.bin.onUnknownField(i,s.no,s.wireType,s.data);return t}}}function si(n){if(n===void 0)return n;if(Be(n))return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function xt(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function sd(n,e,t){return{syntax:n,json:zc(),bin:Xc(),util:Object.assign(Object.assign({},nd()),{newFieldList:e,initFields:t}),makeMessageType(i,s,r){return Oc(this,i,s,r)},makeEnum:Ac,makeEnumType:Ps,getEnumType:Dc,makeExtension(i,s,r){return Vc(this,i,s,r)}}}class rd{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const i of this.list())t[i.jsonName]=t[i.name]=i;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const i of this.list())t[i.no]=i;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function Zs(n,e){const t=er(n);return e?t:ud(ld(t))}function od(n){return Zs(n,!1)}const ad=er;function er(n){let e=!1;const t=[];for(let i=0;i<n.length;i++){let s=n.charAt(i);switch(s){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(s),e=!1;break;default:e&&(e=!1,s=s.toUpperCase()),t.push(s);break}}return t.join("")}const cd=new Set(["constructor","toString","toJSON","valueOf"]),dd=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),tr=n=>"".concat(n,"$"),ld=n=>dd.has(n)?tr(n):n,ud=n=>cd.has(n)?tr(n):n;class hd{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=od(e)}addField(e){ee(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function pd(n,e){var t,i,s,r,a,o;const c=[];let d;for(const l of typeof n=="function"?n():n){const u=l;if(u.localName=Zs(l.name,l.oneof!==void 0),u.jsonName=(t=l.jsonName)!==null&&t!==void 0?t:ad(l.name),u.repeated=(i=l.repeated)!==null&&i!==void 0?i:!1,l.kind=="scalar"&&(u.L=(s=l.L)!==null&&s!==void 0?s:Ge.BIGINT),u.delimited=(r=l.delimited)!==null&&r!==void 0?r:!1,u.req=(a=l.req)!==null&&a!==void 0?a:!1,u.opt=(o=l.opt)!==null&&o!==void 0?o:!1,l.packed===void 0&&(u.packed=l.kind=="enum"||l.kind=="scalar"&&l.T!=k.BYTES&&l.T!=k.STRING),l.oneof!==void 0){const h=typeof l.oneof=="string"?l.oneof:l.oneof.name;(!d||d.name!=h)&&(d=new hd(h)),u.oneof=d,d.addField(u)}c.push(u)}return c}const g=sd("proto3",n=>new rd(n,e=>pd(e)),n=>{for(const e of n.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,i=n;if(e.repeated){i[t]=[];continue}switch(e.kind){case"oneof":i[t]={case:void 0};break;case"enum":i[t]=0;break;case"map":i[t]={};break;case"scalar":i[t]=pt(e.T,e.L);break}}});class ve extends Fi{constructor(e){super(),this.seconds=X.zero,this.nanos=0,g.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(g.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const s=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(s))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(s<Date.parse("0001-01-01T00:00:00Z")||s>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=X.parse(s/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const s=(this.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?i="."+s.substring(0,3)+"Z":s.substring(6)==="000"?i="."+s.substring(0,6)+"Z":i="."+s+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return ve.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new ve({seconds:X.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new ve().fromBinary(e,t)}static fromJson(e,t){return new ve().fromJson(e,t)}static fromJsonString(e,t){return new ve().fromJsonString(e,t)}static equals(e,t){return g.util.equals(ve,e,t)}}ve.runtime=g,ve.typeName="google.protobuf.Timestamp",ve.fields=g.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const md=g.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ve},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:fd,repeated:!0},{no:5,name:"events",kind:"message",T:vd,repeated:!0}]),fd=g.makeMessageType("livekit.TimeSeriesMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:gd,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),gd=g.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ve},{no:3,name:"value",kind:"scalar",T:2}]),vd=g.makeMessageType("livekit.EventMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:ve},{no:7,name:"normalized_end_timestamp",kind:"message",T:ve,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),ir=g.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Re=g.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),oe=g.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),Wi=g.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Mt=g.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Lt=g.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),ke=g.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),rt=g.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),bd=g.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),ae=g.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),ri=g.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:oi,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:gr}]),oi=g.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),yd=g.makeMessageType("livekit.ParticipantPermission",()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:g.getEnumType(oe),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}]),ot=g.makeMessageType("livekit.ParticipantInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:g.getEnumType(ft)},{no:4,name:"tracks",kind:"message",T:gt,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:yd},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:g.getEnumType(Ut)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:g.getEnumType(ke)},{no:18,name:"kind_details",kind:"enum",T:g.getEnumType(Td),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:Ki,repeated:!0}]),ft=g.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Ut=g.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"},{no:8,name:"BRIDGE"}]),Td=g.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"},{no:2,name:"CONNECTOR_WHATSAPP"},{no:3,name:"CONNECTOR_TWILIO"},{no:4,name:"BRIDGE_RTSP"}]),se=g.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),_d=g.makeMessageType("livekit.SimulcastCodecInfo",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:ze,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:g.getEnumType(nr)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),gt=g.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:g.getEnumType(Re)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:g.getEnumType(oe)},{no:10,name:"layers",kind:"message",T:ze,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:_d,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:g.getEnumType(se)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:gr},{no:19,name:"audio_features",kind:"enum",T:g.getEnumType(ae),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:g.getEnumType(ir)}]),Ki=g.makeMessageType("livekit.DataTrackInfo",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"sid",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"encryption",kind:"enum",T:g.getEnumType(se)}]),kd=g.makeMessageType("livekit.DataTrackSubscriptionOptions",()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}]),ze=g.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:g.getEnumType(Wi)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9},{no:8,name:"repair_ssrc",kind:"scalar",T:13}]),nr=g.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),pe=g.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:g.getEnumType(j)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:Gi,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Sd,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:ar,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Cd,oneof:"value"},{no:8,name:"metrics",kind:"message",T:md,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:ai,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Hi,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:zi,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Ji,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:ci,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:di,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:li,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:sr,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),j=g.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),sr=g.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:g.getEnumType(se)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}]),rr=g.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:Gi,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:ai,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:Hi,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:zi,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Ji,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:ci,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:di,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:li,oneof:"value"}]),Sd=g.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:or,repeated:!0}]),or=g.makeMessageType("livekit.SpeakerInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]),Gi=g.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}]),ar=g.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),Cd=g.makeMessageType("livekit.Transcription",()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:Ed,repeated:!0}]),Ed=g.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),ai=g.makeMessageType("livekit.ChatMessage",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}]),Hi=g.makeMessageType("livekit.RpcRequest",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}]),zi=g.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Ji=g.makeMessageType("livekit.RpcResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:cr,oneof:"value"}]),cr=g.makeMessageType("livekit.RpcError",()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}]),dr=g.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),lr=g.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:g.getEnumType(ur)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}]),ur=g.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),hr=g.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:g.getEnumType(pr)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}]),pr=g.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),mr=g.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:fr},{no:2,name:"screen",kind:"message",T:fr},{no:3,name:"resume_connection",kind:"enum",T:g.getEnumType(Lt)},{no:4,name:"disabled_codecs",kind:"message",T:Rd},{no:5,name:"force_relay",kind:"enum",T:g.getEnumType(Lt)}]),fr=g.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:g.getEnumType(Lt)}]),Rd=g.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:oi,repeated:!0},{no:2,name:"publish",kind:"message",T:oi,repeated:!0}]),gr=g.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),$i=g.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),vr=g.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:g.getEnumType($i)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}],{localName:"DataStream_TextHeader"}),br=g.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),ci=g.makeMessageType("livekit.DataStream.Header",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:g.getEnumType(se)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:vr,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:br,oneof:"content_header"}],{localName:"DataStream_Header"}),di=g.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),li=g.makeMessageType("livekit.DataStream.Trailer",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"DataStream_Trailer"}),wd=g.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),we=g.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Qi=g.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Pd=g.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Id=g.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Je,oneof:"message"},{no:2,name:"answer",kind:"message",T:Je,oneof:"message"},{no:3,name:"trickle",kind:"message",T:ui,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Ft,oneof:"message"},{no:5,name:"mute",kind:"message",T:hi,oneof:"message"},{no:6,name:"subscription",kind:"message",T:pi,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Sr,oneof:"message"},{no:8,name:"leave",kind:"message",T:mi,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Er,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Pr,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:nn,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Ne,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:en,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Ar,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Zi,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Cr,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:Tr,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:kr,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:Ud,oneof:"message"}]),yr=g.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:Nd,oneof:"message"},{no:2,name:"answer",kind:"message",T:Je,oneof:"message"},{no:3,name:"offer",kind:"message",T:Je,oneof:"message"},{no:4,name:"trickle",kind:"message",T:ui,oneof:"message"},{no:5,name:"update",kind:"message",T:Ld,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Xi,oneof:"message"},{no:8,name:"leave",kind:"message",T:mi,oneof:"message"},{no:9,name:"mute",kind:"message",T:hi,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Bd,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Vd,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:qd,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Kd,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Hd,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Jd,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Md,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:xd,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Qd,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Zd,oneof:"message"},{no:22,name:"request_response",kind:"message",T:el,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:tl,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:$d,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:rl,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:zd,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:_r,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:Dd,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:Ad,oneof:"message"}]),Yi=g.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:ze,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:g.getEnumType(nr)}]),Ft=g.makeMessageType("livekit.AddTrackRequest",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:g.getEnumType(Re)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:g.getEnumType(oe)},{no:9,name:"layers",kind:"message",T:ze,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Yi,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:g.getEnumType(se)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:g.getEnumType(ir)},{no:17,name:"audio_features",kind:"enum",T:g.getEnumType(ae),repeated:!0}]),Tr=g.makeMessageType("livekit.PublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"encryption",kind:"enum",T:g.getEnumType(se)}]),_r=g.makeMessageType("livekit.PublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:Ki}]),kr=g.makeMessageType("livekit.UnpublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}]),Dd=g.makeMessageType("livekit.UnpublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:Ki}]),Ad=g.makeMessageType("livekit.DataTrackSubscriberHandles",()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:Od}}]),Od=g.makeMessageType("livekit.DataTrackSubscriberHandles.PublishedDataTrack",()=>[{no:1,name:"publisher_identity",kind:"scalar",T:9},{no:2,name:"publisher_sid",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9}],{localName:"DataTrackSubscriberHandles_PublishedDataTrack"}),ui=g.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:g.getEnumType(we)},{no:3,name:"final",kind:"scalar",T:8}]),hi=g.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),Nd=g.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:ri},{no:2,name:"participant",kind:"message",T:ot},{no:3,name:"other_participants",kind:"message",T:ot,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Rr,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:mr},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:lr},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:oi,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),xd=g.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Rr,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:mr},{no:3,name:"server_info",kind:"message",T:lr},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Xi=g.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:gt}]),Md=g.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Je=g.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}]),Ld=g.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:ot,repeated:!0}]),pi=g.makeMessageType("livekit.UpdateSubscription",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:dr,repeated:!0}]),Ud=g.makeMessageType("livekit.UpdateDataSubscription",()=>[{no:1,name:"updates",kind:"message",T:Fd,repeated:!0}]),Fd=g.makeMessageType("livekit.UpdateDataSubscription.Update",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"options",kind:"message",T:kd}],{localName:"UpdateDataSubscription_Update"}),Sr=g.makeMessageType("livekit.UpdateTrackSettings",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:g.getEnumType(Wi)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}]),Zi=g.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:g.getEnumType(ae),repeated:!0}]),Cr=g.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),mi=g.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:g.getEnumType(ke)},{no:3,name:"action",kind:"enum",T:g.getEnumType(vt)},{no:4,name:"regions",kind:"message",T:Yd}]),vt=g.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Er=g.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:ze,repeated:!0}]),en=g.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),Rr=g.makeMessageType("livekit.ICEServer",()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}]),Bd=g.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:or,repeated:!0}]),Vd=g.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:ri}]),jd=g.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:g.getEnumType(Mt)},{no:3,name:"score",kind:"scalar",T:2}]),qd=g.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:jd,repeated:!0}]),Wd=g.makeMessageType("livekit.StreamStateInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:g.getEnumType(Qi)}]),Kd=g.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:Wd,repeated:!0}]),tn=g.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:g.getEnumType(Wi)},{no:2,name:"enabled",kind:"scalar",T:8}]),Gd=g.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:tn,repeated:!0}]),Hd=g.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:tn,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Gd,repeated:!0}]),zd=g.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:wd,repeated:!0}]),wr=g.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}]),Pr=g.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:wr,repeated:!0}]),Jd=g.makeMessageType("livekit.SubscriptionPermissionUpdate",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}]),$d=g.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:ri},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:ot},{no:4,name:"other_participants",kind:"message",T:ot,repeated:!0}]),nn=g.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Je},{no:2,name:"subscription",kind:"message",T:pi},{no:3,name:"publish_tracks",kind:"message",T:Xi,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Dr,repeated:!0},{no:5,name:"offer",kind:"message",T:Je},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Ir,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:_r,repeated:!0}]),Ir=g.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Dr=g.makeMessageType("livekit.DataChannelInfo",()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:g.getEnumType(we)}]),Ne=g.makeMessageType("livekit.SimulateScenario",()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:g.getEnumType(Pd),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}]),Ar=g.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),Qd=g.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),Yd=g.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:Xd,repeated:!0}]),Xd=g.makeMessageType("livekit.RegionInfo",()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]),Zd=g.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:g.getEnumType(bd)}]),el=g.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:g.getEnumType(sn)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:ui,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Ft,oneof:"request"},{no:6,name:"mute",kind:"message",T:hi,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:en,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Zi,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Cr,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:Tr,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:kr,oneof:"request"}]),sn=g.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"},{no:7,name:"INVALID_HANDLE"},{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"}]),tl=g.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Or=g.makeMessageType("livekit.ConnectionSettings",()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8},{no:5,name:"auto_subscribe_data_track",kind:"scalar",T:8,opt:!0}]),il=g.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:hr},{no:2,name:"connection_settings",kind:"message",T:Or},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:Ft,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:Je},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:g.getEnumType(rt)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:nn}]),nl=g.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:g.getEnumType(sl)},{no:2,name:"join_request",kind:"scalar",T:12}]),sl=g.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),rl=g.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function ol(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var fi={exports:{}},al=fi.exports,Nr;function cl(){return Nr||(Nr=1,(function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(al,function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},a=null;function o(v,R){var _=v[R];if(typeof _.bind=="function")return _.bind(v);try{return Function.prototype.bind.call(_,v)}catch{return function(){return Function.prototype.apply.apply(_,[v,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(v){return v==="debug"&&(v="log"),typeof console===t?!1:v==="trace"&&i?c:console[v]!==void 0?o(console,v):console.log!==void 0?o(console,"log"):e}function l(){for(var v=this.getLevel(),R=0;R<s.length;R++){var _=s[R];this[_]=R<v?e:this.methodFactory(_,v,this.name)}if(this.log=this.debug,typeof console===t&&v<this.levels.SILENT)return"No console available for logging"}function u(v){return function(){typeof console!==t&&(l.call(this),this[v].apply(this,arguments))}}function h(v,R,_){return d(v)||u.apply(this,arguments)}function f(v,R){var _=this,A,x,y,T="loglevel";typeof v=="string"?T+=":"+v:typeof v=="symbol"&&(T=void 0);function C(L){var q=(s[L]||"silent").toUpperCase();if(!(typeof window===t||!T)){try{window.localStorage[T]=q;return}catch{}try{window.document.cookie=encodeURIComponent(T)+"="+q+";"}catch{}}}function N(){var L;if(!(typeof window===t||!T)){try{L=window.localStorage[T]}catch{}if(typeof L===t)try{var q=window.document.cookie,Z=encodeURIComponent(T),_e=q.indexOf(Z+"=");_e!==-1&&(L=/^([^;]+)/.exec(q.slice(_e+Z.length+1))[1])}catch{}return _.levels[L]===void 0&&(L=void 0),L}}function U(){if(!(typeof window===t||!T)){try{window.localStorage.removeItem(T)}catch{}try{window.document.cookie=encodeURIComponent(T)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function M(L){var q=L;if(typeof q=="string"&&_.levels[q.toUpperCase()]!==void 0&&(q=_.levels[q.toUpperCase()]),typeof q=="number"&&q>=0&&q<=_.levels.SILENT)return q;throw new TypeError("log.setLevel() called with invalid level: "+L)}_.name=v,_.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},_.methodFactory=R||h,_.getLevel=function(){return y??x??A},_.setLevel=function(L,q){return y=M(L),q!==!1&&C(y),l.call(_)},_.setDefaultLevel=function(L){x=M(L),N()||_.setLevel(L,!1)},_.resetLevel=function(){y=null,U(),l.call(_)},_.enableAll=function(L){_.setLevel(_.levels.TRACE,L)},_.disableAll=function(L){_.setLevel(_.levels.SILENT,L)},_.rebuild=function(){if(a!==_&&(A=M(a.getLevel())),l.call(_),a===_)for(var L in r)r[L].rebuild()},A=M(a?a.getLevel():"WARN");var O=N();O!=null&&(y=M(O)),l.call(_)}a=new f,a.getLogger=function(R){if(typeof R!="symbol"&&typeof R!="string"||R==="")throw new TypeError("You must supply a name when creating a logger.");var _=r[R];return _||(_=r[R]=new f(R,a.methodFactory)),_};var b=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=b),a},a.getLoggers=function(){return r},a.default=a,a})})(fi)),fi.exports}var gi=cl(),rn;(function(n){n[n.trace=0]="trace",n[n.debug=1]="debug",n[n.info=2]="info",n[n.warn=3]="warn",n[n.error=4]="error",n[n.silent=5]="silent"})(rn||(rn={}));var Pe;(function(n){n.Default="livekit",n.Room="livekit-room",n.TokenSource="livekit-token-source",n.Participant="livekit-participant",n.Track="livekit-track",n.Publication="livekit-track-publication",n.Engine="livekit-engine",n.Signal="livekit-signal",n.PCManager="livekit-pc-manager",n.PCTransport="livekit-pc-transport",n.E2EE="lk-e2ee"})(Pe||(Pe={}));let V=gi.getLogger("livekit");Object.values(Pe).map(n=>gi.getLogger(n)),V.setDefaultLevel(rn.info);function Ve(n){const e=gi.getLogger(n);return e.setDefaultLevel(V.getLevel()),e}const dl=gi.getLogger("lk-e2ee"),Bt=7e3,ll=[0,300,4*300,9*300,16*300,Bt,Bt,Bt,Bt,Bt];class ul{constructor(e){this._retryDelays=e!==void 0?[...e]:ll}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function hl(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(n);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(n,i[s])&&(t[i[s]]=n[i[s]]);return t}function p(n,e,t,i){function s(r){return r instanceof t?r:new t(function(a){a(r)})}return new(t||(t=Promise))(function(r,a){function o(l){try{d(i.next(l))}catch(u){a(u)}}function c(l){try{d(i.throw(l))}catch(u){a(u)}}function d(l){l.done?r(l.value):s(l.value).then(o,c)}d((i=i.apply(n,e||[])).next())})}function xr(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function je(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof xr=="function"?xr(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(r){t[r]=n[r]&&function(a){return new Promise(function(o,c){a=n[r](a),s(o,c,a.done,a.value)})}}function s(r,a,o,c){Promise.resolve(c).then(function(d){r({value:d,done:o})},a)}}typeof SuppressedError=="function"&&SuppressedError;var vi={exports:{}},Mr;function pl(){if(Mr)return vi.exports;Mr=1;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(T,C,N){return Function.prototype.apply.call(T,C,N)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(T){return Object.getOwnPropertyNames(T).concat(Object.getOwnPropertySymbols(T))}:t=function(T){return Object.getOwnPropertyNames(T)};function i(y){console&&console.warn&&console.warn(y)}var s=Number.isNaN||function(T){return T!==T};function r(){r.init.call(this)}vi.exports=r,vi.exports.once=_,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var a=10;function o(y){if(typeof y!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof y)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(y){if(typeof y!="number"||y<0||s(y))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+y+".");a=y}}),r.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(T){if(typeof T!="number"||T<0||s(T))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+T+".");return this._maxListeners=T,this};function c(y){return y._maxListeners===void 0?r.defaultMaxListeners:y._maxListeners}r.prototype.getMaxListeners=function(){return c(this)},r.prototype.emit=function(T){for(var C=[],N=1;N<arguments.length;N++)C.push(arguments[N]);var U=T==="error",M=this._events;if(M!==void 0)U=U&&M.error===void 0;else if(!U)return!1;if(U){var O;if(C.length>0&&(O=C[0]),O instanceof Error)throw O;var L=new Error("Unhandled error."+(O?" ("+O.message+")":""));throw L.context=O,L}var q=M[T];if(q===void 0)return!1;if(typeof q=="function")e(q,this,C);else for(var Z=q.length,_e=b(q,Z),N=0;N<Z;++N)e(_e[N],this,C);return!0};function d(y,T,C,N){var U,M,O;if(o(C),M=y._events,M===void 0?(M=y._events=Object.create(null),y._eventsCount=0):(M.newListener!==void 0&&(y.emit("newListener",T,C.listener?C.listener:C),M=y._events),O=M[T]),O===void 0)O=M[T]=C,++y._eventsCount;else if(typeof O=="function"?O=M[T]=N?[C,O]:[O,C]:N?O.unshift(C):O.push(C),U=c(y),U>0&&O.length>U&&!O.warned){O.warned=!0;var L=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(T)+" listeners added. Use emitter.setMaxListeners() to increase limit");L.name="MaxListenersExceededWarning",L.emitter=y,L.type=T,L.count=O.length,i(L)}return y}r.prototype.addListener=function(T,C){return d(this,T,C,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(T,C){return d(this,T,C,!0)};function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(y,T,C){var N={fired:!1,wrapFn:void 0,target:y,type:T,listener:C},U=l.bind(N);return U.listener=C,N.wrapFn=U,U}r.prototype.once=function(T,C){return o(C),this.on(T,u(this,T,C)),this},r.prototype.prependOnceListener=function(T,C){return o(C),this.prependListener(T,u(this,T,C)),this},r.prototype.removeListener=function(T,C){var N,U,M,O,L;if(o(C),U=this._events,U===void 0)return this;if(N=U[T],N===void 0)return this;if(N===C||N.listener===C)--this._eventsCount===0?this._events=Object.create(null):(delete U[T],U.removeListener&&this.emit("removeListener",T,N.listener||C));else if(typeof N!="function"){for(M=-1,O=N.length-1;O>=0;O--)if(N[O]===C||N[O].listener===C){L=N[O].listener,M=O;break}if(M<0)return this;M===0?N.shift():v(N,M),N.length===1&&(U[T]=N[0]),U.removeListener!==void 0&&this.emit("removeListener",T,L||C)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(T){var C,N,U;if(N=this._events,N===void 0)return this;if(N.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):N[T]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete N[T]),this;if(arguments.length===0){var M=Object.keys(N),O;for(U=0;U<M.length;++U)O=M[U],O!=="removeListener"&&this.removeAllListeners(O);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(C=N[T],typeof C=="function")this.removeListener(T,C);else if(C!==void 0)for(U=C.length-1;U>=0;U--)this.removeListener(T,C[U]);return this};function h(y,T,C){var N=y._events;if(N===void 0)return[];var U=N[T];return U===void 0?[]:typeof U=="function"?C?[U.listener||U]:[U]:C?R(U):b(U,U.length)}r.prototype.listeners=function(T){return h(this,T,!0)},r.prototype.rawListeners=function(T){return h(this,T,!1)},r.listenerCount=function(y,T){return typeof y.listenerCount=="function"?y.listenerCount(T):f.call(y,T)},r.prototype.listenerCount=f;function f(y){var T=this._events;if(T!==void 0){var C=T[y];if(typeof C=="function")return 1;if(C!==void 0)return C.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function b(y,T){for(var C=new Array(T),N=0;N<T;++N)C[N]=y[N];return C}function v(y,T){for(;T+1<y.length;T++)y[T]=y[T+1];y.pop()}function R(y){for(var T=new Array(y.length),C=0;C<T.length;++C)T[C]=y[C].listener||y[C];return T}function _(y,T){return new Promise(function(C,N){function U(O){y.removeListener(T,M),N(O)}function M(){typeof y.removeListener=="function"&&y.removeListener("error",U),C([].slice.call(arguments))}x(y,T,M,{once:!0}),T!=="error"&&A(y,U,{once:!0})})}function A(y,T,C){typeof y.on=="function"&&x(y,"error",T,C)}function x(y,T,C,N){if(typeof y.on=="function")N.once?y.once(T,C):y.on(T,C);else if(typeof y.addEventListener=="function")y.addEventListener(T,function U(M){N.once&&y.removeEventListener(T,U),C(M)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof y)}return vi.exports}var xe=pl();let Lr=!0,Ur=!0;function Vt(n,e,t){const i=n.match(e);return i&&i.length>=t&&parseFloat(i[t],10)}function at(n,e,t){if(!n.RTCPeerConnection)return;const i=n.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(a,o){if(a!==e)return s.apply(this,arguments);const c=d=>{const l=t(d);l&&(o.handleEvent?o.handleEvent(l):o(l))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,c),s.apply(this,[a,c])};const r=i.removeEventListener;i.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(o))return r.apply(this,arguments);const c=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,r.apply(this,[a,c])},Object.defineProperty(i,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function ml(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(Lr=n,n?"adapter.js logging disabled":"adapter.js logging enabled")}function fl(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(Ur=!n,"adapter.js deprecation warnings "+(n?"disabled":"enabled"))}function Fr(){if(typeof window=="object"){if(Lr)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function on(n,e){Ur&&console.warn(n+" is deprecated, please use "+e+" instead.")}function gl(n){const e={browser:null,version:null};if(typeof n>"u"||!n.navigator||!n.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=n;if(t.userAgentData&&t.userAgentData.brands){const i=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(Vt(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(Vt(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(n.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(Vt(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype,e._safariVersion=Vt(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function Br(n){return Object.prototype.toString.call(n)==="[object Object]"}function Vr(n){return Br(n)?Object.keys(n).reduce(function(e,t){const i=Br(n[t]),s=i?Vr(n[t]):n[t],r=i&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):n}function an(n,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?an(n,n.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(s=>{an(n,n.get(s),t)})}))}function jr(n,e,t){const i=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return n.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&r.push(a)}),r.forEach(a=>{n.forEach(o=>{o.type===i&&o.trackId===a.id&&an(n,o,s)})}),s}const qr=Fr;function Wr(n,e){const t=n&&n.navigator;if(!t.mediaDevices)return;const i=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const c={};return Object.keys(o).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const l=typeof o[d]=="object"?o[d]:{ideal:o[d]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const u=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(l.ideal!==void 0){c.optional=c.optional||[];let h={};typeof l.ideal=="number"?(h[u("min",d)]=l.ideal,c.optional.push(h),h={},h[u("max",d)]=l.ideal,c.optional.push(h)):(h[u("",d)]=l.ideal,c.optional.push(h))}l.exact!==void 0&&typeof l.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",d)]=l.exact):["min","max"].forEach(h=>{l[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(h,d)]=l[h])})}),o.advanced&&(c.optional=(c.optional||[]).concat(o.advanced)),c},s=function(o,c){if(e.version>=61)return c(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const d=function(l,u,h){u in l&&!(h in l)&&(l[h]=l[u],delete l[u])};o=JSON.parse(JSON.stringify(o)),d(o.audio,"autoGainControl","googAutoGainControl"),d(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(o.audio)}if(o&&typeof o.video=="object"){let d=o.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const l=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete o.video.facingMode;let u;if(d.exact==="environment"||d.ideal==="environment"?u=["back","rear"]:(d.exact==="user"||d.ideal==="user")&&(u=["front"]),u)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(b=>b.kind==="videoinput");let f=h.find(b=>u.some(v=>b.label.toLowerCase().includes(v)));return!f&&h.length&&u.includes("back")&&(f=h[h.length-1]),f&&(o.video.deviceId=d.exact?{exact:f.deviceId}:{ideal:f.deviceId}),o.video=i(o.video),qr("chrome: "+JSON.stringify(o)),c(o)})}o.video=i(o.video)}return qr("chrome: "+JSON.stringify(o)),c(o)},r=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,c,d){s(o,l=>{t.webkitGetUserMedia(l,c,u=>{d&&d(r(u))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,d=>o(d).then(l=>{if(d.audio&&!l.getAudioTracks().length||d.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(r(l))))}}}function Kr(n){n.MediaStream=n.MediaStream||n.webkitMediaStream}function Gr(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("ontrack"in n.RTCPeerConnection.prototype)){Object.defineProperty(n.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",s=>{let r;n.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===s.track.id):r={track:s.track};const a=new Event("track");a.track=s.track,a.receiver=r,a.transceiver={receiver:r},a.streams=[i.stream],this.dispatchEvent(a)}),i.stream.getTracks().forEach(s=>{let r;n.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===s.id):r={track:s};const a=new Event("track");a.track=s,a.receiver=r,a.transceiver={receiver:r},a.streams=[i.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else at(n,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Hr(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("getSenders"in n.RTCPeerConnection.prototype)&&"createDTMFSender"in n.RTCPeerConnection.prototype){const e=function(s,r){return{track:r,get dtmf(){return this._dtmf===void 0&&(r.kind==="audio"?this._dtmf=s.createDTMFSender(r):this._dtmf=null),this._dtmf},_pc:s}};if(!n.RTCPeerConnection.prototype.getSenders){n.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(o,c){let d=s.apply(this,arguments);return d||(d=e(this,o),this._senders.push(d)),d};const r=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(o){r.apply(this,arguments);const c=this._senders.indexOf(o);c!==-1&&this._senders.splice(c,1)}}const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],i.apply(this,[r]),r.getTracks().forEach(a=>{const o=this._senders.find(c=>c.track===a);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof n=="object"&&n.RTCPeerConnection&&"getSenders"in n.RTCPeerConnection.prototype&&"createDTMFSender"in n.RTCPeerConnection.prototype&&n.RTCRtpSender&&!("dtmf"in n.RTCRtpSender.prototype)){const e=n.RTCPeerConnection.prototype.getSenders;n.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i},Object.defineProperty(n.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function zr(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender&&n.RTCRtpReceiver))return;if(!("getStats"in n.RTCRtpSender.prototype)){const t=n.RTCPeerConnection.prototype.getSenders;t&&(n.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(a=>a._pc=this),r});const i=n.RTCPeerConnection.prototype.addTrack;i&&(n.RTCPeerConnection.prototype.addTrack=function(){const r=i.apply(this,arguments);return r._pc=this,r}),n.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(a=>jr(a,r.track,!0))}}if(!("getStats"in n.RTCRtpReceiver.prototype)){const t=n.RTCPeerConnection.prototype.getReceivers;t&&(n.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(r=>r._pc=this),s}),at(n,"track",i=>(i.receiver._pc=i.srcElement,i)),n.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>jr(r,s.track,!1))}}if(!("getStats"in n.RTCRtpSender.prototype&&"getStats"in n.RTCRtpReceiver.prototype))return;const e=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof n.MediaStreamTrack){const i=arguments[0];let s,r,a;return this.getSenders().forEach(o=>{o.track===i&&(s?a=!0:s=o)}),this.getReceivers().forEach(o=>(o.track===i&&(r?a=!0:r=o),o.track===i)),a||s&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Jr(n){n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(c)===-1&&this._shimmedLocalStreams[o.id].push(c):this._shimmedLocalStreams[o.id]=[o,c],c};const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(d=>{if(this.getSenders().find(u=>u.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(d=>o.indexOf(d)===-1);this._shimmedLocalStreams[a.id]=[a].concat(c)};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],i.apply(this,arguments)};const s=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const c=this._shimmedLocalStreams[o].indexOf(a);c!==-1&&this._shimmedLocalStreams[o].splice(c,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),s.apply(this,arguments)}}function $r(n,e){if(!n.RTCPeerConnection)return;if(n.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Jr(n);const t=n.RTCPeerConnection.prototype.getLocalStreams;n.RTCPeerConnection.prototype.getLocalStreams=function(){const l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(u=>this._reverseStreams[u.id])};const i=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(u=>{if(this.getSenders().find(f=>f.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const u=new n.MediaStream(l.getTracks());this._streams[l.id]=u,this._reverseStreams[u.id]=l,l=u}i.apply(this,[l])};const s=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(l){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[l.id]||l]),delete this._reverseStreams[this._streams[l.id]?this._streams[l.id].id:l.id],delete this._streams[l.id]},n.RTCPeerConnection.prototype.addTrack=function(l,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(v=>v===l))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(v=>v.track===l))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const b=this._streams[u.id];if(b)b.addTrack(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const v=new n.MediaStream([l]);this._streams[u.id]=v,this._reverseStreams[v.id]=u,this.addStream(v)}return this.getSenders().find(v=>v.track===l)};function r(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const f=d._reverseStreams[h],b=d._streams[f.id];u=u.replace(new RegExp(b.id,"g"),f.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function a(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const f=d._reverseStreams[h],b=d._streams[f.id];u=u.replace(new RegExp(f.id,"g"),b.id)}),new RTCSessionDescription({type:l.type,sdp:u})}["createOffer","createAnswer"].forEach(function(d){const l=n.RTCPeerConnection.prototype[d],u={[d](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[b=>{const v=r(this,b);h[0].apply(null,[v])},b=>{h[1]&&h[1].apply(null,b)},arguments[2]]):l.apply(this,arguments).then(b=>r(this,b))}};n.RTCPeerConnection.prototype[d]=u[d]});const o=n.RTCPeerConnection.prototype.setLocalDescription;n.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(n.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(n.RTCPeerConnection.prototype,"localDescription",{get(){const d=c.get.apply(this);return d.type===""?d:r(this,d)}}),n.RTCPeerConnection.prototype.removeTrack=function(l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!l._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(l._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(v=>l.track===v)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function cn(n,e){!n.RTCPeerConnection&&n.webkitRTCPeerConnection&&(n.RTCPeerConnection=n.webkitRTCPeerConnection),n.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=n.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};n.RTCPeerConnection.prototype[t]=s[t]})}function Qr(n,e){at(n,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}var Yr=Object.freeze({__proto__:null,fixNegotiationNeeded:Qr,shimAddTrackRemoveTrack:$r,shimAddTrackRemoveTrackWithNative:Jr,shimGetSendersWithDtmf:Hr,shimGetUserMedia:Wr,shimMediaStream:Kr,shimOnTrack:Gr,shimPeerConnection:cn,shimSenderReceiverGetStats:zr});function Xr(n,e){const t=n&&n.navigator,i=n&&n.MediaStreamTrack;if(t.getUserMedia=function(s,r,a){on("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(a,o,c){o in a&&!(c in a)&&(a[c]=a[o],delete a[o])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a.audio,"autoGainControl","mozAutoGainControl"),s(a.audio,"noiseSuppression","mozNoiseSuppression")),r(a)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return s(o,"mozAutoGainControl","autoGainControl"),s(o,"mozNoiseSuppression","noiseSuppression"),o}}if(i&&i.prototype.applyConstraints){const a=i.prototype.applyConstraints;i.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o,"autoGainControl","mozAutoGainControl"),s(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function vl(n,e){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,n.navigator.mediaDevices.getUserMedia(i)})}function Zr(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function dn(n,e){if(typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection))return;!n.RTCPeerConnection&&n.mozRTCPeerConnection&&(n.RTCPeerConnection=n.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const r=n.RTCPeerConnection.prototype[s],a={[s](){return arguments[0]=new(s==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};n.RTCPeerConnection.prototype[s]=a[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){const[r,a,o]=arguments;return i.apply(this,[r||null]).then(c=>{if(e.version<53&&!a)try{c.forEach(d=>{d.type=t[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;c.forEach((l,u)=>{c.set(u,Object.assign({},l,{type:t[l.type]||l.type}))})}return c}).then(a,o)}}function eo(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpSender.prototype)return;const e=n.RTCPeerConnection.prototype.getSenders;e&&(n.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(r=>r._pc=this),s});const t=n.RTCPeerConnection.prototype.addTrack;t&&(n.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),n.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function to(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpReceiver.prototype)return;const e=n.RTCPeerConnection.prototype.getReceivers;e&&(n.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i}),at(n,"track",t=>(t.receiver._pc=t.srcElement,t)),n.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function io(n){!n.RTCPeerConnection||"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){on("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function no(n){n.DataChannel&&!n.RTCDataChannel&&(n.RTCDataChannel=n.DataChannel)}function so(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.addTransceiver;e&&(n.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const s=i.length>0;s&&i.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(s){const{sender:a}=r,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=i,a.sendEncodings=i,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return r})}function ro(n){if(!(typeof n=="object"&&n.RTCRtpSender))return;const e=n.RTCRtpSender.prototype.getParameters;e&&(n.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function oo(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function ao(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createAnswer;n.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var co=Object.freeze({__proto__:null,shimAddTransceiver:so,shimCreateAnswer:ao,shimCreateOffer:oo,shimGetDisplayMedia:vl,shimGetParameters:ro,shimGetUserMedia:Xr,shimOnTrack:Zr,shimPeerConnection:dn,shimRTCDataChannel:no,shimReceiverGetStats:to,shimRemoveStream:io,shimSenderGetStats:eo});function lo(n){if(!(typeof n!="object"||!n.RTCPeerConnection)){if("getLocalStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in n.RTCPeerConnection.prototype)){const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(s=>e.call(this,s,i)),i.getVideoTracks().forEach(s=>e.call(this,s,i))},n.RTCPeerConnection.prototype.addTrack=function(i){for(var s=arguments.length,r=new Array(s>1?s-1:0),a=1;a<s;a++)r[a-1]=arguments[a];return r&&r.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),e.apply(this,arguments)}}"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const s=t.getTracks();this.getSenders().forEach(r=>{s.includes(r.track)&&this.removeTrack(r)})})}}function uo(n){if(!(typeof n!="object"||!n.RTCPeerConnection)&&("getRemoteStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in n.RTCPeerConnection.prototype))){Object.defineProperty(n.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const r=new Event("addstream");r.stream=s,this.dispatchEvent(r)})})}});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(r=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(r)>=0)return;i._remoteStreams.push(r);const a=new Event("addstream");a.stream=r,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function ho(n){if(typeof n!="object"||!n.RTCPeerConnection)return;const e=n.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[u]);return l?(h.then(d,l),Promise.resolve()):h},e.createAnswer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=i.apply(this,[u]);return l?(h.then(d,l),Promise.resolve()):h};let o=function(c,d,l){const u=s.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u};e.setLocalDescription=o,o=function(c,d,l){const u=r.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.setRemoteDescription=o,o=function(c,d,l){const u=a.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.addIceCandidate=o}function po(n){const e=n&&n.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>i(mo(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(i,s,r){e.mediaDevices.getUserMedia(i).then(s,r)}.bind(e))}function mo(n){return n&&n.video!==void 0?Object.assign({},n,{video:Vr(n.video)}):n}function fo(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection;n.RTCPeerConnection=function(i,s){if(i&&i.iceServers){const r=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?(on("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,r.push(o)):r.push(i.iceServers[a])}i.iceServers=r}return new e(i,s)},n.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(n.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function go(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function vo(n){const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const r=this.getTransceivers().find(a=>a.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function bo(n){typeof n!="object"||n.AudioContext||(n.AudioContext=n.webkitAudioContext)}var yo=Object.freeze({__proto__:null,shimAudioContext:bo,shimCallbacksAPI:ho,shimConstraints:mo,shimCreateOfferLegacy:vo,shimGetUserMedia:po,shimLocalStreamsAPI:lo,shimRTCIceServerUrls:fo,shimRemoteStreamsAPI:uo,shimTrackEventTransceiver:go}),ln={exports:{}},To;function bl(){return To||(To=1,(function(n){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
110
+ `;function yc(){const n=new Blob([bc],{type:"text/javascript"});return URL.createObjectURL(n)}class _c extends vc{constructor(e){super(),this.options=e,this._stream=null,this._audioContext=null,this._sourceNode=null,this._workletNode=null,this._targetSampleRate=Li,this._bitDepth=gs,this._channels=1;const t=e?.input;this._targetSampleRate=t?.sampleRate||Li,this._bitDepth=t?.bitDepth||gs,this._channels=t?.channels||1}async start(){this.ensureNotDisposed();try{const t={audio:this.options?.input?.constraints||{channelCount:this._channels}};this._stream=await navigator.mediaDevices.getUserMedia(t);const r=this._stream.getAudioTracks()[0].getSettings().sampleRate||44100;this._audioContext=new AudioContext({sampleRate:r});const a=yc();await this._audioContext.audioWorklet.addModule(a),this._sourceNode=this._audioContext.createMediaStreamSource(this._stream),this._workletNode=new AudioWorkletNode(this._audioContext,"audio-resampler",{processorOptions:{targetSampleRate:this._targetSampleRate,bitDepth:this._bitDepth,channels:this._channels},numberOfInputs:1,numberOfOutputs:0}),this._workletNode.port.onmessage=o=>{const{type:c,data:d,sampleRate:l}=o.data;c==="audioData"&&d&&this.emitAudioData(d,l)},this._sourceNode.connect(this._workletNode),m.info(`Audio capture started: input=${r}Hz -> output=${this._targetSampleRate}Hz, ${this._bitDepth}bit`)}catch(e){throw G.fromError(e,B.AUDIO_CAPTURE_FAILED)}}stop(){this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),this._workletNode&&(this._workletNode.port.onmessage=null,this._workletNode.disconnect(),this._workletNode=null),this._sourceNode&&(this._sourceNode.disconnect(),this._sourceNode=null),this._audioContext&&(this._audioContext.close(),this._audioContext=null),m.info("Audio capture stopped")}onDispose(){this.stop()}}class Tc{create(e){return new _c(e)}}class kc extends j{constructor(e,t,i){super(),this._source=null,this._isCapturing=!1,this._currentOutputTrackId=null,this._context=e,this._inputPipeline=new sc(t),this._outputPipeline=new rc,this._frameSender=new gc(e,t),this._sourceFactory=i||new Tc,this._inputPipeline.onProcessedAudio=(s,r)=>{this._context.eventBus.emit("inner:audio:frame:received",{data:s,sampleRate:r})},m.info("Audio Controller created")}setWebSocketSender(e){this._frameSender.setWebSocketSender(e)}async startCapture(){if(this.ensureNotDisposed(),this._isCapturing){m.warn("Audio capture already started");return}try{this._source||(this._source=this._sourceFactory.create(this._context.options.audio),this._source.onAudioData=(e,t)=>{this._inputPipeline.process(e,t)}),await this._source.start(),this._isCapturing=!0,this._frameSender.start(),this._context.eventBus.emit("inner:audio:input:started",void 0),m.info("Audio capture started")}catch(e){throw this._context.emitError(e,B.AUDIO_CAPTURE_START_FAILED)}}stopCapture(){this.ensureNotDisposed(),this._isCapturing&&(this._source&&this._source.stop(),this._frameSender.stop(),this._isCapturing=!1,this._context.eventBus.emit("inner:audio:input:stopped",void 0),m.info("Audio capture stopped"))}get isCapturing(){return this._isCapturing}setOutputTrack(e,t,i){this.ensureNotDisposed(),this._outputPipeline.setTrack(e),this._currentOutputTrackId=t,this._context.eventBus.emit("inner:audio:track:added",{trackId:t,participantId:i}),m.info("Audio output track ready")}removeOutputTrack(e){this.ensureNotDisposed(),this._currentOutputTrackId===e&&(this._outputPipeline.removeTrack(),this._currentOutputTrackId=null,this._context.eventBus.emit("inner:audio:track:removed",{trackId:e}),m.info("Audio output track removed"))}setVolume(e){this.ensureNotDisposed(),this._outputPipeline.setVolume(e),this._context.eventBus.emit("inner:audio:volume:changed",{volume:e}),m.debug(`Audio volume set to: ${e}`)}getVolume(){return this._outputPipeline.getVolume()}mute(){this.ensureNotDisposed(),this._outputPipeline.mute(),this._context.eventBus.emit("inner:audio:muted",void 0),m.debug("Audio muted")}unmute(){this.ensureNotDisposed(),this._outputPipeline.unmute(),this._context.eventBus.emit("inner:audio:unmuted",void 0),m.debug("Audio unmuted")}getOutputElement(){return this._outputPipeline.getAudioElement()}isMuted(){return this._outputPipeline.isMuted()}onDispose(){this.stopCapture(),this._source&&(this._source.dispose(),this._source=null),this._inputPipeline.dispose(),this._outputPipeline.dispose(),this._frameSender.dispose(),m.info("Audio Controller disposed")}}class Sc extends j{constructor(){super(...arguments),this._stream=null,this._videoElement=null}async start(){if(this.ensureNotDisposed(),this._stream){m.warn("Camera capture already started");return}try{const e=await navigator.mediaDevices.getUserMedia({video:!0});if(this._stream=e,!this._videoElement){const t=document.createElement("video");t.autoplay=!0,t.muted=!0,t.playsInline=!0,t.style.position="fixed",t.style.opacity="0",t.style.pointerEvents="none",t.style.width="0",t.style.height="0",t.style.zIndex="-1",typeof document<"u"&&document.body&&document.body.appendChild(t),this._videoElement=t}this._videoElement.srcObject=this._stream,this._videoElement.play().catch(t=>{m.error("Failed to start camera video playback",t)})}catch(e){throw G.fromError(e,B.SDK_ERROR)}}stop(){if(this._stream&&(this._stream.getTracks().forEach(e=>e.stop()),this._stream=null),this._videoElement){this._videoElement.srcObject=null;const e=this._videoElement.parentNode;e&&e.removeChild(this._videoElement),this._videoElement=null}m.info("Camera capture stopped")}getStream(){return this.ensureNotDisposed(),this._stream}getVideoElement(){return this.ensureNotDisposed(),this._videoElement}getTrack(){if(this.ensureNotDisposed(),!this._stream)return null;const e=this._stream.getVideoTracks();return e.length>0?e[0]:null}onDispose(){this.stop()}}const Yt=640,Cs=640;class Cc extends j{constructor(e,t,i){super(),this._videoElement=null,this._canvas=null,this._videoElement=e,this._onFrame=t,this._context=i,this._handleServerCommand=this._onServerCommand.bind(this)}setVideoElement(e){this._videoElement=e}start(){this.ensureNotDisposed(),this._canvas||(typeof OffscreenCanvas<"u"?this._canvas=new OffscreenCanvas(Yt,Cs):(this._canvas=document.createElement("canvas"),this._canvas.width=Yt,this._canvas.height=Cs)),this._context.eventBus.on("inner:conversation:server:command",this._handleServerCommand)}_onServerCommand({code:e}){e===500&&this._captureFrame()}stop(){this._context.eventBus.off("inner:conversation:server:command",this._handleServerCommand)}_captureFrame(){const e=this._videoElement,t=this._canvas;if(!e||!t||e.readyState<2||e.videoWidth===0||e.videoHeight===0)return;const i=t.getContext("2d");if(!i)return;const s=e.videoWidth,r=e.videoHeight,a=Yt,o=Yt*r/s;t.width!==a&&(t.width=a),t.height!==o&&(t.height=o),i.clearRect(0,0,t.width,t.height),i.drawImage(e,0,0,s,r,0,0,a,o),typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas&&typeof t.convertToBlob=="function"?t.convertToBlob({type:"image/jpeg",quality:Ot}).then(c=>{if(c)try{this._onFrame(c,a,o,0,Ot)}catch(d){m.error("ScreenshotScheduler onFrame callback error",d)}}).catch(c=>{m.error("ScreenshotScheduler convertToBlob error",c)}):t instanceof HTMLCanvasElement&&t.toBlob(c=>{if(c)try{this._onFrame(c,a,o,0,Ot)}catch(d){m.error("ScreenshotScheduler onFrame callback error",d)}},"image/jpeg",Ot)}onDispose(){this.stop(),this._canvas=null,this._videoElement=null}}async function Ec(n,e){const t=await n.arrayBuffer();return{data:new Uint8Array(t),width:e.width,height:e.height,format:e.format,quality:e.quality}}const Rc=12,wc=2,Pc=0,Es=0,Rs=4,ws=65535,Ps=4294967295;function Ic(n){const e=Math.floor(n);return e<0?0:e>255?255:e}function Bi(n){const e=Math.floor(n);return e<0?0:e>ws?ws:e}function Dc(n){const e=Math.floor(n);return e<0?0:e>Ps?Ps:e}function Ac(n){const e=Math.floor(n);return e<Es?Es:e>Rs?Rs:e}function Oc(n){const e=new ArrayBuffer(Rc),t=new DataView(e),i=Ac(n.format)&15,s=wc<<6|Pc<<4|i;return t.setUint8(0,s),t.setUint8(1,Ic(n.quality)),t.setUint16(2,Bi(n.id),!1),t.setUint16(4,Bi(n.width),!1),t.setUint16(6,Bi(n.height),!1),t.setUint32(8,Dc(n.payloadLength),!1),new Uint8Array(e)}const Nc=65535;class xc extends j{constructor(){super(...arguments),this._wsSender=null,this._imageId=0}setWebSocketSender(e){this._wsSender=e}send(e,t){if(this.ensureNotDisposed(),!this._wsSender||!this._wsSender.isConnected())return;const i=e.byteLength,s=Oc({format:t.format,quality:t.quality,id:this._nextId(),width:t.width,height:t.height,payloadLength:i}),r=new Uint8Array(s.byteLength+i);r.set(s,0),r.set(e,s.byteLength),this._wsSender.sendBinary(r)}_nextId(){const e=this._imageId;return this._imageId=this._imageId>=Nc?0:this._imageId+1,e}onDispose(){this._wsSender=null}}class Mc extends j{constructor(e){super(),this._isRunning=!1,this._context=e,this._source=new Sc,this._sender=new xc;const t=(i,s,r,a,o=Ot)=>{Ec(i,{width:s,height:r,format:a,quality:o}).then(c=>{this._sender.send(c.data,{width:c.width,height:c.height,format:c.format,quality:c.quality})})};this._scheduler=new Cc(null,t,e)}async startCamera(){if(this.ensureNotDisposed(),this._isRunning){m.warn("Camera already running");return}await this._source.start();const e=this._source.getVideoElement();this._scheduler.setVideoElement(e),this._scheduler.start(),this._isRunning=!0,this._context.eventBus.emit("inner:camera:started",void 0),m.info("Camera started")}stopCamera(){this.ensureNotDisposed(),this._isRunning&&(this._scheduler.stop(),this._source.stop(),this._isRunning=!1,this._context.eventBus.emit("inner:camera:stopped",void 0),m.info("Camera stopped"))}isCameraRunning(){return this._isRunning}getStream(){return this.ensureNotDisposed(),this._source.getStream()}getTrack(){return this.ensureNotDisposed(),this._source.getTrack()}attachTo(e){this.ensureNotDisposed();const t=this._source.getStream();t&&(e.srcObject=t,e.play().catch(i=>m.error("attachTo play failed",i)))}setWebSocketSender(e){this._sender.setWebSocketSender(e)}onDispose(){this.stopCamera(),this._source.dispose(),this._scheduler.dispose(),this._sender.dispose()}}D.ConversationStateType=void 0,(function(n){n.IDLE="idle",n.WAITING="waiting",n.STREAMING="streaming",n.COMPLETED="completed",n.ERROR="error"})(D.ConversationStateType||(D.ConversationStateType={}));class Lc extends ys{constructor(){super(...arguments),this._currentState=D.ConversationStateType.IDLE,this.transitionTable=[{from:D.ConversationStateType.IDLE,to:[D.ConversationStateType.WAITING,D.ConversationStateType.ERROR]},{from:D.ConversationStateType.WAITING,to:[D.ConversationStateType.STREAMING,D.ConversationStateType.ERROR]},{from:D.ConversationStateType.STREAMING,to:[D.ConversationStateType.COMPLETED,D.ConversationStateType.ERROR]},{from:D.ConversationStateType.COMPLETED,to:[D.ConversationStateType.IDLE,D.ConversationStateType.WAITING,D.ConversationStateType.ERROR]},{from:D.ConversationStateType.ERROR,to:[D.ConversationStateType.IDLE]}]}reset(){this._currentState=D.ConversationStateType.IDLE}}class Is extends j{constructor(e,t){super(),this._currentQuestion=null,this._currentAnswer=null,this._sessionId=e,this._stateMachine=new Lc,m.info(`Conversation session created: ${e}`)}get sessionId(){return this._sessionId}get state(){return this._stateMachine.getCurrentState()}_setQuestion(e){this._currentQuestion=e,this._stateMachine.transitionTo(D.ConversationStateType.WAITING),this._syncContextState()}get currentQuestion(){return this._currentQuestion}_startAnswer(e){this._currentAnswer={questionId:e,text:"",isComplete:!1,timestamp:Date.now()},this._stateMachine.transitionTo(D.ConversationStateType.STREAMING),this._syncContextState()}_appendAnswerChunk(e){this._currentAnswer&&(this._currentAnswer.text+=e)}_completeAnswer(){this._currentAnswer&&(this._currentAnswer.isComplete=!0,this._currentAnswer.completedAt=Date.now()),this._stateMachine.transitionTo(D.ConversationStateType.COMPLETED),this._syncContextState()}get currentAnswer(){return this._currentAnswer}_setError(e){this._stateMachine.transitionTo(D.ConversationStateType.ERROR),this._syncContextState()}_syncContextState(){}handleEvent(e){const t=this._stateMachine.getCurrentState();switch(e.type){case"QUESTION":if(t!==D.ConversationStateType.IDLE&&t!==D.ConversationStateType.COMPLETED){m.warn(`Ignoring QUESTION event in invalid state: ${t}`);return}this._setQuestion(e.payload);break;case"ANSWER_START":if(t!==D.ConversationStateType.WAITING){m.warn(`Ignoring ANSWER_START event in invalid state: ${t}. Expected: WAITING`);return}this._startAnswer(e.payload);break;case"ANSWER_CHUNK":if(t!==D.ConversationStateType.STREAMING){m.warn(`Ignoring ANSWER_CHUNK event in invalid state: ${t}. Expected: STREAMING`);return}this._appendAnswerChunk(e.payload&&e.payload.chunk||""),e.payload&&e.payload.isComplete&&this._completeAnswer();break;case"ANSWER_COMPLETE":if(t!==D.ConversationStateType.STREAMING){m.warn(`Ignoring ANSWER_COMPLETE event in invalid state: ${t}. Expected: STREAMING`);return}this._completeAnswer();break;case"ERROR":this._setError(e.payload);break;default:m.warn(`Unknown event type: ${e.type}`);break}}reset(){this._stateMachine.reset(),this._currentQuestion=null,this._currentAnswer=null}onDispose(){this.reset(),m.info(`Conversation session disposed: ${this._sessionId}`)}}class Uc extends j{constructor(){super(...arguments),this._buffers=new Map}appendChunk(e,t){this.ensureNotDisposed();const s=(this._buffers.get(e)||"")+t;return this._buffers.set(e,s),m.debug(`Message chunk appended for question ${e}, length: ${s.length}`),s}getMessage(e){return this._buffers.get(e)||null}complete(e){const t=this.getMessage(e)||"";return this._buffers.delete(e),m.debug(`Message assembly completed for question ${e}, length: ${t.length}`),t}clear(e){this._buffers.delete(e)}onDispose(){this._buffers.clear(),m.info("Message Assembler disposed")}}class Fc{generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}generateQuestionId(){return Math.random().toString(36).substring(2,6)}}class Bc extends j{constructor(e,t){super(),this._transport=null,this._sessions=new Map,this._context=e,this._assembler=new Uc,this._idService=new Fc,m.info("Conversation Manager created")}setTransport(e){this._transport=e}async sendQuestion(e,t={speed:100,mood:0,vol:50}){this.ensureNotDisposed();const i=this._idService.generateQuestionId(),s={id:i,text:e,timestamp:Date.now(),inputMode:"text"},r=this._idService.generateSessionId(),a=new Is(r,this._context);if(a.handleEvent({type:"QUESTION",payload:s}),this._sessions.set(i,a),this._transport)try{this._transport.sendText(i,e,200,t)}catch(o){throw m.error("Error sending question via transport:",o),a.handleEvent({type:"ERROR",payload:"Failed to send question"}),this._context.eventBus.emit("inner:sdk:error",{error:o instanceof Error?o:new Error(String(o))}),o}else m.warn("Transport not set, question not sent");return this._context.eventBus.emit("inner:conversation:question:sent",{questionId:i,text:e}),this._context.eventBus.emit("inner:conversation:answer:waiting",{questionId:i}),m.info(`Question sent: ${i}`),i}handleServerPong(){this.ensureNotDisposed(),this._transport&&this._transport.handlePongReceived()}willDisconnect(){this.ensureNotDisposed(),this._transport?.willDisconnect()}handleTextInput(e){this.sendQuestion(e).catch(t=>{m.error("Error sending question:",t)})}handleAnswerChunk(e,t,i){this.ensureNotDisposed();const s=this._sessions.get(e);if(!s){m.warn(`No active session for answer chunk: ${e}`);return}if(s.state===D.ConversationStateType.WAITING&&s.handleEvent({type:"ANSWER_START",payload:e}),i){s.handleEvent({type:"ANSWER_COMPLETE"});const a=this._assembler.complete(e);this._context.eventBus.emit("inner:conversation:answer:completed",{questionId:e,fullAnswer:a});try{s.dispose()}catch(o){m.error("Error disposing session:",o)}this._sessions.delete(e)}else s.handleEvent({type:"ANSWER_CHUNK",payload:{uid:e,chunk:t,isComplete:i}}),this._assembler.appendChunk(e,t),this._context.eventBus.emit("inner:conversation:answer:chunk",{questionId:e,chunk:t,isComplete:i})}handleServerInitiatedMessage(e,t){this.ensureNotDisposed(),this._context.eventBus.emit("inner:conversation:server:message",{questionId:e,message:t,type:"text"})}handleAsrTextReceived(e,t){this.ensureNotDisposed();const i=this._idService.generateSessionId(),s=new Is(i,this._context);s.handleEvent({type:"QUESTION",payload:{id:e,text:t,timestamp:Date.now(),inputMode:"voice"}}),this._sessions.set(e,s),this._context.eventBus.emit("inner:conversation:asr:received",{questionId:e,text:t})}handleServerCommand(e,t){this.ensureNotDisposed(),this._context.eventBus.emit("inner:conversation:server:command",{code:e,command:t})}onDispose(){for(const e of this._sessions.values())try{e.dispose()}catch(t){m.error("Error disposing session:",t)}this._sessions.clear(),this._assembler.dispose(),m.info("Conversation Manager disposed")}}class Vc extends j{constructor(e,t){super(),this._manager=new Bc(e,t),m.info("Conversation Controller created")}get manager(){return this._manager}setTransport(e){this._manager.setTransport(e)}async sendQuestion(e,t){return this.ensureNotDisposed(),this._manager.sendQuestion(e,t)}onDispose(){this._manager.dispose(),m.info("Conversation Controller disposed")}}class jc extends j{constructor(){super(...arguments),this._tracks=new Map,this._participants=new Map}register(e,t,i){this.ensureNotDisposed(),this._tracks.set(e,t),this._participants.has(i)||this._participants.set(i,new Set),this._participants.get(i).add(e),t.on("ended",()=>{m.debug(`Track ended: ${e}`),this.unregister(e)}),m.debug(`Track registered: ${e} from participant ${i}`)}unregister(e){const t=this._tracks.get(e);if(t){t.stop(),this._tracks.delete(e);for(const[i,s]of this._participants.entries())if(s.has(e)){s.delete(e),s.size===0&&this._participants.delete(i);break}m.debug(`Track unregistered: ${e}`)}}getTrack(e){return this._tracks.get(e)||null}getParticipantTracks(e){const t=this._participants.get(e);return t?Array.from(t):[]}getAllTrackIds(){return Array.from(this._tracks.keys())}getVideoAvailability(){let e=!1,t=!1,i=!1;for(const s of this._tracks.values()){const r=s.mediaStreamTrack;if(r.kind==="video"&&(e=!0,r.readyState==="live"&&(t=!0),r.enabled&&(i=!0),r.readyState==="live"&&r.enabled))return{available:!0}}return e?t?i?{available:!1,reason:ht.NO_VIDEO_TRACK}:{available:!1,reason:ht.TRACK_MUTED}:{available:!1,reason:ht.TRACK_ENDED}:{available:!1,reason:ht.NO_VIDEO_TRACK}}clear(){for(const e of this._tracks.values())e.stop();this._tracks.clear(),this._participants.clear(),m.info("All tracks cleared")}onDispose(){this.clear()}}class Ds extends j{constructor(e,t){super(),this._videoController=null,this._room=null,this._context=e,this._trackRegistry=t,this._loosTrackTimer=null,m.info("Video Track Handler created")}setRoom(e){this._room=e}setVideoController(e){this._videoController=e}handleTrackSubscribed(e,t,i){this.ensureNotDisposed(),this._loosTrackTimer&&clearTimeout(this._loosTrackTimer),this._trackRegistry.register(t,e,i),this._videoController&&e.attach(this._videoController.getSource().getInternalElement()),e.on("videoPlaybackStarted",()=>{m.info("inner:rtc:video:available"),this._context.eventBus.emit("inner:rtc:video:available",void 0)}),this._context.eventBus.emit("inner:video:track:added",{trackId:t,participantId:i}),m.debug(`Video track subscribed: ${t}`)}handleTrackUnsubscribed(e,t,i){this.ensureNotDisposed(),this._videoController&&e.detach(this._videoController.getSource().getInternalElement()),e.removeAllListeners(),this._context.eventBus.emit("inner:video:track:removed",{trackId:t,participantId:i}),this._loosTrackTimer&&clearTimeout(this._loosTrackTimer),this._loosTrackTimer=setTimeout(()=>{this._context.eventBus.emit("inner:rtc:video:unavailable",void 0)},Ba),this._trackRegistry.unregister(t),m.debug(`Video track unsubscribed: ${t}`)}supports(e){return e.mediaStreamTrack.kind==="video"}onDispose(){this._loosTrackTimer&&(clearTimeout(this._loosTrackTimer),this._loosTrackTimer=null),m.info("Video Track Handler disposed")}}class As extends j{constructor(e,t){super(),this._audioController=null,this._room=null,this._context=e,this._trackRegistry=t,m.info("Audio Track Handler created")}setRoom(e){this._room=e}setAudioController(e){this._audioController=e}handleTrackSubscribed(e,t,i){this.ensureNotDisposed(),this._trackRegistry.register(t,e,i),this._audioController?e.attach(this._audioController.getOutputElement()):this._context.eventBus.emit("inner:audio:track:added",{trackId:t,participantId:i}),m.debug(`Audio track subscribed: ${t}`)}handleTrackUnsubscribed(e,t,i){this.ensureNotDisposed(),this._audioController?(this._audioController.removeOutputTrack(t),e.detach(this._audioController.getOutputElement())):this._context.eventBus.emit("inner:audio:track:removed",{trackId:t}),this._trackRegistry.unregister(t),m.debug(`Audio track unsubscribed: ${t}`)}supports(e){return e.mediaStreamTrack.kind==="audio"}onDispose(){m.info("Audio Track Handler disposed")}}class qc extends j{constructor(e,t){super(),this._room=null,this._context=e,this._trackRegistry=t,this._handlers=[new Ds(e,t),new As(e,t)],m.info("LiveKit Event Adapter created")}setRoom(e){this._room=e,this._handlers.forEach(t=>{t.setRoom(e)}),console.log("LiveKit room set:",this._room)}setVideoController(e){const t=this._handlers.find(i=>i instanceof Ds);t&&t.setVideoController(e)}setAudioController(e){const t=this._handlers.find(i=>i instanceof As);t&&t.setAudioController(e)}handleTrackSubscribed(e,t,i){this.ensureNotDisposed();const s=this._findHandler(e);s?s.handleTrackSubscribed(e,t,i):m.warn(`No handler found for track, trackId: ${t}`)}handleTrackUnsubscribed(e,t){this.ensureNotDisposed();const i=this._trackRegistry.getTrack(e);if(i){const s=this._findHandler(i);s?s.handleTrackUnsubscribed(i,e,t):(this._trackRegistry.unregister(e),m.warn(`No handler found for track, trackId: ${e}`))}}_findHandler(e){return this._handlers.find(t=>t.supports(e))||null}onDispose(){this._handlers.forEach(e=>{try{e.dispose()}catch(t){m.error("Error disposing track handler:",t)}}),this._handlers.length=0,m.info("LiveKit Event Adapter disposed")}}function Wc(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(i!=="default"&&!(i in n)){var s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,s.get?s:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(n)}var Kc=Object.defineProperty,Hc=(n,e,t)=>e in n?Kc(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Os=(n,e,t)=>Hc(n,typeof e!="symbol"?e+"":e,t);class he{constructor(){Os(this,"_locking"),Os(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(s=>e=()=>{this._locks-=1,s()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function ee(n,e){if(!n)throw new Error(e)}const Gc=34028234663852886e22,zc=-34028234663852886e22,Jc=4294967295,$c=2147483647,Qc=-2147483648;function Xt(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>$c||n<Qc)throw new Error("invalid int 32: "+n)}function Vi(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>Jc||n<0)throw new Error("invalid uint 32: "+n)}function Ns(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>Gc||n<zc))throw new Error("invalid float 32: "+n)}const xs=Symbol("@bufbuild/protobuf/enum-type");function Yc(n){const e=n[xs];return ee(e,"missing enum type on enum object"),e}function Ms(n,e,t,i){n[xs]=Ls(e,t.map(s=>({no:s.no,name:s.name,localName:n[s.no]})))}function Ls(n,e,t){const i=Object.create(null),s=Object.create(null),r=[];for(const a of e){const o=Us(a);r.push(o),i[a.name]=o,s[a.no]=o}return{typeName:n,values:r,findName(a){return i[a]},findNumber(a){return s[a]}}}function Xc(n,e,t){const i={};for(const s of e){const r=Us(s);i[r.localName]=r.no,i[r.no]=r.localName}return Ms(i,n,e),i}function Us(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class ji{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType(),s=i.runtime.bin,r=s.makeReadOptions(t);return s.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const i=this.getType(),s=i.runtime.json,r=s.makeReadOptions(t);return s.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(s){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(s instanceof Error?s.message:String(s)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType(),i=t.runtime.bin,s=i.makeWriteOptions(e),r=s.writerFactory();return i.writeMessage(this,r,s),r.finish()}toJson(e){const t=this.getType(),i=t.runtime.json,s=i.makeWriteOptions(e);return i.writeMessage(this,s)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,(t=e?.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Zc(n,e,t,i){var s;const r=(s=i?.localName)!==null&&s!==void 0?s:e.substring(e.lastIndexOf(".")+1),a={[r]:function(o){n.util.initFields(this),n.util.initPartial(o,this)}}[r];return Object.setPrototypeOf(a.prototype,new ji),Object.assign(a,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary(o,c){return new a().fromBinary(o,c)},fromJson(o,c){return new a().fromJson(o,c)},fromJsonString(o,c){return new a().fromJsonString(o,c)},equals(o,c){return n.util.equals(a,o,c)}}),a}function ed(){let n=0,e=0;for(let i=0;i<28;i+=7){let s=this.buf[this.pos++];if(n|=(s&127)<<i,(s&128)==0)return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<i,(s&128)==0)return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function qi(n,e,t){for(let r=0;r<28;r=r+7){const a=n>>>r,o=!(!(a>>>7)&&e==0),c=(o?a|128:a)&255;if(t.push(c),!o)return}const i=n>>>28&15|(e&7)<<4,s=e>>3!=0;if(t.push((s?i|128:i)&255),!!s){for(let r=3;r<31;r=r+7){const a=e>>>r,o=!!(a>>>7),c=(o?a|128:a)&255;if(t.push(c),!o)return}t.push(e>>>31&1)}}const Zt=4294967296;function Fs(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,s=0;function r(a,o){const c=Number(n.slice(a,o));s*=t,i=i*t+c,i>=Zt&&(s=s+(i/Zt|0),i=i%Zt)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?Vs(i,s):Wi(i,s)}function td(n,e){let t=Wi(n,e);const i=t.hi&2147483648;i&&(t=Vs(t.lo,t.hi));const s=Bs(t.lo,t.hi);return i?"-"+s:s}function Bs(n,e){if({lo:n,hi:e}=id(n,e),e<=2097151)return String(Zt*e+n);const t=n&16777215,i=(n>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+i*6777216+s*6710656,a=i+s*8147497,o=s*2;const c=1e7;return r>=c&&(a+=Math.floor(r/c),r%=c),a>=c&&(o+=Math.floor(a/c),a%=c),o.toString()+js(a)+js(r)}function id(n,e){return{lo:n>>>0,hi:e>>>0}}function Wi(n,e){return{lo:n|0,hi:e|0}}function Vs(n,e){return e=~e,n?n=~n+1:e+=1,Wi(n,e)}const js=n=>{const e=String(n);return"0000000".slice(e.length)+e};function qs(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function nd(){let n=this.buf[this.pos++],e=n&127;if((n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,(n&128)==0)return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;(n&128)!==0&&t<10;t++)n=this.buf[this.pos++];if((n&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function sd(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const s=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),a=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>r||d<s)throw new Error("int64 invalid: ".concat(c));return d},uParse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>o||d<a)throw new Error("uint64 invalid: ".concat(c));return d},enc(c){return n.setBigInt64(0,this.parse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(c){return n.setBigInt64(0,this.uParse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigInt64(0,!0)},uDec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigUint64(0,!0)}}}const t=s=>ee(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),i=s=>ee(/^[0-9]+$/.test(s),"uint64 invalid: ".concat(s));return{zero:"0",supported:!1,parse(s){return typeof s!="string"&&(s=s.toString()),t(s),s},uParse(s){return typeof s!="string"&&(s=s.toString()),i(s),s},enc(s){return typeof s!="string"&&(s=s.toString()),t(s),Fs(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),i(s),Fs(s)},dec(s,r){return td(s,r)},uDec(s,r){return Bs(s,r)}}}const X=sd();var k;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(k||(k={}));var He;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(He||(He={}));function Ge(n,e,t){if(e===t)return!0;if(n==k.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}switch(n){case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return e==t}return!1}function pt(n,e){switch(n){case k.BOOL:return!1;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return e==0?X.zero:"0";case k.DOUBLE:case k.FLOAT:return 0;case k.BYTES:return new Uint8Array(0);case k.STRING:return"";default:return 0}}function Ws(n,e){switch(n){case k.BOOL:return e===!1;case k.STRING:return e==="";case k.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var ne;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(ne||(ne={}));class rd{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let s=0;s<this.chunks.length;s++)e+=this.chunks[s].length;let t=new Uint8Array(e),i=0;for(let s=0;s<this.chunks.length;s++)t.set(this.chunks[s],i),i+=this.chunks[s].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Vi(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Xt(e),qs(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Ns(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Vi(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Xt(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Xt(e),e=(e<<1^e>>31)>>>0,qs(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=X.enc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=X.uEnc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=X.enc(e);return qi(t.lo,t.hi,this.buf),this}sint64(e){let t=X.enc(e),i=t.hi>>31,s=t.lo<<1^i,r=(t.hi<<1|t.lo>>>31)^i;return qi(s,r,this.buf),this}uint64(e){let t=X.uEnc(e);return qi(t.lo,t.hi,this.buf),this}}class od{constructor(e,t){this.varint64=ed,this.uint32=nd,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case ne.Varint:for(;this.buf[this.pos++]&128;);break;case ne.Bit64:this.pos+=4;case ne.Bit32:this.pos+=4;break;case ne.LengthDelimited:let s=this.uint32();this.pos+=s;break;case ne.StartGroup:for(;;){const[r,a]=this.tag();if(a===ne.EndGroup){if(t!==void 0&&r!==t)throw new Error("invalid end group tag");break}this.skip(a,r)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return X.dec(...this.varint64())}uint64(){return X.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,X.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return X.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return X.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function ad(n,e,t,i){let s;return{typeName:e,extendee:t,get field(){if(!s){const r=typeof i=="function"?i():i;r.name=e.split(".").pop(),r.jsonName="[".concat(e,"]"),s=n.util.newFieldList([r]).list()[0]}return s},runtime:n}}function Ks(n){const e=n.field.localName,t=Object.create(null);return t[e]=cd(n),[t,()=>t[e]]}function cd(n){const e=n.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return pt(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function dd(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=n.length-1;t>=0;--t)if(n[t].no==e.no)return[n[t]];return[]}return n.filter(t=>t.no===e.no)}let Fe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),ei=[];for(let n=0;n<Fe.length;n++)ei[Fe[n].charCodeAt(0)]=n;ei[45]=Fe.indexOf("+"),ei[95]=Fe.indexOf("/");const Hs={dec(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let t=new Uint8Array(e),i=0,s=0,r,a=0;for(let o=0;o<n.length;o++){if(r=ei[n.charCodeAt(o)],r===void 0)switch(n[o]){case"=":s=0;case`
111
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:a=r,s=1;break;case 1:t[i++]=a<<2|(r&48)>>4,a=r,s=2;break;case 2:t[i++]=(a&15)<<4|(r&60)>>2,a=r,s=3;break;case 3:t[i++]=(a&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return t.subarray(0,i)},enc(n){let e="",t=0,i,s=0;for(let r=0;r<n.length;r++)switch(i=n[r],t){case 0:e+=Fe[i>>2],s=(i&3)<<4,t=1;break;case 1:e+=Fe[s|i>>4],s=(i&15)<<2,t=2;break;case 2:e+=Fe[s|i>>6],e+=Fe[i&63],t=0;break}return t&&(e+=Fe[s],e+="=",t==1&&(e+="=")),e}};function ld(n,e,t){zs(e,n);const i=e.runtime.bin.makeReadOptions(t),s=dd(n.getType().runtime.bin.listUnknownFields(n),e.field),[r,a]=Ks(e);for(const o of s)e.runtime.bin.readField(r,i.readerFactory(o.data),e.field,o.wireType,i);return a()}function ud(n,e,t,i){zs(e,n);const s=e.runtime.bin.makeReadOptions(i),r=e.runtime.bin.makeWriteOptions(i);if(Gs(n,e)){const d=n.getType().runtime.bin.listUnknownFields(n).filter(l=>l.no!=e.field.no);n.getType().runtime.bin.discardUnknownFields(n);for(const l of d)n.getType().runtime.bin.onUnknownField(n,l.no,l.wireType,l.data)}const a=r.writerFactory();let o=e.field;!o.opt&&!o.repeated&&(o.kind=="enum"||o.kind=="scalar")&&(o=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(o,t,a,r);const c=s.readerFactory(a.finish());for(;c.pos<c.len;){const[d,l]=c.tag(),u=c.skip(l,d);n.getType().runtime.bin.onUnknownField(n,d,l,u)}}function Gs(n,e){const t=n.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(n).find(i=>i.no==e.field.no)}function zs(n,e){ee(n.extendee.typeName==e.getType().typeName,"extension ".concat(n.typeName," can only be applied to message ").concat(n.extendee.typeName))}function Js(n,e){const t=n.localName;if(n.repeated)return e[t].length>0;if(n.oneof)return e[n.oneof.localName].case===t;switch(n.kind){case"enum":case"scalar":return n.opt||n.req?e[t]!==void 0:n.kind=="enum"?e[t]!==n.T.values[0].no:!Ws(n.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function $s(n,e){const t=n.localName,i=!n.opt&&!n.req;if(n.repeated)e[t]=[];else if(n.oneof)e[n.oneof.localName]={case:void 0};else switch(n.kind){case"map":e[t]={};break;case"enum":e[t]=i?n.T.values[0].no:void 0;break;case"scalar":e[t]=i?pt(n.T,n.L):void 0;break;case"message":e[t]=void 0;break}}function Be(n,e){if(n===null||typeof n!="object"||!Object.getOwnPropertyNames(ji.prototype).every(i=>i in n&&typeof n[i]=="function"))return!1;const t=n.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function Qs(n,e){return Be(e)||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}k.DOUBLE,k.FLOAT,k.INT64,k.UINT64,k.INT32,k.UINT32,k.BOOL,k.STRING,k.BYTES;const Ys={ignoreUnknownFields:!1},Xs={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function hd(n){return n?Object.assign(Object.assign({},Ys),n):Ys}function pd(n){return n?Object.assign(Object.assign({},Xs),n):Xs}const ti=Symbol(),ii=Symbol();function md(){return{makeReadOptions:hd,makeWriteOptions:pd,readMessage(n,e,t,i){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(n.typeName," from JSON: ").concat(Oe(e)));i=i??new n;const s=new Map,r=t.typeRegistry;for(const[a,o]of Object.entries(e)){const c=n.fields.findJsonName(a);if(c){if(c.oneof){if(o===null&&c.kind=="scalar")continue;const d=s.get(c.oneof);if(d!==void 0)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(d,'", "').concat(a,'"'));s.set(c.oneof,a)}Zs(i,o,c,t,n)}else{let d=!1;if(r?.findExtension&&a.startsWith("[")&&a.endsWith("]")){const l=r.findExtension(a.substring(1,a.length-1));if(l&&l.extendee.typeName==n.typeName){d=!0;const[u,h]=Ks(l);Zs(u,o,l.field,t,l),ud(i,l,h(),t)}}if(!d&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: key "').concat(a,'" is unknown'))}}return i},writeMessage(n,e){const t=n.getType(),i={};let s;try{for(s of t.fields.byNumber()){if(!Js(s,n)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!gd(s))continue}const a=s.oneof?n[s.oneof.localName].value:n[s.localName],o=er(s,a,e);o!==void 0&&(i[e.useProtoFieldName?s.name:s.jsonName]=o)}const r=e.typeRegistry;if(r?.findExtensionFor)for(const a of t.runtime.bin.listUnknownFields(n)){const o=r.findExtensionFor(t.typeName,a.no);if(o&&Gs(n,o)){const c=ld(n,o,e),d=er(o.field,c,e);d!==void 0&&(i[o.field.jsonName]=d)}}}catch(r){const a=s?"cannot encode field ".concat(t.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),o=r instanceof Error?r.message:String(r);throw new Error(a+(o.length>0?": ".concat(o):""))}return i},readScalar(n,e,t){return Nt(n,e,t??He.BIGINT,!0)},writeScalar(n,e,t){if(e!==void 0&&(t||Ws(n,e)))return ni(n,e)},debug:Oe}}function Oe(n){if(n===null)return"null";switch(typeof n){case"object":return Array.isArray(n)?"array":"object";case"string":return n.length>100?"string":'"'.concat(n.split('"').join('\\"'),'"');default:return String(n)}}function Zs(n,e,t,i,s){let r=t.localName;if(t.repeated){if(ee(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Oe(e)));const a=n[r];for(const o of e){if(o===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Oe(o)));switch(t.kind){case"message":a.push(t.T.fromJson(o,i));break;case"enum":const c=Ki(t.T,o,i.ignoreUnknownFields,!0);c!==ii&&a.push(c);break;case"scalar":try{a.push(Nt(t.T,o,t.L,!0))}catch(d){let l="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Oe(o));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Oe(e)));const a=n[r];for(const[o,c]of Object.entries(e)){if(c===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: map value null"));let d;try{d=fd(t.K,o)}catch(l){let u="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Oe(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}switch(t.V.kind){case"message":a[d]=t.V.T.fromJson(c,i);break;case"enum":const l=Ki(t.V.T,c,i.ignoreUnknownFields,!0);l!==ii&&(a[d]=l);break;case"scalar":try{a[d]=Nt(t.V.T,c,He.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Oe(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}}else switch(t.oneof&&(n=n[t.oneof.localName]={case:r},r="value"),t.kind){case"message":const a=t.T;if(e===null&&a.typeName!="google.protobuf.Value")return;let o=n[r];Be(o)?o.fromJson(e,i):(n[r]=o=a.fromJson(e,i),a.fieldWrapper&&!t.oneof&&(n[r]=a.fieldWrapper.unwrapField(o)));break;case"enum":const c=Ki(t.T,e,i.ignoreUnknownFields,!1);switch(c){case ti:$s(t,n);break;case ii:break;default:n[r]=c;break}break;case"scalar":try{const d=Nt(t.T,e,t.L,!1);d===ti?$s(t,n):n[r]=d}catch(d){let l="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Oe(e));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}function fd(n,e){if(n===k.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Nt(n,e,He.BIGINT,!0).toString()}function Nt(n,e,t,i){if(e===null)return i?pt(n,t):ti;switch(n){case k.DOUBLE:case k.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const s=Number(e);if(Number.isNaN(s)||!Number.isFinite(s))break;return n==k.FLOAT&&Ns(s),s;case k.INT32:case k.FIXED32:case k.SFIXED32:case k.SINT32:case k.UINT32:let r;if(typeof e=="number"?r=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(r=Number(e)),r===void 0)break;return n==k.UINT32||n==k.FIXED32?Vi(r):Xt(r),r;case k.INT64:case k.SFIXED64:case k.SINT64:if(typeof e!="number"&&typeof e!="string")break;const a=X.parse(e);return t?a.toString():a;case k.FIXED64:case k.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=X.uParse(e);return t?o.toString():o;case k.BOOL:if(typeof e!="boolean")break;return e;case k.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case k.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return Hs.dec(e)}throw new Error}function Ki(n,e,t,i){if(e===null)return n.typeName=="google.protobuf.NullValue"?0:i?n.values[0].no:ti;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const s=n.findName(e);if(s!==void 0)return s.no;if(t)return ii;break}throw new Error("cannot decode enum ".concat(n.typeName," from JSON: ").concat(Oe(e)))}function gd(n){return n.repeated||n.kind=="map"?!0:!(n.oneof||n.kind=="message"||n.opt||n.req)}function er(n,e,t){if(n.kind=="map"){ee(typeof e=="object"&&e!=null);const i={},s=Object.entries(e);switch(n.V.kind){case"scalar":for(const[a,o]of s)i[a.toString()]=ni(n.V.T,o);break;case"message":for(const[a,o]of s)i[a.toString()]=o.toJson(t);break;case"enum":const r=n.V.T;for(const[a,o]of s)i[a.toString()]=Hi(r,o,t.enumAsInteger);break}return t.emitDefaultValues||s.length>0?i:void 0}if(n.repeated){ee(Array.isArray(e));const i=[];switch(n.kind){case"scalar":for(let s=0;s<e.length;s++)i.push(ni(n.T,e[s]));break;case"enum":for(let s=0;s<e.length;s++)i.push(Hi(n.T,e[s],t.enumAsInteger));break;case"message":for(let s=0;s<e.length;s++)i.push(e[s].toJson(t));break}return t.emitDefaultValues||i.length>0?i:void 0}switch(n.kind){case"scalar":return ni(n.T,e);case"enum":return Hi(n.T,e,t.enumAsInteger);case"message":return Qs(n.T,e).toJson(t)}}function Hi(n,e,t){var i;if(ee(typeof e=="number"),n.typeName=="google.protobuf.NullValue")return null;if(t)return e;const s=n.findNumber(e);return(i=s?.name)!==null&&i!==void 0?i:e}function ni(n,e){switch(n){case k.INT32:case k.SFIXED32:case k.SINT32:case k.FIXED32:case k.UINT32:return ee(typeof e=="number"),e;case k.FLOAT:case k.DOUBLE:return ee(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case k.STRING:return ee(typeof e=="string"),e;case k.BOOL:return ee(typeof e=="boolean"),e;case k.UINT64:case k.FIXED64:case k.INT64:case k.SFIXED64:case k.SINT64:return ee(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case k.BYTES:return ee(e instanceof Uint8Array),Hs.enc(e)}}const mt=Symbol("@bufbuild/protobuf/unknown-fields"),tr={readUnknownFields:!0,readerFactory:n=>new od(n)},ir={writeUnknownFields:!0,writerFactory:()=>new rd};function vd(n){return n?Object.assign(Object.assign({},tr),n):tr}function bd(n){return n?Object.assign(Object.assign({},ir),n):ir}function yd(){return{makeReadOptions:vd,makeWriteOptions:bd,listUnknownFields(n){var e;return(e=n[mt])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[mt]},writeUnknownFields(n,e){const i=n[mt];if(i)for(const s of i)e.tag(s.no,s.wireType).raw(s.data)},onUnknownField(n,e,t,i){const s=n;Array.isArray(s[mt])||(s[mt]=[]),s[mt].push({no:e,wireType:t,data:i})},readMessage(n,e,t,i,s){const r=n.getType(),a=s?e.len:e.pos+t;let o,c;for(;e.pos<a&&([o,c]=e.tag(),!(s===!0&&c==ne.EndGroup));){const d=r.fields.find(o);if(!d){const l=e.skip(c,o);i.readUnknownFields&&this.onUnknownField(n,o,c,l);continue}nr(n,e,d,c,i)}if(s&&(c!=ne.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:nr,writeMessage(n,e,t){const i=n.getType();for(const s of i.fields.byNumber()){if(!Js(s,n)){if(s.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(s.name," to binary: required field not set"));continue}const r=s.oneof?n[s.oneof.localName].value:n[s.localName];sr(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(n,e),e},writeField(n,e,t,i){e!==void 0&&sr(n,e,t,i)}}}function nr(n,e,t,i,s){let{repeated:r,localName:a}=t;switch(t.oneof&&(n=n[t.oneof.localName],n.case!=a&&delete n.value,n.case=a,a="value"),t.kind){case"scalar":case"enum":const o=t.kind=="enum"?k.INT32:t.T;let c=ri;if(t.kind=="scalar"&&t.L>0&&(c=Td),r){let h=n[a];if(i==ne.LengthDelimited&&o!=k.STRING&&o!=k.BYTES){let b=e.uint32()+e.pos;for(;e.pos<b;)h.push(c(e,o))}else h.push(c(e,o))}else n[a]=c(e,o);break;case"message":const d=t.T;r?n[a].push(si(e,new d,s,t)):Be(n[a])?si(e,n[a],s,t):(n[a]=si(e,new d,s,t),d.fieldWrapper&&!t.oneof&&!t.repeated&&(n[a]=d.fieldWrapper.unwrapField(n[a])));break;case"map":let[l,u]=_d(t,e,s);n[a][l]=u;break}}function si(n,e,t,i){const s=e.getType().runtime.bin,r=i?.delimited;return s.readMessage(e,n,r?i.no:n.uint32(),t,r),e}function _d(n,e,t){const i=e.uint32(),s=e.pos+i;let r,a;for(;e.pos<s;){const[o]=e.tag();switch(o){case 1:r=ri(e,n.K);break;case 2:switch(n.V.kind){case"scalar":a=ri(e,n.V.T);break;case"enum":a=e.int32();break;case"message":a=si(e,new n.V.T,t,void 0);break}break}}if(r===void 0&&(r=pt(n.K,He.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),a===void 0)switch(n.V.kind){case"scalar":a=pt(n.V.T,He.BIGINT);break;case"enum":a=n.V.T.values[0].no;break;case"message":a=new n.V.T;break}return[r,a]}function Td(n,e){const t=ri(n,e);return typeof t=="bigint"?t.toString():t}function ri(n,e){switch(e){case k.STRING:return n.string();case k.BOOL:return n.bool();case k.DOUBLE:return n.double();case k.FLOAT:return n.float();case k.INT32:return n.int32();case k.INT64:return n.int64();case k.UINT64:return n.uint64();case k.FIXED64:return n.fixed64();case k.BYTES:return n.bytes();case k.FIXED32:return n.fixed32();case k.SFIXED32:return n.sfixed32();case k.SFIXED64:return n.sfixed64();case k.SINT64:return n.sint64();case k.UINT32:return n.uint32();case k.SINT32:return n.sint32()}}function sr(n,e,t,i){ee(e!==void 0);const s=n.repeated;switch(n.kind){case"scalar":case"enum":let r=n.kind=="enum"?k.INT32:n.T;if(s)if(ee(Array.isArray(e)),n.packed)Sd(t,r,n.no,e);else for(const a of e)xt(t,r,n.no,a);else xt(t,r,n.no,e);break;case"message":if(s){ee(Array.isArray(e));for(const a of e)rr(t,i,n,a)}else rr(t,i,n,e);break;case"map":ee(typeof e=="object"&&e!=null);for(const[a,o]of Object.entries(e))kd(t,i,n,a,o);break}}function kd(n,e,t,i,s){n.tag(t.no,ne.LengthDelimited),n.fork();let r=i;switch(t.K){case k.INT32:case k.FIXED32:case k.UINT32:case k.SFIXED32:case k.SINT32:r=Number.parseInt(i);break;case k.BOOL:ee(i=="true"||i=="false"),r=i=="true";break}switch(xt(n,t.K,1,r),t.V.kind){case"scalar":xt(n,t.V.T,2,s);break;case"enum":xt(n,k.INT32,2,s);break;case"message":ee(s!==void 0),n.tag(2,ne.LengthDelimited).bytes(s.toBinary(e));break}n.join()}function rr(n,e,t,i){const s=Qs(t.T,i);t.delimited?n.tag(t.no,ne.StartGroup).raw(s.toBinary(e)).tag(t.no,ne.EndGroup):n.tag(t.no,ne.LengthDelimited).bytes(s.toBinary(e))}function xt(n,e,t,i){ee(i!==void 0);let[s,r]=or(e);n.tag(t,s)[r](i)}function Sd(n,e,t,i){if(!i.length)return;n.tag(t,ne.LengthDelimited).fork();let[,s]=or(e);for(let r=0;r<i.length;r++)n[s](i[r]);n.join()}function or(n){let e=ne.Varint;switch(n){case k.BYTES:case k.STRING:e=ne.LengthDelimited;break;case k.DOUBLE:case k.FIXED64:case k.SFIXED64:e=ne.Bit64;break;case k.FIXED32:case k.SFIXED32:case k.FLOAT:e=ne.Bit32;break}const t=k[n].toLowerCase();return[e,t]}function Cd(){return{setEnumType:Ms,initPartial(n,e){if(n===void 0)return;const t=e.getType();for(const i of t.fields.byMember()){const s=i.localName,r=e,a=n;if(a[s]!=null)switch(i.kind){case"oneof":const o=a[s].case;if(o===void 0)continue;const c=i.findField(o);let d=a[s].value;c&&c.kind=="message"&&!Be(d,c.T)?d=new c.T(d):c&&c.kind==="scalar"&&c.T===k.BYTES&&(d=Mt(d)),r[s]={case:o,value:d};break;case"scalar":case"enum":let l=a[s];i.T===k.BYTES&&(l=i.repeated?l.map(Mt):Mt(l)),r[s]=l;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===k.BYTES)for(const[f,b]of Object.entries(a[s]))r[s][f]=Mt(b);else Object.assign(r[s],a[s]);break;case"message":const h=i.V.T;for(const f of Object.keys(a[s])){let b=a[s][f];h.fieldWrapper||(b=new h(b)),r[s][f]=b}break}break;case"message":const u=i.T;if(i.repeated)r[s]=a[s].map(h=>Be(h,u)?h:new u(h));else{const h=a[s];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[s]=Mt(h):r[s]=h:r[s]=Be(h,u)?h:new u(h)}break}}},equals(n,e,t){return e===t?!0:!e||!t?!1:n.fields.byMember().every(i=>{const s=e[i.localName],r=t[i.localName];if(i.repeated){if(s.length!==r.length)return!1;switch(i.kind){case"message":return s.every((a,o)=>i.T.equals(a,r[o]));case"scalar":return s.every((a,o)=>Ge(i.T,a,r[o]));case"enum":return s.every((a,o)=>Ge(k.INT32,a,r[o]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":let a=s,o=r;return i.T.fieldWrapper&&(a!==void 0&&!Be(a)&&(a=i.T.fieldWrapper.wrapField(a)),o!==void 0&&!Be(o)&&(o=i.T.fieldWrapper.wrapField(o))),i.T.equals(a,o);case"enum":return Ge(k.INT32,s,r);case"scalar":return Ge(i.T,s,r);case"oneof":if(s.case!==r.case)return!1;const c=i.findField(s.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(s.value,r.value);case"enum":return Ge(k.INT32,s.value,r.value);case"scalar":return Ge(c.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const d=Object.keys(s).concat(Object.keys(r));switch(i.V.kind){case"message":const l=i.V.T;return d.every(h=>l.equals(s[h],r[h]));case"enum":return d.every(h=>Ge(k.INT32,s[h],r[h]));case"scalar":const u=i.V.T;return d.every(h=>Ge(u,s[h],r[h]))}break}})},clone(n){const e=n.getType(),t=new e,i=t;for(const s of e.fields.byMember()){const r=n[s.localName];let a;if(s.repeated)a=r.map(oi);else if(s.kind=="map"){a=i[s.localName];for(const[o,c]of Object.entries(r))a[o]=oi(c)}else s.kind=="oneof"?a=s.findField(r.case)?{case:r.case,value:oi(r.value)}:{case:void 0}:a=oi(r);i[s.localName]=a}for(const s of e.runtime.bin.listUnknownFields(n))e.runtime.bin.onUnknownField(i,s.no,s.wireType,s.data);return t}}}function oi(n){if(n===void 0)return n;if(Be(n))return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function Mt(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function Ed(n,e,t){return{syntax:n,json:md(),bin:yd(),util:Object.assign(Object.assign({},Cd()),{newFieldList:e,initFields:t}),makeMessageType(i,s,r){return Zc(this,i,s,r)},makeEnum:Xc,makeEnumType:Ls,getEnumType:Yc,makeExtension(i,s,r){return ad(this,i,s,r)}}}class Rd{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const i of this.list())t[i.jsonName]=t[i.name]=i;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const i of this.list())t[i.no]=i;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function ar(n,e){const t=cr(n);return e?t:Od(Ad(t))}function wd(n){return ar(n,!1)}const Pd=cr;function cr(n){let e=!1;const t=[];for(let i=0;i<n.length;i++){let s=n.charAt(i);switch(s){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(s),e=!1;break;default:e&&(e=!1,s=s.toUpperCase()),t.push(s);break}}return t.join("")}const Id=new Set(["constructor","toString","toJSON","valueOf"]),Dd=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),dr=n=>"".concat(n,"$"),Ad=n=>Dd.has(n)?dr(n):n,Od=n=>Id.has(n)?dr(n):n;class Nd{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=wd(e)}addField(e){ee(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function xd(n,e){var t,i,s,r,a,o;const c=[];let d;for(const l of typeof n=="function"?n():n){const u=l;if(u.localName=ar(l.name,l.oneof!==void 0),u.jsonName=(t=l.jsonName)!==null&&t!==void 0?t:Pd(l.name),u.repeated=(i=l.repeated)!==null&&i!==void 0?i:!1,l.kind=="scalar"&&(u.L=(s=l.L)!==null&&s!==void 0?s:He.BIGINT),u.delimited=(r=l.delimited)!==null&&r!==void 0?r:!1,u.req=(a=l.req)!==null&&a!==void 0?a:!1,u.opt=(o=l.opt)!==null&&o!==void 0?o:!1,l.packed===void 0&&(u.packed=l.kind=="enum"||l.kind=="scalar"&&l.T!=k.BYTES&&l.T!=k.STRING),l.oneof!==void 0){const h=typeof l.oneof=="string"?l.oneof:l.oneof.name;(!d||d.name!=h)&&(d=new Nd(h)),u.oneof=d,d.addField(u)}c.push(u)}return c}const g=Ed("proto3",n=>new Rd(n,e=>xd(e)),n=>{for(const e of n.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,i=n;if(e.repeated){i[t]=[];continue}switch(e.kind){case"oneof":i[t]={case:void 0};break;case"enum":i[t]=0;break;case"map":i[t]={};break;case"scalar":i[t]=pt(e.T,e.L);break}}});class ve extends ji{constructor(e){super(),this.seconds=X.zero,this.nanos=0,g.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(g.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const s=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(s))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(s<Date.parse("0001-01-01T00:00:00Z")||s>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=X.parse(s/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const s=(this.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?i="."+s.substring(0,3)+"Z":s.substring(6)==="000"?i="."+s.substring(0,6)+"Z":i="."+s+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return ve.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new ve({seconds:X.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new ve().fromBinary(e,t)}static fromJson(e,t){return new ve().fromJson(e,t)}static fromJsonString(e,t){return new ve().fromJsonString(e,t)}static equals(e,t){return g.util.equals(ve,e,t)}}ve.runtime=g,ve.typeName="google.protobuf.Timestamp",ve.fields=g.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const Md=g.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ve},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Ld,repeated:!0},{no:5,name:"events",kind:"message",T:Fd,repeated:!0}]),Ld=g.makeMessageType("livekit.TimeSeriesMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:Ud,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),Ud=g.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ve},{no:3,name:"value",kind:"scalar",T:2}]),Fd=g.makeMessageType("livekit.EventMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:ve},{no:7,name:"normalized_end_timestamp",kind:"message",T:ve,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),lr=g.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Re=g.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),oe=g.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),Gi=g.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Lt=g.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Ut=g.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),ke=g.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),rt=g.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),Bd=g.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),ae=g.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),ai=g.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:ci,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:Cr}]),ci=g.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Vd=g.makeMessageType("livekit.ParticipantPermission",()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:g.getEnumType(oe),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}]),ot=g.makeMessageType("livekit.ParticipantInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:g.getEnumType(ft)},{no:4,name:"tracks",kind:"message",T:gt,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:Vd},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:g.getEnumType(Ft)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:g.getEnumType(ke)},{no:18,name:"kind_details",kind:"enum",T:g.getEnumType(jd),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:zi,repeated:!0}]),ft=g.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Ft=g.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"},{no:8,name:"BRIDGE"}]),jd=g.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"},{no:2,name:"CONNECTOR_WHATSAPP"},{no:3,name:"CONNECTOR_TWILIO"},{no:4,name:"BRIDGE_RTSP"}]),se=g.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),qd=g.makeMessageType("livekit.SimulcastCodecInfo",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:ze,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:g.getEnumType(ur)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),gt=g.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:g.getEnumType(Re)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:g.getEnumType(oe)},{no:10,name:"layers",kind:"message",T:ze,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:qd,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:g.getEnumType(se)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Cr},{no:19,name:"audio_features",kind:"enum",T:g.getEnumType(ae),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:g.getEnumType(lr)}]),zi=g.makeMessageType("livekit.DataTrackInfo",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"sid",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"encryption",kind:"enum",T:g.getEnumType(se)}]),Wd=g.makeMessageType("livekit.DataTrackSubscriptionOptions",()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}]),ze=g.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:g.getEnumType(Gi)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9},{no:8,name:"repair_ssrc",kind:"scalar",T:13}]),ur=g.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),pe=g.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:g.getEnumType(q)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:Ji,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Kd,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:fr,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Hd,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Md,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:di,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:$i,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Qi,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Yi,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:li,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:ui,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:hi,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:hr,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),q=g.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),hr=g.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:g.getEnumType(se)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}]),pr=g.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:Ji,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:di,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:$i,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Qi,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Yi,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:li,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:ui,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:hi,oneof:"value"}]),Kd=g.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:mr,repeated:!0}]),mr=g.makeMessageType("livekit.SpeakerInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]),Ji=g.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}]),fr=g.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),Hd=g.makeMessageType("livekit.Transcription",()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:Gd,repeated:!0}]),Gd=g.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),di=g.makeMessageType("livekit.ChatMessage",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}]),$i=g.makeMessageType("livekit.RpcRequest",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}]),Qi=g.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Yi=g.makeMessageType("livekit.RpcResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:gr,oneof:"value"}]),gr=g.makeMessageType("livekit.RpcError",()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}]),vr=g.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),br=g.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:g.getEnumType(yr)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}]),yr=g.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),_r=g.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:g.getEnumType(Tr)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}]),Tr=g.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),kr=g.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Sr},{no:2,name:"screen",kind:"message",T:Sr},{no:3,name:"resume_connection",kind:"enum",T:g.getEnumType(Ut)},{no:4,name:"disabled_codecs",kind:"message",T:zd},{no:5,name:"force_relay",kind:"enum",T:g.getEnumType(Ut)}]),Sr=g.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:g.getEnumType(Ut)}]),zd=g.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:ci,repeated:!0},{no:2,name:"publish",kind:"message",T:ci,repeated:!0}]),Cr=g.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Xi=g.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Er=g.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:g.getEnumType(Xi)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}],{localName:"DataStream_TextHeader"}),Rr=g.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),li=g.makeMessageType("livekit.DataStream.Header",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:g.getEnumType(se)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Er,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Rr,oneof:"content_header"}],{localName:"DataStream_Header"}),ui=g.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),hi=g.makeMessageType("livekit.DataStream.Trailer",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"DataStream_Trailer"}),Jd=g.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),we=g.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Zi=g.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),$d=g.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Qd=g.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Je,oneof:"message"},{no:2,name:"answer",kind:"message",T:Je,oneof:"message"},{no:3,name:"trickle",kind:"message",T:pi,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Bt,oneof:"message"},{no:5,name:"mute",kind:"message",T:mi,oneof:"message"},{no:6,name:"subscription",kind:"message",T:fi,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Ar,oneof:"message"},{no:8,name:"leave",kind:"message",T:gi,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Nr,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:Lr,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:on,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Ne,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:sn,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Br,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:nn,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Or,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:Pr,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:Dr,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:sl,oneof:"message"}]),wr=g.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:el,oneof:"message"},{no:2,name:"answer",kind:"message",T:Je,oneof:"message"},{no:3,name:"offer",kind:"message",T:Je,oneof:"message"},{no:4,name:"trickle",kind:"message",T:pi,oneof:"message"},{no:5,name:"update",kind:"message",T:nl,oneof:"message"},{no:6,name:"track_published",kind:"message",T:tn,oneof:"message"},{no:8,name:"leave",kind:"message",T:gi,oneof:"message"},{no:9,name:"mute",kind:"message",T:mi,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:ol,oneof:"message"},{no:11,name:"room_update",kind:"message",T:al,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:dl,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:ul,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:pl,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:fl,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:il,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:tl,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:vl,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:_l,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Tl,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:kl,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:gl,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Rl,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:ml,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:Ir,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:Yd,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:Xd,oneof:"message"}]),en=g.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:ze,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:g.getEnumType(ur)}]),Bt=g.makeMessageType("livekit.AddTrackRequest",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:g.getEnumType(Re)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:g.getEnumType(oe)},{no:9,name:"layers",kind:"message",T:ze,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:en,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:g.getEnumType(se)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:g.getEnumType(lr)},{no:17,name:"audio_features",kind:"enum",T:g.getEnumType(ae),repeated:!0}]),Pr=g.makeMessageType("livekit.PublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"encryption",kind:"enum",T:g.getEnumType(se)}]),Ir=g.makeMessageType("livekit.PublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:zi}]),Dr=g.makeMessageType("livekit.UnpublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}]),Yd=g.makeMessageType("livekit.UnpublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:zi}]),Xd=g.makeMessageType("livekit.DataTrackSubscriberHandles",()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:Zd}}]),Zd=g.makeMessageType("livekit.DataTrackSubscriberHandles.PublishedDataTrack",()=>[{no:1,name:"publisher_identity",kind:"scalar",T:9},{no:2,name:"publisher_sid",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9}],{localName:"DataTrackSubscriberHandles_PublishedDataTrack"}),pi=g.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:g.getEnumType(we)},{no:3,name:"final",kind:"scalar",T:8}]),mi=g.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),el=g.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:ai},{no:2,name:"participant",kind:"message",T:ot},{no:3,name:"other_participants",kind:"message",T:ot,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:xr,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:kr},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:br},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:ci,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),tl=g.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:xr,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:kr},{no:3,name:"server_info",kind:"message",T:br},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),tn=g.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:gt}]),il=g.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Je=g.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}]),nl=g.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:ot,repeated:!0}]),fi=g.makeMessageType("livekit.UpdateSubscription",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:vr,repeated:!0}]),sl=g.makeMessageType("livekit.UpdateDataSubscription",()=>[{no:1,name:"updates",kind:"message",T:rl,repeated:!0}]),rl=g.makeMessageType("livekit.UpdateDataSubscription.Update",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"options",kind:"message",T:Wd}],{localName:"UpdateDataSubscription_Update"}),Ar=g.makeMessageType("livekit.UpdateTrackSettings",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:g.getEnumType(Gi)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}]),nn=g.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:g.getEnumType(ae),repeated:!0}]),Or=g.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),gi=g.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:g.getEnumType(ke)},{no:3,name:"action",kind:"enum",T:g.getEnumType(vt)},{no:4,name:"regions",kind:"message",T:bl}]),vt=g.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Nr=g.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:ze,repeated:!0}]),sn=g.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),xr=g.makeMessageType("livekit.ICEServer",()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}]),ol=g.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:mr,repeated:!0}]),al=g.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:ai}]),cl=g.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:g.getEnumType(Lt)},{no:3,name:"score",kind:"scalar",T:2}]),dl=g.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:cl,repeated:!0}]),ll=g.makeMessageType("livekit.StreamStateInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:g.getEnumType(Zi)}]),ul=g.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:ll,repeated:!0}]),rn=g.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:g.getEnumType(Gi)},{no:2,name:"enabled",kind:"scalar",T:8}]),hl=g.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:rn,repeated:!0}]),pl=g.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:rn,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:hl,repeated:!0}]),ml=g.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Jd,repeated:!0}]),Mr=g.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}]),Lr=g.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Mr,repeated:!0}]),fl=g.makeMessageType("livekit.SubscriptionPermissionUpdate",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}]),gl=g.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:ai},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:ot},{no:4,name:"other_participants",kind:"message",T:ot,repeated:!0}]),on=g.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Je},{no:2,name:"subscription",kind:"message",T:fi},{no:3,name:"publish_tracks",kind:"message",T:tn,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Fr,repeated:!0},{no:5,name:"offer",kind:"message",T:Je},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Ur,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:Ir,repeated:!0}]),Ur=g.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Fr=g.makeMessageType("livekit.DataChannelInfo",()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:g.getEnumType(we)}]),Ne=g.makeMessageType("livekit.SimulateScenario",()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:g.getEnumType($d),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}]),Br=g.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),vl=g.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),bl=g.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:yl,repeated:!0}]),yl=g.makeMessageType("livekit.RegionInfo",()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]),_l=g.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:g.getEnumType(Bd)}]),Tl=g.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:g.getEnumType(an)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:pi,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Bt,oneof:"request"},{no:6,name:"mute",kind:"message",T:mi,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:sn,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:nn,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Or,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:Pr,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:Dr,oneof:"request"}]),an=g.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"},{no:7,name:"INVALID_HANDLE"},{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"}]),kl=g.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Vr=g.makeMessageType("livekit.ConnectionSettings",()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8},{no:5,name:"auto_subscribe_data_track",kind:"scalar",T:8,opt:!0}]),Sl=g.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:_r},{no:2,name:"connection_settings",kind:"message",T:Vr},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:Bt,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:Je},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:g.getEnumType(rt)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:on}]),Cl=g.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:g.getEnumType(El)},{no:2,name:"join_request",kind:"scalar",T:12}]),El=g.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Rl=g.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function wl(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var vi={exports:{}},Pl=vi.exports,jr;function Il(){return jr||(jr=1,(function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(Pl,function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},a=null;function o(v,R){var T=v[R];if(typeof T.bind=="function")return T.bind(v);try{return Function.prototype.bind.call(T,v)}catch{return function(){return Function.prototype.apply.apply(T,[v,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(v){return v==="debug"&&(v="log"),typeof console===t?!1:v==="trace"&&i?c:console[v]!==void 0?o(console,v):console.log!==void 0?o(console,"log"):e}function l(){for(var v=this.getLevel(),R=0;R<s.length;R++){var T=s[R];this[T]=R<v?e:this.methodFactory(T,v,this.name)}if(this.log=this.debug,typeof console===t&&v<this.levels.SILENT)return"No console available for logging"}function u(v){return function(){typeof console!==t&&(l.call(this),this[v].apply(this,arguments))}}function h(v,R,T){return d(v)||u.apply(this,arguments)}function f(v,R){var T=this,A,x,y,_="loglevel";typeof v=="string"?_+=":"+v:typeof v=="symbol"&&(_=void 0);function C(L){var W=(s[L]||"silent").toUpperCase();if(!(typeof window===t||!_)){try{window.localStorage[_]=W;return}catch{}try{window.document.cookie=encodeURIComponent(_)+"="+W+";"}catch{}}}function N(){var L;if(!(typeof window===t||!_)){try{L=window.localStorage[_]}catch{}if(typeof L===t)try{var W=window.document.cookie,Z=encodeURIComponent(_),Te=W.indexOf(Z+"=");Te!==-1&&(L=/^([^;]+)/.exec(W.slice(Te+Z.length+1))[1])}catch{}return T.levels[L]===void 0&&(L=void 0),L}}function U(){if(!(typeof window===t||!_)){try{window.localStorage.removeItem(_)}catch{}try{window.document.cookie=encodeURIComponent(_)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function M(L){var W=L;if(typeof W=="string"&&T.levels[W.toUpperCase()]!==void 0&&(W=T.levels[W.toUpperCase()]),typeof W=="number"&&W>=0&&W<=T.levels.SILENT)return W;throw new TypeError("log.setLevel() called with invalid level: "+L)}T.name=v,T.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},T.methodFactory=R||h,T.getLevel=function(){return y??x??A},T.setLevel=function(L,W){return y=M(L),W!==!1&&C(y),l.call(T)},T.setDefaultLevel=function(L){x=M(L),N()||T.setLevel(L,!1)},T.resetLevel=function(){y=null,U(),l.call(T)},T.enableAll=function(L){T.setLevel(T.levels.TRACE,L)},T.disableAll=function(L){T.setLevel(T.levels.SILENT,L)},T.rebuild=function(){if(a!==T&&(A=M(a.getLevel())),l.call(T),a===T)for(var L in r)r[L].rebuild()},A=M(a?a.getLevel():"WARN");var O=N();O!=null&&(y=M(O)),l.call(T)}a=new f,a.getLogger=function(R){if(typeof R!="symbol"&&typeof R!="string"||R==="")throw new TypeError("You must supply a name when creating a logger.");var T=r[R];return T||(T=r[R]=new f(R,a.methodFactory)),T};var b=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=b),a},a.getLoggers=function(){return r},a.default=a,a})})(vi)),vi.exports}var bi=Il(),cn;(function(n){n[n.trace=0]="trace",n[n.debug=1]="debug",n[n.info=2]="info",n[n.warn=3]="warn",n[n.error=4]="error",n[n.silent=5]="silent"})(cn||(cn={}));var Pe;(function(n){n.Default="livekit",n.Room="livekit-room",n.TokenSource="livekit-token-source",n.Participant="livekit-participant",n.Track="livekit-track",n.Publication="livekit-track-publication",n.Engine="livekit-engine",n.Signal="livekit-signal",n.PCManager="livekit-pc-manager",n.PCTransport="livekit-pc-transport",n.E2EE="lk-e2ee"})(Pe||(Pe={}));let V=bi.getLogger("livekit");Object.values(Pe).map(n=>bi.getLogger(n)),V.setDefaultLevel(cn.info);function Ve(n){const e=bi.getLogger(n);return e.setDefaultLevel(V.getLevel()),e}const Dl=bi.getLogger("lk-e2ee"),Vt=7e3,Al=[0,300,4*300,9*300,16*300,Vt,Vt,Vt,Vt,Vt];class Ol{constructor(e){this._retryDelays=e!==void 0?[...e]:Al}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function Nl(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(n);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(n,i[s])&&(t[i[s]]=n[i[s]]);return t}function p(n,e,t,i){function s(r){return r instanceof t?r:new t(function(a){a(r)})}return new(t||(t=Promise))(function(r,a){function o(l){try{d(i.next(l))}catch(u){a(u)}}function c(l){try{d(i.throw(l))}catch(u){a(u)}}function d(l){l.done?r(l.value):s(l.value).then(o,c)}d((i=i.apply(n,e||[])).next())})}function qr(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function je(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof qr=="function"?qr(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(r){t[r]=n[r]&&function(a){return new Promise(function(o,c){a=n[r](a),s(o,c,a.done,a.value)})}}function s(r,a,o,c){Promise.resolve(c).then(function(d){r({value:d,done:o})},a)}}typeof SuppressedError=="function"&&SuppressedError;var yi={exports:{}},Wr;function xl(){if(Wr)return yi.exports;Wr=1;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(_,C,N){return Function.prototype.apply.call(_,C,N)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(_){return Object.getOwnPropertyNames(_).concat(Object.getOwnPropertySymbols(_))}:t=function(_){return Object.getOwnPropertyNames(_)};function i(y){console&&console.warn&&console.warn(y)}var s=Number.isNaN||function(_){return _!==_};function r(){r.init.call(this)}yi.exports=r,yi.exports.once=T,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var a=10;function o(y){if(typeof y!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof y)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(y){if(typeof y!="number"||y<0||s(y))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+y+".");a=y}}),r.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(_){if(typeof _!="number"||_<0||s(_))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+_+".");return this._maxListeners=_,this};function c(y){return y._maxListeners===void 0?r.defaultMaxListeners:y._maxListeners}r.prototype.getMaxListeners=function(){return c(this)},r.prototype.emit=function(_){for(var C=[],N=1;N<arguments.length;N++)C.push(arguments[N]);var U=_==="error",M=this._events;if(M!==void 0)U=U&&M.error===void 0;else if(!U)return!1;if(U){var O;if(C.length>0&&(O=C[0]),O instanceof Error)throw O;var L=new Error("Unhandled error."+(O?" ("+O.message+")":""));throw L.context=O,L}var W=M[_];if(W===void 0)return!1;if(typeof W=="function")e(W,this,C);else for(var Z=W.length,Te=b(W,Z),N=0;N<Z;++N)e(Te[N],this,C);return!0};function d(y,_,C,N){var U,M,O;if(o(C),M=y._events,M===void 0?(M=y._events=Object.create(null),y._eventsCount=0):(M.newListener!==void 0&&(y.emit("newListener",_,C.listener?C.listener:C),M=y._events),O=M[_]),O===void 0)O=M[_]=C,++y._eventsCount;else if(typeof O=="function"?O=M[_]=N?[C,O]:[O,C]:N?O.unshift(C):O.push(C),U=c(y),U>0&&O.length>U&&!O.warned){O.warned=!0;var L=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+String(_)+" listeners added. Use emitter.setMaxListeners() to increase limit");L.name="MaxListenersExceededWarning",L.emitter=y,L.type=_,L.count=O.length,i(L)}return y}r.prototype.addListener=function(_,C){return d(this,_,C,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(_,C){return d(this,_,C,!0)};function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(y,_,C){var N={fired:!1,wrapFn:void 0,target:y,type:_,listener:C},U=l.bind(N);return U.listener=C,N.wrapFn=U,U}r.prototype.once=function(_,C){return o(C),this.on(_,u(this,_,C)),this},r.prototype.prependOnceListener=function(_,C){return o(C),this.prependListener(_,u(this,_,C)),this},r.prototype.removeListener=function(_,C){var N,U,M,O,L;if(o(C),U=this._events,U===void 0)return this;if(N=U[_],N===void 0)return this;if(N===C||N.listener===C)--this._eventsCount===0?this._events=Object.create(null):(delete U[_],U.removeListener&&this.emit("removeListener",_,N.listener||C));else if(typeof N!="function"){for(M=-1,O=N.length-1;O>=0;O--)if(N[O]===C||N[O].listener===C){L=N[O].listener,M=O;break}if(M<0)return this;M===0?N.shift():v(N,M),N.length===1&&(U[_]=N[0]),U.removeListener!==void 0&&this.emit("removeListener",_,L||C)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(_){var C,N,U;if(N=this._events,N===void 0)return this;if(N.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):N[_]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete N[_]),this;if(arguments.length===0){var M=Object.keys(N),O;for(U=0;U<M.length;++U)O=M[U],O!=="removeListener"&&this.removeAllListeners(O);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(C=N[_],typeof C=="function")this.removeListener(_,C);else if(C!==void 0)for(U=C.length-1;U>=0;U--)this.removeListener(_,C[U]);return this};function h(y,_,C){var N=y._events;if(N===void 0)return[];var U=N[_];return U===void 0?[]:typeof U=="function"?C?[U.listener||U]:[U]:C?R(U):b(U,U.length)}r.prototype.listeners=function(_){return h(this,_,!0)},r.prototype.rawListeners=function(_){return h(this,_,!1)},r.listenerCount=function(y,_){return typeof y.listenerCount=="function"?y.listenerCount(_):f.call(y,_)},r.prototype.listenerCount=f;function f(y){var _=this._events;if(_!==void 0){var C=_[y];if(typeof C=="function")return 1;if(C!==void 0)return C.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function b(y,_){for(var C=new Array(_),N=0;N<_;++N)C[N]=y[N];return C}function v(y,_){for(;_+1<y.length;_++)y[_]=y[_+1];y.pop()}function R(y){for(var _=new Array(y.length),C=0;C<_.length;++C)_[C]=y[C].listener||y[C];return _}function T(y,_){return new Promise(function(C,N){function U(O){y.removeListener(_,M),N(O)}function M(){typeof y.removeListener=="function"&&y.removeListener("error",U),C([].slice.call(arguments))}x(y,_,M,{once:!0}),_!=="error"&&A(y,U,{once:!0})})}function A(y,_,C){typeof y.on=="function"&&x(y,"error",_,C)}function x(y,_,C,N){if(typeof y.on=="function")N.once?y.once(_,C):y.on(_,C);else if(typeof y.addEventListener=="function")y.addEventListener(_,function U(M){N.once&&y.removeEventListener(_,U),C(M)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof y)}return yi.exports}var xe=xl();let Kr=!0,Hr=!0;function jt(n,e,t){const i=n.match(e);return i&&i.length>=t&&parseFloat(i[t],10)}function at(n,e,t){if(!n.RTCPeerConnection)return;const i=n.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(a,o){if(a!==e)return s.apply(this,arguments);const c=d=>{const l=t(d);l&&(o.handleEvent?o.handleEvent(l):o(l))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,c),s.apply(this,[a,c])};const r=i.removeEventListener;i.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(o))return r.apply(this,arguments);const c=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,r.apply(this,[a,c])},Object.defineProperty(i,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function Ml(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(Kr=n,n?"adapter.js logging disabled":"adapter.js logging enabled")}function Ll(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(Hr=!n,"adapter.js deprecation warnings "+(n?"disabled":"enabled"))}function Gr(){if(typeof window=="object"){if(Kr)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function dn(n,e){Hr&&console.warn(n+" is deprecated, please use "+e+" instead.")}function Ul(n){const e={browser:null,version:null};if(typeof n>"u"||!n.navigator||!n.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=n;if(t.userAgentData&&t.userAgentData.brands){const i=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(jt(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(jt(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(n.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(jt(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype,e._safariVersion=jt(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function zr(n){return Object.prototype.toString.call(n)==="[object Object]"}function Jr(n){return zr(n)?Object.keys(n).reduce(function(e,t){const i=zr(n[t]),s=i?Jr(n[t]):n[t],r=i&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):n}function ln(n,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?ln(n,n.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(s=>{ln(n,n.get(s),t)})}))}function $r(n,e,t){const i=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return n.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&r.push(a)}),r.forEach(a=>{n.forEach(o=>{o.type===i&&o.trackId===a.id&&ln(n,o,s)})}),s}const Qr=Gr;function Yr(n,e){const t=n&&n.navigator;if(!t.mediaDevices)return;const i=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const c={};return Object.keys(o).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const l=typeof o[d]=="object"?o[d]:{ideal:o[d]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const u=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(l.ideal!==void 0){c.optional=c.optional||[];let h={};typeof l.ideal=="number"?(h[u("min",d)]=l.ideal,c.optional.push(h),h={},h[u("max",d)]=l.ideal,c.optional.push(h)):(h[u("",d)]=l.ideal,c.optional.push(h))}l.exact!==void 0&&typeof l.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",d)]=l.exact):["min","max"].forEach(h=>{l[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(h,d)]=l[h])})}),o.advanced&&(c.optional=(c.optional||[]).concat(o.advanced)),c},s=function(o,c){if(e.version>=61)return c(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const d=function(l,u,h){u in l&&!(h in l)&&(l[h]=l[u],delete l[u])};o=JSON.parse(JSON.stringify(o)),d(o.audio,"autoGainControl","googAutoGainControl"),d(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(o.audio)}if(o&&typeof o.video=="object"){let d=o.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const l=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete o.video.facingMode;let u;if(d.exact==="environment"||d.ideal==="environment"?u=["back","rear"]:(d.exact==="user"||d.ideal==="user")&&(u=["front"]),u)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(b=>b.kind==="videoinput");let f=h.find(b=>u.some(v=>b.label.toLowerCase().includes(v)));return!f&&h.length&&u.includes("back")&&(f=h[h.length-1]),f&&(o.video.deviceId=d.exact?{exact:f.deviceId}:{ideal:f.deviceId}),o.video=i(o.video),Qr("chrome: "+JSON.stringify(o)),c(o)})}o.video=i(o.video)}return Qr("chrome: "+JSON.stringify(o)),c(o)},r=function(o){return e.version>=64?o:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[o.name]||o.name,message:o.message,constraint:o.constraint||o.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},a=function(o,c,d){s(o,l=>{t.webkitGetUserMedia(l,c,u=>{d&&d(r(u))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,d=>o(d).then(l=>{if(d.audio&&!l.getAudioTracks().length||d.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(r(l))))}}}function Xr(n){n.MediaStream=n.MediaStream||n.webkitMediaStream}function Zr(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("ontrack"in n.RTCPeerConnection.prototype)){Object.defineProperty(n.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",s=>{let r;n.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===s.track.id):r={track:s.track};const a=new Event("track");a.track=s.track,a.receiver=r,a.transceiver={receiver:r},a.streams=[i.stream],this.dispatchEvent(a)}),i.stream.getTracks().forEach(s=>{let r;n.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===s.id):r={track:s};const a=new Event("track");a.track=s,a.receiver=r,a.transceiver={receiver:r},a.streams=[i.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else at(n,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function eo(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("getSenders"in n.RTCPeerConnection.prototype)&&"createDTMFSender"in n.RTCPeerConnection.prototype){const e=function(s,r){return{track:r,get dtmf(){return this._dtmf===void 0&&(r.kind==="audio"?this._dtmf=s.createDTMFSender(r):this._dtmf=null),this._dtmf},_pc:s}};if(!n.RTCPeerConnection.prototype.getSenders){n.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(o,c){let d=s.apply(this,arguments);return d||(d=e(this,o),this._senders.push(d)),d};const r=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(o){r.apply(this,arguments);const c=this._senders.indexOf(o);c!==-1&&this._senders.splice(c,1)}}const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],i.apply(this,[r]),r.getTracks().forEach(a=>{const o=this._senders.find(c=>c.track===a);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof n=="object"&&n.RTCPeerConnection&&"getSenders"in n.RTCPeerConnection.prototype&&"createDTMFSender"in n.RTCPeerConnection.prototype&&n.RTCRtpSender&&!("dtmf"in n.RTCRtpSender.prototype)){const e=n.RTCPeerConnection.prototype.getSenders;n.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i},Object.defineProperty(n.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function to(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender&&n.RTCRtpReceiver))return;if(!("getStats"in n.RTCRtpSender.prototype)){const t=n.RTCPeerConnection.prototype.getSenders;t&&(n.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(a=>a._pc=this),r});const i=n.RTCPeerConnection.prototype.addTrack;i&&(n.RTCPeerConnection.prototype.addTrack=function(){const r=i.apply(this,arguments);return r._pc=this,r}),n.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(a=>$r(a,r.track,!0))}}if(!("getStats"in n.RTCRtpReceiver.prototype)){const t=n.RTCPeerConnection.prototype.getReceivers;t&&(n.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(r=>r._pc=this),s}),at(n,"track",i=>(i.receiver._pc=i.srcElement,i)),n.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>$r(r,s.track,!1))}}if(!("getStats"in n.RTCRtpSender.prototype&&"getStats"in n.RTCRtpReceiver.prototype))return;const e=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof n.MediaStreamTrack){const i=arguments[0];let s,r,a;return this.getSenders().forEach(o=>{o.track===i&&(s?a=!0:s=o)}),this.getReceivers().forEach(o=>(o.track===i&&(r?a=!0:r=o),o.track===i)),a||s&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function io(n){n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(c)===-1&&this._shimmedLocalStreams[o.id].push(c):this._shimmedLocalStreams[o.id]=[o,c],c};const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(d=>{if(this.getSenders().find(u=>u.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(d=>o.indexOf(d)===-1);this._shimmedLocalStreams[a.id]=[a].concat(c)};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],i.apply(this,arguments)};const s=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const c=this._shimmedLocalStreams[o].indexOf(a);c!==-1&&this._shimmedLocalStreams[o].splice(c,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),s.apply(this,arguments)}}function no(n,e){if(!n.RTCPeerConnection)return;if(n.RTCPeerConnection.prototype.addTrack&&e.version>=65)return io(n);const t=n.RTCPeerConnection.prototype.getLocalStreams;n.RTCPeerConnection.prototype.getLocalStreams=function(){const l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(u=>this._reverseStreams[u.id])};const i=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(u=>{if(this.getSenders().find(f=>f.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const u=new n.MediaStream(l.getTracks());this._streams[l.id]=u,this._reverseStreams[u.id]=l,l=u}i.apply(this,[l])};const s=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(l){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[l.id]||l]),delete this._reverseStreams[this._streams[l.id]?this._streams[l.id].id:l.id],delete this._streams[l.id]},n.RTCPeerConnection.prototype.addTrack=function(l,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(v=>v===l))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(v=>v.track===l))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const b=this._streams[u.id];if(b)b.addTrack(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const v=new n.MediaStream([l]);this._streams[u.id]=v,this._reverseStreams[v.id]=u,this.addStream(v)}return this.getSenders().find(v=>v.track===l)};function r(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const f=d._reverseStreams[h],b=d._streams[f.id];u=u.replace(new RegExp(b.id,"g"),f.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function a(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const f=d._reverseStreams[h],b=d._streams[f.id];u=u.replace(new RegExp(f.id,"g"),b.id)}),new RTCSessionDescription({type:l.type,sdp:u})}["createOffer","createAnswer"].forEach(function(d){const l=n.RTCPeerConnection.prototype[d],u={[d](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[b=>{const v=r(this,b);h[0].apply(null,[v])},b=>{h[1]&&h[1].apply(null,b)},arguments[2]]):l.apply(this,arguments).then(b=>r(this,b))}};n.RTCPeerConnection.prototype[d]=u[d]});const o=n.RTCPeerConnection.prototype.setLocalDescription;n.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(n.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(n.RTCPeerConnection.prototype,"localDescription",{get(){const d=c.get.apply(this);return d.type===""?d:r(this,d)}}),n.RTCPeerConnection.prototype.removeTrack=function(l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!l._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(l._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(v=>l.track===v)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function un(n,e){!n.RTCPeerConnection&&n.webkitRTCPeerConnection&&(n.RTCPeerConnection=n.webkitRTCPeerConnection),n.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=n.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};n.RTCPeerConnection.prototype[t]=s[t]})}function so(n,e){at(n,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}var ro=Object.freeze({__proto__:null,fixNegotiationNeeded:so,shimAddTrackRemoveTrack:no,shimAddTrackRemoveTrackWithNative:io,shimGetSendersWithDtmf:eo,shimGetUserMedia:Yr,shimMediaStream:Xr,shimOnTrack:Zr,shimPeerConnection:un,shimSenderReceiverGetStats:to});function oo(n,e){const t=n&&n.navigator,i=n&&n.MediaStreamTrack;if(t.getUserMedia=function(s,r,a){dn("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(a,o,c){o in a&&!(c in a)&&(a[c]=a[o],delete a[o])},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(a){return typeof a=="object"&&typeof a.audio=="object"&&(a=JSON.parse(JSON.stringify(a)),s(a.audio,"autoGainControl","mozAutoGainControl"),s(a.audio,"noiseSuppression","mozNoiseSuppression")),r(a)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return s(o,"mozAutoGainControl","autoGainControl"),s(o,"mozNoiseSuppression","noiseSuppression"),o}}if(i&&i.prototype.applyConstraints){const a=i.prototype.applyConstraints;i.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o,"autoGainControl","mozAutoGainControl"),s(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function Fl(n,e){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,n.navigator.mediaDevices.getUserMedia(i)})}function ao(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function hn(n,e){if(typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection))return;!n.RTCPeerConnection&&n.mozRTCPeerConnection&&(n.RTCPeerConnection=n.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const r=n.RTCPeerConnection.prototype[s],a={[s](){return arguments[0]=new(s==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};n.RTCPeerConnection.prototype[s]=a[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){const[r,a,o]=arguments;return i.apply(this,[r||null]).then(c=>{if(e.version<53&&!a)try{c.forEach(d=>{d.type=t[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;c.forEach((l,u)=>{c.set(u,Object.assign({},l,{type:t[l.type]||l.type}))})}return c}).then(a,o)}}function co(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpSender.prototype)return;const e=n.RTCPeerConnection.prototype.getSenders;e&&(n.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(r=>r._pc=this),s});const t=n.RTCPeerConnection.prototype.addTrack;t&&(n.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),n.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function lo(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpReceiver.prototype)return;const e=n.RTCPeerConnection.prototype.getReceivers;e&&(n.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i}),at(n,"track",t=>(t.receiver._pc=t.srcElement,t)),n.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function uo(n){!n.RTCPeerConnection||"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){dn("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function ho(n){n.DataChannel&&!n.RTCDataChannel&&(n.RTCDataChannel=n.DataChannel)}function po(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.addTransceiver;e&&(n.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const s=i.length>0;s&&i.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(s){const{sender:a}=r,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=i,a.sendEncodings=i,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return r})}function mo(n){if(!(typeof n=="object"&&n.RTCRtpSender))return;const e=n.RTCRtpSender.prototype.getParameters;e&&(n.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function fo(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function go(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createAnswer;n.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var vo=Object.freeze({__proto__:null,shimAddTransceiver:po,shimCreateAnswer:go,shimCreateOffer:fo,shimGetDisplayMedia:Fl,shimGetParameters:mo,shimGetUserMedia:oo,shimOnTrack:ao,shimPeerConnection:hn,shimRTCDataChannel:ho,shimReceiverGetStats:lo,shimRemoveStream:uo,shimSenderGetStats:co});function bo(n){if(!(typeof n!="object"||!n.RTCPeerConnection)){if("getLocalStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in n.RTCPeerConnection.prototype)){const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(s=>e.call(this,s,i)),i.getVideoTracks().forEach(s=>e.call(this,s,i))},n.RTCPeerConnection.prototype.addTrack=function(i){for(var s=arguments.length,r=new Array(s>1?s-1:0),a=1;a<s;a++)r[a-1]=arguments[a];return r&&r.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),e.apply(this,arguments)}}"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const s=t.getTracks();this.getSenders().forEach(r=>{s.includes(r.track)&&this.removeTrack(r)})})}}function yo(n){if(!(typeof n!="object"||!n.RTCPeerConnection)&&("getRemoteStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in n.RTCPeerConnection.prototype))){Object.defineProperty(n.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const r=new Event("addstream");r.stream=s,this.dispatchEvent(r)})})}});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(r=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(r)>=0)return;i._remoteStreams.push(r);const a=new Event("addstream");a.stream=r,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function _o(n){if(typeof n!="object"||!n.RTCPeerConnection)return;const e=n.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[u]);return l?(h.then(d,l),Promise.resolve()):h},e.createAnswer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=i.apply(this,[u]);return l?(h.then(d,l),Promise.resolve()):h};let o=function(c,d,l){const u=s.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u};e.setLocalDescription=o,o=function(c,d,l){const u=r.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.setRemoteDescription=o,o=function(c,d,l){const u=a.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.addIceCandidate=o}function To(n){const e=n&&n.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>i(ko(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(i,s,r){e.mediaDevices.getUserMedia(i).then(s,r)}.bind(e))}function ko(n){return n&&n.video!==void 0?Object.assign({},n,{video:Jr(n.video)}):n}function So(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection;n.RTCPeerConnection=function(i,s){if(i&&i.iceServers){const r=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?(dn("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,r.push(o)):r.push(i.iceServers[a])}i.iceServers=r}return new e(i,s)},n.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(n.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Co(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Eo(n){const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const r=this.getTransceivers().find(a=>a.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Ro(n){typeof n!="object"||n.AudioContext||(n.AudioContext=n.webkitAudioContext)}var wo=Object.freeze({__proto__:null,shimAudioContext:Ro,shimCallbacksAPI:_o,shimConstraints:ko,shimCreateOfferLegacy:Eo,shimGetUserMedia:To,shimLocalStreamsAPI:bo,shimRTCIceServerUrls:So,shimRemoteStreamsAPI:yo,shimTrackEventTransceiver:Co}),pn={exports:{}},Po;function Bl(){return Po||(Po=1,(function(n){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
112
112
  `).map(i=>i.trim())},e.splitSections=function(t){return t.split(`
113
113
  m=`).map((s,r)=>(r>0?"m="+s:s).trim()+`\r
114
114
  `)},e.getDescription=function(t){const i=e.splitSections(t);return i&&i[0]},e.getMediaSections=function(t){const i=e.splitSections(t);return i.shift(),i},e.matchPrefix=function(t,i){return e.splitLines(t).filter(s=>s.indexOf(i)===0)},e.parseCandidate=function(t){let i;t.indexOf("a=candidate:")===0?i=t.substring(12).split(" "):i=t.substring(10).split(" ");const s={foundation:i[0],component:{1:"rtp",2:"rtcp"}[i[1]]||i[1],protocol:i[2].toLowerCase(),priority:parseInt(i[3],10),ip:i[4],address:i[4],port:parseInt(i[5],10),type:i[7]};for(let r=8;r<i.length;r+=2)switch(i[r]){case"raddr":s.relatedAddress=i[r+1];break;case"rport":s.relatedPort=parseInt(i[r+1],10);break;case"tcptype":s.tcpType=i[r+1];break;case"ufrag":s.ufrag=i[r+1],s.usernameFragment=i[r+1];break;default:s[i[r]]===void 0&&(s[i[r]]=i[r+1]);break}return s},e.writeCandidate=function(t){const i=[];i.push(t.foundation);const s=t.component;s==="rtp"?i.push(1):s==="rtcp"?i.push(2):i.push(s),i.push(t.protocol.toUpperCase()),i.push(t.priority),i.push(t.address||t.ip),i.push(t.port);const r=t.type;return i.push("typ"),i.push(r),r!=="host"&&t.relatedAddress&&t.relatedPort&&(i.push("raddr"),i.push(t.relatedAddress),i.push("rport"),i.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(i.push("tcptype"),i.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(i.push("ufrag"),i.push(t.usernameFragment||t.ufrag)),"candidate:"+i.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let i=t.substring(9).split(" ");const s={payloadType:parseInt(i.shift(),10)};return i=i[0].split("/"),s.name=i[0],s.clockRate=parseInt(i[1],10),s.channels=i.length===3?parseInt(i[2],10):1,s.numChannels=s.channels,s},e.writeRtpMap=function(t){let i=t.payloadType;t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType);const s=t.channels||t.numChannels||1;return"a=rtpmap:"+i+" "+t.name+"/"+t.clockRate+(s!==1?"/"+s:"")+`\r
@@ -139,9 +139,9 @@ a=ice-pwd:`+t.password+`\r
139
139
  o=`+(s||"thisisadapterortc")+" "+r+" "+a+` IN IP4 127.0.0.1\r
140
140
  s=-\r
141
141
  t=0 0\r
142
- `},e.getDirection=function(t,i){const s=e.splitLines(t);for(let r=0;r<s.length;r++)switch(s[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[r].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const i=e.splitLines(t);for(let s=0;s<i.length;s++)if(i[s].length<2||i[s].charAt(1)!=="=")return!1;return!0},n.exports=e})(ln)),ln.exports}var _o=bl(),bt=ol(_o),yl=kc({__proto__:null,default:bt},[_o]);function bi(n){if(!n.RTCIceCandidate||n.RTCIceCandidate&&"foundation"in n.RTCIceCandidate.prototype)return;const e=n.RTCIceCandidate;n.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&(i=JSON.parse(JSON.stringify(i)),i.candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const s=new e(i),r=bt.parseCandidate(i.candidate);for(const a in r)a in s||Object.defineProperty(s,a,{value:r[a]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(i)},n.RTCIceCandidate.prototype=e.prototype,at(n,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new n.RTCIceCandidate(t.candidate),writable:"false"}),t))}function un(n){!n.RTCIceCandidate||n.RTCIceCandidate&&"relayProtocol"in n.RTCIceCandidate.prototype||at(n,"icecandidate",e=>{if(e.candidate){const t=bt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function yi(n,e){if(!n.RTCPeerConnection)return;"sctp"in n.RTCPeerConnection.prototype||Object.defineProperty(n.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(o){if(!o||!o.sdp)return!1;const c=bt.splitSections(o.sdp);return c.shift(),c.some(d=>{const l=bt.parseMLine(d);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},i=function(o){const c=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const d=parseInt(c[1],10);return d!==d?-1:d},s=function(o){let c=65536;return e.browser==="firefox"&&(e.version<57?o===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},r=function(o,c){let d=65536;e.browser==="firefox"&&e.version===57&&(d=65535);const l=bt.matchPrefix(o.sdp,"a=max-message-size:");return l.length>0?d=parseInt(l[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(d=2147483637),d},a=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const c=i(arguments[0]),d=s(c),l=r(arguments[0],c);let u;d===0&&l===0?u=Number.POSITIVE_INFINITY:d===0||l===0?u=Math.max(d,l):u=Math.min(d,l);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return u}}),this._sctp=h}return a.apply(this,arguments)}}function Ti(n){if(!(n.RTCPeerConnection&&"createDataChannel"in n.RTCPeerConnection.prototype))return;function e(i,s){const r=i.send;i.send=function(){const o=arguments[0],c=o.length||o.size||o.byteLength;if(i.readyState==="open"&&s.sctp&&c>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return r.apply(i,arguments)}}const t=n.RTCPeerConnection.prototype.createDataChannel;n.RTCPeerConnection.prototype.createDataChannel=function(){const s=t.apply(this,arguments);return e(s,this),s},at(n,"datachannel",i=>(e(i.channel,i.target),i))}function hn(n){if(!n.RTCPeerConnection||"connectionState"in n.RTCPeerConnection.prototype)return;const e=n.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const i=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const r=s.target;if(r._lastConnectionState!==r.connectionState){r._lastConnectionState=r.connectionState;const a=new Event("connectionstatechange",s);r.dispatchEvent(a)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function pn(n,e){if(!n.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const t=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
142
+ `},e.getDirection=function(t,i){const s=e.splitLines(t);for(let r=0;r<s.length;r++)switch(s[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[r].substring(2)}return i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const i=e.splitLines(t);for(let s=0;s<i.length;s++)if(i[s].length<2||i[s].charAt(1)!=="=")return!1;return!0},n.exports=e})(pn)),pn.exports}var Io=Bl(),bt=wl(Io),Vl=Wc({__proto__:null,default:bt},[Io]);function _i(n){if(!n.RTCIceCandidate||n.RTCIceCandidate&&"foundation"in n.RTCIceCandidate.prototype)return;const e=n.RTCIceCandidate;n.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&(i=JSON.parse(JSON.stringify(i)),i.candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const s=new e(i),r=bt.parseCandidate(i.candidate);for(const a in r)a in s||Object.defineProperty(s,a,{value:r[a]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(i)},n.RTCIceCandidate.prototype=e.prototype,at(n,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new n.RTCIceCandidate(t.candidate),writable:"false"}),t))}function mn(n){!n.RTCIceCandidate||n.RTCIceCandidate&&"relayProtocol"in n.RTCIceCandidate.prototype||at(n,"icecandidate",e=>{if(e.candidate){const t=bt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Ti(n,e){if(!n.RTCPeerConnection)return;"sctp"in n.RTCPeerConnection.prototype||Object.defineProperty(n.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(o){if(!o||!o.sdp)return!1;const c=bt.splitSections(o.sdp);return c.shift(),c.some(d=>{const l=bt.parseMLine(d);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},i=function(o){const c=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const d=parseInt(c[1],10);return d!==d?-1:d},s=function(o){let c=65536;return e.browser==="firefox"&&(e.version<57?o===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},r=function(o,c){let d=65536;e.browser==="firefox"&&e.version===57&&(d=65535);const l=bt.matchPrefix(o.sdp,"a=max-message-size:");return l.length>0?d=parseInt(l[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(d=2147483637),d},a=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const c=i(arguments[0]),d=s(c),l=r(arguments[0],c);let u;d===0&&l===0?u=Number.POSITIVE_INFINITY:d===0||l===0?u=Math.max(d,l):u=Math.min(d,l);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return u}}),this._sctp=h}return a.apply(this,arguments)}}function ki(n){if(!(n.RTCPeerConnection&&"createDataChannel"in n.RTCPeerConnection.prototype))return;function e(i,s){const r=i.send;i.send=function(){const o=arguments[0],c=o.length||o.size||o.byteLength;if(i.readyState==="open"&&s.sctp&&c>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return r.apply(i,arguments)}}const t=n.RTCPeerConnection.prototype.createDataChannel;n.RTCPeerConnection.prototype.createDataChannel=function(){const s=t.apply(this,arguments);return e(s,this),s},at(n,"datachannel",i=>(e(i.channel,i.target),i))}function fn(n){if(!n.RTCPeerConnection||"connectionState"in n.RTCPeerConnection.prototype)return;const e=n.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const i=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const r=s.target;if(r._lastConnectionState!==r.connectionState){r._lastConnectionState=r.connectionState;const a=new Event("connectionstatechange",s);r.dispatchEvent(a)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function gn(n,e){if(!n.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const t=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
143
143
  a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
144
144
  `).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
145
- `);n.RTCSessionDescription&&s instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function _i(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(n.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ki(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}var Tl=Object.freeze({__proto__:null,removeExtmapAllowMixed:pn,shimAddIceCandidateNullOrEmpty:_i,shimConnectionState:hn,shimMaxMessageSize:yi,shimParameterlessSetLocalDescription:ki,shimRTCIceCandidate:bi,shimRTCIceCandidateRelayProtocol:un,shimSendThrowTypeError:Ti});function _l(){let{window:n}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=Fr,i=gl(n),s={browserDetails:i,commonShim:Tl,extractVersion:Vt,disableLog:ml,disableWarnings:fl,sdp:yl};switch(i.browser){case"chrome":if(!Yr||!cn||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=Yr,_i(n,i),ki(n),Wr(n,i),Kr(n),cn(n,i),Gr(n),$r(n,i),Hr(n),zr(n),Qr(n,i),bi(n),un(n),hn(n),yi(n,i),Ti(n),pn(n,i);break;case"firefox":if(!co||!dn||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=co,_i(n,i),ki(n),Xr(n,i),dn(n,i),Zr(n),io(n),eo(n),to(n),no(n),so(n),ro(n),oo(n),ao(n),bi(n),hn(n),yi(n,i),Ti(n);break;case"safari":if(!yo||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=yo,_i(n,i),ki(n),fo(n),vo(n),ho(n),lo(n),uo(n),go(n),po(n),bo(n),bi(n),un(n),yi(n,i),Ti(n),pn(n,i);break;default:t("Unsupported browser!");break}return s}_l({window:typeof window>"u"?void 0:window});var mn,ko;class ue extends(ko=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}mn=ue,ue.resolve=n=>Reflect.get(ko,"resolve",mn).call(mn,n);const kl=/version\/(\d+(\.?_?\d+)+)/i;let fn;function be(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(fn===void 0||e){const i=Sl.find(s=>{let{test:r}=s;return r.test(t)});fn=i?.describe(t)}return fn}const Sl=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:Si(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:gn(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:Si(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:gn(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:Si(kl,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:gn(n)}}}];function Si(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(n);return i&&i.length>=t&&i[t]||""}function gn(n){return n.includes("mac os")?Si(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var Cl="2.17.1";const El=Cl,Rl=16;class $e extends Error{constructor(e,t,i){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,typeof i?.cause<"u"&&(this.cause=i?.cause)}}class vn extends $e{}var Q;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.ServerUnreachable=1]="ServerUnreachable",n[n.InternalError=2]="InternalError",n[n.Cancelled=3]="Cancelled",n[n.LeaveRequest=4]="LeaveRequest",n[n.Timeout=5]="Timeout",n[n.WebSocket=6]="WebSocket",n[n.ServiceNotFound=7]="ServiceNotFound"})(Q||(Q={}));class F extends vn{constructor(e,t,i,s){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=s,this.reasonName=Q[t]}static notAllowed(e,t,i){return new F(e,Q.NotAllowed,t,i)}static timeout(e){return new F(e,Q.Timeout)}static leaveRequest(e,t){return new F(e,Q.LeaveRequest,void 0,t)}static internal(e,t){return new F(e,Q.InternalError,void 0,t)}static cancelled(e){return new F(e,Q.Cancelled)}static serverUnreachable(e,t){return new F(e,Q.ServerUnreachable,t)}static websocket(e,t,i){return new F(e,Q.WebSocket,t,i)}static serviceNotFound(e,t){return new F(e,Q.ServiceNotFound,void 0,t)}}class bn extends $e{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class qe extends $e{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class wl extends $e{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class re extends $e{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class yt extends $e{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class So extends $e{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Co extends vn{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:sn[t]}}var me;(function(n){n[n.AlreadyOpened=0]="AlreadyOpened",n[n.AbnormalEnd=1]="AbnormalEnd",n[n.DecodeFailed=2]="DecodeFailed",n[n.LengthExceeded=3]="LengthExceeded",n[n.Incomplete=4]="Incomplete",n[n.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",n[n.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"})(me||(me={}));class Se extends vn{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=me[t]}}class Tt extends $e{constructor(e){super(18,e),this.name="SignalReconnectError"}}var Ci;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(Ci||(Ci={})),(function(n){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?n.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?n.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?n.DeviceInUse:n.Other}n.getFailure=e})(Ci||(Ci={}));class de{}de.setTimeout=function(){return setTimeout(...arguments)},de.setInterval=function(){return setInterval(...arguments)},de.clearTimeout=function(){return clearTimeout(...arguments)},de.clearInterval=function(){return clearInterval(...arguments)};var E;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",n.Moved="moved",n.MediaDevicesChanged="mediaDevicesChanged",n.ParticipantConnected="participantConnected",n.ParticipantDisconnected="participantDisconnected",n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalAudioSilenceDetected="localAudioSilenceDetected",n.ActiveSpeakersChanged="activeSpeakersChanged",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.ParticipantAttributesChanged="participantAttributesChanged",n.ParticipantActive="participantActive",n.RoomMetadataChanged="roomMetadataChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.AudioPlaybackStatusChanged="audioPlaybackChanged",n.VideoPlaybackStatusChanged="videoPlaybackChanged",n.MediaDevicesError="mediaDevicesError",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.SignalConnected="signalConnected",n.RecordingStatusChanged="recordingStatusChanged",n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ActiveDeviceChanged="activeDeviceChanged",n.ChatMessage="chatMessage",n.LocalTrackSubscribed="localTrackSubscribed",n.MetricsReceived="metricsReceived"})(E||(E={}));var I;(function(n){n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackCpuConstrained="localTrackCpuConstrained",n.LocalSenderCreated="localSenderCreated",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.IsSpeakingChanged="isSpeakingChanged",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.TrackCpuConstrained="trackCpuConstrained",n.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded",n.AttributesChanged="attributesChanged",n.LocalTrackSubscribed="localTrackSubscribed",n.ChatMessage="chatMessage",n.Active="active"})(I||(I={}));var P;(function(n){n.TransportsCreated="transportsCreated",n.Connected="connected",n.Disconnected="disconnected",n.Resuming="resuming",n.Resumed="resumed",n.Restarting="restarting",n.Restarted="restarted",n.SignalResumed="signalResumed",n.SignalRestarted="signalRestarted",n.Closing="closing",n.MediaTrackAdded="mediaTrackAdded",n.ActiveSpeakersUpdate="activeSpeakersUpdate",n.DataPacketReceived="dataPacketReceived",n.RTPVideoMapUpdate="rtpVideoMapUpdate",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ParticipantUpdate="participantUpdate",n.RoomUpdate="roomUpdate",n.SpeakersChanged="speakersChanged",n.StreamStateChanged="streamStateChanged",n.ConnectionQualityUpdate="connectionQualityUpdate",n.SubscriptionError="subscriptionError",n.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",n.RemoteMute="remoteMute",n.SubscribedQualityUpdate="subscribedQualityUpdate",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackSubscribed="localTrackSubscribed",n.Offline="offline",n.SignalRequestResponse="signalRequestResponse",n.SignalConnected="signalConnected",n.RoomMoved="roomMoved"})(P||(P={}));var w;(function(n){n.Message="message",n.Muted="muted",n.Unmuted="unmuted",n.Restarted="restarted",n.Ended="ended",n.Subscribed="subscribed",n.Unsubscribed="unsubscribed",n.CpuConstrained="cpuConstrained",n.UpdateSettings="updateSettings",n.UpdateSubscription="updateSubscription",n.AudioPlaybackStarted="audioPlaybackStarted",n.AudioPlaybackFailed="audioPlaybackFailed",n.AudioSilenceDetected="audioSilenceDetected",n.VisibilityChanged="visibilityChanged",n.VideoDimensionsChanged="videoDimensionsChanged",n.VideoPlaybackStarted="videoPlaybackStarted",n.VideoPlaybackFailed="videoPlaybackFailed",n.ElementAttached="elementAttached",n.ElementDetached="elementDetached",n.UpstreamPaused="upstreamPaused",n.UpstreamResumed="upstreamResumed",n.SubscriptionPermissionChanged="subscriptionPermissionChanged",n.SubscriptionStatusChanged="subscriptionStatusChanged",n.SubscriptionFailed="subscriptionFailed",n.TrackProcessorUpdate="trackProcessorUpdate",n.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",n.TranscriptionReceived="transcriptionReceived",n.TimeSyncUpdate="timeSyncUpdate",n.PreConnectBufferFlushed="preConnectBufferFlushed"})(w||(w={}));function Pl(n){return typeof n>"u"?n:typeof structuredClone=="function"?typeof n=="object"&&n!==null?structuredClone(Object.assign({},n)):structuredClone(n):JSON.parse(JSON.stringify(n))}class ${constructor(e,t,i,s,r){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&i!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:s,priority:r};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Il=["vp8","h264"],Dl=["vp8","h264","vp9","av1","h265"];function Al(n){return!!Il.find(e=>e===n)}const Ol=Al;var Eo;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(Eo||(Eo={}));var yn;(function(n){n.telephone={maxBitrate:12e3},n.speech={maxBitrate:24e3},n.music={maxBitrate:48e3},n.musicStereo={maxBitrate:64e3},n.musicHighQuality={maxBitrate:96e3},n.musicHighQualityStereo={maxBitrate:128e3}})(yn||(yn={}));const jt={h90:new $(160,90,9e4,20),h180:new $(320,180,16e4,20),h216:new $(384,216,18e4,20),h360:new $(640,360,45e4,20),h540:new $(960,540,8e5,25),h720:new $(1280,720,17e5,30),h1080:new $(1920,1080,3e6,30),h1440:new $(2560,1440,5e6,30),h2160:new $(3840,2160,8e6,30)},Tn={h120:new $(160,120,7e4,20),h180:new $(240,180,125e3,20),h240:new $(320,240,14e4,20),h360:new $(480,360,33e4,20),h480:new $(640,480,5e5,20),h540:new $(720,540,6e5,25),h720:new $(960,720,13e5,30),h1080:new $(1440,1080,23e5,30),h1440:new $(1920,1440,38e5,30)},_n={h360fps3:new $(640,360,2e5,3,"medium"),h360fps15:new $(640,360,4e5,15,"medium"),h720fps5:new $(1280,720,8e5,5,"medium"),h720fps15:new $(1280,720,15e5,15,"medium"),h720fps30:new $(1280,720,2e6,30,"medium"),h1080fps15:new $(1920,1080,25e5,15,"medium"),h1080fps30:new $(1920,1080,5e6,30,"medium"),original:new $(0,0,7e6,30,"medium")};function Ro(n,e,t){var i,s,r,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:d}=Io(n??{}),l=e?.processor,u=t?.processor,h=o??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(kn(h.audio,e),(i=(r=h.audio).deviceId)!==null&&i!==void 0||(r.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=c??l)),h.video&&(kn(h.video,t),(s=(a=h.video).deviceId)!==null&&s!==void 0||(a.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=d??u)),h}function kn(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function Sn(n){var e,t,i,s;const r={};if(n.video)if(typeof n.video=="object"){const a={},o=a,c=n.video;Object.keys(c).forEach(d=>{d==="resolution"?kn(o,c.resolution):o[d]=c[d]}),r.video=a,(e=(i=r.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else r.video=n.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return n.audio?typeof n.audio=="object"?(r.audio=n.audio,(t=(s=r.audio).deviceId)!==null&&t!==void 0||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function wo(n){return p(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const i=Po();if(i){const s=i.createAnalyser();s.fftSize=2048;const r=s.frequencyBinCount,a=new Uint8Array(r);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),yield le(t),s.getByteTimeDomainData(a);const c=a.some(d=>d!==128&&d!==0);return i.close(),!c}return!1})()})}function Po(){var n;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((n=window.document)===null||n===void 0)&&n.body)){const i=()=>p(this,void 0,void 0,function*(){var s;try{t.state==="suspended"&&(yield t.resume())}catch(r){console.warn("Error trying to auto-resume audio context",r)}finally{(s=window.document.body)===null||s===void 0||s.removeEventListener("click",i)}});t.addEventListener("statechange",()=>{var s;t.state==="closed"&&((s=window.document.body)===null||s===void 0||s.removeEventListener("click",i))}),window.document.body.addEventListener("click",i)}return t}}function Nl(n){return n==="audioinput"?S.Source.Microphone:n==="videoinput"?S.Source.Camera:S.Source.Unknown}function Cn(n){return n===S.Source.Microphone?"audioinput":n===S.Source.Camera?"videoinput":void 0}function xl(n){var e,t;let i=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(i=typeof i=="boolean"?{}:i,dt()?i=Object.assign(Object.assign({},i),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:n.resolution.width},height:{ideal:n.resolution.height},frameRate:n.resolution.frameRate})),{audio:(t=n.audio)!==null&&t!==void 0?t:!1,video:i,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function qt(n){return n.split("/")[1].toLowerCase()}function Ml(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new Xi({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function W(n){return"mediaStreamTrack"in n?{trackID:n.sid,source:n.source,muted:n.isMuted,enabled:n.mediaStreamTrack.enabled,kind:n.kind,streamID:n.mediaStreamID,streamTrackID:n.mediaStreamTrack.id}:{trackID:n.trackSid,enabled:n.isEnabled,muted:n.isMuted,trackInfo:Object.assign({mimeType:n.mimeType,name:n.trackName,encrypted:n.isEncrypted,kind:n.kind,source:n.source},n.track?W(n.track):{})}}function Ll(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function Ul(n,e){var t;n===void 0&&(n={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(n)],s={};for(const r of i)n[r]!==e[r]&&(s[r]=(t=e[r])!==null&&t!==void 0?t:"");return s}function Io(n){const e=Object.assign({},n);let t,i;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(i=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:Pl(e)}}function Fl(n){switch(n){case oe.CAMERA:return S.Source.Camera;case oe.MICROPHONE:return S.Source.Microphone;case oe.SCREEN_SHARE:return S.Source.ScreenShare;case oe.SCREEN_SHARE_AUDIO:return S.Source.ScreenShareAudio;default:return S.Source.Unknown}}function Do(n,e){return n.width*n.height<e.width*e.height}function Bl(n,e){var t;return(t=n.layers)===null||t===void 0?void 0:t.find(i=>i.quality===e)}const Vl=5e3,Wt=[];var Te;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Te||(Te={}));class S extends xe.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=S.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=V,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Vl):this.handleAppVisibilityChanged()},this.log=Ve((s=i.loggerName)!==null&&s!==void 0?s:Pe.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=S.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),W(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===S.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===S.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Wt.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&Wt.splice(Wt.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),_t(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),s=i.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?w.AudioPlaybackStarted:w.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?w.AudioPlaybackFailed:w.VideoPlaybackFailed,r):r.name==="AbortError"?V.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):V.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&i.some(a=>a.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(w.ElementAttached,e),e}detach(e){try{if(e){kt(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(w.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(i=>{kt(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(w.ElementDetached,i)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Ve(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Wt.forEach(i=>{i.parentElement||(t=!1)}),t&&Wt.push(e)}}handleAppVisibilityChanged(){return p(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===S.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){ye()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){ye()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function _t(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let i;n.kind==="audio"?i=t.getAudioTracks():i=t.getVideoTracks(),i.includes(n)||(i.forEach(s=>{t.removeTrack(s)}),t.addTrack(n)),(!dt()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(dt()||ct())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function kt(n,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(n),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(n){let e;(function(d){d.Audio="audio",d.Video="video",d.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(d){d.Camera="camera",d.Microphone="microphone",d.ScreenShare="screen_share",d.ScreenShareAudio="screen_share_audio",d.Unknown="unknown"})(t=n.Source||(n.Source={}));let i;(function(d){d.Active="active",d.Paused="paused",d.Unknown="unknown"})(i=n.StreamState||(n.StreamState={}));function s(d){switch(d){case e.Audio:return Re.AUDIO;case e.Video:return Re.VIDEO;default:return Re.DATA}}n.kindToProto=s;function r(d){switch(d){case Re.AUDIO:return e.Audio;case Re.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=r;function a(d){switch(d){case t.Camera:return oe.CAMERA;case t.Microphone:return oe.MICROPHONE;case t.ScreenShare:return oe.SCREEN_SHARE;case t.ScreenShareAudio:return oe.SCREEN_SHARE_AUDIO;default:return oe.UNKNOWN}}n.sourceToProto=a;function o(d){switch(d){case oe.CAMERA:return t.Camera;case oe.MICROPHONE:return t.Microphone;case oe.SCREEN_SHARE:return t.ScreenShare;case oe.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function c(d){switch(d){case Qi.ACTIVE:return i.Active;case Qi.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=c})(S||(S={}));const jl="|",Ao="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function ql(n){const e=n.split(jl);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function le(n){return new ue(e=>de.setTimeout(e,n))}function En(){return"addTransceiver"in RTCPeerConnection.prototype}function Rn(){return"addTrack"in RTCPeerConnection.prototype}function Wl(){if(!("getCapabilities"in RTCRtpSender)||dt()||ct())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function Kl(){if(!("getCapabilities"in RTCRtpSender)||ct())return!1;if(dt()){const t=be();if(t?.version&&Le(t.version,"16")<0||t?.os==="iOS"&&t?.osVersion&&Le(t.osVersion,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function Ie(n){return n==="av1"||n==="vp9"}function wn(n){return!document||Kt()?!1:(n||(n=document.createElement("audio")),"setSinkId"in n)}function Gl(){return typeof RTCPeerConnection>"u"?!1:En()||Rn()}function ct(){var n;return((n=be())===null||n===void 0?void 0:n.name)==="Firefox"}function Oo(){const n=be();return!!n&&n.name==="Chrome"&&n.os!=="iOS"}function dt(){var n;return((n=be())===null||n===void 0?void 0:n.name)==="Safari"}function Kt(){const n=be();return n?.name==="Safari"||n?.os==="iOS"}function Hl(){const n=be();return n?.name==="Safari"&&n.version.startsWith("17.")||n?.os==="iOS"&&!!n?.osVersion&&Le(n.osVersion,"17")>=0}function zl(n){return n||(n=be()),n?.name==="Safari"&&Le(n.version,"18.3")>0||n?.os==="iOS"&&!!n?.osVersion&&Le(n.osVersion,"18.3")>0}function No(){var n,e;return ye()?(e=(n=navigator.userAgentData)===null||n===void 0?void 0:n.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function Jl(){const n=be(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&Le(n.osVersion,e)>=0?!0:n.name==="Safari"&&Le(n.version,e)>=0}function ye(){return typeof document<"u"}function Me(){return navigator.product=="ReactNative"}function St(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function Pn(n){return St(n)?n.hostname.split(".")[0]:null}function xo(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Mo(){if(!Me())return;let n=xo();if(n)return n.platform}function Lo(){if(ye())return window.devicePixelRatio;if(Me()){let n=xo();if(n)return n.devicePixelRatio}return 1}function Le(n,e){const t=n.split("."),i=e.split("."),s=Math.min(t.length,i.length);for(let r=0;r<s;++r){const a=parseInt(t[r],10),o=parseInt(i[r],10);if(a>o)return 1;if(a<o)return-1;if(r===s-1&&a===o)return 0}return n===""&&e!==""?-1:e===""?1:t.length==i.length?0:t.length<i.length?-1:1}function $l(n){for(const e of n)e.target.handleResize(e)}function Ql(n){for(const e of n)e.target.handleVisibilityChanged(e)}let In=null;const Uo=()=>(In||(In=new ResizeObserver($l)),In);let Dn=null;const Fo=()=>(Dn||(Dn=new IntersectionObserver(Ql,{root:null,rootMargin:"0px"})),Dn);function Yl(){var n;const e=new hr({sdk:pr.JS,protocol:Rl,version:El});return Me()&&(e.os=(n=Mo())!==null&&n!==void 0?n:""),e}function Bo(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=n,s.height=e;const r=s.getContext("2d");r?.fillRect(0,0,s.width,s.height),i&&r&&(r.beginPath(),r.arc(n/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const a=s.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let Gt;function An(){if(!Gt){const n=new AudioContext,e=n.createOscillator(),t=n.createGain();t.gain.setValueAtTime(0,0);const i=n.createMediaStreamDestination();if(e.connect(t),t.connect(i),e.start(),[Gt]=i.stream.getAudioTracks(),!Gt)throw Error("Could not get empty media stream audio track");Gt.enabled=!1}return Gt.clone()}class Ce{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((i,s)=>p(this,void 0,void 0,function*(){this.resolve=i,this.reject=s,e&&(yield e(i,s))})).finally(()=>{var i;this._isResolved=!0,(i=this.onFinally)===null||i===void 0||i.call(this)})}}function Xl(n){return Dl.includes(n)}function Qe(n){if(typeof n=="string"||typeof n=="number")return n;if(Array.isArray(n))return n[0];if(n.exact!==void 0)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal!==void 0)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function Zl(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function Ht(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function eu(n,e){return n.segments.map(t=>{let{id:i,text:s,language:r,startTime:a,endTime:o,final:c}=t;var d;const l=(d=e.get(i))!==null&&d!==void 0?d:Date.now(),u=Date.now();return c?e.delete(i):e.set(i,l),{id:i,text:s,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:c,language:r,firstReceivedTime:l,lastReceivedTime:u}})}function tu(n){const{id:e,timestamp:t,message:i,editTimestamp:s}=n;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:i}}function Vo(n){switch(n.reason){case Q.LeaveRequest:return n.context;case Q.Cancelled:return ke.CLIENT_INITIATED;case Q.NotAllowed:return ke.USER_REJECTED;case Q.ServerUnreachable:return ke.JOIN_FAILURE;default:return ke.UNKNOWN_REASON}}function Ei(n){return n!==void 0?Number(n):void 0}function lt(n){return n!==void 0?BigInt(n):void 0}function Ct(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function Ue(n){return!!n&&n.kind==S.Kind.Audio}function Ye(n){return!!n&&n.kind==S.Kind.Video}function Xe(n){return Ct(n)&&Ye(n)}function We(n){return Ct(n)&&Ue(n)}function On(n){return!!n&&!n.isLocal}function iu(n){return!!n&&!n.isLocal}function Nn(n){return On(n)&&Ye(n)}function nu(n){return n.isLocal}function su(n,e){const t=[];let i=new TextEncoder().encode(n);for(;i.length>e;){let s=e;for(;s>0;){const r=i[s];if(r!==void 0&&(r&192)!==128)break;s--}t.push(i.slice(0,s)),i=i.slice(s)}return i.length>0&&t.push(i),t}function ru(n){var e;const t=n.get("Cache-Control");if(t){const i=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(i)return parseInt(i,10)}}function ou(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const i=au(n,e);return t?i:xn(i,"v1")}function au(n,e){const t=new URL(Zl(n));return e.forEach((i,s)=>{t.searchParams.set(s,i)}),xn(t,"rtc")}function cu(n){const e=new URL(Ht(n));return xn(e,"validate")}function jo(n){return n.endsWith("/")?n:"".concat(n,"/")}function xn(n,e){return n.pathname="".concat(jo(n.pathname)).concat(e),n}function qo(n){if(typeof n=="string")return yr.fromJson(JSON.parse(n),{ignoreUnknownFields:!0});if(n instanceof ArrayBuffer)return yr.fromBinary(new Uint8Array(n));throw new Error("could not decode websocket message: ".concat(typeof n))}function du(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(n instanceof AbortSignal))return e;const t=n.reason;switch(typeof t){case"string":return t;case"object":return t instanceof Error?t.message:e;default:return"toString"in t?t.toString():e}}const lu=10,zt="lk_e2ee",uu={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:lu,keyringSize:16};var Ze;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(Ze||(Ze={}));var Wo;(function(n){n.KeyRatcheted="keyRatcheted"})(Wo||(Wo={}));var et;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(et||(et={}));var Ko;(function(n){n.Error="cryptorError"})(Ko||(Ko={}));function hu(){return pu()||Mn()}function Mn(){return typeof window.RTCRtpScriptTransform<"u"}function pu(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function mu(n){var e,t,i,s,r;if(((e=n.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=n.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((i=n.value)===null||i===void 0?void 0:i.case)!=="speaker"&&((s=n.value)===null||s===void 0?void 0:s.case)!=="transcription"&&((r=n.value)===null||r===void 0?void 0:r.case)!=="encryptedPacket")return new rr({value:n.value})}class op extends xe.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,i,s)=>{V.debug("key ratcheted event received",{ratchetResult:t,participantId:i,keyIndex:s})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},uu),e),this.on(Ze.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){const s={key:e,participantIdentity:t,keyIndex:i};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(i??0),s),this.emit(Ze.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(Ze.RatchetRequest,e,t)}}var Go;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(Go||(Go={}));class fu extends xe.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=i=>{var s,r;const{kind:a,data:o}=i.data;switch(a){case"error":if(V.error(o.error.message),o.uuid){const l=this.decryptDataRequests.get(o.uuid);if(l?.reject){l.reject(o.error);break}const u=this.encryptDataRequests.get(o.uuid);if(u?.reject){u.reject(o.error);break}}this.emit(et.EncryptionError,o.error,o.participantIdentity);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach(l=>{this.postKey(l)});break;case"enable":if(o.enabled&&this.keyProvider.getKeys().forEach(l=>{this.postKey(l)}),this.encryptionEnabled!==o.enabled&&o.participantIdentity===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity))this.emit(et.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const l=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(o.participantIdentity);if(!l)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(et.ParticipantEncryptionStatusChanged,o.enabled,l)}break;case"ratchetKey":this.keyProvider.emit(Ze.KeyRatcheted,o.ratchetResult,o.participantIdentity,o.keyIndex);break;case"decryptDataResponse":const c=this.decryptDataRequests.get(o.uuid);c?.resolve&&c.resolve(o);break;case"encryptDataResponse":const d=this.encryptDataRequests.get(o.uuid);d?.resolve&&d.resolve(o);break}},this.onWorkerError=i=>{V.error("e2ee worker encountered an error:",{error:i.error}),this.emit(et.EncryptionError,i.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!hu())throw new bn("tried to setup end-to-end encryption on an unsupported browser");if(V.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:dl.getLevel()}};this.worker&&(V.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){V.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?V.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(P.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(E.TrackPublished,(i,s)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==se.NONE,s.identity)),e.on(E.ConnectionStateChanged,i=>{i===J.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==se.NONE,s.identity)})})}).on(E.TrackUnsubscribed,(i,s,r)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:i.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(E.TrackSubscribed,(i,s,r)=>{this.setupE2EEReceiver(i,r.identity,s.trackInfo)}).on(E.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(I.LocalSenderCreated,(i,s)=>p(this,void 0,void 0,function*(){this.setupE2EESender(s,i)})),e.localParticipant.on(I.LocalTrackPublished,i=>{if(!Ye(i.track)||!Kt())return;const s={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:qt(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s)}),t.on(Ze.SetKey,i=>this.postKey(i)).on(Ze.RatchetRequest,(i,s)=>this.postRatchetRequest(i,s))}encryptData(e){return p(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},s=new Ce;return s.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,s),this.worker.postMessage(i),s.promise})}handleEncryptedData(e,t,i,s){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const r=crypto.randomUUID(),a={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:i,keyIndex:s}},o=new Ce;return o.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:s}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const a={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:s}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!i?.mimeType||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?qt(i.mimeType):void 0)}}setupE2EESender(e,t){if(!Ct(e)||!t){t||V.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,s){return p(this,void 0,void 0,function*(){if(this.worker){if(Mn()&&!Oo()){const r={kind:"decode",participantIdentity:i,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(zt in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:i}};this.worker.postMessage(c);return}let r=e.writableStream,a=e.readableStream;if(!r||!a){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,a=c.readable}const o={kind:"decode",data:{readableStream:a,writableStream:r,trackId:t,codec:s,participantIdentity:i,isReuse:zt in e}};this.worker.postMessage(o,[a,r])}e[zt]=!0}})}handleSender(e,t,i){var s;if(!(zt in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Mn()&&!Oo()){V.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{V.info("initialize encoded streams");const r=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(a,[r.readable,r.writable])}e[zt]=!0}}}const gu=500,vu=15e3;class Et{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new Et),this._instance}addFailedConnectionAttempt(e){var t;const i=new URL(e),s=Pn(i);if(!s)return;let r=(t=this.failedConnectionAttempts.get(s))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(s,r+1),this.backOffPromises.set(s,le(Math.min(gu*Math.pow(2,r),vu)))}getBackOffPromise(e){const t=new URL(e),i=t&&Pn(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&Pn(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}Et._instance=null;const Ln="default";class ce{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new ce),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;if(((r=ce.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){V.debug("awaiting getUserMedia promise");try{t?yield ce.userMediaPromiseMap.get(t):yield Promise.all(ce.userMediaPromiseMap.values())}catch{V.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(s&&!(dt()&&i.hasDeviceInUse(t))&&(a.filter(c=>c.kind===t).length===0||a.some(c=>{const d=c.label==="",l=t?c.kind===t:!0;return d&&l}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},d=yield navigator.mediaDevices.getUserMedia(c);a=yield navigator.mediaDevices.enumerateDevices(),d.getTracks().forEach(l=>{l.stop()})}return i._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a})()})}normalizeDeviceId(e,t,i){return p(this,void 0,void 0,function*(){if(t!==Ln)return t;const s=yield this.getDevices(e),r=s.find(o=>o.deviceId===Ln);if(!r){V.warn("could not reliably determine default device");return}const a=s.find(o=>o.deviceId!==Ln&&o.groupId===(i??r.groupId));if(!a){V.warn("could not reliably determine default device");return}return a?.deviceId})}hasDeviceInUse(e){return e?ce.userMediaPromiseMap.has(e):ce.userMediaPromiseMap.size>0}}ce.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],ce.userMediaPromiseMap=new Map;var Jt;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(Jt||(Jt={}));class bu{constructor(){this.pendingTasks=new Map,this.taskMutex=new he,this.nextTaskIndex=0}run(e){return p(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Jt.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Jt.RUNNING,yield e()}finally{t.status=Jt.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return p(this,void 0,void 0,function*(){return this.run(()=>p(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class yu{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,s;if(!((i=t.signal)===null||i===void 0)&&i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,(s=t.protocols)!==null&&s!==void 0?s:[]);r.binaryType="arraybuffer",this.ws=r;const a=function(){let{closeCode:o,reason:c}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return r.close(o,c)};this.opened=new ue((o,c)=>{const d=()=>{c(F.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{o({readable:new ReadableStream({start(l){r.onmessage=u=>{let{data:h}=u;return l.enqueue(h)},r.onerror=u=>l.error(u)},cancel:a}),writable:new WritableStream({write(l){r.send(l)},abort(){r.close()},close:a}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",d)},r.addEventListener("error",d)}),this.closed=new ue((o,c)=>{const d=()=>p(this,void 0,void 0,function*(){const l=new ue(h=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",f=>{h(f)},{once:!0})}),u=yield ue.race([le(250),l]);u?o(u):c(F.websocket("Encountered unspecified websocket error without a timely close event"))});r.onclose=l=>{let{code:u,reason:h}=l;o({closeCode:u,reason:h}),r.removeEventListener("error",d)},r.addEventListener("error",d)}),t.signal&&(t.signal.onabort=()=>r.close()),this.close=a}}const Tu=["syncState","trickle","offer","answer","simulate","leave"];function _u(n){const e=Tu.indexOf(n.case)>=0;return V.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var Y;(function(n){n[n.CONNECTING=0]="CONNECTING",n[n.CONNECTED=1]="CONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.DISCONNECTING=3]="DISCONNECTING",n[n.DISCONNECTED=4]="DISCONNECTED"})(Y||(Y={}));const ku=250;class Un{get currentState(){return this.state}get isDisconnected(){return this.state===Y.DISCONNECTING||this.state===Y.DISCONNECTED}get isEstablishingConnection(){return this.state===Y.CONNECTING||this.state===Y.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=Y.DISCONNECTED,this.log=V,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=Ve((i=t.loggerName)!==null&&i!==void 0?i:Pe.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new bu,this.queuedRequests=[],this.closingLock=new he,this.connectionLock=new he,this.state=Y.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,i,s){return p(this,arguments,void 0,function(r,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){return d.state=Y.CONNECTING,d.options=o,yield d.connect(r,a,o,c,l)})()})}reconnect(e,t,i,s){return p(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=Y.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:s}),void 0,this.useV0SignalPath)})}connect(e,t,i,s){return p(this,arguments,void 0,function(r,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){const u=yield d.connectionLock.lock();d.connectOptions=o,d.useV0SignalPath=l;const h=Yl(),f=l?Su(a,h,o):Cu(a,h,o),b=ou(r,f,l).toString(),v=cu(b).toString();return new Promise((R,_)=>p(d,void 0,void 0,function*(){var A,x;try{let y=!1;const T=O=>p(this,void 0,void 0,function*(){if(y)return;y=!0;const L=O instanceof Event?O.currentTarget:O,q=du(L,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(q)).catch(Z=>{this.log.error(Z),this.close()}):this.close(),C(),_(F.cancelled(q))});c?.addEventListener("abort",T);const C=()=>{clearTimeout(N),c?.removeEventListener("abort",T)},N=setTimeout(()=>{T(F.timeout("room connection has timed out (signal)"))},o.websocketTimeout),U=(O,L)=>{this.handleSignalConnected(O,N,L)},M=new URL(b);M.searchParams.has("access_token")&&M.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(M),Object.assign({reconnect:o.reconnect,reconnectReason:o.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new yu(b);try{this.ws.closed.then(ge=>{var st;this.isEstablishingConnection&&_(F.internal("Websocket got closed during a (re)connection attempt: ".concat(ge.reason))),ge.closeCode!==1e3&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:ge.reason,code:ge.closeCode,wasClean:ge.closeCode===1e3,state:this.state})),this.state===Y.CONNECTED&&this.handleOnClose((st=ge.reason)!==null&&st!==void 0?st:"Unexpected WS error"))}).catch(ge=>{this.isEstablishingConnection&&_(F.internal("Websocket error during a (re)connection attempt: ".concat(ge)))});const O=yield this.ws.opened.catch(ge=>p(this,void 0,void 0,function*(){if(this.state!==Y.CONNECTED){this.state=Y.DISCONNECTED,clearTimeout(N);const st=yield this.handleConnectionError(ge,v);_(st);return}this.handleWSError(ge),_(ge)}));if(clearTimeout(N),!O)return;const L=O.readable.getReader();this.streamWriter=O.writable.getWriter();const q=yield L.read();if(L.releaseLock(),!q.value)throw F.internal("no message received as first message");const Z=qo(q.value),_e=this.validateFirstMessage(Z,(A=o.reconnect)!==null&&A!==void 0?A:!1);if(!_e.isValid){_(_e.error);return}((x=Z.message)===null||x===void 0?void 0:x.case)==="join"&&(this.pingTimeoutDuration=Z.message.value.pingTimeout,this.pingIntervalDuration=Z.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})));const ut=_e.shouldProcessFirstMessage?Z:void 0;U(O,ut),R(_e.response)}catch(O){_(O)}finally{C()}}finally{u()}}))})()})}startReadingLoop(e,t){return p(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield le(this.signalLatency));const{done:i,value:s}=yield e.read();if(i)break;const r=qo(s);this.handleSignalResponse(r)}})}close(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){if([Y.DISCONNECTING||Y.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const s=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Y.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const r=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([r,le(ku)])}}catch(r){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:r}))}finally{t&&(e.state=Y.DISCONNECTED),s()}})()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Rt(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Rt(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new ui({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new hi({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const o=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new en({requestId:o,metadata:i,name:s,attributes:a})}),o})()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new Er({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Pr({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:X.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Ar({timestamp:X.parse(Date.now()),rtt:X.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Zi({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new mi({reason:ke.CLIENT_INITIATED,action:vt.DISCONNECT})})}sendRequest(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!s&&!_u(t)&&i.state===Y.RECONNECTING){i.queuedRequests.push(()=>p(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield i.requestQueue.flush()),i.signalLatency&&(yield le(i.signalLatency)),i.isDisconnected){i.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!i.streamWriter){i.log.error("cannot send signal request before connected, type: ".concat(t?.case),i.logContext);return}const a=new Id({message:t});try{i.useJSON?yield i.streamWriter.write(a.toJsonString()):yield i.streamWriter.write(a.toBinary())}catch(o){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:o}))}})()})}handleSignalResponse(e){var t,i;const s=e.message;if(s==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(s.case==="answer"){const a=Ho(s.value);this.onAnswer&&this.onAnswer(a,s.value.id,s.value.midToTrackId)}else if(s.case==="offer"){const a=Ho(s.value);this.onOffer&&this.onOffer(a,s.value.id,s.value.midToTrackId)}else if(s.case==="trickle"){const a=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(a,s.value.target)}else s.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=s.value.participants)!==null&&t!==void 0?t:[]):s.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.value):s.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=s.value.speakers)!==null&&i!==void 0?i:[]):s.case==="leave"?this.onLeave&&this.onLeave(s.value):s.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.value.sid,s.value.muted):s.case==="roomUpdate"?this.onRoomUpdate&&s.value.room&&this.onRoomUpdate(s.value.room):s.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(s.value):s.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.value):s.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.value):s.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.value):s.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(s.value):s.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.value):s.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(s.value):s.case==="pong"||(s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):s.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(s.value):s.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(s.value.trackSid):s.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(s.value.token),this.onRoomMoved&&this.onRoomMoved(s.value)):s.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(s.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:s.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return p(this,void 0,void 0,function*(){if(this.state===Y.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=de.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&de.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=de.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&de.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=Y.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,s,r,a,o;return((i=e.message)===null||i===void 0?void 0:i.case)==="join"?{isValid:!0,response:e.message.value}:this.state===Y.RECONNECTING&&((s=e.message)===null||s===void 0?void 0:s.case)!=="leave"?((r=e.message)===null||r===void 0?void 0:r.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((a=e.message)===null||a===void 0?void 0:a.case)==="leave"?{isValid:!1,error:F.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:F.internal("Unexpected first message")}:{isValid:!1,error:F.internal("did not receive join response, got ".concat((o=e.message)===null||o===void 0?void 0:o.case," instead"))}}handleConnectionError(e,t){return p(this,void 0,void 0,function*(){try{const i=yield fetch(t);switch(i.status){case 404:return F.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const s=yield i.text();return F.notAllowed(s,i.status);default:break}return e instanceof F?e:F.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof F?i:F.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}}function Ho(n){const e={type:"offer",sdp:n.sdp};switch(n.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=n.type;break}return e}function Rt(n,e){return new Je({sdp:n.sdp,type:n.type,id:e})}function Su(n,e,t){var i;const s=new URLSearchParams;return s.set("access_token",n),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",Me()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),t.adaptiveStream&&s.set("adaptive_stream","1"),t.reconnectReason&&s.set("reconnect_reason",t.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&s.set("network",navigator.connection.type),s}function Cu(n,e,t){const i=new URLSearchParams;i.set("access_token",n);const s=new il({clientInfo:e,connectionSettings:new Or({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);const r=new nl({joinRequest:s.toBinary()});return i.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),i}class zo{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Eu{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const s=i+this.ttl;return this._map.set(e,{value:t,expiresAt:s}),this}get(e){const t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){const t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const[s,r]of i.entries())t.push(e(r,s,i));return t}asValueMap(){const e=new Map;for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var De={},Fn={},Bn={exports:{}},Jo;function Vn(){if(Jo)return Bn.exports;Jo=1;var n=Bn.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(n).forEach(function(e){var t=n[e];t.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),Bn.exports}var $o;function Ru(){return $o||($o=1,(function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,d,l){if(l&&!d)c[l]=e(o[1]);else for(var u=0;u<d.length;u+=1)o[u+1]!=null&&(c[d[u]]=e(o[u+1]))},i=function(o,c,d){var l=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:l&&!c[o.name]&&(c[o.name]={});var u=o.push?{}:l?c[o.name]:c;t(d.match(o.reg),u,o.names,o.name),o.push&&c[o.push].push(u)},s=Vn(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var c={},d=[],l=c;return o.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var h=u[0],f=u.slice(2);h==="m"&&(d.push({rtp:[],fmtp:[]}),l=d[d.length-1]);for(var b=0;b<(s[h]||[]).length;b+=1){var v=s[h][b];if(v.reg.test(f))return i(v,l,f)}}),c.media=d,c};var a=function(o,c){var d=c.split(/=(.+)/,2);return d.length===2?o[d[0]]=e(d[1]):d.length===1&&c.length>1&&(o[d[0]]=void 0),o};n.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(o){return o.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(o){for(var c=[],d=o.split(" ").map(e),l=0;l<d.length;l+=3)c.push({component:d[l],ip:d[l+1],port:d[l+2]});return c},n.parseImageAttributes=function(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},n.parseSimulcastStreamList=function(o){return o.split(";").map(function(c){return c.split(",").map(function(d){var l,u=!1;return d[0]!=="~"?l=e(d):(l=e(d.substring(1,d.length)),u=!0),{scid:l,paused:u}})})}})(Fn)),Fn}var jn,Qo;function wu(){if(Qo)return jn;Qo=1;var n=Vn(),e=/%[sdv%]/g,t=function(a){var o=1,c=arguments,d=c.length;return a.replace(e,function(l){if(o>=d)return l;var u=c[o];switch(o+=1,l){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},i=function(a,o,c){var d=o.format instanceof Function?o.format(o.push?c:c[o.name]):o.format,l=[a+"="+d];if(o.names)for(var u=0;u<o.names.length;u+=1){var h=o.names[u];o.name?l.push(c[o.name][h]):l.push(c[o.names[u]])}else l.push(c[o.name]);return t.apply(null,l)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return jn=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var c=o.outerOrder||s,d=o.innerOrder||r,l=[];return c.forEach(function(u){n[u].forEach(function(h){h.name in a&&a[h.name]!=null?l.push(i(u,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(f){l.push(i(u,h,f))})})}),a.media.forEach(function(u){l.push(i("m",n.m[0],u)),d.forEach(function(h){n[h].forEach(function(f){f.name in u&&u[f.name]!=null?l.push(i(h,f,u)):f.push in u&&u[f.push]!=null&&u[f.push].forEach(function(b){l.push(i(h,f,b))})})})}),l.join(`\r
145
+ `);n.RTCSessionDescription&&s instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function Si(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(n.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Ci(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}var jl=Object.freeze({__proto__:null,removeExtmapAllowMixed:gn,shimAddIceCandidateNullOrEmpty:Si,shimConnectionState:fn,shimMaxMessageSize:Ti,shimParameterlessSetLocalDescription:Ci,shimRTCIceCandidate:_i,shimRTCIceCandidateRelayProtocol:mn,shimSendThrowTypeError:ki});function ql(){let{window:n}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=Gr,i=Ul(n),s={browserDetails:i,commonShim:jl,extractVersion:jt,disableLog:Ml,disableWarnings:Ll,sdp:Vl};switch(i.browser){case"chrome":if(!ro||!un||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=ro,Si(n,i),Ci(n),Yr(n,i),Xr(n),un(n,i),Zr(n),no(n,i),eo(n),to(n),so(n,i),_i(n),mn(n),fn(n),Ti(n,i),ki(n),gn(n,i);break;case"firefox":if(!vo||!hn||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=vo,Si(n,i),Ci(n),oo(n,i),hn(n,i),ao(n),uo(n),co(n),lo(n),ho(n),po(n),mo(n),fo(n),go(n),_i(n),fn(n),Ti(n,i),ki(n);break;case"safari":if(!wo||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=wo,Si(n,i),Ci(n),So(n),Eo(n),_o(n),bo(n),yo(n),Co(n),To(n),Ro(n),_i(n),mn(n),Ti(n,i),ki(n),gn(n,i);break;default:t("Unsupported browser!");break}return s}ql({window:typeof window>"u"?void 0:window});var vn,Do;class ue extends(Do=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}vn=ue,ue.resolve=n=>Reflect.get(Do,"resolve",vn).call(vn,n);const Wl=/version\/(\d+(\.?_?\d+)+)/i;let bn;function be(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(bn===void 0||e){const i=Kl.find(s=>{let{test:r}=s;return r.test(t)});bn=i?.describe(t)}return bn}const Kl=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:Ei(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:yn(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:Ei(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:yn(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:Ei(Wl,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:yn(n)}}}];function Ei(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(n);return i&&i.length>=t&&i[t]||""}function yn(n){return n.includes("mac os")?Ei(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var Hl="2.17.1";const Gl=Hl,zl=16;class $e extends Error{constructor(e,t,i){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,typeof i?.cause<"u"&&(this.cause=i?.cause)}}class _n extends $e{}var Q;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.ServerUnreachable=1]="ServerUnreachable",n[n.InternalError=2]="InternalError",n[n.Cancelled=3]="Cancelled",n[n.LeaveRequest=4]="LeaveRequest",n[n.Timeout=5]="Timeout",n[n.WebSocket=6]="WebSocket",n[n.ServiceNotFound=7]="ServiceNotFound"})(Q||(Q={}));class F extends _n{constructor(e,t,i,s){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=s,this.reasonName=Q[t]}static notAllowed(e,t,i){return new F(e,Q.NotAllowed,t,i)}static timeout(e){return new F(e,Q.Timeout)}static leaveRequest(e,t){return new F(e,Q.LeaveRequest,void 0,t)}static internal(e,t){return new F(e,Q.InternalError,void 0,t)}static cancelled(e){return new F(e,Q.Cancelled)}static serverUnreachable(e,t){return new F(e,Q.ServerUnreachable,t)}static websocket(e,t,i){return new F(e,Q.WebSocket,t,i)}static serviceNotFound(e,t){return new F(e,Q.ServiceNotFound,void 0,t)}}class Tn extends $e{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class qe extends $e{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class Jl extends $e{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class re extends $e{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class yt extends $e{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Ao extends $e{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Oo extends _n{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:an[t]}}var me;(function(n){n[n.AlreadyOpened=0]="AlreadyOpened",n[n.AbnormalEnd=1]="AbnormalEnd",n[n.DecodeFailed=2]="DecodeFailed",n[n.LengthExceeded=3]="LengthExceeded",n[n.Incomplete=4]="Incomplete",n[n.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",n[n.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"})(me||(me={}));class Se extends _n{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=me[t]}}class _t extends $e{constructor(e){super(18,e),this.name="SignalReconnectError"}}var Ri;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(Ri||(Ri={})),(function(n){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?n.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?n.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?n.DeviceInUse:n.Other}n.getFailure=e})(Ri||(Ri={}));class de{}de.setTimeout=function(){return setTimeout(...arguments)},de.setInterval=function(){return setInterval(...arguments)},de.clearTimeout=function(){return clearTimeout(...arguments)},de.clearInterval=function(){return clearInterval(...arguments)};var E;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",n.Moved="moved",n.MediaDevicesChanged="mediaDevicesChanged",n.ParticipantConnected="participantConnected",n.ParticipantDisconnected="participantDisconnected",n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalAudioSilenceDetected="localAudioSilenceDetected",n.ActiveSpeakersChanged="activeSpeakersChanged",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.ParticipantAttributesChanged="participantAttributesChanged",n.ParticipantActive="participantActive",n.RoomMetadataChanged="roomMetadataChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.AudioPlaybackStatusChanged="audioPlaybackChanged",n.VideoPlaybackStatusChanged="videoPlaybackChanged",n.MediaDevicesError="mediaDevicesError",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.SignalConnected="signalConnected",n.RecordingStatusChanged="recordingStatusChanged",n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ActiveDeviceChanged="activeDeviceChanged",n.ChatMessage="chatMessage",n.LocalTrackSubscribed="localTrackSubscribed",n.MetricsReceived="metricsReceived"})(E||(E={}));var I;(function(n){n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackCpuConstrained="localTrackCpuConstrained",n.LocalSenderCreated="localSenderCreated",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.IsSpeakingChanged="isSpeakingChanged",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.TrackCpuConstrained="trackCpuConstrained",n.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded",n.AttributesChanged="attributesChanged",n.LocalTrackSubscribed="localTrackSubscribed",n.ChatMessage="chatMessage",n.Active="active"})(I||(I={}));var P;(function(n){n.TransportsCreated="transportsCreated",n.Connected="connected",n.Disconnected="disconnected",n.Resuming="resuming",n.Resumed="resumed",n.Restarting="restarting",n.Restarted="restarted",n.SignalResumed="signalResumed",n.SignalRestarted="signalRestarted",n.Closing="closing",n.MediaTrackAdded="mediaTrackAdded",n.ActiveSpeakersUpdate="activeSpeakersUpdate",n.DataPacketReceived="dataPacketReceived",n.RTPVideoMapUpdate="rtpVideoMapUpdate",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ParticipantUpdate="participantUpdate",n.RoomUpdate="roomUpdate",n.SpeakersChanged="speakersChanged",n.StreamStateChanged="streamStateChanged",n.ConnectionQualityUpdate="connectionQualityUpdate",n.SubscriptionError="subscriptionError",n.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",n.RemoteMute="remoteMute",n.SubscribedQualityUpdate="subscribedQualityUpdate",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackSubscribed="localTrackSubscribed",n.Offline="offline",n.SignalRequestResponse="signalRequestResponse",n.SignalConnected="signalConnected",n.RoomMoved="roomMoved"})(P||(P={}));var w;(function(n){n.Message="message",n.Muted="muted",n.Unmuted="unmuted",n.Restarted="restarted",n.Ended="ended",n.Subscribed="subscribed",n.Unsubscribed="unsubscribed",n.CpuConstrained="cpuConstrained",n.UpdateSettings="updateSettings",n.UpdateSubscription="updateSubscription",n.AudioPlaybackStarted="audioPlaybackStarted",n.AudioPlaybackFailed="audioPlaybackFailed",n.AudioSilenceDetected="audioSilenceDetected",n.VisibilityChanged="visibilityChanged",n.VideoDimensionsChanged="videoDimensionsChanged",n.VideoPlaybackStarted="videoPlaybackStarted",n.VideoPlaybackFailed="videoPlaybackFailed",n.ElementAttached="elementAttached",n.ElementDetached="elementDetached",n.UpstreamPaused="upstreamPaused",n.UpstreamResumed="upstreamResumed",n.SubscriptionPermissionChanged="subscriptionPermissionChanged",n.SubscriptionStatusChanged="subscriptionStatusChanged",n.SubscriptionFailed="subscriptionFailed",n.TrackProcessorUpdate="trackProcessorUpdate",n.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",n.TranscriptionReceived="transcriptionReceived",n.TimeSyncUpdate="timeSyncUpdate",n.PreConnectBufferFlushed="preConnectBufferFlushed"})(w||(w={}));function $l(n){return typeof n>"u"?n:typeof structuredClone=="function"?typeof n=="object"&&n!==null?structuredClone(Object.assign({},n)):structuredClone(n):JSON.parse(JSON.stringify(n))}class ${constructor(e,t,i,s,r){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&i!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:s,priority:r};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const Ql=["vp8","h264"],Yl=["vp8","h264","vp9","av1","h265"];function Xl(n){return!!Ql.find(e=>e===n)}const Zl=Xl;var No;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(No||(No={}));var kn;(function(n){n.telephone={maxBitrate:12e3},n.speech={maxBitrate:24e3},n.music={maxBitrate:48e3},n.musicStereo={maxBitrate:64e3},n.musicHighQuality={maxBitrate:96e3},n.musicHighQualityStereo={maxBitrate:128e3}})(kn||(kn={}));const qt={h90:new $(160,90,9e4,20),h180:new $(320,180,16e4,20),h216:new $(384,216,18e4,20),h360:new $(640,360,45e4,20),h540:new $(960,540,8e5,25),h720:new $(1280,720,17e5,30),h1080:new $(1920,1080,3e6,30),h1440:new $(2560,1440,5e6,30),h2160:new $(3840,2160,8e6,30)},Sn={h120:new $(160,120,7e4,20),h180:new $(240,180,125e3,20),h240:new $(320,240,14e4,20),h360:new $(480,360,33e4,20),h480:new $(640,480,5e5,20),h540:new $(720,540,6e5,25),h720:new $(960,720,13e5,30),h1080:new $(1440,1080,23e5,30),h1440:new $(1920,1440,38e5,30)},Cn={h360fps3:new $(640,360,2e5,3,"medium"),h360fps15:new $(640,360,4e5,15,"medium"),h720fps5:new $(1280,720,8e5,5,"medium"),h720fps15:new $(1280,720,15e5,15,"medium"),h720fps30:new $(1280,720,2e6,30,"medium"),h1080fps15:new $(1920,1080,25e5,15,"medium"),h1080fps30:new $(1920,1080,5e6,30,"medium"),original:new $(0,0,7e6,30,"medium")};function xo(n,e,t){var i,s,r,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:d}=Uo(n??{}),l=e?.processor,u=t?.processor,h=o??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(En(h.audio,e),(i=(r=h.audio).deviceId)!==null&&i!==void 0||(r.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=c??l)),h.video&&(En(h.video,t),(s=(a=h.video).deviceId)!==null&&s!==void 0||(a.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=d??u)),h}function En(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function Rn(n){var e,t,i,s;const r={};if(n.video)if(typeof n.video=="object"){const a={},o=a,c=n.video;Object.keys(c).forEach(d=>{d==="resolution"?En(o,c.resolution):o[d]=c[d]}),r.video=a,(e=(i=r.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else r.video=n.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return n.audio?typeof n.audio=="object"?(r.audio=n.audio,(t=(s=r.audio).deviceId)!==null&&t!==void 0||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function Mo(n){return p(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const i=Lo();if(i){const s=i.createAnalyser();s.fftSize=2048;const r=s.frequencyBinCount,a=new Uint8Array(r);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),yield le(t),s.getByteTimeDomainData(a);const c=a.some(d=>d!==128&&d!==0);return i.close(),!c}return!1})()})}function Lo(){var n;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((n=window.document)===null||n===void 0)&&n.body)){const i=()=>p(this,void 0,void 0,function*(){var s;try{t.state==="suspended"&&(yield t.resume())}catch(r){console.warn("Error trying to auto-resume audio context",r)}finally{(s=window.document.body)===null||s===void 0||s.removeEventListener("click",i)}});t.addEventListener("statechange",()=>{var s;t.state==="closed"&&((s=window.document.body)===null||s===void 0||s.removeEventListener("click",i))}),window.document.body.addEventListener("click",i)}return t}}function eu(n){return n==="audioinput"?S.Source.Microphone:n==="videoinput"?S.Source.Camera:S.Source.Unknown}function wn(n){return n===S.Source.Microphone?"audioinput":n===S.Source.Camera?"videoinput":void 0}function tu(n){var e,t;let i=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(i=typeof i=="boolean"?{}:i,dt()?i=Object.assign(Object.assign({},i),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:n.resolution.width},height:{ideal:n.resolution.height},frameRate:n.resolution.frameRate})),{audio:(t=n.audio)!==null&&t!==void 0?t:!1,video:i,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function Wt(n){return n.split("/")[1].toLowerCase()}function iu(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new tn({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function K(n){return"mediaStreamTrack"in n?{trackID:n.sid,source:n.source,muted:n.isMuted,enabled:n.mediaStreamTrack.enabled,kind:n.kind,streamID:n.mediaStreamID,streamTrackID:n.mediaStreamTrack.id}:{trackID:n.trackSid,enabled:n.isEnabled,muted:n.isMuted,trackInfo:Object.assign({mimeType:n.mimeType,name:n.trackName,encrypted:n.isEncrypted,kind:n.kind,source:n.source},n.track?K(n.track):{})}}function nu(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function su(n,e){var t;n===void 0&&(n={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(n)],s={};for(const r of i)n[r]!==e[r]&&(s[r]=(t=e[r])!==null&&t!==void 0?t:"");return s}function Uo(n){const e=Object.assign({},n);let t,i;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(i=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:$l(e)}}function ru(n){switch(n){case oe.CAMERA:return S.Source.Camera;case oe.MICROPHONE:return S.Source.Microphone;case oe.SCREEN_SHARE:return S.Source.ScreenShare;case oe.SCREEN_SHARE_AUDIO:return S.Source.ScreenShareAudio;default:return S.Source.Unknown}}function Fo(n,e){return n.width*n.height<e.width*e.height}function ou(n,e){var t;return(t=n.layers)===null||t===void 0?void 0:t.find(i=>i.quality===e)}const au=5e3,Kt=[];var _e;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(_e||(_e={}));class S extends xe.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=S.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=V,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),au):this.handleAppVisibilityChanged()},this.log=Ve((s=i.loggerName)!==null&&s!==void 0?s:Pe.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=S.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),K(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===S.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===S.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Kt.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&Kt.splice(Kt.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Tt(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),s=i.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?w.AudioPlaybackStarted:w.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?w.AudioPlaybackFailed:w.VideoPlaybackFailed,r):r.name==="AbortError"?V.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):V.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&i.some(a=>a.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(w.ElementAttached,e),e}detach(e){try{if(e){kt(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(w.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(i=>{kt(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(w.ElementDetached,i)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Ve(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Kt.forEach(i=>{i.parentElement||(t=!1)}),t&&Kt.push(e)}}handleAppVisibilityChanged(){return p(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===S.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){ye()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){ye()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Tt(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let i;n.kind==="audio"?i=t.getAudioTracks():i=t.getVideoTracks(),i.includes(n)||(i.forEach(s=>{t.removeTrack(s)}),t.addTrack(n)),(!dt()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(dt()||ct())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function kt(n,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(n),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(n){let e;(function(d){d.Audio="audio",d.Video="video",d.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(d){d.Camera="camera",d.Microphone="microphone",d.ScreenShare="screen_share",d.ScreenShareAudio="screen_share_audio",d.Unknown="unknown"})(t=n.Source||(n.Source={}));let i;(function(d){d.Active="active",d.Paused="paused",d.Unknown="unknown"})(i=n.StreamState||(n.StreamState={}));function s(d){switch(d){case e.Audio:return Re.AUDIO;case e.Video:return Re.VIDEO;default:return Re.DATA}}n.kindToProto=s;function r(d){switch(d){case Re.AUDIO:return e.Audio;case Re.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=r;function a(d){switch(d){case t.Camera:return oe.CAMERA;case t.Microphone:return oe.MICROPHONE;case t.ScreenShare:return oe.SCREEN_SHARE;case t.ScreenShareAudio:return oe.SCREEN_SHARE_AUDIO;default:return oe.UNKNOWN}}n.sourceToProto=a;function o(d){switch(d){case oe.CAMERA:return t.Camera;case oe.MICROPHONE:return t.Microphone;case oe.SCREEN_SHARE:return t.ScreenShare;case oe.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function c(d){switch(d){case Zi.ACTIVE:return i.Active;case Zi.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=c})(S||(S={}));const cu="|",Bo="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function du(n){const e=n.split(cu);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function le(n){return new ue(e=>de.setTimeout(e,n))}function Pn(){return"addTransceiver"in RTCPeerConnection.prototype}function In(){return"addTrack"in RTCPeerConnection.prototype}function lu(){if(!("getCapabilities"in RTCRtpSender)||dt()||ct())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function uu(){if(!("getCapabilities"in RTCRtpSender)||ct())return!1;if(dt()){const t=be();if(t?.version&&Le(t.version,"16")<0||t?.os==="iOS"&&t?.osVersion&&Le(t.osVersion,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function Ie(n){return n==="av1"||n==="vp9"}function Dn(n){return!document||Ht()?!1:(n||(n=document.createElement("audio")),"setSinkId"in n)}function hu(){return typeof RTCPeerConnection>"u"?!1:Pn()||In()}function ct(){var n;return((n=be())===null||n===void 0?void 0:n.name)==="Firefox"}function Vo(){const n=be();return!!n&&n.name==="Chrome"&&n.os!=="iOS"}function dt(){var n;return((n=be())===null||n===void 0?void 0:n.name)==="Safari"}function Ht(){const n=be();return n?.name==="Safari"||n?.os==="iOS"}function pu(){const n=be();return n?.name==="Safari"&&n.version.startsWith("17.")||n?.os==="iOS"&&!!n?.osVersion&&Le(n.osVersion,"17")>=0}function mu(n){return n||(n=be()),n?.name==="Safari"&&Le(n.version,"18.3")>0||n?.os==="iOS"&&!!n?.osVersion&&Le(n.osVersion,"18.3")>0}function jo(){var n,e;return ye()?(e=(n=navigator.userAgentData)===null||n===void 0?void 0:n.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function fu(){const n=be(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&Le(n.osVersion,e)>=0?!0:n.name==="Safari"&&Le(n.version,e)>=0}function ye(){return typeof document<"u"}function Me(){return navigator.product=="ReactNative"}function St(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function An(n){return St(n)?n.hostname.split(".")[0]:null}function qo(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Wo(){if(!Me())return;let n=qo();if(n)return n.platform}function Ko(){if(ye())return window.devicePixelRatio;if(Me()){let n=qo();if(n)return n.devicePixelRatio}return 1}function Le(n,e){const t=n.split("."),i=e.split("."),s=Math.min(t.length,i.length);for(let r=0;r<s;++r){const a=parseInt(t[r],10),o=parseInt(i[r],10);if(a>o)return 1;if(a<o)return-1;if(r===s-1&&a===o)return 0}return n===""&&e!==""?-1:e===""?1:t.length==i.length?0:t.length<i.length?-1:1}function gu(n){for(const e of n)e.target.handleResize(e)}function vu(n){for(const e of n)e.target.handleVisibilityChanged(e)}let On=null;const Ho=()=>(On||(On=new ResizeObserver(gu)),On);let Nn=null;const Go=()=>(Nn||(Nn=new IntersectionObserver(vu,{root:null,rootMargin:"0px"})),Nn);function bu(){var n;const e=new _r({sdk:Tr.JS,protocol:zl,version:Gl});return Me()&&(e.os=(n=Wo())!==null&&n!==void 0?n:""),e}function zo(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=n,s.height=e;const r=s.getContext("2d");r?.fillRect(0,0,s.width,s.height),i&&r&&(r.beginPath(),r.arc(n/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const a=s.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let Gt;function xn(){if(!Gt){const n=new AudioContext,e=n.createOscillator(),t=n.createGain();t.gain.setValueAtTime(0,0);const i=n.createMediaStreamDestination();if(e.connect(t),t.connect(i),e.start(),[Gt]=i.stream.getAudioTracks(),!Gt)throw Error("Could not get empty media stream audio track");Gt.enabled=!1}return Gt.clone()}class Ce{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((i,s)=>p(this,void 0,void 0,function*(){this.resolve=i,this.reject=s,e&&(yield e(i,s))})).finally(()=>{var i;this._isResolved=!0,(i=this.onFinally)===null||i===void 0||i.call(this)})}}function yu(n){return Yl.includes(n)}function Qe(n){if(typeof n=="string"||typeof n=="number")return n;if(Array.isArray(n))return n[0];if(n.exact!==void 0)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal!==void 0)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function _u(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function zt(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function Tu(n,e){return n.segments.map(t=>{let{id:i,text:s,language:r,startTime:a,endTime:o,final:c}=t;var d;const l=(d=e.get(i))!==null&&d!==void 0?d:Date.now(),u=Date.now();return c?e.delete(i):e.set(i,l),{id:i,text:s,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:c,language:r,firstReceivedTime:l,lastReceivedTime:u}})}function ku(n){const{id:e,timestamp:t,message:i,editTimestamp:s}=n;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:i}}function Jo(n){switch(n.reason){case Q.LeaveRequest:return n.context;case Q.Cancelled:return ke.CLIENT_INITIATED;case Q.NotAllowed:return ke.USER_REJECTED;case Q.ServerUnreachable:return ke.JOIN_FAILURE;default:return ke.UNKNOWN_REASON}}function wi(n){return n!==void 0?Number(n):void 0}function lt(n){return n!==void 0?BigInt(n):void 0}function Ct(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function Ue(n){return!!n&&n.kind==S.Kind.Audio}function Ye(n){return!!n&&n.kind==S.Kind.Video}function Xe(n){return Ct(n)&&Ye(n)}function We(n){return Ct(n)&&Ue(n)}function Mn(n){return!!n&&!n.isLocal}function Su(n){return!!n&&!n.isLocal}function Ln(n){return Mn(n)&&Ye(n)}function Cu(n){return n.isLocal}function Eu(n,e){const t=[];let i=new TextEncoder().encode(n);for(;i.length>e;){let s=e;for(;s>0;){const r=i[s];if(r!==void 0&&(r&192)!==128)break;s--}t.push(i.slice(0,s)),i=i.slice(s)}return i.length>0&&t.push(i),t}function Ru(n){var e;const t=n.get("Cache-Control");if(t){const i=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(i)return parseInt(i,10)}}function wu(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const i=Pu(n,e);return t?i:Un(i,"v1")}function Pu(n,e){const t=new URL(_u(n));return e.forEach((i,s)=>{t.searchParams.set(s,i)}),Un(t,"rtc")}function Iu(n){const e=new URL(zt(n));return Un(e,"validate")}function $o(n){return n.endsWith("/")?n:"".concat(n,"/")}function Un(n,e){return n.pathname="".concat($o(n.pathname)).concat(e),n}function Qo(n){if(typeof n=="string")return wr.fromJson(JSON.parse(n),{ignoreUnknownFields:!0});if(n instanceof ArrayBuffer)return wr.fromBinary(new Uint8Array(n));throw new Error("could not decode websocket message: ".concat(typeof n))}function Du(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(n instanceof AbortSignal))return e;const t=n.reason;switch(typeof t){case"string":return t;case"object":return t instanceof Error?t.message:e;default:return"toString"in t?t.toString():e}}const Au=10,Jt="lk_e2ee",Ou={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:Au,keyringSize:16};var Ze;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(Ze||(Ze={}));var Yo;(function(n){n.KeyRatcheted="keyRatcheted"})(Yo||(Yo={}));var et;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(et||(et={}));var Xo;(function(n){n.Error="cryptorError"})(Xo||(Xo={}));function Nu(){return xu()||Fn()}function Fn(){return typeof window.RTCRtpScriptTransform<"u"}function xu(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function Mu(n){var e,t,i,s,r;if(((e=n.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=n.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((i=n.value)===null||i===void 0?void 0:i.case)!=="speaker"&&((s=n.value)===null||s===void 0?void 0:s.case)!=="transcription"&&((r=n.value)===null||r===void 0?void 0:r.case)!=="encryptedPacket")return new pr({value:n.value})}class wp extends xe.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,i,s)=>{V.debug("key ratcheted event received",{ratchetResult:t,participantId:i,keyIndex:s})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Ou),e),this.on(Ze.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){const s={key:e,participantIdentity:t,keyIndex:i};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(i??0),s),this.emit(Ze.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(Ze.RatchetRequest,e,t)}}var Zo;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(Zo||(Zo={}));class Lu extends xe.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=i=>{var s,r;const{kind:a,data:o}=i.data;switch(a){case"error":if(V.error(o.error.message),o.uuid){const l=this.decryptDataRequests.get(o.uuid);if(l?.reject){l.reject(o.error);break}const u=this.encryptDataRequests.get(o.uuid);if(u?.reject){u.reject(o.error);break}}this.emit(et.EncryptionError,o.error,o.participantIdentity);break;case"initAck":o.enabled&&this.keyProvider.getKeys().forEach(l=>{this.postKey(l)});break;case"enable":if(o.enabled&&this.keyProvider.getKeys().forEach(l=>{this.postKey(l)}),this.encryptionEnabled!==o.enabled&&o.participantIdentity===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity))this.emit(et.ParticipantEncryptionStatusChanged,o.enabled,this.room.localParticipant),this.encryptionEnabled=o.enabled;else if(o.participantIdentity){const l=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(o.participantIdentity);if(!l)throw TypeError("couldn't set encryption status, participant not found".concat(o.participantIdentity));this.emit(et.ParticipantEncryptionStatusChanged,o.enabled,l)}break;case"ratchetKey":this.keyProvider.emit(Ze.KeyRatcheted,o.ratchetResult,o.participantIdentity,o.keyIndex);break;case"decryptDataResponse":const c=this.decryptDataRequests.get(o.uuid);c?.resolve&&c.resolve(o);break;case"encryptDataResponse":const d=this.encryptDataRequests.get(o.uuid);d?.resolve&&d.resolve(o);break}},this.onWorkerError=i=>{V.error("e2ee worker encountered an error:",{error:i.error}),this.emit(et.EncryptionError,i.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!Nu())throw new Tn("tried to setup end-to-end encryption on an unsupported browser");if(V.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Dl.getLevel()}};this.worker&&(V.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){V.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?V.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(P.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(E.TrackPublished,(i,s)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==se.NONE,s.identity)),e.on(E.ConnectionStateChanged,i=>{i===J.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==se.NONE,s.identity)})})}).on(E.TrackUnsubscribed,(i,s,r)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:i.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(E.TrackSubscribed,(i,s,r)=>{this.setupE2EEReceiver(i,r.identity,s.trackInfo)}).on(E.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(I.LocalSenderCreated,(i,s)=>p(this,void 0,void 0,function*(){this.setupE2EESender(s,i)})),e.localParticipant.on(I.LocalTrackPublished,i=>{if(!Ye(i.track)||!Ht())return;const s={kind:"updateCodec",data:{trackId:i.track.mediaStreamID,codec:Wt(i.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s)}),t.on(Ze.SetKey,i=>this.postKey(i)).on(Ze.RatchetRequest,(i,s)=>this.postRatchetRequest(i,s))}encryptData(e){return p(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),i={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},s=new Ce;return s.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,s),this.worker.postMessage(i),s.promise})}handleEncryptedData(e,t,i,s){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const r=crypto.randomUUID(),a={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:i,keyIndex:s}},o=new Ce;return o.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:s}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const a={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:s}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!i?.mimeType||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?Wt(i.mimeType):void 0)}}setupE2EESender(e,t){if(!Ct(e)||!t){t||V.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,s){return p(this,void 0,void 0,function*(){if(this.worker){if(Fn()&&!Vo()){const r={kind:"decode",participantIdentity:i,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(Jt in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:i}};this.worker.postMessage(c);return}let r=e.writableStream,a=e.readableStream;if(!r||!a){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,a=c.readable}const o={kind:"decode",data:{readableStream:a,writableStream:r,trackId:t,codec:s,participantIdentity:i,isReuse:Jt in e}};this.worker.postMessage(o,[a,r])}e[Jt]=!0}})}handleSender(e,t,i){var s;if(!(Jt in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Fn()&&!Vo()){V.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{V.info("initialize encoded streams");const r=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(a,[r.readable,r.writable])}e[Jt]=!0}}}const Uu=500,Fu=15e3;class Et{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new Et),this._instance}addFailedConnectionAttempt(e){var t;const i=new URL(e),s=An(i);if(!s)return;let r=(t=this.failedConnectionAttempts.get(s))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(s,r+1),this.backOffPromises.set(s,le(Math.min(Uu*Math.pow(2,r),Fu)))}getBackOffPromise(e){const t=new URL(e),i=t&&An(t);return i&&this.backOffPromises.get(i)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),i=t&&An(t);i&&(this.failedConnectionAttempts.set(i,0),this.backOffPromises.set(i,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}Et._instance=null;const Bn="default";class ce{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new ce),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;if(((r=ce.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){V.debug("awaiting getUserMedia promise");try{t?yield ce.userMediaPromiseMap.get(t):yield Promise.all(ce.userMediaPromiseMap.values())}catch{V.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(s&&!(dt()&&i.hasDeviceInUse(t))&&(a.filter(c=>c.kind===t).length===0||a.some(c=>{const d=c.label==="",l=t?c.kind===t:!0;return d&&l}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},d=yield navigator.mediaDevices.getUserMedia(c);a=yield navigator.mediaDevices.enumerateDevices(),d.getTracks().forEach(l=>{l.stop()})}return i._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a})()})}normalizeDeviceId(e,t,i){return p(this,void 0,void 0,function*(){if(t!==Bn)return t;const s=yield this.getDevices(e),r=s.find(o=>o.deviceId===Bn);if(!r){V.warn("could not reliably determine default device");return}const a=s.find(o=>o.deviceId!==Bn&&o.groupId===(i??r.groupId));if(!a){V.warn("could not reliably determine default device");return}return a?.deviceId})}hasDeviceInUse(e){return e?ce.userMediaPromiseMap.has(e):ce.userMediaPromiseMap.size>0}}ce.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],ce.userMediaPromiseMap=new Map;var $t;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})($t||($t={}));class Bu{constructor(){this.pendingTasks=new Map,this.taskMutex=new he,this.nextTaskIndex=0}run(e){return p(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:$t.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=$t.RUNNING,yield e()}finally{t.status=$t.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return p(this,void 0,void 0,function*(){return this.run(()=>p(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class Vu{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i,s;if(!((i=t.signal)===null||i===void 0)&&i.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,(s=t.protocols)!==null&&s!==void 0?s:[]);r.binaryType="arraybuffer",this.ws=r;const a=function(){let{closeCode:o,reason:c}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return r.close(o,c)};this.opened=new ue((o,c)=>{const d=()=>{c(F.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{o({readable:new ReadableStream({start(l){r.onmessage=u=>{let{data:h}=u;return l.enqueue(h)},r.onerror=u=>l.error(u)},cancel:a}),writable:new WritableStream({write(l){r.send(l)},abort(){r.close()},close:a}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",d)},r.addEventListener("error",d)}),this.closed=new ue((o,c)=>{const d=()=>p(this,void 0,void 0,function*(){const l=new ue(h=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",f=>{h(f)},{once:!0})}),u=yield ue.race([le(250),l]);u?o(u):c(F.websocket("Encountered unspecified websocket error without a timely close event"))});r.onclose=l=>{let{code:u,reason:h}=l;o({closeCode:u,reason:h}),r.removeEventListener("error",d)},r.addEventListener("error",d)}),t.signal&&(t.signal.onabort=()=>r.close()),this.close=a}}const ju=["syncState","trickle","offer","answer","simulate","leave"];function qu(n){const e=ju.indexOf(n.case)>=0;return V.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var Y;(function(n){n[n.CONNECTING=0]="CONNECTING",n[n.CONNECTED=1]="CONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.DISCONNECTING=3]="DISCONNECTING",n[n.DISCONNECTED=4]="DISCONNECTED"})(Y||(Y={}));const Wu=250;class Vn{get currentState(){return this.state}get isDisconnected(){return this.state===Y.DISCONNECTING||this.state===Y.DISCONNECTED}get isEstablishingConnection(){return this.state===Y.CONNECTING||this.state===Y.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=Y.DISCONNECTED,this.log=V,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.log=Ve((i=t.loggerName)!==null&&i!==void 0?i:Pe.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new Bu,this.queuedRequests=[],this.closingLock=new he,this.connectionLock=new he,this.state=Y.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,i,s){return p(this,arguments,void 0,function(r,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){return d.state=Y.CONNECTING,d.options=o,yield d.connect(r,a,o,c,l)})()})}reconnect(e,t,i,s){return p(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=Y.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:s}),void 0,this.useV0SignalPath)})}connect(e,t,i,s){return p(this,arguments,void 0,function(r,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){const u=yield d.connectionLock.lock();d.connectOptions=o,d.useV0SignalPath=l;const h=bu(),f=l?Ku(a,h,o):Hu(a,h,o),b=wu(r,f,l).toString(),v=Iu(b).toString();return new Promise((R,T)=>p(d,void 0,void 0,function*(){var A,x;try{let y=!1;const _=O=>p(this,void 0,void 0,function*(){if(y)return;y=!0;const L=O instanceof Event?O.currentTarget:O,W=Du(L,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(W)).catch(Z=>{this.log.error(Z),this.close()}):this.close(),C(),T(F.cancelled(W))});c?.addEventListener("abort",_);const C=()=>{clearTimeout(N),c?.removeEventListener("abort",_)},N=setTimeout(()=>{_(F.timeout("room connection has timed out (signal)"))},o.websocketTimeout),U=(O,L)=>{this.handleSignalConnected(O,N,L)},M=new URL(b);M.searchParams.has("access_token")&&M.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(M),Object.assign({reconnect:o.reconnect,reconnectReason:o.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new Vu(b);try{this.ws.closed.then(ge=>{var st;this.isEstablishingConnection&&T(F.internal("Websocket got closed during a (re)connection attempt: ".concat(ge.reason))),ge.closeCode!==1e3&&(this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:ge.reason,code:ge.closeCode,wasClean:ge.closeCode===1e3,state:this.state})),this.state===Y.CONNECTED&&this.handleOnClose((st=ge.reason)!==null&&st!==void 0?st:"Unexpected WS error"))}).catch(ge=>{this.isEstablishingConnection&&T(F.internal("Websocket error during a (re)connection attempt: ".concat(ge)))});const O=yield this.ws.opened.catch(ge=>p(this,void 0,void 0,function*(){if(this.state!==Y.CONNECTED){this.state=Y.DISCONNECTED,clearTimeout(N);const st=yield this.handleConnectionError(ge,v);T(st);return}this.handleWSError(ge),T(ge)}));if(clearTimeout(N),!O)return;const L=O.readable.getReader();this.streamWriter=O.writable.getWriter();const W=yield L.read();if(L.releaseLock(),!W.value)throw F.internal("no message received as first message");const Z=Qo(W.value),Te=this.validateFirstMessage(Z,(A=o.reconnect)!==null&&A!==void 0?A:!1);if(!Te.isValid){T(Te.error);return}((x=Z.message)===null||x===void 0?void 0:x.case)==="join"&&(this.pingTimeoutDuration=Z.message.value.pingTimeout,this.pingIntervalDuration=Z.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})));const ut=Te.shouldProcessFirstMessage?Z:void 0;U(O,ut),R(Te.response)}catch(O){T(O)}finally{C()}}finally{u()}}))})()})}startReadingLoop(e,t){return p(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield le(this.signalLatency));const{done:i,value:s}=yield e.read();if(i)break;const r=Qo(s);this.handleSignalResponse(r)}})}close(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){if([Y.DISCONNECTING||Y.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const s=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Y.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:i});const r=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([r,le(Wu)])}}catch(r){e.log.debug("websocket error while closing",Object.assign(Object.assign({},e.logContext),{error:r}))}finally{t&&(e.state=Y.DISCONNECTED),s()}})()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Rt(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Rt(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new pi({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new mi({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const o=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new sn({requestId:o,metadata:i,name:s,attributes:a})}),o})()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new Nr({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Lr({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:X.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Br({timestamp:X.parse(Date.now()),rtt:X.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new nn({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new gi({reason:ke.CLIENT_INITIATED,action:vt.DISCONNECT})})}sendRequest(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!s&&!qu(t)&&i.state===Y.RECONNECTING){i.queuedRequests.push(()=>p(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield i.requestQueue.flush()),i.signalLatency&&(yield le(i.signalLatency)),i.isDisconnected){i.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!i.streamWriter){i.log.error("cannot send signal request before connected, type: ".concat(t?.case),i.logContext);return}const a=new Qd({message:t});try{i.useJSON?yield i.streamWriter.write(a.toJsonString()):yield i.streamWriter.write(a.toBinary())}catch(o){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:o}))}})()})}handleSignalResponse(e){var t,i;const s=e.message;if(s==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(s.case==="answer"){const a=ea(s.value);this.onAnswer&&this.onAnswer(a,s.value.id,s.value.midToTrackId)}else if(s.case==="offer"){const a=ea(s.value);this.onOffer&&this.onOffer(a,s.value.id,s.value.midToTrackId)}else if(s.case==="trickle"){const a=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(a,s.value.target)}else s.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=s.value.participants)!==null&&t!==void 0?t:[]):s.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.value):s.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=s.value.speakers)!==null&&i!==void 0?i:[]):s.case==="leave"?this.onLeave&&this.onLeave(s.value):s.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.value.sid,s.value.muted):s.case==="roomUpdate"?this.onRoomUpdate&&s.value.room&&this.onRoomUpdate(s.value.room):s.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(s.value):s.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.value):s.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.value):s.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.value):s.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(s.value):s.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.value):s.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(s.value):s.case==="pong"||(s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):s.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(s.value):s.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(s.value.trackSid):s.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(s.value.token),this.onRoomMoved&&this.onRoomMoved(s.value)):s.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(s.value):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:s.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return p(this,void 0,void 0,function*(){if(this.state===Y.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=de.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&de.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=de.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&de.clearInterval(this.pingInterval)}handleSignalConnected(e,t,i){this.state=Y.CONNECTED,clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),i)}validateFirstMessage(e,t){var i,s,r,a,o;return((i=e.message)===null||i===void 0?void 0:i.case)==="join"?{isValid:!0,response:e.message.value}:this.state===Y.RECONNECTING&&((s=e.message)===null||s===void 0?void 0:s.case)!=="leave"?((r=e.message)===null||r===void 0?void 0:r.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((a=e.message)===null||a===void 0?void 0:a.case)==="leave"?{isValid:!1,error:F.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:F.internal("Unexpected first message")}:{isValid:!1,error:F.internal("did not receive join response, got ".concat((o=e.message)===null||o===void 0?void 0:o.case," instead"))}}handleConnectionError(e,t){return p(this,void 0,void 0,function*(){try{const i=yield fetch(t);switch(i.status){case 404:return F.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const s=yield i.text();return F.notAllowed(s,i.status);default:break}return e instanceof F?e:F.internal("Encountered unknown websocket error during connection: ".concat(e),{status:i.status,statusText:i.statusText})}catch(i){return i instanceof F?i:F.serverUnreachable(i instanceof Error?i.message:"server was not reachable")}})}}function ea(n){const e={type:"offer",sdp:n.sdp};switch(n.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=n.type;break}return e}function Rt(n,e){return new Je({sdp:n.sdp,type:n.type,id:e})}function Ku(n,e,t){var i;const s=new URLSearchParams;return s.set("access_token",n),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",Me()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),t.adaptiveStream&&s.set("adaptive_stream","1"),t.reconnectReason&&s.set("reconnect_reason",t.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&s.set("network",navigator.connection.type),s}function Hu(n,e,t){const i=new URLSearchParams;i.set("access_token",n);const s=new Sl({clientInfo:e,connectionSettings:new Vr({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);const r=new Cl({joinRequest:s.toBinary()});return i.set("join_request",btoa(new TextDecoder("utf-8").decode(r.toBinary()))),i}class ta{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Gu{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();const s=i+this.ttl;return this._map.set(e,{value:t,expiresAt:s}),this}get(e){const t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){const t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],i=this.asValueMap();for(const[s,r]of i.entries())t.push(e(r,s,i));return t}asValueMap(){const e=new Map;for(const[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var De={},jn={},qn={exports:{}},ia;function Wn(){if(ia)return qn.exports;ia=1;var n=qn.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(n).forEach(function(e){var t=n[e];t.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),qn.exports}var na;function zu(){return na||(na=1,(function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,d,l){if(l&&!d)c[l]=e(o[1]);else for(var u=0;u<d.length;u+=1)o[u+1]!=null&&(c[d[u]]=e(o[u+1]))},i=function(o,c,d){var l=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:l&&!c[o.name]&&(c[o.name]={});var u=o.push?{}:l?c[o.name]:c;t(d.match(o.reg),u,o.names,o.name),o.push&&c[o.push].push(u)},s=Wn(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var c={},d=[],l=c;return o.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var h=u[0],f=u.slice(2);h==="m"&&(d.push({rtp:[],fmtp:[]}),l=d[d.length-1]);for(var b=0;b<(s[h]||[]).length;b+=1){var v=s[h][b];if(v.reg.test(f))return i(v,l,f)}}),c.media=d,c};var a=function(o,c){var d=c.split(/=(.+)/,2);return d.length===2?o[d[0]]=e(d[1]):d.length===1&&c.length>1&&(o[d[0]]=void 0),o};n.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(o){return o.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(o){for(var c=[],d=o.split(" ").map(e),l=0;l<d.length;l+=3)c.push({component:d[l],ip:d[l+1],port:d[l+2]});return c},n.parseImageAttributes=function(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},n.parseSimulcastStreamList=function(o){return o.split(";").map(function(c){return c.split(",").map(function(d){var l,u=!1;return d[0]!=="~"?l=e(d):(l=e(d.substring(1,d.length)),u=!0),{scid:l,paused:u}})})}})(jn)),jn}var Kn,sa;function Ju(){if(sa)return Kn;sa=1;var n=Wn(),e=/%[sdv%]/g,t=function(a){var o=1,c=arguments,d=c.length;return a.replace(e,function(l){if(o>=d)return l;var u=c[o];switch(o+=1,l){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},i=function(a,o,c){var d=o.format instanceof Function?o.format(o.push?c:c[o.name]):o.format,l=[a+"="+d];if(o.names)for(var u=0;u<o.names.length;u+=1){var h=o.names[u];o.name?l.push(c[o.name][h]):l.push(c[o.names[u]])}else l.push(c[o.name]);return t.apply(null,l)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return Kn=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var c=o.outerOrder||s,d=o.innerOrder||r,l=[];return c.forEach(function(u){n[u].forEach(function(h){h.name in a&&a[h.name]!=null?l.push(i(u,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(f){l.push(i(u,h,f))})})}),a.media.forEach(function(u){l.push(i("m",n.m[0],u)),d.forEach(function(h){n[h].forEach(function(f){f.name in u&&u[f.name]!=null?l.push(i(h,f,u)):f.push in u&&u[f.push]!=null&&u[f.push].forEach(function(b){l.push(i(h,f,b))})})})}),l.join(`\r
146
146
  `)+`\r
147
- `},jn}var Yo;function Pu(){if(Yo)return De;Yo=1;var n=Ru(),e=wu(),t=Vn();return De.grammar=t,De.write=e,De.parse=n.parse,De.parseParams=n.parseParams,De.parseFmtpConfig=n.parseFmtpConfig,De.parsePayloads=n.parsePayloads,De.parseRemoteCandidates=n.parseRemoteCandidates,De.parseImageAttributes=n.parseImageAttributes,De.parseSimulcastStreamList=n.parseSimulcastStreamList,De}var tt=Pu();function qn(n,e,t){var i,s,r;e===void 0&&(e=50),t===void 0&&(t={});var a=(i=t.isImmediate)!=null&&i,o=(s=t.callback)!=null&&s,c=t.maxWait,d=Date.now(),l=[];function u(){if(c!==void 0){var f=Date.now()-d;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),b=this;return new Promise(function(v,R){var _=a&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,d=Date.now(),!a){var x=n.apply(b,f);o&&o(x),l.forEach(function(y){return(0,y.resolve)(x)}),l=[]}},u()),_){var A=n.apply(b,f);return o&&o(A),v(A)}l.push({resolve:v,reject:R})})};return h.cancel=function(f){r!==void 0&&clearTimeout(r),l.forEach(function(b){return(0,b.reject)(f)}),l=[]},h}const Iu=.7,Du=20,wt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Xo extends xe.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=V,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=qn(s=>p(this,void 0,void 0,function*(){this.emit(wt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),Du),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=Ve((i=t.loggerName)!==null&&i!==void 0?i:Pe.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new he}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return p(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return p(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let{stereoMids:r,nackMids:a}=Au(e);this.remoteStereoMids=r,this.remoteNackMids=a}else if(e.type==="answer"){const r=tt.parse((i=e.sdp)!==null&&i!==void 0?i:"");r.media.forEach(a=>{const o=Wn(a.mid);a.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||o!=c.transceiver.mid)return!1;let d=0;if(a.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(d=u.payload,!0):!1),d===0)return!0;let l=!1;for(const u of a.fmtp)if(u.payload===d){u.config=u.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),l=!0;break}return l||c.maxbr>0&&a.fmtp.push({payload:d,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),s=tt.write(r)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(wt.NegotiationComplete),e.sdp&&tt.parse(e.sdp).media.forEach(a=>{a.type==="video"&&this.emit(wt.RTPVideoPayloadTypes,a.rtp)})),!0})}createAndSendOffer(e){return p(this,void 0,void 0,function*(){var t;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const o=this._pc.remoteDescription;if(e?.iceRestart&&o)yield this._pc.setRemoteDescription(o);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const s=this.latestOfferId+1;this.latestOfferId=s;const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const a=tt.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(a.media.forEach(o=>{ea(o),o.type==="audio"?Zo(o,["all"],[]):o.type==="video"&&this.trackBitrates.some(c=>{if(!o.msid||!c.cid||!o.msid.includes(c.cid))return!1;let d=0;if(o.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(d=u.payload,!0):!1),d===0||(Ie(c.codec)&&!dt()&&this.ensureVideoDDExtensionForSVC(o,a),!Ie(c.codec)))return!0;const l=Math.round(c.maxbr*Iu);for(const u of o.fmtp)if(u.payload===d){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),this.latestOfferId>s){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:s}));return}yield this.setMungedSDP(r,tt.write(a)),this.onOffer(r,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=tt.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(s=>{ea(s),s.type==="audio"&&Zo(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,tt.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new re("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new re("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return p(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,s=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),i.set(o.id,o);break;case"remote-candidate":s.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return s.get(a)})}setMungedSDP(e,t,i){return p(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const a={error:r,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new yt(r)}})}ensureVideoDDExtensionForSVC(e,t){var i,s;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===Ao))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var c;o.type==="video"&&((c=o.ext)===null||c===void 0||c.forEach(d=>{d.value>a&&(a=d.value)}))}),this.ddExtID=a+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:Ao})}}}function Zo(n,e,t){const i=Wn(n.mid);let s=0;n.rtp.some(r=>r.codec==="opus"?(s=r.payload,!0):!1),s>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(i)&&!n.rtcpFb.some(r=>r.payload===s&&r.type==="nack")&&n.rtcpFb.push({payload:s,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&n.fmtp.some(r=>r.payload===s?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function Au(n){var e;const t=[],i=[],s=tt.parse((e=n.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(a=>{var o;const c=Wn(a.mid);a.type==="audio"&&(a.rtp.some(d=>d.codec==="opus"?(r=d.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(d=>d.payload===r&&d.type==="nack")&&i.push(c),a.fmtp.some(d=>d.payload===r?(d.config.includes("sprop-stereo=1")&&t.push(c),!0):!1))}),{stereoMids:t,nackMids:i}}function ea(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}function Wn(n){return typeof n=="number"?n.toFixed(0):n}const Kn="vp8",Ou={audioPreset:yn.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:_n.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Kn,backupCodec:!0,preConnectBuffer:!1},ta={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},ia={deviceId:{ideal:"default"},resolution:jt.h720.resolution},Nu={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new ul,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Gn={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var te;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(te||(te={}));class xu{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,i){var s;this.peerConnectionTimeout=Gn.peerConnectionTimeout,this.log=V,this.updateState=()=>{var r,a;const o=this.state,c=this.requiredTransports.map(d=>d.getConnectionState());c.every(d=>d==="connected")?this.state=te.CONNECTED:c.some(d=>d==="failed")?this.state=te.FAILED:c.some(d=>d==="connecting")?this.state=te.CONNECTING:c.every(d=>d==="closed")?this.state=te.CLOSED:c.some(d=>d==="closed")?this.state=te.CLOSING:c.every(d=>d==="new")&&(this.state=te.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(te[o]," to ").concat(te[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),(a=this.subscriber)===null||a===void 0?void 0:a.getConnectionState()))},this.log=Ve((s=i.loggerName)!==null&&s!==void 0?s:Pe.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=t!=="subscriber-primary",this.isSubscriberConnectionRequired=t==="subscriber-primary",this.publisher=new Xo(e,i),this._mode=t,t!=="publisher-only"&&(this.subscriber=new Xo(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,we.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,r)},this.subscriber.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,we.PUBLISHER)},this.publisher.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)},this.publisher.onOffer=(r,a)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,r,a)},this.state=te.NEW,this.connectionLock=new he,this.remoteOfferLock=new he}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return p(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(s){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:s}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return p(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return p(this,void 0,void 0,function*(){var i;t===we.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return p(this,void 0,void 0,function*(){var i,s,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(i=this.subscriber)===null||i===void 0?void 0:i.getSignallingState().toString()}));const a=yield this.remoteOfferLock.lock();try{return(yield(s=this.subscriber)===null||s===void 0?void 0:s.setRemoteDescription(e,t))?yield(r=this.subscriber)===null||r===void 0?void 0:r.createAndSetAnswer():void 0}finally{a()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),(i=this.subscriber)===null||i===void 0||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return p(this,void 0,void 0,function*(){var i;const s=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return p(this,void 0,void 0,function*(){return new ue((t,i)=>p(this,void 0,void 0,function*(){const s=setTimeout(()=>{i(new yt("negotiation timed out"))},this.peerConnectionTimeout),r=()=>{clearTimeout(s),i(new yt("negotiation aborted"))};e.signal.addEventListener("abort",r),this.publisher.once(wt.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(wt.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(s),a instanceof Error?i(a):i(new Error(String(a)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const i=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(s=>s.receiver===e);return i?.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===we.PUBLISHER?this.publisher.getConnectedAddress():e===we.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((c,d)=>p(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),de.clearTimeout(u),d(F.cancelled("room connection has been cancelled"))};s?.signal.aborted&&l(),s?.signal.addEventListener("abort",l);const u=de.setTimeout(()=>{s?.signal.removeEventListener("abort",l),d(F.internal("could not establish pc connection"))},a);for(;this.state!==te.CONNECTED;)if(yield le(50),s?.signal.aborted){d(F.cancelled("room connection has been cancelled"));return}de.clearTimeout(u),s?.signal.removeEventListener("abort",l),c()}))})()})}}const na=5e3,Mu=3e4;class z{static fetchRegionSettings(e,t,i){return p(this,void 0,void 0,function*(){const s=yield z.fetchLock.lock();try{const r=yield fetch("".concat(Lu(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(r.ok){const a=ru(r.headers),o=a?a*1e3:na;return{regionSettings:yield r.json(),updatedAtInMs:Date.now(),maxAgeInMs:o}}else throw r.status===401?F.notAllowed("Could not fetch region settings: ".concat(r.statusText),r.status):F.internal("Could not fetch region settings: ".concat(r.statusText))}catch(r){throw r instanceof F?r:i?.aborted?F.cancelled("Region fetching was aborted"):F.serverUnreachable("Could not fetch region settings, ".concat(r instanceof Error?"".concat(r.name,": ").concat(r.message):r))}finally{s()}})}static scheduleRefetch(e,t,i){return p(this,void 0,void 0,function*(){const s=z.settingsTimeouts.get(e.hostname);clearTimeout(s),z.settingsTimeouts.set(e.hostname,setTimeout(()=>p(this,void 0,void 0,function*(){try{const r=yield z.fetchRegionSettings(e,t);z.updateCachedRegionSettings(e,t,r)}catch(r){if(r instanceof F&&r.reason===Q.NotAllowed){V.debug("token is not valid, cancelling auto region refresh");return}V.debug("auto refetching of region settings failed",{error:r}),z.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){z.cache.set(e.hostname,i),z.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=z.settingsTimeouts.get(e);t&&(clearTimeout(t),z.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=z.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=z.connectionTrackers.get(e);i&&i.connectionCount===0&&(V.debug("stopping region refetch after disconnect delay",{hostname:e}),z.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},Mu))}static cancelCleanup(e){const t=z.connectionTrackers.get(e);t?.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=z.connectionTrackers.get(e);t||(t={connectionCount:0},z.connectionTrackers.set(e,t)),t.connectionCount++,z.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=z.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&z.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return St(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return p(this,void 0,void 0,function*(){return z.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return p(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=z.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),z.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(s=>!this.attemptedRegions.find(r=>r.url===s.url));if(i.length>0){const s=i[0];return this.attemptedRegions.push(s),V.debug("next region: ".concat(s.region)),s.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){z.updateCachedRegionSettings(this.serverUrl,this.token,e)}}z.cache=new Map,z.settingsTimeouts=new Map,z.connectionTrackers=new Map,z.fetchLock=new he;function Lu(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class ie extends Error{constructor(e,t,i){super(t),this.code=e,this.message=ra(t,ie.MAX_MESSAGE_BYTES),this.data=i?ra(i,ie.MAX_DATA_BYTES):void 0}static fromProto(e){return new ie(e.code,e.message,e.data)}toProto(){return new cr({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new ie(ie.ErrorCode[e],ie.ErrorMessage[e],t)}}ie.MAX_MESSAGE_BYTES=256,ie.MAX_DATA_BYTES=15360,ie.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},ie.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const sa=15360;function Hn(n){return new TextEncoder().encode(n).length}function ra(n,e){if(Hn(n)<=e)return n;let t=0,i=n.length;const s=new TextEncoder;for(;t<i;){const r=Math.floor((t+i+1)/2);s.encode(n.slice(0,r)).length<=e?t=r:i=r-1}return n.slice(0,t)}const zn=2e3;function Ri(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}const Jn=typeof MediaRecorder<"u";class Uu{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const Fu=Jn?MediaRecorder:Uu;class Bu extends Fu{constructor(e,t){if(!Jn)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let i,s;const r=()=>s===void 0,a=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),s?.close(),s=void 0},o=c=>{s?.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),s=void 0};this.byteStream=new ReadableStream({start:c=>{s=c,i=d=>p(this,void 0,void 0,function*(){let l;if(d.data.arrayBuffer){const u=yield d.data.arrayBuffer();l=new Uint8Array(u)}else if(d.data.byteArray)l=d.data.byteArray;else throw new Error("no data available!");r()||c.enqueue(l)}),this.addEventListener("dataavailable",i)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}}function Vu(){return Jn}const ju=1e3,qu=1e4;class oa extends S{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=qn(()=>p(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>p(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(w.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new he,this.pauseUpstreamLock=new he,this.trackChangeLock=new he,this.trackChangeLock.lock().then(a=>p(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{a()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==S.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return p(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{kt(this._mediaStreamTrack,r)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let s;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(_t(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{_t(s??e,r)}))})}waitForDimensions(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ju;return(function*(){var i;if(e.kind===S.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=be())===null||i===void 0?void 0:i.os)==="iOS"&&(yield le(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield le(50)}throw new qe("unable to get track dimensions after timeout")})()})}setDeviceId(e){return p(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Qe(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Qe(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===S.Source.ScreenShare)return;const{deviceId:i,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===S.Kind.Audio?"audioinput":"videoinput";return t?ce.getInstance().normalizeDeviceId(r,i,s):i})()})}mute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return p(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new qe("unable to replace an unpublished track");let s,r;return typeof t=="boolean"?s=t:t!==void 0&&(s=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=s??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return p(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:s}=e,r=hl(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===S.Kind.Video?a.video=i||s?{deviceId:i,facingMode:s}:!0:a.audio=i?Object.assign({deviceId:i},r):!0,this.attachedElements.forEach(d=>{kt(this.mediaStreamTrack,d)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===S.Kind.Video&&(yield c.applyConstraints(r)),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(w.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?w.Muted:w.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),No()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(w.UpstreamPaused,this);const i=be();if(i?.name==="Safari"&&Le(i.version,"12.0")<0)throw new bn("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(w.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return p(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;const a=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext};if(yield t.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(_t(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(d=>{d instanceof DOMException&&d.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:d})),setTimeout(()=>{o.play().catch(l=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:l}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:d}))}),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const d of i.attachedElements)d!==i.processorElement&&s&&(kt(i._mediaStreamTrack,d),_t(i.processor.processedTrack,d));yield(r=i.sender)===null||r===void 0?void 0:r.replaceTrack(i.processor.processedTrack)}i.emit(w.TrackProcessorUpdate,i.processor)}finally{a()}})()})}getProcessor(){return this.processor}stopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}})()})}internalStopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,s;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((s=e.processorElement)===null||s===void 0||s.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(w.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!Vu()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new Bu(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},qu)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class wi extends oa{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,S.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=Ri(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(w.AudioTrackFeatureUpdate,this,ae.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(w.AudioTrackFeatureUpdate,this,ae.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===S.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Qe(this._constraints.deviceId);return this.source===S.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return p(this,void 0,void 0,function*(){let t;if(e){const i=Sn({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return p(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){ye()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},zn)))}setProcessor(e){return p(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!Me()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(w.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(s=>{s.type==="outbound-rtp"&&(i={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),i})}checkForSilence(){return p(this,void 0,void 0,function*(){const e=yield wo(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(w.AudioSilenceDetected)),e})}}function Wu(n,e,t){switch(n.kind){case"audio":return new wi(n,e,!1,void 0,t);case"video":return new Pi(n,e,!1,t);default:throw new qe("unsupported track type: ".concat(n.kind))}}const Ku=Object.values(jt),Gu=Object.values(Tn),Hu=Object.values(_n),zu=[jt.h180,jt.h360],Ju=[Tn.h180,Tn.h360],$u=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,s;return new $(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,n.encoding.priority)}),$n=["q","h","f"];function Qn(n,e,t,i){var s,r;let a=i?.videoEncoding;n&&(a=i?.screenShareEncoding);const o=i?.simulcast,c=i?.scalabilityMode,d=i?.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=Yu(n,e,t,d),V.debug("using video encoding",a));const l=a.maxFramerate,u=new $(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&Ie(d)){const b=new da(c),v=[];if(b.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const R=be();if(Kt()||Me()||R?.name==="Chrome"&&Le(R?.version,"113")<0){const _=b.suffix=="h"?2:3,A=zl(R);for(let x=0;x<b.spatial;x+=1)v.push({rid:$n[2-x],maxBitrate:a.maxBitrate/Math.pow(_,x),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:A?Math.pow(2,x):void 0});v[0].scalabilityMode=c}else v.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(v[0].priority=u.encoding.priority,v[0].networkPriority=u.encoding.priority),V.debug("using svc encoding",{encodings:v}),v}if(!o)return[a];let h=[];n?h=(s=ca(i?.screenShareSimulcastLayers))!==null&&s!==void 0?s:aa(n,u):h=(r=ca(i?.videoSimulcastLayers))!==null&&r!==void 0?r:aa(n,u);let f;if(h.length>0){const b=h[0];h.length>1&&([,f]=h);const v=Math.max(e,t);if(v>=960&&f)return Yn(e,t,[b,f,u],l);if(v>=480)return Yn(e,t,[b,u],l)}return Yn(e,t,[u])}function Qu(n,e,t){var i,s,r,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&V.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),c=(i=o.width)!==null&&i!==void 0?i:(s=n.dimensions)===null||s===void 0?void 0:s.width,d=(r=o.height)!==null&&r!==void 0?r:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===S.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Qn(n.source===S.Source.ScreenShare,c,d,t)}function Yu(n,e,t,i){const s=Xu(n,e,t);let{encoding:r}=s[0];const a=Math.max(e,t);for(let o=0;o<s.length;o+=1){const c=s[o];if(r=c.encoding,c.width>=a)break}if(i)switch(i){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function Xu(n,e,t){if(n)return Hu;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?Ku:Gu}function aa(n,e){if(n)return $u(e);const{width:t,height:i}=e,s=t>i?t/i:i/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?zu:Ju}function Yn(n,e,t,i){const s=[];if(t.forEach((r,a)=>{if(a>=$n.length)return;const o=Math.min(n,e),d={rid:$n[a],scaleResolutionDownBy:Math.max(1,o/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},l=i&&r.encoding.maxFramerate?Math.min(i,r.encoding.maxFramerate):r.encoding.maxFramerate;l&&(d.maxFramerate=l);const u=ct()||a===0;r.encoding.priority&&u&&(d.priority=r.encoding.priority,d.networkPriority=r.encoding.priority),s.push(d)}),Me()&&Mo()==="ios"){let r;s.forEach(o=>{r?o.maxFramerate&&o.maxFramerate>r&&(r=o.maxFramerate):r=o.maxFramerate});let a=!0;s.forEach(o=>{var c;o.maxFramerate!=r&&(a&&(a=!1,V.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),V.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),o.maxFramerate=r)})}return s}function ca(n){if(n)return n.sort((e,t)=>{const{encoding:i}=e,{encoding:s}=t;return i.maxBitrate>s.maxBitrate?1:i.maxBitrate<s.maxBitrate?-1:i.maxBitrate===s.maxBitrate&&i.maxFramerate&&s.maxFramerate?i.maxFramerate>s.maxFramerate?1:-1:0})}class da{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function Zu(n){return n.source===S.Source.ScreenShare||n.constraints.height&&Qe(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const eh=5e3;class Pi extends oa{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,S.Kind.Video,t,i,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const a=new Map(r.map(c=>[c.rid,c])),o=r.some(c=>c.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(w.CpuConstrained)),this.prevStats){let c=0;a.forEach((d,l)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);c+=Ri(d,h)}),this._currentBitrate=c}this.prevStats=a}),this.senderLock=new he}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!ye())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},zn))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return p(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=je(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0)r=d.value,o=!1,yield(a=r.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(l){i={error:l}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return p(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=je(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0){r=d.value,o=!1;const l=r;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){i={error:l}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===S.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===S.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(s=>{var r;if(s.type==="outbound-rtp"){const a={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,framesPerSecond:s.framesPerSecond,framesSent:s.framesSent,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationDurations:s.qualityLimitationDurations,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,targetBitrate:s.targetBitrate,timestamp:s.timestamp},o=i.get(s.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((s,r)=>{var a,o;return((a=r.frameWidth)!==null&&a!==void 0?a:0)-((o=s.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=Te.LOW;i<=Te.HIGH;i+=1)t.push(new tn({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Ie(this.codec),t)}restartTrack(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a;let o;if(e){const u=Sn({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var c=!0,d=je(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;c=!0){r=l.value,c=!1;const u=r;u.sender&&((a=u.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){i={error:u}}finally{try{!c&&!t&&(s=d.return)&&(yield s.call(d))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return p(this,arguments,void 0,function(i){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var a,o,c,d,l,u;if(yield t.setProcessor.call(s,i,r),!((l=s.processor)===null||l===void 0)&&l.processedTrack)try{for(var h=!0,f=je(s.simulcastCodecs.values()),b;b=yield f.next(),a=b.done,!a;h=!0)d=b.value,h=!1,yield(u=d.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(v){o={error:v}}finally{try{!h&&!a&&(c=f.return)&&(yield c.call(f))}finally{if(o)throw o.error}}})()})}setDegradationPreference(e){return p(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},eh))}setPublishingCodecs(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a,o,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(Ie(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=je(e);s=yield i.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const l=c;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(Ie(l.codec),l.qualities);else{const u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of l.qualities)if(h.enabled){d.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield la(u.sender,u.encodings,l.qualities,this.senderLock,Ie(l.codec),this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!r&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return d})}setPublishingLayers(e,t){return p(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield la(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return p(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const t=this.sender.getParameters();t.encodings=t.encodings.map((i,s)=>{var r;return Object.assign(Object.assign({},i),{active:s===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((r=this.mediaStreamTrack.getSettings().height)!==null&&r!==void 0?r:360)/360)),scalabilityMode:s===0&&Ie(this.codec)?"L1T3":void 0,maxFramerate:s===0?15:0,maxBitrate:s===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),No()&&this.isInBackground&&this.source===S.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function la(n,e,t,i,s,r,a){return p(this,void 0,void 0,function*(){const o=yield i.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:n,qualities:t,senderEncodings:e}));try{const c=n.getParameters(),{encodings:d}=c;if(!d)return;if(d.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:d,senderEncodings:e}));return}let l=!1;!1&&d[0].scalabilityMode||(s&&t.some(f=>f.enabled)&&t.forEach(f=>f.enabled=!0),d.forEach((h,f)=>{var b;let v=(b=h.rid)!==null&&b!==void 0?b:"";v===""&&(v="q");const R=ua(v),_=t.find(A=>A.quality===R);_&&h.active!==_.enabled&&(l=!0,h.active=_.enabled,r.debug("setting layer ".concat(_.quality," to ").concat(h.active?"enabled":"disabled"),a),ct()&&(_.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),l&&(c.encodings=d,r.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:c.encodings})),yield n.setParameters(c))}finally{o()}})}function ua(n){switch(n){case"f":return Te.HIGH;case"h":return Te.MEDIUM;case"q":return Te.LOW;default:return Te.HIGH}}function ha(n,e,t,i){if(!t)return[new ze({quality:Te.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const s=t[0].scalabilityMode,r=new da(s),a=[],o=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let d=0;d<r.spatial;d+=1)a.push(new ze({quality:Math.min(Te.HIGH,r.spatial-1)-d,width:Math.ceil(n/Math.pow(o,d)),height:Math.ceil(e/Math.pow(o,d)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,d)):0,ssrc:0}));return a}return t.map(s=>{var r,a,o;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let d=ua((a=s.rid)!==null&&a!==void 0?a:"");return new ze({quality:d,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(o=s.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const pa="_lossy",ma="_reliable",th=2*1e3,Xn="leave-reconnect",ih=3e4,nh=8*1024,sh=256*1024;var Ee;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(Ee||(Ee={}));class rh extends xe.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Gn.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Ee.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=V,this.reliableDataSequence=1,this.reliableMessageBuffer=new zo,this.reliableReceivedState=new Eu(ih),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>p(this,[i],void 0,function(s){var r=this;let{channel:a}=s;return(function*(){if(a){if(a.label===ma)r.reliableDCSub=a;else if(a.label===pa)r.lossyDCSub=a;else return;r.log.debug("on data channel ".concat(a.id,", ").concat(a.label),r.logContext),a.onmessage=r.handleDataMessage}})()}),this.handleDataMessage=i=>p(this,void 0,void 0,function*(){var s,r,a,o,c;const d=yield this.dataProcessLock.lock();try{let l;if(i.data instanceof ArrayBuffer)l=i.data;else if(i.data instanceof Blob)l=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const u=pe.fromBinary(new Uint8Array(l));if(u.sequence>0&&u.participantSid!==""){const h=this.reliableReceivedState.get(u.participantSid);if(h&&u.sequence<=h)return;this.reliableReceivedState.set(u.participantSid,u.sequence)}if(((s=u.value)===null||s===void 0?void 0:s.case)==="speaker")this.emit(P.ActiveSpeakersUpdate,u.value.value.speakers);else if(((r=u.value)===null||r===void 0?void 0:r.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const h=yield(a=this.e2eeManager)===null||a===void 0?void 0:a.handleEncryptedData(u.value.value.encryptedValue,u.value.value.iv,u.participantIdentity,u.value.value.keyIndex),f=rr.fromBinary(h.payload),b=new pe({value:f.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((o=b.value)===null||o===void 0?void 0:o.case)==="user"&&fa(b,b.value.value),this.emit(P.DataPacketReceived,b,u.value.value.encryptionType)}else((c=u.value)===null||c===void 0?void 0:c.case)==="user"&&fa(u,u.value.value),this.emit(P.DataPacketReceived,u,se.NONE)}finally{d()}}),this.handleDataError=i=>{const r=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:a}=i.error;this.log.error("DataChannel error on ".concat(r,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:a}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const r=i.currentTarget.maxRetransmits===0?j.LOSSY:j.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(i,s)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(P.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){r(a);return}i===Xn&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=de.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,s)=>{this.pcState===Ee.Connected&&i();const r=()=>{this.off(P.Disconnected,a),i()},a=()=>{this.off(P.Restarted,r),s()};this.once(P.Restarted,r),this.once(P.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{if(i===j.RELIABLE){const r=this.dataChannelForKind(i);r&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount)}const s=this.isBufferStatusLow(i);typeof s<"u"&&s!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,s),this.emit(P.DCBufferStatusChanged,s,i))},this.isBufferStatusLow=i=>{const s=this.dataChannelForKind(i);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>p(this,void 0,void 0,function*(){!this.url||!(yield fetch(Ht(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===Y.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Y.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(rt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>p(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Ht(this.url),{method:"HEAD"}),le(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=Ve((t=e.loggerName)!==null&&t!==void 0?t:Pe.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Un(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new he,this.dataProcessLock=new he,this.dcBufferStatus=new Map([[j.LOSSY,!0],[j.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(P.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(P.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(P.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(P.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(P.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(P.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(P.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(P.SignalRequestResponse,i)}get logContext(){var e,t,i,s,r,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(s=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||s===void 0?void 0:s.sid,participant:(a=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||a===void 0?void 0:a.identity,pID:this.participantSid}}join(e,t,i,s){return p(this,arguments,void 0,function(r,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){d.url=r,d.token=a,d.signalOpts=o,d.maxJoinAttempts=o.maxRetries;try{d.joinAttempts+=1,d.setupSignalClientCallbacks();const u=yield d.client.join(r,a,o,c,l);return d._isClosed=!1,d.latestJoinResponse=u,d.subscriberPrimary=u.subscriberPrimary,d.pcManager||(yield d.configure(u,!l)),(!d.subscriberPrimary||u.fastPublish)&&d.negotiate().catch(h=>{V.error(h,d.logContext)}),d.registerOnLineListener(),d.clientConfiguration=u.clientConfiguration,d.emit(P.SignalConnected,u),u}catch(u){if(u instanceof F){if(u.reason===Q.ServerUnreachable){if(d.log.warn("Couldn't connect to server, attempt ".concat(d.joinAttempts," of ").concat(d.maxJoinAttempts),d.logContext),d.joinAttempts<d.maxJoinAttempts)return d.join(r,a,o,c,l)}else if(u.reason===Q.ServiceNotFound)return d.log.warn("Initial connection failed: ".concat(u.message," \u2013 Retrying")),d.join(r,a,o,c,!0)}throw u}})()})}close(){return p(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(P.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return p(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new zo,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return p(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new qe("a track with the same ID has already been published");return new Promise((t,i)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(F.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return p(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return p(this,void 0,void 0,function*(){var i,s;if(this.pcManager&&this.pcManager.currentState!==te.NEW)return;this.participantSid=(i=e.participant)===null||i===void 0?void 0:i.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new xu(r,t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(P.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(a,o)=>{this.client.sendIceCandidate(a,o)},this.pcManager.onPublisherOffer=(a,o)=>{this.client.sendOffer(a,o)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(a,o,c)=>p(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(a),this.logContext),["closed","disconnected","failed"].includes(o)&&(this.publisherConnectionPromise=void 0),a===te.CONNECTED){const u=this.pcState===Ee.New;this.pcState=Ee.Connected,u&&this.emit(P.Connected,e)}else a===te.FAILED&&(this.pcState===Ee.Connected||this.pcState===Ee.Reconnecting)&&(this.pcState=Ee.Disconnected,this.handleDisconnect("peerconnection failed",c==="failed"?rt.RR_SUBSCRIBER_FAILED:rt.RR_PUBLISHER_FAILED));const d=this.client.isDisconnected||this.client.currentState===Y.RECONNECTING,l=[te.FAILED,te.CLOSING,te.CLOSED].includes(a);d&&l&&!this._isClosed&&this.emit(P.Offline)}),this.pcManager.onTrack=a=>{a.streams.length!==0&&this.emit(P.MediaTrackAdded,a.track,a.streams[0],a.receiver)},oh((s=e.serverInfo)===null||s===void 0?void 0:s.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>p(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>p(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const s=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);s&&this.client.sendAnswer(s,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(P.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(P.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(P.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(P.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(P.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,i;const s={direction:"recvonly"};for(let r=0;r<e.numAudios;r++)(t=this.pcManager)===null||t===void 0||t.addPublisherTransceiverOfKind("audio",s);for(let r=0;r<e.numVideos;r++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("video",s);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",rt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e?.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:na,regionSettings:e.regions})),e.action){case vt.DISCONNECT:this.emit(P.Disconnected,e?.reason),this.close();break;case vt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Xn);break;case vt.RESUME:this.handleDisconnect(Xn)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const s=[];e.iceServers.forEach(r=>{const a={urls:r.urls};r.username&&(a.username=r.username),r.credential&&(a.credential=r.credential),s.push(a)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Lt.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(pa,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(ma,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(j.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,nh),sh)}},1e3))}createSender(e,t,i){return p(this,void 0,void 0,function*(){if(En())return yield this.createTransceiverRTCRtpSender(e,t,i);if(Rn())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new re("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(En())return this.createSimulcastTransceiverSender(e,t,i,s);if(Rn())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new re("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),Ye(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:s};return i&&(r.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return p(this,void 0,void 0,function*(){var t,i,s;if(!this._isClosed){if(this.attemptingReconnect){V.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Lt.DISABLED||((s=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&s!==void 0?s:te.NEW)===te.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let a=!0;r instanceof re?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),a=!1):r instanceof Tt||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",rt.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(P.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return p(this,void 0,void 0,function*(){var t,i,s;try{if(!this.url||!this.token)throw new re("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(P.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Tt;r=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(a){throw a instanceof F&&a.reason===Q.NotAllowed?new re("could not reconnect, token might be expired"):new Tt}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(P.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==Y.CONNECTED)throw new Tt("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(P.Restarted)}catch(r){const a=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return p(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new re("could not reconnect, url or token not saved");if(!this.pcManager)throw new re("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(P.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(s){let r="";throw s instanceof Error&&(r=s.message,this.log.error(s.message,Object.assign(Object.assign({},this.logContext),{error:s}))),s instanceof F&&s.reason===Q.NotAllowed?new re("could not reconnect, token might be expired"):s instanceof F&&s.reason===Q.LeaveRequest?s:new Tt(r)}if(this.emit(P.SignalResumed),i){const s=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(s),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Y.CONNECTED)throw new Tt("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i?.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(P.Resumed)})}waitForPCInitialConnection(e,t){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return p(this,void 0,void 0,function*(){this.pcState=Ee.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield le(th),!this.pcManager)throw new re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ee.Connected}catch(e){throw this.pcState=Ee.Disconnected,F.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,s){return p(this,void 0,void 0,function*(){const r=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcResponse",value:new Ji({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(r,j.RELIABLE)})}publishRpcAck(e,t){return p(this,void 0,void 0,function*(){const i=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcAck",value:new zi({requestId:t})}});yield this.sendDataPacket(i,j.RELIABLE)})}sendDataPacket(e,t){return p(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const r=mu(e);if(r){const a=yield this.e2eeManager.encryptData(r.toBinary());e.value={case:"encryptedPacket",value:new sr({encryptedValue:a.payload,iv:a.iv,keyIndex:a.keyIndex})}}}t===j.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),s=this.dataChannelForKind(t);if(s){if(t===j.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(t)){this.lossyDataDropCount+=1,this.lossyDataDropCount%100===0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext);return}this.lossyDataStatCurrentBytes+=i.byteLength}if(this.attemptingReconnect)return;s.send(i)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return p(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(j.RELIABLE);const t=this.dataChannelForKind(j.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{t.send(i.data)})),this.updateAndEmitDCBufferStatus(j.RELIABLE)})}waitForBufferStatusLow(e){return new ue((t,i)=>p(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>i(new re("engine closed"));for(this.once(P.Closing,s);!this.dcBufferStatus.get(e);)yield le(10);this.off(P.Closing,s),t()}}))}ensureDataTransportConnected(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var r;if(!i.pcManager)throw new re("PC manager is closed");const a=s?i.pcManager.subscriber:i.pcManager.publisher,o=s?"Subscriber":"Publisher";if(!a)throw F.internal("".concat(o," connection not set"));let c=!1;!s&&!i.dataChannelForKind(t,s)&&(i.createDataChannels(),c=!0),!c&&!s&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate().catch(u=>{V.error(u,i.logContext)});const d=i.dataChannelForKind(t,s);if(d?.readyState==="open")return;const l=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<l;){if(a.isICEConnected&&((r=i.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield le(50)}throw F.internal("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()))})()})}ensurePublisherConnected(e){return p(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==te.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return p(this,void 0,void 0,function*(){return new ue((e,t)=>p(this,void 0,void 0,function*(){if(!this.pcManager){t(new yt("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,s=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t(new yt("cannot negotiate on closed engine")),this.on(P.Closing,s),this.pcManager.publisher.once(wt.RTPVideoPayloadTypes,r=>{const a=new Map;r.forEach(o=>{const c=o.codec.toLowerCase();Xl(c)&&a.set(o.payload,c)}),this.emit(P.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(r){r instanceof yt&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",rt.RR_UNKNOWN),r instanceof Error?t(r):t(new Error(String(r)))}finally{this.off(P.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===j.LOSSY)return this.lossyDCSub;if(e===j.RELIABLE)return this.reliableDCSub}else{if(e===j.LOSSY)return this.lossyDC;if(e===j.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,s,r,a;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const o=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),d=(i=this.pcManager.subscriber)===null||i===void 0?void 0:i.getRemoteDescription(),l=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),u=(a=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&a!==void 0?a:!0,h=new Array,f=new Array;e.forEach(b=>{b.isDesired!==u&&h.push(b.trackSid),b.isEnabled||f.push(b.trackSid)}),this.client.sendSyncState(new nn({answer:this.pcManager.mode==="publisher-only"?c?Rt({sdp:c.sdp,type:c.type}):void 0:l?Rt({sdp:l.sdp,type:l.type}):void 0,offer:this.pcManager.mode==="publisher-only"?o?Rt({sdp:o.sdp,type:o.type}):void 0:d?Rt({sdp:d.sdp,type:d.type}):void 0,subscription:new pi({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:Ml(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((b,v)=>new Ir({publisherSid:v,lastSeq:b}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,s)=>{i?.id!==void 0&&i.id!==null&&e.push(new Dr({label:i.label,id:i.id,target:s}))};return t(this.dataChannelForKind(j.LOSSY),we.PUBLISHER),t(this.dataChannelForKind(j.RELIABLE),we.PUBLISHER),t(this.dataChannelForKind(j.LOSSY,!0),we.SUBSCRIBER),t(this.dataChannelForKind(j.RELIABLE,!0),we.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&de.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){ye()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){ye()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(i){const s=Object.entries(this.midToTrackId).find(r=>{let[a]=r;return a===i});if(s)return s[1]}}}function oh(n){return n!==void 0&&n>13}function fa(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}class ga{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new Se("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),me.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Se("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),me.LengthExceeded)}}constructor(e,t,i,s){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=s}}class ah extends ga{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new Ce,i=null,s=null;if(this.signal){const a=this.signal;s=()=>{var o;(o=t.reject)===null||o===void 0||o.call(t,a.reason)},a.addEventListener("abort",s),i=a}const r=()=>{e.releaseLock(),i&&s&&i.removeEventListener("abort",s),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){var a,o;try{const{done:c,value:d}=yield Promise.race([e.read(),t.promise,(o=(a=this.outOfBandFailureRejectingFuture)===null||a===void 0?void 0:a.promise)!==null&&o!==void 0?o:new Promise(()=>{})]);return c?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(d),{done:!1,value:d.content})}catch(c){throw r(),c}}),return(){return p(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,a;let o=new Set;const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=je(c),u;u=yield l.next(),i=u.done,!i;d=!0){a=u.value,d=!1;const h=a;o.add(h)}}catch(h){s={error:h}}finally{try{!d&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return Array.from(o)})()})}}class ch extends ga{constructor(e,t,i,s){super(e,t,i,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=Ei(e.chunkIndex),s=this.receivedChunks.get(i);if(s&&s.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let i=new Ce,s=null,r=null;if(this.signal){const o=this.signal;r=()=>{var c;(c=i.reject)===null||c===void 0||c.call(i,o.reason)},o.addEventListener("abort",r),s=o}const a=()=>{e.releaseLock(),s&&r&&s.removeEventListener("abort",r),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){var o,c;try{const{done:d,value:l}=yield Promise.race([e.read(),i.promise,(c=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&c!==void 0?c:new Promise(()=>{})]);if(d)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(l);let u;try{u=t.decode(l.content)}catch(h){throw new Se("Cannot decode datastream chunk ".concat(l.chunkIndex," as text: ").concat(h),me.DecodeFailed)}return{done:!1,value:u}}}catch(d){throw a(),d}}),return(){return p(this,void 0,void 0,function*(){return a(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,a;let o="";const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=je(c),u;u=yield l.next(),i=u.done,!i;d=!0)a=u.value,d=!1,o+=a}catch(h){s={error:h}}finally{try{!d&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return o})()})}}class dh{constructor(){this.log=V,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Se('A text stream handler for topic "'.concat(e,'" has already been set.'),me.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Se('A byte stream handler for topic "'.concat(e,'" has already been set.'),me.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,i,s,r;const a=Array.from(this.textStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e),o=Array.from(this.byteStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e);if(a.length>0||o.length>0){const c=new Se("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),me.AbnormalEnd);for(const[d,l]of o)(i=(t=l.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(t,c),this.byteStreamControllers.delete(d);for(const[d,l]of a)(r=(s=l.outOfBandFailureRejectingFuture).reject)===null||r===void 0||r.call(s,c),this.textStreamControllers.delete(d)}}handleDataStreamPacket(e,t){return p(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,i){return p(this,void 0,void 0,function*(){var s;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let a;const o=new Ce;o.promise.catch(l=>{this.log.error(l)});const c={id:e.streamId,name:(s=e.contentHeader.value.name)!==null&&s!==void 0?s:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Ei(e.timestamp),attributes:e.attributes,encryptionType:i},d=new ReadableStream({start:l=>{if(a=l,this.textStreamControllers.has(e.streamId))throw new Se("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),me.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:c,controller:a,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});r(new ah(c,d,Ei(e.totalLength),o),{identity:t})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let a;const o=new Ce;o.promise.catch(l=>{this.log.error(l)});const c={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i,attachedStreamIds:e.contentHeader.value.attachedStreamIds},d=new ReadableStream({start:l=>{if(a=l,this.textStreamControllers.has(e.streamId))throw new Se("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),me.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:c,controller:a,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});r(new ch(c,d,Ei(e.totalLength),o),{identity:t})}})}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),me.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const s=this.textStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?(s.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),me.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&s.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),me.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const s=this.byteStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?s.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),me.EncryptionTypeMismatch)):(s.info.attributes=Object.assign(Object.assign({},s.info.attributes),e.attributes),s.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class va{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return p(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class lh extends va{}class uh extends va{}const ba=15e3;class hh{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return p(this,void 0,void 0,function*(){var i;const s=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(i=t?.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(o?o.length+1:1).fill(0),d=(u,h)=>{var f;c[h]=u;const b=c.reduce((v,R)=>v+R,0);(f=t?.onProgress)===null||f===void 0||f.call(t,b)},l=yield this.streamText({streamId:s,totalSize:a,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:o,attributes:t?.attributes});return yield l.write(e),d(1,0),yield l.close(),t?.attachments&&o&&(yield Promise.all(t.attachments.map((u,h)=>p(this,void 0,void 0,function*(){return this._sendFile(o[h],u,{topic:t.topic,mimeType:u.type,onProgress:f=>{d(f,h+1)}})})))),l.info})}streamText(e){return p(this,void 0,void 0,function*(){var t,i,s;const r=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e?.topic)!==null&&i!==void 0?i:"",size:e?.totalSize,attributes:e?.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?se.GCM:se.NONE,attachedStreamIds:e?.attachedStreamIds},o=new ci({streamId:r,mimeType:a.mimeType,topic:a.topic,timestamp:lt(a.timestamp),totalLength:lt(e?.totalSize),attributes:a.attributes,contentHeader:{case:"textHeader",value:new vr({version:e?.version,attachedStreamIds:a.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?$i.UPDATE:$i.CREATE})}}),c=e?.destinationIdentities,d=new pe({destinationIdentities:c,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(d,j.RELIABLE);let l=0;const u=this.engine,h=new WritableStream({write(v){return p(this,void 0,void 0,function*(){for(const R of su(v,ba)){const _=new di({content:R,streamId:r,chunkIndex:lt(l)}),A=new pe({destinationIdentities:c,value:{case:"streamChunk",value:_}});yield u.sendDataPacket(A,j.RELIABLE),l+=1}})},close(){return p(this,void 0,void 0,function*(){const v=new li({streamId:r}),R=new pe({destinationIdentities:c,value:{case:"streamTrailer",value:v}});yield u.sendDataPacket(R,j.RELIABLE)})},abort(v){console.log("Sink error:",v)}});let f=()=>p(this,void 0,void 0,function*(){yield b.close()});u.once(P.Closing,f);const b=new lh(h,a,()=>this.engine.off(P.Closing,f));return b})}sendFile(e,t){return p(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return p(this,void 0,void 0,function*(){var s;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(s=i?.mimeType)!==null&&s!==void 0?s:t.type,topic:i?.topic,destinationIdentities:i?.destinationIdentities}),a=t.stream().getReader();for(;;){const{done:o,value:c}=yield a.read();if(o)break;yield r.write(c)}return yield r.close(),r.info})}streamBytes(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a,o;const c=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),d=e?.destinationIdentities,l={id:c,mimeType:(i=e?.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(s=e?.topic)!==null&&s!==void 0?s:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(r=e?.name)!==null&&r!==void 0?r:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?se.GCM:se.NONE},u=new ci({totalLength:lt((o=l.size)!==null&&o!==void 0?o:0),mimeType:l.mimeType,streamId:c,topic:l.topic,timestamp:lt(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new br({name:l.name})}}),h=new pe({destinationIdentities:d,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,j.RELIABLE);let f=0;const b=new he,v=this.engine,R=this.log,_=new WritableStream({write(x){return p(this,void 0,void 0,function*(){const y=yield b.lock();let T=0;try{for(;T<x.byteLength;){const C=x.slice(T,T+ba),N=new pe({destinationIdentities:d,value:{case:"streamChunk",value:new di({content:C,streamId:c,chunkIndex:lt(f)})}});yield v.sendDataPacket(N,j.RELIABLE),f+=1,T+=C.byteLength}}finally{y()}})},close(){return p(this,void 0,void 0,function*(){const x=new li({streamId:c}),y=new pe({destinationIdentities:d,value:{case:"streamTrailer",value:x}});yield v.sendDataPacket(y,j.RELIABLE)})},abort(x){R.error("Sink error:",x)}});return new uh(_,l)})}}class ya extends S{constructor(e,t,i,s,r){super(e,i,r),this.sid=t,this.receiver=s}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?w.Muted:w.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(w.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return p(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),zn)),Ll()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:s,rtpTimestamp:r}=i;r&&this.rtpTimestamp!==r&&(this.emit(w.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class ph extends ya{constructor(e,t,i,s,r,a){super(e,t,S.Kind.Audio,i,a),this.monitorReceiver=()=>p(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=Ri(o,this.prevStats)),this.prevStats=o}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Me()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Me())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return p(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(wn(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&wn(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{i.connect(s),i=s}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(w.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(w.AudioPlaybackFailed,s)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}}const Zn=100;class mh extends ya{constructor(e,t,i,s,r){super(e,t,S.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>p(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=Ri(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=qn(()=>{this.updateDimensions()},Zn),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===S.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?kt(this._mediaStreamTrack,t):_t(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new fh(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(i=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&i!==""&&s.get(i)&&(t.mimeType=s.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;const s=this.elementInfos.reduce((c,d)=>Math.max(c,d.visibilityChangedAt||0),0),r=!((i=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,a=this.elementInfos.some(c=>c.pictureInPicture),o=this.elementInfos.some(c=>c.visible)&&!r||a;if(!(this.lastVisible===o&&!e)){if(!o&&Date.now()-s<Zn){de.setTimeout(()=>{this.updateVisibility()},Zn);return}this.lastVisible=o,this.emit(w.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let i=0,s=0;const r=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*r,c=a.height()*r;o+c>i+s&&(i=o,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:i,height:s},this.emit(w.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Lo():t||(Lo()>2?2:1)}}class fh{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var s;const{target:r,isIntersecting:a}=i;r===this.element&&(this.isIntersecting=a,this.isPiP=$t(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var i,s,r;(s=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),this.isPiP=$t(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=$t(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??es(e),this.isPiP=ye()&&$t(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=es(this.element),this.isPiP=$t(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Fo().observe(this.element),Uo().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,s,r;(e=Fo())===null||e===void 0||e.unobserve(this.element),(t=Uo())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(r=(s=window.documentPictureInPicture)===null||s===void 0?void 0:s.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function $t(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?es(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function es(n,e){const t=e||window;let i=n.offsetTop,s=n.offsetLeft;const r=n.offsetWidth,a=n.offsetHeight,{hidden:o}=n,{display:c}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,s+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&s<t.pageXOffset+t.innerWidth&&i+a>t.pageYOffset&&s+r>t.pageXOffset&&!o&&c!=="none"}class Ke extends xe.EventEmitter{constructor(e,t,i,s){var r;super(),this.metadataMuted=!1,this.encryption=se.NONE,this.log=V,this.handleMuted=()=>{this.emit(w.Muted)},this.handleUnmuted=()=>{this.emit(w.Unmuted)},this.log=Ve((r=s?.loggerName)!==null&&r!==void 0?r:Pe.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=S.Source.Unknown}setTrack(e){this.track&&(this.track.off(w.Muted,this.handleMuted),this.track.off(w.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(w.Muted,this.handleMuted),e.on(w.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),W(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==se.NONE}get audioTrack(){if(Ue(this.track))return this.track}get videoTrack(){if(Ye(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=S.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===S.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(n.PermissionStatus||(n.PermissionStatus={}))})(Ke||(Ke={}));class ts extends Ke{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(w.Ended)},this.handleCpuConstrained=()=>{this.track&&Ye(this.track)&&this.emit(w.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(w.Ended,this.handleTrackEnded),this.track.off(w.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(w.Ended,this.handleTrackEnded),e.on(w.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Ue(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(ae.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(ae.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(ae.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(ae.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(ae.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(ae.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Ii(n,e){return p(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:s,optionsWithoutProcessor:r}=Io(n);let a=r.audio,o=r.video;if(i&&typeof r.audio=="object"&&(r.audio.processor=i),s&&typeof r.video=="object"&&(r.video.processor=s),n.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const u=r.audio.deviceId;r.audio.deviceId={exact:u},t=!0,a=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:u}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const u=r.video.deviceId;r.video.deviceId={exact:u},t=!0,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}r.audio===!0?r.audio={deviceId:"default"}:typeof r.audio=="object"&&r.audio!==null&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const c=Ro(r,ta,ia),d=Sn(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(ce.userMediaPromiseMap.set("audioinput",l),l.catch(()=>ce.userMediaPromiseMap.delete("audioinput"))),r.video&&(ce.userMediaPromiseMap.set("videoinput",l),l.catch(()=>ce.userMediaPromiseMap.delete("videoinput")));try{const u=yield l;return yield Promise.all(u.getTracks().map(h=>p(this,void 0,void 0,function*(){const f=h.kind==="audio";let b=f?c.audio:c.video;(typeof b=="boolean"||!b)&&(b={});let v;const R=f?d.audio:d.video;typeof R!="boolean"&&(v=R);const _=h.getSettings().deviceId;v?.deviceId&&Qe(v.deviceId)!==_?v.deviceId=_:v||(v={deviceId:_});const A=Wu(h,v,e);return A.kind===S.Kind.Video?A.source=S.Source.Camera:A.kind===S.Kind.Audio&&(A.source=S.Source.Microphone),A.mediaStream=u,Ue(A)&&i?yield A.setProcessor(i):Ye(A)&&s&&(yield A.setProcessor(s)),A})))}catch(u){if(!t)throw u;return Ii(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function gh(n){return p(this,void 0,void 0,function*(){return(yield Ii({audio:!1,video:!0}))[0]})}function vh(n){return p(this,void 0,void 0,function*(){return(yield Ii({audio:!0,video:!1}))[0]})}var it;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(it||(it={}));function bh(n){switch(n){case Mt.EXCELLENT:return it.Excellent;case Mt.GOOD:return it.Good;case Mt.POOR:return it.Poor;case Mt.LOST:return it.Lost;default:return it.Unknown}}class Ta extends xe.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Ut.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===ft.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,s,r,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Ut.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=it.Unknown,this.log=V,this.log=Ve((c=a?.loggerName)!==null&&c!==void 0?c:Pe.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Ce,this.once(I.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(S.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(S.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(S.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===ft.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==ft.ACTIVE&&this.emit(I.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(I.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(I.ParticipantNameChanged,e)}_setAttributes(e){const t=Ul(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(I.AttributesChanged,t)}setPermissions(e){var t,i,s,r,a,o;const c=this.permissions,d=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var h;return l!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,d&&this.emit(I.ParticipantPermissionsChanged,c),d}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(I.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=bh(e),t!==this._connectionQuality&&this.emit(I.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Ue(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(w.Muted,()=>{this.emit(I.TrackMuted,e)}),e.on(w.Unmuted,()=>{this.emit(I.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case S.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case S.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function yh(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new wr({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}class Th extends Ta{constructor(e,t,i,s,r,a){super(e,t,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=se.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Ce)},this.handleReconnected=()=>{var o,c;(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.resolve)===null||c===void 0||c.call(o),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var o,c,d,l,u,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.reject)===null||c===void 0||c.call(o,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((l=(d=this.signalConnectedFuture).reject)===null||l===void 0||l.call(d,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(h=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=o=>{var c,d;o.participant&&this.updateInfo(o.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Ce),(d=(c=this.signalConnectedFuture).resolve)===null||d===void 0||d.call(c)},this.handleSignalRequestResponse=o=>{const{requestId:c,reason:d,message:l}=o,u=this.pendingSignalRequests.get(c);u&&(d!==sn.OK&&u.reject(new Co(l,d)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=o=>{switch(o.value.case){case"rpcResponse":let c=o.value.value,d=null,l=null;c.value.case==="payload"?d=c.value.value:c.value.case==="error"&&(l=ie.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,d,l);break;case"rpcAck":let u=o.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(o=>yh(o)))},this.onTrackUnmuted=o=>{this.onTrackMuted(o,o.isUpstreamPaused)},this.onTrackMuted=(o,c)=>{if(c===void 0&&(c=!0),!o.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),W(o)));return}this.engine.updateMuteStatus(o.sid,c)},this.onTrackUpstreamPaused=o=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),W(o))),this.onTrackMuted(o,!0)},this.onTrackUpstreamResumed=o=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),W(o))),this.onTrackMuted(o,o.isMuted)},this.onTrackFeatureUpdate=o=>{const c=this.audioTrackPublications.get(o.sid);if(!c){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(o.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(c.trackSid,c.getTrackFeatures())},this.onTrackCpuConstrained=(o,c)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),W(c))),this.emit(I.LocalTrackCpuConstrained,o,c)},this.handleSubscribedQualityUpdate=o=>p(this,void 0,void 0,function*(){var c,d,l,u,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const f=this.videoTrackPublications.get(o.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}if(!f.videoTrack)return;const b=yield f.videoTrack.setPublishingCodecs(o.subscribedCodecs);try{for(var v=!0,R=je(b),_;_=yield R.next(),c=_.done,!c;v=!0){u=_.value,v=!1;const A=u;Ol(A)&&(this.log.debug("publish ".concat(A," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),W(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,A,f.options))}}catch(A){d={error:A}}finally{try{!v&&!c&&(l=R.return)&&(yield l.call(R))}finally{if(d)throw d.error}}}),this.handleLocalTrackUnpublished=o=>{const c=this.trackPublications.get(o.trackSid);if(!c){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}this.unpublishTrack(c.track)},this.handleTrackEnded=o=>p(this,void 0,void 0,function*(){if(o.source===S.Source.ScreenShare||o.source===S.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),W(o))),this.unpublishTrack(o);else if(o.isUserProvided)yield o.mute();else if(We(o)||Xe(o))try{if(ye())try{const c=yield navigator?.permissions.query({name:o.source===S.Source.Camera?"camera":"microphone"});if(c&&c.state==="denied")throw this.log.warn("user has revoked access to ".concat(o.source),Object.assign(Object.assign({},this.logContext),W(o))),c.onchange=()=>{c.state!=="denied"&&(o.isMuted||o.restartTrack(),c.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}o.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),W(o))),We(o)?yield o.restartTrack({deviceId:"default"}):yield o.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),W(o))),yield o.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=s,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=a}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==se.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(P.RemoteMute,(i,s)=>{const r=this.trackPublications.get(i);!r||!r.track||(s?r.mute():r.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(P.Connected,this.handleReconnected).on(P.SignalConnected,this.handleSignalConnected).on(P.SignalRestarted,this.handleReconnected).on(P.SignalResumed,this.handleReconnected).on(P.Restarting,this.handleReconnecting).on(P.Resuming,this.handleReconnecting).on(P.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(P.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(P.Closing,this.handleClosing).on(P.SignalRequestResponse,this.handleSignalRequestResponse).on(P.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return p(this,arguments,void 0,function(t){var i=this;let{metadata:s,name:r,attributes:a}=t;return(function*(){return new ue((o,c)=>p(i,void 0,void 0,function*(){var d,l;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((d=s??this.metadata)!==null&&d!==void 0?d:"",(l=r??this.name)!==null&&l!==void 0?l:"",a),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:b=>{c(b),u=!0},values:{name:r,metadata:s,attributes:a}});performance.now()-f<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!a||Object.entries(a).every(b=>{let[v,R]=b;return this.attributes[v]===R||R===""&&!this.attributes[v]}))){this.pendingSignalRequests.delete(h),o();return}yield le(50)}c(new Co("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?c(u):c(new Error(String(u)))}}))})()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(S.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(S.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(S.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){this.encryptionType=e?se.GCM:se.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,s){return p(this,void 0,void 0,function*(){var r,a;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let c;if(this.pendingPublishing.has(e)){const d=yield this.waitForPendingPublicationOfSource(e);return d||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield d?.unmute(),d}this.pendingPublishing.add(e);try{switch(e){case S.Source.Camera:c=yield this.createTracks({video:(r=i)!==null&&r!==void 0?r:!0});break;case S.Source.Microphone:c=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case S.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new qe(e)}}catch(d){throw c?.forEach(l=>{l.stop()}),d instanceof Error&&this.emit(I.MediaDevicesError,d,Cn(e)),this.pendingPublishing.delete(e),d}for(const d of c){const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===S.Source.Microphone&&Ue(d)&&l.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),d.startPreConnectBuffer())}try{const d=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),W(u))),d.push(this.publishTrack(u,s));[o]=yield Promise.all(d)}catch(d){throw c?.forEach(l=>{l.stop()}),d}finally{this.pendingPublishing.delete(e)}}else if(!o?.track&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===S.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(S.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return p(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(S.Source.Camera)||this.pendingPublishing.has(S.Source.Microphone))){this.pendingPublishing.add(S.Source.Camera),this.pendingPublishing.add(S.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(S.Source.Camera),this.pendingPublishing.delete(S.Source.Microphone)}}})}createTracks(e){return p(this,void 0,void 0,function*(){var t,i;e??(e={});const s=Ro(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield Ii(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Ue(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=S.Source.Microphone,this.emit(I.AudioStreamAcquired)),Ye(o)&&(this.cameraError=void 0,o.source=S.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return p(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new bn("getDisplayMedia not supported");e.resolution===void 0&&!Hl()&&(e.resolution=_n.h1080fps30.resolution);const t=xl(e),i=yield navigator.mediaDevices.getDisplayMedia(t),s=i.getVideoTracks();if(s.length===0)throw new qe("no video track found");const r=new Pi(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=S.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(i.getAudioTracks().length>0){this.emit(I.AudioStreamAcquired);const o=new wi(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=S.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return p(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var o,c,d,l;We(i)&&i.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!a&&(yield r.republishPromise),Ct(i)&&r.pendingPublishPromises.has(i)&&(yield r.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let _;switch(i.source){case S.Source.Microphone:_="audioinput";break;case S.Source.Camera:_="videoinput"}_&&r.activeDeviceMap.has(_)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(_)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new wi(i,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":i=new Pi(i,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new qe("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(_=>{_.track&&_.track===i&&(h=_)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),W(h))),h;const f=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s),b="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,v=(c=f.forceStereo)!==null&&c!==void 0?c:b;v&&(f.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),W(i))),f.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(d=f.dtx)!==null&&d!==void 0||(f.dtx=!1),(l=f.red)!==null&&l!==void 0||(f.red=!1)),!Jl()&&r.roomOptions.e2ee&&(r.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},r.logContext)),f.simulcast=!1),f.source&&(i.source=f.source);const R=new Promise((_,A)=>p(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Y.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:W(i)}));let x=!1;const y=setTimeout(()=>{x=!0,i.stop(),A(new So("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(y),x)return;const T=yield this.publish(i,f,v);_(T)}else try{const x=yield this.publish(i,f,v);_(x)}catch(x){A(x)}}catch(x){A(x)}}));r.pendingPublishPromises.set(i,R);try{return yield R}catch(_){throw _}finally{r.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Ce),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),W(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(s=>Fl(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),W(e))),!1)}publish(e,t,i){return p(this,void 0,void 0,function*(){var s,r,a,o,c,d,l,u,h,f;if(!this.hasPermissionsToPublish(e))throw new So("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(M=>Ct(e)&&M.source===e.source)&&e.source!==S.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),W(e))),t.stopMicTrackOnMute&&Ue(e)&&(e.stopOnMute=!0),e.source===S.Source.ScreenShare&&ct()&&(t.simulcast=!1),t.videoCodec==="av1"&&!Wl()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!Kl()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Kn),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(M=>t.videoCodec===qt(M.mime))||(t.videoCodec=qt(this.enabledPublishVideoCodecs[0].mime)));const v=t.videoCodec;e.on(w.Muted,this.onTrackMuted),e.on(w.Unmuted,this.onTrackUnmuted),e.on(w.Ended,this.handleTrackEnded),e.on(w.UpstreamPaused,this.onTrackUpstreamPaused),e.on(w.UpstreamResumed,this.onTrackUpstreamResumed),e.on(w.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const R=[],_=!(!((s=t.dtx)!==null&&s!==void 0)||s),A=e.getSourceTrackSettings();A.autoGainControl&&R.push(ae.TF_AUTO_GAIN_CONTROL),A.echoCancellation&&R.push(ae.TF_ECHO_CANCELLATION),A.noiseSuppression&&R.push(ae.TF_NOISE_SUPPRESSION),A.channelCount&&A.channelCount>1&&R.push(ae.TF_STEREO),_&&R.push(ae.TF_NO_DTX),We(e)&&e.hasPreConnectBuffer&&R.push(ae.TF_PRECONNECT_BUFFER);const x=new Ft({cid:e.mediaStreamTrack.id,name:t.name,type:S.kindToProto(e.kind),muted:e.isMuted,source:S.sourceToProto(e.source),disableDtx:_,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:R});let y;if(e.kind===S.Kind.Video){let M={width:0,height:0};try{M=yield e.waitForDimensions()}catch{const L=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:jt.h720.resolution;M={width:L.width,height:L.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),W(e)),{dims:M}))}x.width=M.width,x.height=M.height,Xe(e)&&(Ie(v)&&(e.source===S.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),W(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),x.simulcastCodecs=[new Yi({codec:v,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Kn}),t.backupCodec&&v!==t.backupCodec.codec&&x.encryption===se.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),x.simulcastCodecs.push(new Yi({codec:t.backupCodec.codec,cid:""})))),y=Qn(e.source===S.Source.ScreenShare,x.width,x.height,t),x.layers=ha(x.width,x.height,y,Ie(t.videoCodec))}else e.kind===S.Kind.Audio&&(y=[{maxBitrate:(d=t.audioPreset)===null||d===void 0?void 0:d.maxBitrate,priority:(u=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new re("cannot publish track when not connected");const T=()=>p(this,void 0,void 0,function*(){var M,O,L;if(!this.engine.pcManager)throw new re("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,y),this.emit(I.LocalSenderCreated,e.sender,e),Xe(e)&&((M=t.degradationPreference)!==null&&M!==void 0||(t.degradationPreference=Zu(e)),e.setDegradationPreference(t.degradationPreference)),y)if(ct()&&e.kind===S.Kind.Audio){let q;for(const Z of this.engine.pcManager.publisher.getTransceivers())if(Z.sender===e.sender){q=Z;break}q&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:q,codec:"opus",maxbr:!((O=y[0])===null||O===void 0)&&O.maxBitrate?y[0].maxBitrate/1e3:0})}else e.codec&&Ie(e.codec)&&(!((L=y[0])===null||L===void 0)&&L.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:x.cid,codec:e.codec,maxbr:y[0].maxBitrate/1e3});yield this.engine.negotiate()});let C;const N=new Promise((M,O)=>p(this,void 0,void 0,function*(){var L;try{C=yield this.engine.addTrack(x),M(C)}catch(q){e.sender&&(!((L=this.engine.pcManager)===null||L===void 0)&&L.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(Z=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),W(e)),{error:Z}))})),O(q)}}));if(this.enabledPublishVideoCodecs.length>0)C=(yield Promise.all([N,T()]))[0];else{C=yield N;let M;if(C.codecs.forEach(O=>{M===void 0&&(M=O.mimeType)}),M&&e.kind===S.Kind.Video){const O=qt(M);O!==v&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),W(e)),{codec:O})),t.videoCodec=O,y=Qn(e.source===S.Source.ScreenShare,x.width,x.height,t))}yield T()}const U=new ts(e.kind,C,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(U.on(w.CpuConstrained,M=>this.onTrackCpuConstrained(M,U)),U.options=t,e.sid=C.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:y,trackInfo:C})),Xe(e)?e.startMonitor(this.engine.client):We(e)&&e.startMonitor(),this.addTrackPublication(U),this.emit(I.LocalTrackPublished,U),We(e)&&C.audioFeatures.includes(ae.TF_PRECONNECT_BUFFER)){const M=e.getPreConnectBuffer(),O=e.getPreConnectBufferMimeType();this.on(I.LocalTrackSubscribed,L=>{if(L.trackSid===C.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),W(e))),e.stopPreConnectBuffer()}}),M&&new Promise((q,Z)=>p(this,void 0,void 0,function*(){var _e,ut,ge,st,ns,ss;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),W(e)));const cs=setTimeout(()=>{Z(new Error("agent not active within 10 seconds"))},1e4),sp=yield this.waitUntilActiveAgentPresent();clearTimeout(cs),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),W(e)));const Ia=yield this.streamBytes({name:"preconnect-buffer",mimeType:O,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[sp.identity],attributes:{trackId:U.trackSid,sampleRate:String((ns=A.sampleRate)!==null&&ns!==void 0?ns:"48000"),channels:String((ss=A.channelCount)!==null&&ss!==void 0?ss:"1")}});try{for(var rs=!0,os=je(M),as;as=yield os.next(),_e=as.done,!_e;rs=!0){st=as.value,rs=!1;const ds=st;yield Ia.write(ds)}}catch(ds){ut={error:ds}}finally{try{!rs&&!_e&&(ge=os.return)&&(yield ge.call(os))}finally{if(ut)throw ut.error}}yield Ia.close(),q()}catch(cs){Z(cs)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),W(e)))}).catch(q=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),W(e)),{error:q}))})}return U})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return p(this,void 0,void 0,function*(){var s;if(this.encryptionType!==se.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new qe("track is not published");if(!Xe(e))throw new qe("track is not a video track");const a=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),i),o=Qu(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),W(e)));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const d=new Ft({cid:c.mediaStreamTrack.id,type:S.kindToProto(e.kind),muted:e.isMuted,source:S.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=ha(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new re("cannot publish track when not connected");const l=()=>p(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(d),l()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:h}))})}unpublishTrack(e,t){return p(this,void 0,void 0,function*(){var i,s;if(Ct(e)){const d=this.pendingPublishPromises.get(e);d&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),W(e))),yield d)}const r=this.getPublicationForTrack(e),a=r?W(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));return}e=r.track,e.off(w.Muted,this.onTrackMuted),e.off(w.Unmuted,this.onTrackUnmuted),e.off(w.Ended,this.handleTrackEnded),e.off(w.UpstreamPaused,this.onTrackUpstreamPaused),e.off(w.UpstreamResumed,this.onTrackUpstreamResumed),e.off(w.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(s=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t?e.stop():e.stopMonitor();let o=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<te.FAILED&&c)try{for(const d of this.engine.pcManager.publisher.getTransceivers())d.sender===c&&(d.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),Xe(e)){for(const[,d]of e.simulcastCodecs)d.sender&&(this.engine.removeTrack(d.sender)&&(o=!0),d.sender=void 0);e.simulcastCodecs.clear()}}catch(d){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:d}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case S.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case S.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(I.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return p(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new ue((r,a)=>p(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),o.push(c))}),yield Promise.all(o.map(c=>p(this,void 0,void 0,function*(){const d=c.track;yield this.unpublishTrack(d,!1),s&&!d.isMuted&&d.source!==S.Source.ScreenShare&&d.source!==S.Source.ScreenShareAudio&&(We(d)||Xe(d))&&!d.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield d.restartTrack()),yield this.publishOrRepublishTrack(d,c.options,!0)}))),r()}catch(o){o instanceof Error?a(o):a(new Error(String(o)))}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const r=s.reliable?j.RELIABLE:j.LOSSY,a=s.destinationIdentities,o=s.topic;let c=new Gi({participantIdentity:i.identity,payload:t,destinationIdentities:a,topic:o});const d=new pe({kind:r,value:{case:"user",value:c}});yield i.engine.sendDataPacket(d,r)})()})}publishDtmf(e,t){return p(this,void 0,void 0,function*(){const i=new pe({kind:j.RELIABLE,value:{case:"sipDtmf",value:new ar({code:e,digit:t})}});yield this.engine.sendDataPacket(i,j.RELIABLE)})}sendChatMessage(e,t){return p(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},s=new pe({value:{case:"chatMessage",value:new ai(Object.assign(Object.assign({},i),{timestamp:X.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(s,j.RELIABLE),this.emit(I.ChatMessage,i),i})}editChatMessage(e,t){return p(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new pe({value:{case:"chatMessage",value:new ai(Object.assign(Object.assign({},i),{timestamp:X.parse(i.timestamp),editTimestamp:X.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,j.RELIABLE),this.emit(I.ChatMessage,i),i})}sendText(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:i,payload:s,responseTimeout:r=15e3}=e;const a=7e3,o=a+1e3;return new ue((c,d)=>p(this,void 0,void 0,function*(){var l,u,h,f;if(Hn(s)>sa){d(ie.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((u=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||u===void 0)&&u.version&&Le((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){d(ie.builtIn("UNSUPPORTED_SERVER"));return}const b=Math.max(r,o),v=crypto.randomUUID();yield this.publishRpcRequest(t,v,i,s,b);const R=setTimeout(()=>{this.pendingAcks.delete(v),d(ie.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(v),clearTimeout(_)},a);this.pendingAcks.set(v,{resolve:()=>{clearTimeout(R)},participantIdentity:t});const _=setTimeout(()=>{this.pendingResponses.delete(v),d(ie.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(v,{resolve:(A,x)=>{clearTimeout(_),this.pendingAcks.has(v)&&(this.log.warn("RPC response received before ack",v),this.pendingAcks.delete(v),clearTimeout(R)),x?d(x):c(A??"")},participantIdentity:t})}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const s=this.pendingResponses.get(e);s?(s.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,s,r){return p(this,void 0,void 0,function*(){const a=new pe({destinationIdentities:[e],kind:j.RELIABLE,value:{case:"rpcRequest",value:new Hi({id:t,method:i,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(a,j.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:s}]of this.pendingResponses)i===e&&(s(null,ie.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var i,s;const r=this.trackPublications.get(t.sid);if(r){const a=r.isMuted||((s=(i=r.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&s!==void 0?s:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),W(r)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}setActiveAgent(e){var t,i,s,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||i===void 0||i.call(t,e):(r=(s=this.activeAgentFuture)===null||s===void 0?void 0:s.reject)===null||r===void 0||r.call(s,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Ce),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(We(s)||Xe(s))&&s.mediaStreamTrack===e&&(t=i):e===s&&(t=i))}),t}waitForPendingPublicationOfSource(e){return p(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[a]=r;return a.source===e});if(s)return s[1];yield le(20)}})}}class _h extends Ke{constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=r=>{this.setTrack(void 0),this.emit(w.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.visible=r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensionsAdaptiveStream=r,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new pi({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new dr({participantSid:"",trackSids:[this.trackSid]})]});this.emit(w.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?Ke.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ke.SubscriptionStatus.Subscribed:Ke.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ke.PermissionStatus.Allowed:Ke.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(Nn(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Nn(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Te.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(w.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(w.VisibilityChanged,this.handleVisibilityChange),s.off(w.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(w.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(w.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(w.VisibilityChanged,this.handleVisibilityChange),e.on(w.Ended,this.handleEnded),this.emit(w.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(w.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?w.Muted:w.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(w.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(w.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Nn(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Sr({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===S.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Do(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=Bl(this.trackInfo,this.requestedMaxQuality);i&&Do(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:Te.HIGH})),e.quality=Te.HIGH)}this.emit(w.UpdateSettings,e)}}class Di extends Ta{static fromParticipantInfo(e,t,i){return new Di(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,s,r,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ut.STANDARD;super(t,i||"",s,r,a,o,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(w.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),W(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(w.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(w.SubscriptionPermissionChanged,t=>{this.emit(I.TrackSubscriptionPermissionChanged,e,t)}),e.on(w.SubscriptionStatusChanged,t=>{this.emit(I.TrackSubscriptionStatusChanged,e,t)}),e.on(w.Subscribed,t=>{this.emit(I.TrackSubscribed,t,e)}),e.on(w.Unsubscribed,t=>{this.emit(I.TrackUnsubscribed,t,e)}),e.on(w.SubscriptionFailed,t=>{this.emit(I.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:S.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:S.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,s,r,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(I.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,s,r,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),W(o))),this.emit(I.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let d;return c?d=new mh(e,t,s,r):d=new ph(e,t,s,this.audioContext,this.audioOutput),d.source=o.source,d.isMuted=o.isMuted,d.setMediaStream(i),d.start(),o.setTrack(d),this.volumeMap.has(o.source)&&On(d)&&Ue(d)&&d.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach(s=>{var r,a;let o=this.getTrackPublicationBySid(s.sid);if(o)o.updateInfo(s);else{const c=S.kindFromProto(s.type);if(!c)return;o=new _h(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(s),i.set(s.sid,o);const d=Array.from(this.trackPublications.values()).find(l=>l.source===o?.source);d&&o.source!==S.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:W(d),newTrack:W(o)})),this.addTrackPublication(o)}t.set(s.sid,o)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),W(s))),this.unpublishTrack(s.trackSid,!0))}),i.forEach(s=>{this.emit(I.TrackPublished,s)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:s}=i;switch(s&&(s.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case S.Kind.Audio:this.audioTrackPublications.delete(e);break;case S.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(I.TrackUnpublished,i)}setAudioOutput(e){return p(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var s;Ue(i.track)&&On(i.track)&&t.push(i.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var J;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(J||(J={}));const kh=4*1e3;class Pt extends xe.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,i,s,r,a;if(super(),t=this,this.state=J.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=V,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(o,c,d)=>p(this,void 0,void 0,function*(){var l;if(!Gl())throw Me()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const u=yield this.disconnectLock.lock();if(this.state===J.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(J.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==jo(o)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),St(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new z(o,c):this.regionUrlProvider.updateToken(c),this.regionUrlProvider.fetchRegionSettings().then(b=>{var v;(v=this.regionUrlProvider)===null||v===void 0||v.setServerReportedRegions(b)}).catch(b=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:b}))}));const h=(b,v,R)=>p(this,void 0,void 0,function*(){var _,A;this.abortController&&this.abortController.abort();const x=new AbortController;this.abortController=x,u?.();try{if(yield Et.getInstance().getBackOffPromise(o),x.signal.aborted)throw F.cancelled("Connection attempt aborted");yield this.attemptConnection(R??o,c,d,x),this.abortController=void 0,b()}catch(y){if(this.regionUrlProvider&&y instanceof F&&y.reason!==Q.Cancelled&&y.reason!==Q.NotAllowed){let T=null;try{this.log.debug("Fetching next region"),T=yield this.regionUrlProvider.getNextBestRegionUrl((_=this.abortController)===null||_===void 0?void 0:_.signal)}catch(C){if(C instanceof F&&(C.status===401||C.reason===Q.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),v(C);return}}[Q.InternalError,Q.ServerUnreachable,Q.Timeout].includes(y.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Et.getInstance().addFailedConnectionAttempt(o)),T&&!(!((A=this.abortController)===null||A===void 0)&&A.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(y.message,". Retrying with another region: ").concat(T),this.logContext),this.recreateEngine(),yield h(b,v,T)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Vo(y)),v(y))}else{let T=ke.UNKNOWN_REASON;y instanceof F&&(T=Vo(y)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,T),v(y)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ce((b,v)=>{h(b,v,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,c,d,l,u,h)=>p(this,void 0,void 0,function*(){var f,b,v;const R=yield d.join(o,c,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},h.signal,!u.singlePeerConnection);let _=R.serverInfo;if(_||(_={version:R.serverVersion,region:R.serverRegion}),this.serverInfo=_,this.log.debug("connected to Livekit Server ".concat(Object.entries(_).map(A=>{let[x,y]=A;return"".concat(x,": ").concat(y)}).join(", ")),{room:(f=R.room)===null||f===void 0?void 0:f.name,roomSid:(b=R.room)===null||b===void 0?void 0:b.sid,identity:(v=R.participant)===null||v===void 0?void 0:v.identity}),!_.version)throw new wl("unknown server version");return _.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),R}),this.applyJoinResponse=o=>{const c=o.participant;if(this.localParticipant.sid=c.sid,this.localParticipant.identity=c.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(d){this.log.error(d instanceof Error?d.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:d}))}this.handleParticipantUpdates([c,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,c,d,l)=>p(this,void 0,void 0,function*(){var u,h;this.state===J.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((h=this.regionUrlProvider)===null||h===void 0)&&h.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Gn),d),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(o,c,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const b=l.signal.aborted?F.cancelled("Signal connection aborted"):F.serverUnreachable("could not establish signal connection");throw f instanceof Error&&(b.message="".concat(b.message,": ").concat(f.message)),f instanceof F&&(b.reason=f.reason,b.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),b}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),F.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}ye()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),ye()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(J.Connected),this.emit(E.Connected),Et.getInstance().resetFailedConnectionAttempts(o),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var o=arguments.length,c=new Array(o),d=0;d<o;d++)c[d]=arguments[d];return p(t,[...c],void 0,function(){var l=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var h,f,b;const v=yield l.disconnectLock.lock();try{if(l.state===J.Disconnected){l.log.debug("already disconnected",l.logContext);return}if(l.log.info("disconnect from room",Object.assign({},l.logContext)),l.state===J.Connecting||l.state===J.Reconnecting||l.isResuming){const R="Abort connection attempt due to user initiated disconnect";l.log.warn(R,l.logContext),(h=l.abortController)===null||h===void 0||h.abort(R),(b=(f=l.connectFuture)===null||f===void 0?void 0:f.reject)===null||b===void 0||b.call(f,F.cancelled("Client initiated disconnect")),l.connectFuture=void 0}l.engine&&(l.engine.client.isDisconnected||(yield l.engine.client.sendLeave()),yield l.engine.close()),l.handleDisconnect(u,ke.CLIENT_INITIATED),l.engine=void 0}finally{v()}})()})},this.onPageLeave=()=>p(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>p(this,void 0,void 0,function*(){const o=[],c=be();if(c&&c.os==="iOS"){const d="livekit-dummy-audio-el";let l=document.getElementById(d);if(!l){l=document.createElement("audio"),l.id=d,l.autoplay=!0,l.hidden=!0;const u=An();u.enabled=!0;const h=new MediaStream([u]);l.srcObject=h,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:h,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(E.Disconnected,()=>{l?.remove(),l=null})}o.push(l)}this.remoteParticipants.forEach(d=>{d.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(u=>{o.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(d=>(d.muted=!1,d.play()))]),this.handleAudioPlaybackStarted()}catch(d){throw this.handleAudioPlaybackFailed(d),d}}),this.startVideo=()=>p(this,void 0,void 0,function*(){const o=[];for(const c of this.remoteParticipants.values())c.videoTrackPublications.forEach(d=>{var l;(l=d.track)===null||l===void 0||l.attachedElements.forEach(u=>{o.includes(u)||o.push(u)})});yield Promise.all(o.map(c=>c.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(c=>{c.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const o of this.remoteParticipants.values())this.handleParticipantDisconnected(o.identity,o);this.setAndEmitConnectionState(J.Reconnecting)&&this.emit(E.Reconnecting)},this.handleSignalRestarted=o=>p(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),Object.assign(Object.assign({},this.logContext),{region:o.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(o);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(c){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:c}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:o.serverRegion}))}catch{return}this.setAndEmitConnectionState(J.Connected),this.emit(E.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(c=>{var d;if(c.identity===this.localParticipant.identity){this.localParticipant.updateInfo(c);return}c.identity===""&&(c.identity=(d=this.sidToIdentity.get(c.sid))!==null&&d!==void 0?d:"");let l=this.remoteParticipants.get(c.identity);c.state===ft.DISCONNECTED?this.handleParticipantDisconnected(c.identity,l):l=this.getOrCreateParticipant(c.identity,c)})},this.handleActiveSpeakersUpdate=o=>{const c=[],d={};o.forEach(l=>{if(d[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),c.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(l.sid);u&&(u.audioLevel=l.level,u.setIsSpeaking(!0),c.push(u))}}),d[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{d[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=c,this.emitWhenConnected(E.ActiveSpeakersChanged,c)},this.handleSpeakersChanged=o=>{const c=new Map;this.activeSpeakers.forEach(l=>{const u=this.remoteParticipants.get(l.identity);u&&u.sid!==l.sid||c.set(l.sid,l)}),o.forEach(l=>{let u=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=l.level,u.setIsSpeaking(l.active),l.active?c.set(l.sid,u):c.delete(l.sid))});const d=Array.from(c.values());d.sort((l,u)=>u.audioLevel-l.audioLevel),this.activeSpeakers=d,this.emitWhenConnected(E.ActiveSpeakersChanged,d)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(c=>{const d=this.getRemoteParticipantBySid(c.participantSid);if(!d)return;const l=d.getTrackPublicationBySid(c.trackSid);if(!l||!l.track)return;const u=S.streamStateFromProto(c.state);l.track.setStreamState(u),u!==l.track.streamState&&(d.emit(I.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(E.TrackStreamStateChanged,l,l.track.streamState,d))})},this.handleSubscriptionPermissionUpdate=o=>{const c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;const d=c.getTrackPublicationBySid(o.trackSid);d&&d.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const c=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(o.trackSid));if(!c)return;const d=c.getTrackPublicationBySid(o.trackSid);d&&d.setSubscriptionError(o.err)},this.handleDataPacket=(o,c)=>{const d=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(d,o.value.value,o.kind,c);else if(o.value.case==="transcription")this.handleTranscription(d,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(d,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(d,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,d);else if(o.value.case==="streamHeader"||o.value.case==="streamChunk"||o.value.case==="streamTrailer")this.handleDataStream(o,c);else if(o.value.case==="rpcRequest"){const l=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,l.id,l.method,l.payload,l.responseTimeoutMs,l.version)}},this.handleUserPacket=(o,c,d,l)=>{this.emit(E.DataReceived,c.payload,o,d,c.topic,l),o?.emit(I.DataReceived,c.payload,d,l)},this.handleSipDtmf=(o,c)=>{this.emit(E.SipDTMFReceived,c,o),o?.emit(I.SipDTMFReceived,c)},this.handleTranscription=(o,c)=>{const d=c.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(c.transcribedParticipantIdentity),l=d?.trackPublications.get(c.trackId),u=eu(c,this.transcriptionReceivedTimes);l?.emit(w.TranscriptionReceived,u),d?.emit(I.TranscriptionReceived,u,l),this.emit(E.TranscriptionReceived,u,d,l)},this.handleChatMessage=(o,c)=>{const d=tu(c);this.emit(E.ChatMessage,d,o)},this.handleMetrics=(o,c)=>{this.emit(E.MetricsReceived,o,c)},this.handleDataStream=(o,c)=>{this.incomingDataStreamManager.handleDataStreamPacket(o,c)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(E.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:o})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(E.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(E.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(E.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>p(this,void 0,void 0,function*(){var o;((o=be())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(E.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const c=this.roomInfo;this.roomInfo=o,c&&c.metadata!==o.metadata&&this.emitWhenConnected(E.RoomMetadataChanged,o.metadata),c?.activeRecording!==o.activeRecording&&this.emitWhenConnected(E.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(c=>{if(c.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(c.quality);return}const d=this.getRemoteParticipantBySid(c.participantSid);d&&d.setConnectionQuality(c.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(E.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(E.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(E.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(E.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(E.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var c;(c=o?.onPublish)===null||c===void 0||c.call(o,this)},this.onLocalTrackPublished=o=>p(this,void 0,void 0,function*(){var c,d,l,u,h,f;(c=o.track)===null||c===void 0||c.on(w.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=o.track)===null||d===void 0||d.on(w.Restarted,this.onLocalTrackRestarted),(h=(u=(l=o.track)===null||l===void 0?void 0:l.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||h===void 0||h.call(u,this),this.emit(E.LocalTrackPublished,o,this.localParticipant),We(o.track)&&(yield o.track.checkForSilence())&&this.emit(E.LocalAudioSilenceDetected,o);const b=yield(f=o.track)===null||f===void 0?void 0:f.getDeviceId(!1),v=Cn(o.source);v&&b&&b!==this.localParticipant.activeDeviceMap.get(v)&&(this.localParticipant.activeDeviceMap.set(v,b),this.emit(E.ActiveDeviceChanged,v,b))}),this.onLocalTrackUnpublished=o=>{var c,d;(c=o.track)===null||c===void 0||c.off(w.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=o.track)===null||d===void 0||d.off(w.Restarted,this.onLocalTrackRestarted),this.emit(E.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>p(this,void 0,void 0,function*(){const c=yield o.getDeviceId(!1),d=Cn(o.source);d&&c&&c!==this.localParticipant.activeDeviceMap.get(d)&&(this.log.debug("local track restarted, setting ".concat(d," ").concat(c," active"),this.logContext),this.localParticipant.activeDeviceMap.set(d,c),this.emit(E.ActiveDeviceChanged,d,c))}),this.onLocalConnectionQualityChanged=o=>{this.emit(E.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,c)=>{this.emit(E.MediaDevicesError,o,c)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(E.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(E.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Nu),e),this.log=Ve((i=this.options.loggerName)!==null&&i!==void 0?i:Pe.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},ta),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},ia),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Ou),e?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new dh,this.outgoingDataStreamManager=new hh(this.engine,this.log),this.disconnectLock=new he,this.localParticipant=new Th("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Qe(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Qe(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Qe(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),ye()){const o=new AbortController;(a=(r=navigator.mediaDevices)===null||r===void 0?void 0:r.addEventListener)===null||a===void 0||a.call(r,"devicechange",this.handleDeviceChange,{signal:o.signal}),Pt.cleanupRegistry&&Pt.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;const t=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new fu(i,t),this.e2eeManager.on(et.ParticipantEncryptionStatusChanged,(s,r)=>{nu(r)&&(this.isE2EEEnabled=s),this.emit(E.ParticipantEncryptionStatusChanged,s,r)}),this.e2eeManager.on(et.EncryptionError,(s,r)=>{const a=r?this.getParticipantByIdentity(r):void 0;this.emit(E.EncryptionError,s,a)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===J.Disconnected?ue.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?ue.resolve(this.roomInfo.sid):new ue((e,t)=>{const i=s=>{s.sid!==""&&(this.engine.off(P.RoomUpdate,i),e(s.sid))};this.engine.on(P.RoomUpdate,i),this.once(E.Disconnected,()=>{this.engine.off(P.RoomUpdate,i),t(new re("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new rh(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(P.ParticipantUpdate,this.handleParticipantUpdates).on(P.RoomUpdate,this.handleRoomUpdate).on(P.SpeakersChanged,this.handleSpeakersChanged).on(P.StreamStateChanged,this.handleStreamStateUpdate).on(P.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(P.SubscriptionError,this.handleSubscriptionError).on(P.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(P.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(P.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(P.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(P.DataPacketReceived,this.handleDataPacket).on(P.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(J.SignalReconnecting)&&this.emit(E.SignalReconnecting)}).on(P.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(J.Connected)&&this.emit(E.Reconnected)}).on(P.SignalResumed,()=>{this.bufferedEvents=[],(this.state===J.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(P.Restarting,this.handleRestarting).on(P.SignalRestarted,this.handleSignalRestarted).on(P.Offline,()=>{this.setAndEmitConnectionState(J.Reconnecting)&&this.emit(E.Reconnecting)}).on(P.DCBufferStatusChanged,(e,t)=>{this.emit(E.DCBufferStatusChanged,e,t)}).on(P.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:s}=i;return s===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(I.LocalTrackSubscribed,t),this.emitWhenConnected(E.LocalTrackSubscribed,t,this.localParticipant)}).on(P.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(E.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return ce.getInstance().getDevices(e,t)}prepareConnection(e,t){return p(this,void 0,void 0,function*(){if(this.state===J.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(St(new URL(e))&&t){this.regionUrlProvider=new z(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===J.Disconnected&&(this.regionUrl=i,yield fetch(Ht(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(Ht(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return p(this,void 0,void 0,function*(){let i=()=>p(this,void 0,void 0,function*(){}),s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new Ne({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new Ne({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new Ne({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new Ne({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Ne({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Ne({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":s=new Ne({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>p(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new mi({reason:ke.CLIENT_INITIATED,action:vt.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new Ne({scenario:{case:"subscriberBandwidth",value:lt(t)}});break;case"leave-full-reconnect":s=new Ne({scenario:{case:"leaveRequestFullReconnect",value:!0}})}s&&(yield this.engine.client.sendSimulateScenario(s),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var o,c,d,l,u,h,f;let b=!0,v=!1;const R=a?{exact:s}:s;if(i==="audioinput"){v=r.localParticipant.audioTrackPublications.size===0;const _=(o=r.getActiveDevice(i))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=R;const A=Array.from(r.localParticipant.audioTrackPublications.values()).filter(y=>y.source===S.Source.Microphone);try{b=(yield Promise.all(A.map(y=>{var T;return(T=y.audioTrack)===null||T===void 0?void 0:T.setDeviceId(R)}))).every(y=>y===!0)}catch(y){throw r.options.audioCaptureDefaults.deviceId=_,y}const x=A.some(y=>{var T,C;return(C=(T=y.track)===null||T===void 0?void 0:T.isMuted)!==null&&C!==void 0?C:!1});b&&x&&(v=!0)}else if(i==="videoinput"){v=r.localParticipant.videoTrackPublications.size===0;const _=(c=r.getActiveDevice(i))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=R;const A=Array.from(r.localParticipant.videoTrackPublications.values()).filter(y=>y.source===S.Source.Camera);try{b=(yield Promise.all(A.map(y=>{var T;return(T=y.videoTrack)===null||T===void 0?void 0:T.setDeviceId(R)}))).every(y=>y===!0)}catch(y){throw r.options.videoCaptureDefaults.deviceId=_,y}const x=A.some(y=>{var T,C;return(C=(T=y.track)===null||T===void 0?void 0:T.isMuted)!==null&&C!==void 0?C:!1});b&&x&&(v=!0)}else if(i==="audiooutput"){if(v=!0,!wn()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");r.options.webAudioMix&&(s=(d=yield ce.getInstance().normalizeDeviceId("audiooutput",s))!==null&&d!==void 0?d:""),(l=(f=r.options).audioOutput)!==null&&l!==void 0||(f.audioOutput={});const _=(u=r.getActiveDevice(i))!==null&&u!==void 0?u:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=s;try{r.options.webAudioMix&&((h=r.audioContext)===null||h===void 0||h.setSinkId(s)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(A=>A.setAudioOutput({deviceId:s})))}catch(A){throw r.options.audioOutput.deviceId=_,A}}return v&&(r.localParticipant.activeDeviceMap.set(i,s),r.emit(E.ActiveDeviceChanged,i,s)),b})()})}setupLocalParticipantEvents(){this.localParticipant.on(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(I.AttributesChanged,this.onLocalAttributesChanged).on(I.TrackMuted,this.onLocalTrackMuted).on(I.TrackUnmuted,this.onLocalTrackUnmuted).on(I.LocalTrackPublished,this.onLocalTrackPublished).on(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(I.MediaDevicesError,this.onMediaDevicesError).on(I.AudioStreamAcquired,this.startAudio).on(I.ChatMessage,this.onLocalChatMessageSent).on(I.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===J.Connecting||this.state===J.Reconnecting){const u=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(f=>f.id)}),this.onTrackAdded(e,t,i),h()},h=()=>{this.off(E.Reconnected,u),this.off(E.Connected,u),this.off(E.Disconnected,h)};this.once(E.Reconnected,u),this.once(E.Connected,u),this.once(E.Disconnected,h);return}if(this.state===J.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const s=ql(t.id),r=s[0];let a=s[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===r);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}if(!o.startsWith("TR")){const u=this.engine.getTrackIdForReceiver(i);if(!u){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(r),this.logContext);return}o=u}o.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(r,", streamId: ").concat(a,", trackId: ").concat(o),Object.assign(Object.assign({},this.logContext),{rpID:r,streamId:a,trackId:o}));let d;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?d=this.options.adaptiveStream:d={});const l=c.addSubscribedMediaTrack(e,o,t,i,d);l?.isEncrypted&&!this.e2eeManager&&this.emit(E.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i,s;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==J.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(a=>{r.unpublishTrack(a.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var a,o,c;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((a=r.track)===null||a===void 0||a.detach(),(o=r.track)===null||o===void 0||o.stop()):(c=r.track)===null||c===void 0||c.stopMonitor()}),this.localParticipant.off(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(I.AttributesChanged,this.onLocalAttributesChanged).off(I.TrackMuted,this.onLocalTrackMuted).off(I.TrackUnmuted,this.onLocalTrackUnmuted).off(I.LocalTrackPublished,this.onLocalTrackPublished).off(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(I.MediaDevicesError,this.onMediaDevicesError).off(I.AudioStreamAcquired,this.startAudio).off(I.ChatMessage,this.onLocalChatMessageSent).off(I.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),ye()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(s=(i=navigator.mediaDevices)===null||i===void 0?void 0:i.removeEventListener)===null||s===void 0||s.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(J.Disconnected),this.emit(E.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(E.ParticipantDisconnected,t),t.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,i,s,r,a){return p(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,ie.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,ie.builtIn("UNSUPPORTED_METHOD"));return}let c=null,d=null;try{const l=yield o({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});Hn(l)>sa?(c=ie.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):d=l}catch(l){l instanceof ie?c=l:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),l),c=ie.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,d,c)})}selectDefaultDevices(){return p(this,void 0,void 0,function*(){var e,t,i;const s=ce.getInstance().previousDevices,r=yield ce.getInstance().getDevices(void 0,!1),a=be();if(a?.name==="Chrome"&&a.os!=="iOS")for(let c of r){const d=s.find(l=>l.deviceId===c.deviceId);d&&d.label!==""&&d.kind===c.kind&&d.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(E.ActiveDeviceChanged,c.kind,c.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let c of o){const d=Nl(c),l=this.localParticipant.getTrackPublication(d);if(l&&(!((e=l.track)===null||e===void 0)&&e.isUserProvided))continue;const u=r.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((t=s.filter(f=>f.kind===c)[0])===null||t===void 0?void 0:t.deviceId)&&u.length>0&&((i=u[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!Kt()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Kt())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return p(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Po())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),le(200)])}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(E.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let s;return t?s=Di.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new Di(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(E.ParticipantConnected,i),i.on(I.TrackPublished,s=>{this.emitWhenConnected(E.TrackPublished,s,i)}).on(I.TrackSubscribed,(s,r)=>{s.kind===S.Kind.Audio?(s.on(w.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(w.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===S.Kind.Video&&(s.on(w.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(w.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(E.TrackSubscribed,s,r,i)}).on(I.TrackUnpublished,s=>{this.emit(E.TrackUnpublished,s,i)}).on(I.TrackUnsubscribed,(s,r)=>{this.emit(E.TrackUnsubscribed,s,r,i)}).on(I.TrackMuted,s=>{this.emitWhenConnected(E.TrackMuted,s,i)}).on(I.TrackUnmuted,s=>{this.emitWhenConnected(E.TrackUnmuted,s,i)}).on(I.ParticipantMetadataChanged,s=>{this.emitWhenConnected(E.ParticipantMetadataChanged,s,i)}).on(I.ParticipantNameChanged,s=>{this.emitWhenConnected(E.ParticipantNameChanged,s,i)}).on(I.AttributesChanged,s=>{this.emitWhenConnected(E.ParticipantAttributesChanged,s,i)}).on(I.ConnectionQualityChanged,s=>{this.emitWhenConnected(E.ConnectionQualityChanged,s,i)}).on(I.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(E.ParticipantPermissionsChanged,s,i)}).on(I.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(E.TrackSubscriptionStatusChanged,s,r,i)}).on(I.TrackSubscriptionFailed,(s,r)=>{this.emit(E.TrackSubscriptionFailed,s,i,r)}).on(I.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(E.TrackSubscriptionPermissionChanged,s,r,i)}).on(I.Active,()=>{this.emitWhenConnected(E.ParticipantActive,i),i.kind===Ut.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,s)=>(i.push(...s.getTrackPublications()),i),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&iu(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=de.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ke.STATE_MISMATCH))):e=0},kh)}clearConnectionReconcile(){this.connectionReconcileInterval&&de.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(E.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(this.state===J.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===J.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return p(this,void 0,void 0,function*(){var t,i,s,r;const a=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new ri({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:X.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new ot({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected),this.emit(E.Connected),this.setAndEmitConnectionState(J.Connected),a.video){const c=new ts(S.Kind.Video,new gt({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO,name:"video-dummy"}),new Pi(a.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Bo(160*((i=o.aspectRatios[0])!==null&&i!==void 0?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(I.LocalTrackPublished,c)}if(a.audio){const c=new ts(S.Kind.Audio,new gt({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO}),new wi(a.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:An(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(I.LocalTrackPublished,c)}for(let c=0;c<o.count-1;c+=1){let d=new ot({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(c),state:ft.ACTIVE,tracks:[],joinedAt:X.parse(Date.now())});const l=this.getOrCreateParticipant(d.identity,d);if(o.video){const u=Bo(160*((r=o.aspectRatios[c%o.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),h=new gt({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}if(o.audio){const u=An(),h=new gt({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}l.updateInfo(d)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(e!==E.ActiveSpeakersChanged&&e!==E.TranscriptionReceived){const r=_a(i).filter(a=>a!==void 0);(e===E.TrackSubscribed||e===E.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...i)}}Pt.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function _a(n){return n.map(e=>{if(e)return Array.isArray(e)?_a(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Ae;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(Ae||(Ae={}));class nt extends xe.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Ae.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Pt(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return p(this,void 0,void 0,function*(){if(this.status!==Ae.IDLE)throw Error("check is running already");this.setStatus(Ae.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==Ae.SKIPPED&&this.setStatus(this.isSuccess()?Ae.SUCCESS:Ae.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return p(this,void 0,void 0,function*(){return this.room.state===J.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return p(this,void 0,void 0,function*(){this.room&&this.room.state!==J.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Ae.SKIPPED)}switchProtocol(e){return p(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(E.Reconnecting,()=>{t=!0}),this.room.once(E.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(i)return;yield le(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Sh extends nt{get description(){return"Cloud regions"}perform(){return p(this,void 0,void 0,function*(){const e=new z(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let r=0;r<3;r++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((r,a)=>(r.duration-a.duration)*.5+(r.rtt-a.rtt)*.5);const s=t[0];this.bestStats=s,this.appendMessage("best Cloud region: ".concat(s.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return p(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const s=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!s)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,c=1e6/a,d="A".repeat(a),l=Date.now();for(let b=0;b<c;b++)yield r.write(d);yield r.close();const u=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:s,rtt:1e4,duration:u-l};return h?.forEach(b=>{b.type==="candidate-pair"&&b.nominated&&(f.rtt=b.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const is=1e4;class Ch extends nt{get description(){return"Connection via UDP vs TCP"}perform(){return p(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(is/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(is/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return p(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let s=0;const r=()=>{s=(s+1)%360,i.fillStyle="hsl(".concat(s,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const o=t.captureStream(30).getVideoTracks()[0],d=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>p(this,void 0,void 0,function*(){const h=yield d.getRTCStatsReport();h?.forEach(f=>{f.type==="outbound-rtp"?(l.packetsSent=f.packetsSent,l.qualityLimitationDurations=f.qualityLimitationDurations,l.bitrateTotal+=f.targetBitrate,l.count++):f.type==="remote-inbound-rtp"&&(l.packetsLost=f.packetsLost,l.rttTotal+=f.roundTripTime,l.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,is)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}}class Eh extends nt{get description(){return"Can publish audio"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield vh();if(yield wo(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let a=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class Rh extends nt{get description(){return"Can publish video"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield gh();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(r+=a.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return p(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(s=>{i.onplay=()=>{setTimeout(()=>{var r,a,o,c;const d=document.createElement("canvas"),l=e.getSettings(),u=(a=(r=l.width)!==null&&r!==void 0?r:i.videoWidth)!==null&&a!==void 0?a:1280,h=(c=(o=l.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&c!==void 0?c:720;d.width=u,d.height=h;const f=d.getContext("2d");f.drawImage(i,0,0);const v=f.getImageData(0,0,d.width,d.height).data;let R=!0;for(let _=0;_<v.length;_+=4)if(v[_]!==0||v[_+1]!==0||v[_+2]!==0){R=!1;break}R?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},i.play()}),t.getTracks().forEach(s=>s.stop()),i.remove()})}}class wh extends nt{get description(){return"Resuming connection after interruption"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,s=!1,r;const a=new Promise(d=>{setTimeout(d,5e3),r=d}),o=()=>{i=!0};t.on(E.SignalReconnecting,o).on(E.Reconnecting,o).on(E.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield a,i){if(!s||t.state!==J.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class Ph extends nt{get description(){return"Can connect via TURN"}perform(){return p(this,void 0,void 0,function*(){var e,t,i;St(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new z(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const s=new Un,r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let a=!1,o=!1,c=!1;for(let d of r.iceServers)for(let l of d.urls)l.startsWith("turn:")?(o=!0,c=!0):l.startsWith("turns:")&&(o=!0,c=!0,a=!0),l.startsWith("stun:")&&(c=!0);c?o&&!a&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield s.close(),!((i=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||i===void 0)&&i.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(d=>setTimeout(d,0)))})}}class Ih extends nt{get description(){return"Establishing WebRTC connection"}perform(){return p(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(E.SignalConnected,()=>{var i;const s=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,a)=>{if(r.candidate){const o=new RTCIceCandidate(r);let c="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(Dh(o.address)?c+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,c+=" (passive)"):o.protocol==="udp"&&(t=!0)),this.appendMessage(c)}s&&s(r,a)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),V.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function Dh(n){const e=n.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class Ah extends nt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return p(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new Un,r;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(St(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));const c=yield new z(this.url,this.token).getNextBestRegionUrl();c&&(r=yield s.join(c,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}r?(this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===ur.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=r.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield s.close()})}}class ap extends xe.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Ae.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==Ae.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return p(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),s=a=>{this.updateCheck(t,a)};i.on("update",s);const r=yield i.run();return i.off("update",s),r})}checkWebsocket(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Ah)})}checkWebRTC(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Ih)})}checkTURN(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Ph)})}checkReconnect(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(wh)})}checkPublishAudio(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Eh)})}checkPublishVideo(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Rh)})}checkConnectionProtocol(){return p(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Ch);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Sh)})}}function K(n,e,t){return(e=Nh(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function Oh(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var i=t.call(n,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function Nh(n){var e=Oh(n,"string");return typeof e=="symbol"?e:e+""}new TextEncoder,new TextDecoder;class fe extends Error{constructor(e,t){var i;super(e,t),K(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}K(fe,"code","ERR_JOSE_GENERIC");class xh extends fe{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),K(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),K(this,"claim",void 0),K(this,"reason",void 0),K(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}K(xh,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class Mh extends fe{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),K(this,"code","ERR_JWT_EXPIRED"),K(this,"claim",void 0),K(this,"reason",void 0),K(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}K(Mh,"code","ERR_JWT_EXPIRED");class Lh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}K(Lh,"code","ERR_JOSE_ALG_NOT_ALLOWED");class Uh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JOSE_NOT_SUPPORTED")}}K(Uh,"code","ERR_JOSE_NOT_SUPPORTED");class Fh extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),K(this,"code","ERR_JWE_DECRYPTION_FAILED")}}K(Fh,"code","ERR_JWE_DECRYPTION_FAILED");class Bh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWE_INVALID")}}K(Bh,"code","ERR_JWE_INVALID");class Vh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWS_INVALID")}}K(Vh,"code","ERR_JWS_INVALID");class jh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWT_INVALID")}}K(jh,"code","ERR_JWT_INVALID");class qh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWK_INVALID")}}K(qh,"code","ERR_JWK_INVALID");class Wh extends fe{constructor(){super(...arguments),K(this,"code","ERR_JWKS_INVALID")}}K(Wh,"code","ERR_JWKS_INVALID");class Kh extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),K(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}K(Kh,"code","ERR_JWKS_NO_MATCHING_KEY");class Gh extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),K(this,Symbol.asyncIterator,void 0),K(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}K(Gh,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class Hh extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),K(this,"code","ERR_JWKS_TIMEOUT")}}K(Hh,"code","ERR_JWKS_TIMEOUT");class zh extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),K(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}K(zh,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");var ka;(function(n){n[n.Reserved=0]="Reserved",n[n.TooLarge=1]="TooLarge"})(ka||(ka={}));var Sa;(function(n){n[n.TooShort=0]="TooShort",n[n.HeaderOverrun=1]="HeaderOverrun",n[n.MissingExtWords=2]="MissingExtWords",n[n.UnsupportedVersion=3]="UnsupportedVersion",n[n.InvalidHandle=4]="InvalidHandle",n[n.MalformedExt=5]="MalformedExt"})(Sa||(Sa={}));var Ca;(function(n){n[n.TooSmallForHeader=0]="TooSmallForHeader",n[n.TooSmallForPayload=1]="TooSmallForPayload"})(Ca||(Ca={}));var Ai;(function(n){n[n.UserTimestamp=2]="UserTimestamp",n[n.E2ee=1]="E2ee"})(Ai||(Ai={})),Ai.UserTimestamp,Ai.E2ee;var Ea;(function(n){n[n.Start=0]="Start",n[n.Inter=1]="Inter",n[n.Final=2]="Final",n[n.Single=3]="Single"})(Ea||(Ea={}));class Jh extends G{constructor(e){super(),this._room=null,this._context=e,this._trackRegistry=new Tc,this._eventAdapter=new _c(e,this._trackRegistry),this._maxAttempts=e.options.reconnect?.maxAttempts||It,this._maxDelay=(e.options.reconnect?.delay??Ni)*Dt,m.info("LiveKit Service created")}async connect(e,t,i,s){if(this.ensureNotDisposed(),this._room&&this._room.isConnected()){m.warn("Already connected to LiveKit room");return}try{m.info(`Connecting to LiveKit room: ${i} at ${e}`);const r=new Pt({reconnectPolicy:{nextRetryDelayInMs:a=>a.elapsedMs<this._maxDelay?Math.min(Dt*Math.pow(2,a.retryCount),this._maxDelay):null}});r.prepareConnection(e,t),r.on(E.TrackSubscribed,(a,o,c)=>{this._handleTrackSubscribed(a,o,c)}),r.on(E.TrackUnsubscribed,(a,o,c)=>{this._handleTrackUnsubscribed(a,o,c)}),r.on(E.TrackMuted,(a,o)=>{this._handleTrackMuted(a,o)}),r.on(E.TrackUnmuted,(a,o)=>{this._handleTrackUnmuted(a,o)}),r.on(E.Connected,()=>{m.info("Connected to LiveKit room"),this._context.eventBus.emit("inner:rtc:connected",void 0)}),r.on(E.Disconnected,a=>{a?m.info(`LiveKit room disconnected: ${a}`):m.info("LiveKit room disconnected"),a!==ke.CLIENT_INITIATED&&this._context.eventBus.emit("inner:rtc:disconnected",{reason:a?String(a):void 0}),this._room=null}),m.info("Connecting to LiveKit room..."),await r.connect(e,t,{autoSubscribe:!0,maxRetries:this._context.options.reconnect?.maxAttempts||It}),this._eventAdapter.setRoom(r),this._room=r}catch(r){throw H.fromError(r,B.LIVEKIT_CONNECT_FAILED)}}_handleTrackSubscribed(e,t,i){try{if(!e.mediaStreamTrack){m.warn("Track does not have MediaStreamTrack");return}e.kind==="audio"&&i.on(I.IsSpeakingChanged,o=>{console.log("\u8F68\u9053 \u8BF4\u8BDD\u72B6\u6001:",o)});const r=t.trackSid,a=i.identity;this._eventAdapter.handleTrackSubscribed(e,r,a)}catch(s){m.error("Error handling track subscribed:",s)}}_handleTrackUnsubscribed(e,t,i){try{const s=t,r=i,a=s.trackSid,o=r.identity;this._trackRegistry.getTrack(a)?.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:unavailable",void 0),this._eventAdapter.handleTrackUnsubscribed(a,o)}catch(s){m.error("Error handling track unsubscribed:",s)}}_handleTrackMuted(e,t){try{e.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:unavailable",void 0)}catch(i){m.error("Error handling track muted:",i)}}_handleTrackUnmuted(e,t){try{e.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:available",void 0)}catch(i){m.error("Error handling track unmuted:",i)}}async disconnect(){if(this._room)try{await this._room.disconnect(),this._room=null,this._context.eventBus.emit("inner:rtc:disconnected",{reason:"Disconnected from LiveKit room"}),m.info("Disconnected from LiveKit room")}catch(e){m.error("Error disconnecting from LiveKit room:",e),this._room=null}}isConnected(){return this._room?this._room.state===J.Connected:!1}getTrackRegistry(){return this._trackRegistry}get trackRegistry(){return this._trackRegistry}getEventAdapter(){return this._eventAdapter}onDispose(){this.disconnect(),this._trackRegistry.dispose(),this._eventAdapter.dispose(),m.info("LiveKit Service disposed")}}class $h extends G{constructor(e){super(),this._conversationManager=null,this._context=e,m.info("WebSocket Dispatcher created")}setConversationManager(e){this._conversationManager=e,m.debug("Conversation manager set in dispatcher")}dispatch(e){this.ensureNotDisposed();try{if(e.type==="ws"){this._handleWSServerMessage(e);return}if(e.type==="text"){this._handleServerTextMessage(e);return}}catch(t){m.error("Error dispatching message:",t)}}_handleWSServerMessage(e){e.code===101?(this._conversationManager?.handleServerPong(),m.debug("Received pingpong response")):e.code===102&&(m.warn("Server will disconnect"),this._conversationManager?.willDisconnect())}_handleServerTextMessage(e){if(!this._conversationManager){m.warn("Conversation manager not set, text message ignored");return}const{uid:t,payload:i,code:s}=e;s===200?(this._conversationManager.handleAnswerChunk(t,i,!1),m.debug(`Answer received (code 401) for uid: ${t}`)):s===201?(this._conversationManager.handleAnswerChunk(t,"",!0),m.debug(`Answer completed (code 411) for uid: ${t}`)):s===300?(this._conversationManager.handleAsrTextReceived(t,i),m.debug(`ASR text chunk received (code 410) for uid: ${t}`)):s===400&&(this._conversationManager.handleServerInitiatedMessage(t,i),m.debug(`Server initiated message received (code 412) for uid: ${t}`))}onDispose(){m.info("WebSocket Dispatcher disposed")}}class Qh extends G{constructor(e){super(),this._ws=null,this._dispatcher=null,this._isConnecting=!1,this._activeTimers=new Set,this._retryCount=0,this._maxRetries=It,this._pingTimer=void 0,this._pongTimer=void 0,this._isExplicitDisconnect=!1,this._context=e,this._maxRetries=e.options.reconnect?.maxAttempts??It,this._maxDelay=(e.options.reconnect?.delay??Ni)*Dt,this._dispatcher=new $h(e)}setConversationManager(e){this._dispatcher&&this._dispatcher.setConversationManager(e)}async connect(){if(this.ensureNotDisposed(),this._stopHeartbeat(),!(this._isConnecting||this.isConnected||this._ws?.readyState===WebSocket.OPEN)){this._isConnecting=!0,this._isExplicitDisconnect=!1;try{return this._ws=new WebSocket(this._context.wsUrl),new Promise((e,t)=>{this._ws.onopen=()=>{this._isConnecting=!1,this._retryCount=0,this.sendPing(),this._context.eventBus.emit("inner:ws:connected",void 0),m.info("Conversation transport connected"),e()},this._ws.onerror=i=>{this._isConnecting=!1,m.error("Conversation transport error:",i),this._context.eventBus.emit("inner:sdk:error",{error:new H("WebSocket connection error",B.WS_CONNECT_ERROR,i)}),t(new H("WebSocket connection error",B.WS_CONNECT_ERROR,i))},this._ws.onclose=i=>{const s=i.code,r=i.reason?i.reason:i.wasClean?"Clean close":"Closed by remote";this._handleDisconnect(s,r)},this._ws.onmessage=i=>{this._handleMessage(i.data)}})}catch(e){throw this._isConnecting=!1,this._context.emitError(e,B.WS_CONNECT_FAILED)}}}disconnect(){this._isExplicitDisconnect=!0,this._stopHeartbeat(),this._ws&&(this._ws.close(),this._ws=null),this._context.eventBus.emit("inner:ws:disconnected",{reason:"Client disconnect"}),m.info("Conversation transport disconnected")}_handleDisconnect(e,t){if(this._stopHeartbeat(),this._isConnecting=!1,e!==void 0&&new Set([1e3,1001,1002,1003,1007,1008]).has(e)){this._isExplicitDisconnect=!0;const s=`WebSocket closed (code ${e}): ${t??""}`;this._context.eventBus.emit("inner:ws:disconnected",{reason:s}),m.info(`Conversation transport closed with non-retry code ${e}: ${t??""}`);return}if(!this._isExplicitDisconnect&&this._retryCount<this._maxRetries){this._retryCount++;const s=Math.min(Dt*Math.pow(2,this._retryCount-1),this._maxDelay);m.warn(`Connection lost. Retry ${this._retryCount} in ${s}ms`);const r=setTimeout(()=>{!this._isExplicitDisconnect&&!this.isDisposed&&this.connect().catch(()=>{})},s);this._registerTimer(r)}else this._context.eventBus.emit("inner:ws:disconnected",{reason:"Closed"})}_registerTimer(e){return this._activeTimers.add(e),e}_clearTimer(e){e&&(clearTimeout(e),this._activeTimers.delete(e))}sendPing(){if(!this.isConnected)return;const e={type:"ws",code:101,payload:"ping"};this._ws?.send(JSON.stringify(e)),clearTimeout(this._pongTimer),this._pongTimer=setTimeout(()=>{m.error(`Pong timeout (${hs/Dt}s). Reconnecting...`),this._ws?.close()},hs)}handlePongReceived(){clearTimeout(this._pongTimer),this._clearTimer(this._pingTimer),this._pingTimer=setTimeout(()=>{this.sendPing()},Na)}willDisconnect(){if(this.ensureNotDisposed(),this._ws&&this._ws.readyState===WebSocket.OPEN){const t=JSON.stringify({type:"ws",code:102,payload:"will disconnect"});this._ws.send(t),this._isExplicitDisconnect=!0,this._ws.close(),this._ws=null,this._context.eventBus.emit("inner:ws:disconnected",{reason:"Client responsive to server's disconnect message."})}}sendText(e,t,i=200,s){if(this.ensureNotDisposed(),!this._ws||this._ws.readyState!==WebSocket.OPEN)throw new H("WebSocket is not connected",B.WS_NOT_CONNECTED);try{const a=JSON.stringify({type:"text",code:i,uid:e,metadata:s,payload:t});this._ws.send(a),m.debug("Text message sent via transport:",e)}catch(r){throw this._context.emitError(r,B.WS_TEXT_SEND_FAILED)}}_handleMessage(e){try{if(typeof e!="string")return;const t=JSON.parse(e);m.debug("Message received:",t.type),this._dispatcher?this._dispatcher.dispatch(t):m.warn("Dispatcher not set, message ignored")}catch(t){m.error("Error parsing message:",t),this._context.emitError(t,B.WS_PARSE_ERROR)}}sendBinary(e){if(this.ensureNotDisposed(),!this._ws||this._ws.readyState!==WebSocket.OPEN){m.debug("WebSocket not connected, binary data dropped");return}try{this._ws.send(e),m.debug("Binary data sent via transport")}catch(t){m.error("Error sending binary data:",t)}}get isConnected(){return this._ws?.readyState===WebSocket.OPEN}_stopHeartbeat(){this._clearTimer(this._pingTimer),this._clearTimer(this._pongTimer)}onDispose(){this._stopHeartbeat(),this.disconnect(),this._dispatcher&&(this._dispatcher.dispose(),this._dispatcher=null),m.info("Conversation transport disposed")}}const Oi=["sdk:connected","sdk:disconnected","sdk:error","media:video:available","media:video:unavailable","media:video:trackAdded","media:video:trackRemoved","media:audio:trackAdded","media:audio:trackRemoved","media:audio:captureStarted","media:audio:captureStopped","media:audio:volumeChanged","media:audio:muted","media:audio:unmuted","conversation:question:sent","conversation:answer:waiting","conversation:server:message","conversation:asr:received","conversation:answer:chunk","conversation:answer:completed"],Ra=/^[a-z]+:[a-zA-z]+(:[a-zA-Z]+)?$/;class Yh{constructor(e){this.inner=e,this.listeners=new Map,this.forwardedVideoTrackIds=new Set,this.wsConnected=!1,this.livekitConnected=!1,this.httpConnected=!1,this.internalMap={"inner:sdk:error":{public:"sdk:error",sanitizer:t=>({message:t?.error?.message,code:t?.error?.code})},"inner:rtc:video:available":{public:"media:video:available"},"inner:rtc:video:unavailable":{public:"media:video:unavailable"},"inner:video:track:added":{public:"media:video:trackAdded"},"inner:video:track:removed":{public:"media:video:trackRemoved"},"inner:audio:track:added":{public:"media:audio:trackAdded"},"inner:audio:track:removed":{public:"media:audio:trackRemoved"},"inner:audio:input:started":{public:"media:audio:captureStarted"},"inner:audio:input:stopped":{public:"media:audio:captureStopped"},"inner:audio:volume:changed":{public:"media:audio:volumeChanged",sanitizer:t=>({volume:t?.volume})},"inner:audio:muted":{public:"media:audio:muted"},"inner:audio:unmuted":{public:"media:audio:unmuted"},"inner:conversation:question:sent":{public:"conversation:question:sent",sanitizer:t=>({questionId:t?.questionId,text:String(t?.text||"")})},"inner:conversation:answer:waiting":{public:"conversation:answer:waiting",sanitizer:t=>({questionId:t?.questionId})},"inner:conversation:server:message":{public:"conversation:server:message",sanitizer:t=>({questionId:t?.questionId,message:String(t?.message||""),type:String(t?.type||"")})},"inner:conversation:asr:received":{public:"conversation:asr:received",sanitizer:t=>({questionId:t?.questionId,text:String(t?.text||"")})},"inner:conversation:answer:chunk":{public:"conversation:answer:chunk",sanitizer:t=>({questionId:t?.questionId,chunk:String(t?.chunk||"")})},"inner:conversation:answer:completed":{public:"conversation:answer:completed",sanitizer:t=>({questionId:t?.questionId,fullAnswer:String(t?.fullAnswer||"")})}},Object.keys(this.internalMap).forEach(t=>{this.inner.on(t,i=>this.handleInternalEvent(t,i))}),this.inner.on("inner:sdk:connected",t=>this.handleConnected(t,!0)),this.inner.on("inner:sdk:disconnected",t=>this.handleConnected(t,!1)),Oi.forEach(t=>{this.inner.on(t,i=>this.handlePublicEvent(t,i))})}publicAPI(){return{on:this.on.bind(this),off:this.off.bind(this),once:this.once.bind(this)}}on(e,t){const i=String(e);return this.assertAllowed(i),this.listeners.has(i)||this.listeners.set(i,new Set),this.listeners.get(i).add(t),()=>this.off(e,t)}once(e,t){const i=String(e);this.assertAllowed(i);const s=r=>{try{t(r)}finally{this.off(e,s)}};return this.on(e,s)}off(e,t){const i=String(e);this.assertAllowed(i);const s=this.listeners.get(i);s&&(s.delete(t),s.size===0&&this.listeners.delete(i))}handleInternalEvent(e,t){const i=this.internalMap[e];if(!i)return;const s=i.public;if(Oi.indexOf(s)===-1)return;if(s==="media:video:trackAdded"){const o=t?.trackId||t?.id;if(typeof o=="string"){if(this.forwardedVideoTrackIds.has(o))return;this.forwardedVideoTrackIds.add(o)}}const r=i.sanitizer?i.sanitizer(t):t;if(!Ra.test(s))return;const a=this.listeners.get(s);!a||a.size===0||a.forEach(o=>{try{o(r)}catch(c){console.error("PublicEventEmitter listener error",c)}})}handlePublicEvent(e,t){if(Oi.indexOf(e)===-1)return;const i=Object.values(this.internalMap).find(a=>a.public===e),s=i&&i.sanitizer?i.sanitizer(t):t;if(e==="media:video:trackAdded"){const a=t?.trackId||t?.id;if(typeof a=="string"){if(this.forwardedVideoTrackIds.has(a))return;this.forwardedVideoTrackIds.add(a)}}const r=this.listeners.get(e);!r||r.size===0||r.forEach(a=>{try{a(s)}catch(o){console.error("PublicEventEmitter listener error",o)}})}handleConnected(e,t){e.source==="livekit"?this.livekitConnected=t:e.source==="ws"?this.wsConnected=t:e.source==="http"&&(this.httpConnected=t),this.maybeEmitSdkConnected(t?"connected":"disconnected")}maybeEmitSdkConnected(e){const t=e==="connected",i=t?!!this.livekitConnected:!this.livekitConnected,s=t?!!this.wsConnected:!this.wsConnected,r=t?!!this.httpConnected:!this.httpConnected,a={livekit:i,ws:s,http:r,all:i&&s&&r},o=JSON.stringify(a);this.lastConnectedPayloadJson!==o&&(this.lastConnectedPayloadJson=o,this.inner.emit(`sdk:${e}`,a))}assertAllowed(e){if(Oi.indexOf(e)===-1)throw new Error(`Event "${e}" is not allowed for public consumers`);if(!Ra.test(e))throw new Error(`Event name "${e}" does not follow namespace:domain[:action] naming`)}}class Xh extends G{constructor(e,t,i){super(),this._requestCounter=0,this._context=e,this._baseURL=t||"",this._defaultHeaders=i||{},m.info(`HTTP Service created with baseURL: ${this._baseURL||"none"}`)}setAuthToken(e){this._defaultHeaders.Authorization=`Bearer ${e}`}request(e){this.ensureNotDisposed();const t=e.requestId||`req_${Date.now()}_${++this._requestCounter}`,i=this._buildURL(e.url,e.params),s=this._mergeHeaders(e.headers),r={method:e.method||"GET",headers:s};e.data!==void 0&&(e.method||"GET")!=="GET"&&(typeof e.data=="string"?r.body=e.data:(r.body=JSON.stringify(e.data),!s["Content-Type"]&&!s["content-type"]&&(s["Content-Type"]="application/json")));const a=e.timeout||3e4,o=new AbortController;return r.signal=o.signal,new Promise((c,d)=>{const l=setTimeout(()=>o.abort(),a);fetch(i,r).then(async u=>{clearTimeout(l);const h={};u.headers.forEach((R,_)=>{h[_]=R});let f;const b=u.headers.get("content-type");b&&b.includes("application/json")?f=await u.json():f=await u.text();const v={requestId:t,status:u.status,headers:h,data:f,config:e};m.debug(`HTTP request succeeded: ${e.method} ${i} [${t}]`),c(v)}).catch(u=>{clearTimeout(l);const h=u&&u.name==="AbortError",f={requestId:t,status:u&&u.status||void 0,message:h?"Request aborted (timeout)":u&&u.message||"HTTP request failed",error:u,config:e};m.error(`HTTP request failed: ${e.method} ${i} [${t}]`,u),d(f)})})}get(e,t,i){return this.request({...i,url:e,method:"GET",params:t})}post(e,t,i){return this.request({...i,url:e,method:"POST",data:t})}put(e,t,i){return this.request({...i,url:e,method:"PUT",data:t})}delete(e,t){return this.request({...t,url:e,method:"DELETE"})}patch(e,t,i){return this.request({...i,url:e,method:"PATCH",data:t})}_buildURL(e,t){if(e.startsWith("http://")||e.startsWith("https://"))return this._appendParams(e,t);let i=this._baseURL;return i&&!i.endsWith("/")&&!e.startsWith("/")?i+="/":i&&i.endsWith("/")&&e.startsWith("/")&&(i=i.slice(0,-1)),i+=e,this._appendParams(i,t)}_appendParams(e,t){if(!t||Object.keys(t).length===0)return e;const i=new URLSearchParams;for(const[r,a]of Object.entries(t))i.append(r,String(a));const s=e.includes("?")?"&":"?";return`${e}${s}${i.toString()}`}_mergeHeaders(e){const t={...this._defaultHeaders};return e&&Object.assign(t,e),t}onDispose(){m.info("HTTP Service disposed")}}function Zh(n,e="https"){return n.startsWith(e)?n:`${e}://${n}`}class ep extends G{constructor(e,t){super(),this._context=e,this._httpService=new Xh(e,t||La)}getAuthToken(){return this.ensureNotDisposed(),this._httpService?.request({url:"/auth/login",method:"GET",data:{}}).then(e=>{e.data.code===At&&this._httpService?.setAuthToken(e.data.data.token)}).catch(e=>{throw this._context.emitError(e,B.SDK_AUTH_TOKEN_FAILED)})}getLivekitConfig(){return this.ensureNotDisposed(),this._httpService?.request({url:"/stream/v1/start",method:"POST",data:{avatarName:this._context.options.avatarName,voice:this._context.options.avatarVoice||""}}).then(e=>{if(e.data.code===At){const t=e.data.data;return this._context.setLivekitConfig(Zh(t.livekitUrl,"wss"),t.roomToken,t.roomId),this._context.setWsUrl(`${this._context.options.wsUrlPrefix||Fa}/${t.roomId}/${this._context.options.avatarName}`),this._context.setVideoOptions({renderMode:t.greenScreen.enabled?"processed":"raw",greenScreen:t.greenScreen||{}}),this._context.eventBus.emit("inner:sdk:connected",{source:"http"}),!0}else throw new H(e.data.msg,B.SDK_GET_LIVEKIT_CONFIG_FAILED)}).catch(e=>{throw this._context.eventBus.emit("inner:sdk:error",{error:new H(e.message,B.SDK_GET_LIVEKIT_CONFIG_FAILED)}),H.fromError(e,B.SDK_GET_LIVEKIT_CONFIG_FAILED)})}switchVideo({onceActions:e,loopActions:t}){return this.ensureNotDisposed(),this._httpService?.request({url:"/avatar/v1/switch-video",method:"POST",data:{roomId:this._context.roomId,onceActions:e,loopActions:t}}).then(i=>{if(i.data.code===At)return!0;throw this._context.emitError(i.data.message,B.SDK_SWITCH_VIDEO_FAILED)})}interruptConversation(){return this.ensureNotDisposed(),this._httpService?.request({url:"/stream/v1/interrupt",method:"POST",data:{roomId:this._context.roomId}}).then(e=>{if(e.data.code===At)return!0;throw this._context.emitError(e.data.message,B.SDK_INTERRUPT_CONVERSATION_FAILED)}).finally(()=>{this._context.eventBus.emit("inner:sdk:disconnected",{source:"http"})})}disconnectConversation(){return this.ensureNotDisposed(),this._httpService?.request({url:"/stream/v1/stop",method:"POST",data:{roomId:this._context.roomId}}).then(e=>e.data.code===At).finally(()=>{this._context.eventBus.emit("inner:sdk:disconnected",{source:"http"})})}onDispose(){this._httpService.dispose()}}class wa extends G{constructor(e){super(),this._videoController=null,this._audioController=null,this._conversationController=null,this._liveKitService=null,this._conversationTransport=null,this._connectionCoordinator=null,this._httpController=null,this._preConnectPromise=null,this._lastPreConnectSuccessAt=null,this._context=new Va(e),m.info("SDK Client created")}get events(){return this.ensureNotDisposed(),this._publicEventAPI||(this._publicEmitter=new Yh(this._context.eventBus),this._publicEventAPI=this._publicEmitter.publicAPI()),this._publicEventAPI}pushActions({onceActions:e,loopActions:t}){return this.ensureNotDisposed(),this._ensureConnected(),this._httpController?.switchVideo({onceActions:e,loopActions:t})}interruptConnection(){return this.ensureNotDisposed(),this._ensureConnected(),this._httpController?.interruptConversation()}sendTextQuestion(e){if(this.ensureNotDisposed(),this._ensureConnected(),this._conversationController)return this._conversationController.sendQuestion(e);throw new H("Conversation controller is not available",B.CONVERSATION_CONTROLLER_NOT_AVAILABLE)}setRenderFitMode(e){this.ensureNotDisposed(),this._ensureConnected(),this._videoController&&this._videoController.setRenderFitMode(e)}async startAudioCapture(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);await this._audioController.startCapture()}async stopAudioCapture(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);await this._audioController.stopCapture()}setVolume(e){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);this._audioController.setVolume(e)}getVolume(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);return this._audioController?.getVolume()||1}mute(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);this._audioController.mute()}unmute(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);this._audioController.unmute()}get isMuted(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new H("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);return this._audioController.isMuted()}get isAudioCapturing(){return this.ensureNotDisposed(),this._ensureConnected(),this._audioController?this._audioController.isCapturing:!1}async preConnect(){if(this.ensureNotDisposed(),this._preConnectPromise)return this._preConnectPromise;const e=Date.now();return this._lastPreConnectSuccessAt!==null&&e-this._lastPreConnectSuccessAt<Ba?Promise.resolve(!0):(this._preConnectPromise=(async()=>{try{if(m.info("Creating HTTP controller..."),this._httpController=this._httpController??new ep(this._context,this._context.options.http?.baseURL),m.info("Getting auth token..."),await this._httpController.getAuthToken(),m.info("Getting livekit config..."),!!!await this._httpController?.getLivekitConfig())throw new Error("Config missing");return this._lastPreConnectSuccessAt=Date.now(),!0}catch(t){throw this._context.emitError(t,B.SDK_PRECONNECT_FAILED)}finally{this._preConnectPromise=null}})(),this._preConnectPromise)}async connect(){if(this.ensureNotDisposed(),this._connectionCoordinator&&this._context.sessionState.isConnected){m.warn("SDK already initialized");return}try{if(!await this.preConnect())throw new H("PreConnect failed without explicit error",B.SDK_CONNECT_FAILED)}catch(e){throw this._context.emitError(e,B.SDK_CONNECT_FAILED)}try{if(m.info("Initializing SDK..."),this._connectionCoordinator=new qa(this._context),this._connectionCoordinator.start(),this._connectionCoordinator.startConnecting(),this._videoController=new Ja(this._context,this._context.options.video),this._audioController=new mc(this._context,this._context.options.audio),this._conversationController=new yc(this._context),this._liveKitService=new Jh(this._context),this._conversationTransport=new Qh(this._context),this._liveKitService&&this._videoController&&this._audioController){const e=this._liveKitService.getEventAdapter();e&&(typeof e.setVideoController=="function"&&e.setVideoController(this._videoController),typeof e.setAudioController=="function"&&e.setAudioController(this._audioController))}this._audioController&&this._conversationTransport&&this._audioController.setWebSocketSender({sendBinary:e=>{this._conversationTransport.sendBinary(e)},isConnected:()=>this._conversationTransport.isConnected}),this._conversationTransport&&this._conversationController&&(this._conversationTransport.setConversationManager(this._conversationController.manager),this._conversationController.setTransport(this._conversationTransport)),await this._liveKitService.connect(this._context.livekitUrl,this._context.token,this._context.options.avatarName),this._conversationTransport&&await this._conversationTransport.connect(),m.info("SDK initialized and connected")}catch(e){throw this._connectionCoordinator&&this._connectionCoordinator.transitionToIdle(),await this._cleanup(),this._context.emitError(e,B.SDK_INITIALIZATION_FAILED)}}async disconnect(){if(this.ensureNotDisposed(),!(!this._connectionCoordinator||this._connectionCoordinator.getState()==="idle"||this._connectionCoordinator.getState()==="disposed")){m.info("Disconnecting SDK..."),this._connectionCoordinator.startDisconnecting();try{this._conversationTransport&&this._conversationTransport.disconnect(),this._liveKitService&&await this._liveKitService.disconnect(),this._audioController&&this._audioController.stopCapture(),this._httpController&&await this._httpController.disconnectConversation(),this._preConnectPromise=null,this._connectionCoordinator.completeDisconnecting(),m.info("SDK disconnected")}catch(e){throw m.error("Error during disconnect:",e),this._context.emitError(e,B.SDK_DISCONNECT_FAILED)}}}async reconnect(){this.ensureNotDisposed();const e=this._connectionCoordinator;if(!e?.canStartReconnectingManual()){const i=e?e.getSnapshot():this.connectionSnapshot;return m.warn("SDK reconnect not allowed in current state, returning current snapshot"),i}const t=e.captureSnapshotAndStartReconnectingManual();try{if(this._audioController&&this._audioController.stopCapture(),t.rtc.connected&&!t.rtc.hasVideoTrack&&(await this._liveKitService?.disconnect(),await this._conversationTransport?.disconnect()),this._conversationTransport&&!this._conversationTransport.isConnected){if(!await this.preConnect())throw new H("PreConnect failed without explicit error",B.SDK_CONNECT_FAILED);await this._conversationTransport.connect()}return this._liveKitService&&!this._liveKitService.isConnected()&&await this._liveKitService.connect(this._context.livekitUrl,this._context.token,this._context.options.avatarName),t}catch(i){throw m.error("Error during reconnect:",i),this._context.emitError(i,B.SDK_RECONNECT_FAILED)}}get connectionSnapshot(){return this.ensureNotDisposed(),this._connectionCoordinator?this._connectionCoordinator.getSnapshot():fs(ms("idle"))}async _cleanup(){if(this._conversationTransport&&this._conversationTransport.disconnect(),this._liveKitService)try{await this._liveKitService.disconnect()}catch(e){m.error("Error disconnecting LiveKit:",e)}this._audioController&&this._audioController.stopCapture()}get isConnected(){return this.ensureNotDisposed(),this._context.sessionState.isConnected}_ensureConnected(){if(!this._context.sessionState.isConnected)throw new H("SDK is not connected. Call connect() first.",B.SDK_NOT_CONNECTED)}onDispose(){this.disconnect().catch(e=>{m.error("Error during disconnect in dispose:",e)}),this._videoController&&(this._videoController.dispose(),this._videoController=null),this._audioController&&(this._audioController.dispose(),this._audioController=null),this._conversationController&&(this._conversationController.dispose(),this._conversationController=null),this._liveKitService&&(this._liveKitService.dispose(),this._liveKitService=null),this._conversationTransport&&(this._conversationTransport.dispose(),this._conversationTransport=null),this._httpController&&(this._httpController.dispose(),this._httpController=null),this._connectionCoordinator&&(this._connectionCoordinator.transitionToDisposed(),this._connectionCoordinator.dispose(),this._connectionCoordinator=null),this._context.dispose(),m.info("SDK Client disposed")}}function tp(n){if(!n.avatarName)throw new H("avatarName is required",B.NO_AVATARNAME);return m.info("Creating SDK client with options:",{avatarName:n.avatarName}),new wa(n)}class Pa extends G{constructor(e,t){super(),this._videoElement=null,this._videoUrl=null,this._isPlaying=!1,this._frameCallbackId=null,this._videoUrl=e,t?this._videoElement=t:(this._videoElement=document.createElement("video"),this._videoElement.style.opacity="0",this._videoElement.muted=!0,this._videoElement.playsInline=!0,this._videoElement.loop=!0,document.querySelector("#video-container")?.appendChild(this._videoElement)),m.info("Local Video Debug Source created")}get videoElement(){return this._videoElement}async load(){if(!this._videoElement)throw new Error("Video element or URL not set");return new Promise((e,t)=>{const i=this._videoElement,s=()=>{i.removeEventListener("loadedmetadata",s),i.removeEventListener("error",r),m.info(`Video loaded: ${i.videoWidth}x${i.videoHeight}`),e()},r=a=>{i.removeEventListener("loadedmetadata",s),i.removeEventListener("error",r),t(new Error(`Failed to load video: ${a}`))};i.addEventListener("loadedmetadata",s),i.addEventListener("error",r),i.src=this._videoUrl||"",i.load()})}async play(){if(!this._videoElement)throw new Error("Video element not set");if(!this._isPlaying)try{await this._videoElement.play(),this._videoElement.style.opacity="0",this._videoElement.setAttribute("loop","true"),this._isPlaying=!0,m.info("Video playback started")}catch(e){throw m.error("Failed to play video:",e),e}}pause(){this._videoElement&&this._isPlaying&&(this._videoElement.pause(),this._isPlaying=!1,m.info("Video playback paused"))}stop(){this._videoElement&&(this._videoElement.pause(),this._videoElement.currentTime=0,this._isPlaying=!1,m.info("Video playback stopped"))}get isPlaying(){return this._isPlaying&&this._videoElement!==null&&!this._videoElement.paused}get videoWidth(){return this._videoElement?.videoWidth||0}get videoHeight(){return this._videoElement?.videoHeight||0}async captureFrame(){if(!this._videoElement||this._videoElement.readyState<2)return null;try{if("VideoFrame"in window&&typeof window.VideoFrame=="function")try{return new VideoFrame(this._videoElement,{timestamp:this._videoElement.currentTime*1e6})}catch(i){m.error("",i)}const e=await createImageBitmap(this._videoElement),t=new VideoFrame(e,{timestamp:this._videoElement.currentTime*1e6});return e.close(),t}catch(e){return m.error("Failed to capture video frame:",e),null}}onFrame(e){if(!this._videoElement)return;this.offFrame();const t=this._videoElement;if("requestVideoFrameCallback"in t){const i=(s,r)=>{!this._isPlaying||!this._videoElement||this.captureFrame().then(a=>{a&&(e(a),a.close()),this._isPlaying&&this._videoElement&&(this._frameCallbackId=t.requestVideoFrameCallback(i))}).catch(a=>{m.error("Error in frame callback:",a)})};this._frameCallbackId=t.requestVideoFrameCallback(i)}else{const i=()=>{!this._isPlaying||!this._videoElement||this.captureFrame().then(s=>{s&&(e(s),s.close()),this._isPlaying&&this._videoElement&&(this._frameCallbackId=requestAnimationFrame(i))}).catch(s=>{m.error("Error in frame callback:",s)})};this._frameCallbackId=requestAnimationFrame(i)}}offFrame(){this._frameCallbackId!==null&&(this._videoElement&&"cancelVideoFrameCallback"in this._videoElement?this._videoElement.cancelVideoFrameCallback(this._frameCallbackId):cancelAnimationFrame(this._frameCallbackId),this._frameCallbackId=null)}onDispose(){this.stop(),this.offFrame(),this._videoElement&&this._videoElement.parentElement===document.body&&document.body.removeChild(this._videoElement),this._videoElement=null,this._videoUrl=null,m.info("Local Video Debug Source disposed")}}class ip extends G{constructor(e,t,i){super(),this._outputCanvas=null,this._outputRenderer=null,this._source=new vs;const s={...e,renderMode:"processed"};this._pipeline=new Ts(this._source,s),this._outputRenderer=new Mi(i,t),this._pipeline.setRenderer(this._outputRenderer),this._outputCanvas=this._outputRenderer.getCanvas(),m.info("Video Pipeline Runner created")}get outputCanvas(){return this._outputCanvas}get processor(){return this._pipeline.strategy.getProcessors()[0]||null}setProcessor(e){this._pipeline.setProcessor(e),m.info("Processor set on pipeline")}async processFrame(e){if(this.ensureNotDisposed(),!this._outputRenderer){m.error("Output renderer not available"),e.close();return}try{const t=this._pipeline.strategy.getProcessors()[0]||null;let i=null;if(t){try{i=t.process(e)}catch(s){m.error("Error processing frame:",s),i=e}if(i===null&&"getImageData"in t){const s=t.getImageData();if(s&&this._outputCanvas&&this._outputRenderer.getContext()){const r=this._outputRenderer.getContext();r&&((this._outputCanvas.width!==s.width||this._outputCanvas.height!==s.height)&&(this._outputCanvas.width=s.width,this._outputCanvas.height=s.height),r.putImageData(s,0,0))}e.close();return}i&&i!==e?(this._outputRenderer.render(i),e.close()):i===e?this._outputRenderer.render(e):e.close()}else this._outputRenderer.render(e)}catch(t){m.error("Error in processFrame:",t),e.close()}}setOutputSize(e,t){this._outputCanvas&&(this._outputCanvas.width=e,this._outputCanvas.height=t,m.info(`Output canvas size set to ${e}x${t}`))}onDispose(){this._pipeline.dispose(),this._outputRenderer&&(this._outputRenderer.dispose(),this._outputRenderer=null),this._outputCanvas&&this._outputCanvas.parentElement===document.body&&document.body.removeChild(this._outputCanvas),this._outputCanvas=null,m.info("Video Pipeline Runner disposed")}}class np extends G{constructor(e,t,i,s){if(super(),this._isRunning=!1,this._videoSource=new Pa(e,t),this._options={renderMode:"processed",containerElement:t,...s},this._pipelineRunner=new ip(this._options,t,i),this._options.greenScreen?.enabled){const r=new Li(this._options.greenScreen);this._pipelineRunner.setProcessor(r),m.info("Green screen processor enabled in debugger")}m.info("Standalone Video Debugger created")}async switchSource(e,t){this.ensureNotDisposed();const i=this._videoSource,s=this._isRunning,r=new Pa(e,t);try{await r.load(),s&&await r.play(),r.onFrame(c=>{this._pipelineRunner.processFrame(c).catch(d=>{m.error("Error processing frame:",d)})}),this._videoSource=r;try{i.offFrame(),i.stop(),i.dispose()}catch(c){console.warn("Error disposing old video source during switch:",c)}const a=this._videoSource.videoWidth,o=this._videoSource.videoHeight;a>0&&o>0&&this._pipelineRunner.setOutputSize(a,o)}catch(a){m.error("Failed to switch video source:",a);try{r.dispose()}catch(o){console.warn("Error disposing new video source after failed switch:",o)}throw a}}get outputCanvas(){return this._pipelineRunner.outputCanvas}get videoSource(){return this._videoSource}get processor(){return this._pipelineRunner.processor}setProcessor(e){this._pipelineRunner.setProcessor(e)}updateGreenScreenOptions(e){const t=this._pipelineRunner.processor;if(t&&"updateOptions"in t&&typeof t.updateOptions=="function")t.updateOptions(e),m.info("Green screen options updated");else{const i=this._options.greenScreen||{enabled:!1},s={...i,...e,enabled:e.enabled!==void 0?e.enabled:i.enabled},r=new Li(s);this._pipelineRunner.setProcessor(r),this._options.greenScreen=s,m.info("Green screen processor recreated with new options")}}async initialize(){this.ensureNotDisposed();try{await this._videoSource.load();const e=this._videoSource.videoWidth,t=this._videoSource.videoHeight;e>0&&t>0&&this._pipelineRunner.setOutputSize(e,t),m.info("Video debugger initialized")}catch(e){throw m.error("Failed to initialize video debugger:",e),e}}async start(){if(this.ensureNotDisposed(),this._isRunning){m.warn("Debugger is already running");return}try{this._videoSource.videoWidth===0&&await this.initialize(),await this._videoSource.play(),this._videoSource.onFrame(e=>{this._pipelineRunner.processFrame(e).catch(t=>{m.error("Error processing frame:",t)})}),this._isRunning=!0,m.info("Video debugger started")}catch(e){throw m.error("Failed to start video debugger:",e),e}}stop(){this._isRunning&&(this._videoSource.stop(),this._videoSource.offFrame(),this._isRunning=!1,m.info("Video debugger stopped"))}pause(){this._isRunning&&(this._videoSource.pause(),m.info("Video debugger paused"))}async resume(){this._isRunning&&(await this._videoSource.play(),m.info("Video debugger resumed"))}get isRunning(){return this._isRunning}onDispose(){this.stop(),this._videoSource.dispose(),this._pipelineRunner.dispose(),m.info("Standalone Video Debugger disposed")}}D.DEFAULT_AUDIO_BUFFER_SIZE=Ma,D.DEFAULT_AUDIO_CHANNELS=xa,D.DEFAULT_AUDIO_SAMPLE_RATE=xi,D.DEFAULT_RECONNECT_ATTEMPTS=It,D.DEFAULT_RECONNECT_DELAY=Ni,D.DEFAULT_WS_TIMEOUT=Oa,D.Disposable=G,D.EventBus=ls,D.Logger=m,D.SDKClient=wa,D.SDKError=H,D.SessionState=us,D.StandaloneVideoDebugger=np,D.createClient=tp}));
147
+ `},Kn}var ra;function $u(){if(ra)return De;ra=1;var n=zu(),e=Ju(),t=Wn();return De.grammar=t,De.write=e,De.parse=n.parse,De.parseParams=n.parseParams,De.parseFmtpConfig=n.parseFmtpConfig,De.parsePayloads=n.parsePayloads,De.parseRemoteCandidates=n.parseRemoteCandidates,De.parseImageAttributes=n.parseImageAttributes,De.parseSimulcastStreamList=n.parseSimulcastStreamList,De}var tt=$u();function Hn(n,e,t){var i,s,r;e===void 0&&(e=50),t===void 0&&(t={});var a=(i=t.isImmediate)!=null&&i,o=(s=t.callback)!=null&&s,c=t.maxWait,d=Date.now(),l=[];function u(){if(c!==void 0){var f=Date.now()-d;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),b=this;return new Promise(function(v,R){var T=a&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,d=Date.now(),!a){var x=n.apply(b,f);o&&o(x),l.forEach(function(y){return(0,y.resolve)(x)}),l=[]}},u()),T){var A=n.apply(b,f);return o&&o(A),v(A)}l.push({resolve:v,reject:R})})};return h.cancel=function(f){r!==void 0&&clearTimeout(r),l.forEach(function(b){return(0,b.reject)(f)}),l=[]},h}const Qu=.7,Yu=20,wt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class oa extends xe.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=V,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Hn(s=>p(this,void 0,void 0,function*(){this.emit(wt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),Yu),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=Ve((i=t.loggerName)!==null&&i!==void 0?i:Pe.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new he}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return p(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return p(this,void 0,void 0,function*(){var i;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let{stereoMids:r,nackMids:a}=Xu(e);this.remoteStereoMids=r,this.remoteNackMids=a}else if(e.type==="answer"){const r=tt.parse((i=e.sdp)!==null&&i!==void 0?i:"");r.media.forEach(a=>{const o=Gn(a.mid);a.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||o!=c.transceiver.mid)return!1;let d=0;if(a.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(d=u.payload,!0):!1),d===0)return!0;let l=!1;for(const u of a.fmtp)if(u.payload===d){u.config=u.config.split(";").filter(h=>!h.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(u.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),l=!0;break}return l||c.maxbr>0&&a.fmtp.push({payload:d,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),s=tt.write(r)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(wt.NegotiationComplete),e.sdp&&tt.parse(e.sdp).media.forEach(a=>{a.type==="video"&&this.emit(wt.RTPVideoPayloadTypes,a.rtp)})),!0})}createAndSendOffer(e){return p(this,void 0,void 0,function*(){var t;const i=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const o=this._pc.remoteDescription;if(e?.iceRestart&&o)yield this._pc.setRemoteDescription(o);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const s=this.latestOfferId+1;this.latestOfferId=s;const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const a=tt.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(a.media.forEach(o=>{ca(o),o.type==="audio"?aa(o,["all"],[]):o.type==="video"&&this.trackBitrates.some(c=>{if(!o.msid||!c.cid||!o.msid.includes(c.cid))return!1;let d=0;if(o.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(d=u.payload,!0):!1),d===0||(Ie(c.codec)&&!dt()&&this.ensureVideoDDExtensionForSVC(o,a),!Ie(c.codec)))return!0;const l=Math.round(c.maxbr*Qu);for(const u of o.fmtp)if(u.payload===d){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),this.latestOfferId>s){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:s}));return}yield this.setMungedSDP(r,tt.write(a)),this.onOffer(r,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=tt.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(s=>{ca(s),s.type==="audio"&&aa(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,tt.write(i)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new re("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new re("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return p(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,s=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),i.set(o.id,o);break;case"remote-candidate":s.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return s.get(a)})}setMungedSDP(e,t,i){return p(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const a={error:r,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new yt(r)}})}ensureVideoDDExtensionForSVC(e,t){var i,s;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===Bo))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var c;o.type==="video"&&((c=o.ext)===null||c===void 0||c.forEach(d=>{d.value>a&&(a=d.value)}))}),this.ddExtID=a+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:Bo})}}}function aa(n,e,t){const i=Gn(n.mid);let s=0;n.rtp.some(r=>r.codec==="opus"?(s=r.payload,!0):!1),s>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(i)&&!n.rtcpFb.some(r=>r.payload===s&&r.type==="nack")&&n.rtcpFb.push({payload:s,type:"nack"}),(e.includes(i)||e.length===1&&e[0]==="all")&&n.fmtp.some(r=>r.payload===s?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function Xu(n){var e;const t=[],i=[],s=tt.parse((e=n.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(a=>{var o;const c=Gn(a.mid);a.type==="audio"&&(a.rtp.some(d=>d.codec==="opus"?(r=d.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(d=>d.payload===r&&d.type==="nack")&&i.push(c),a.fmtp.some(d=>d.payload===r?(d.config.includes("sprop-stereo=1")&&t.push(c),!0):!1))}),{stereoMids:t,nackMids:i}}function ca(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}function Gn(n){return typeof n=="number"?n.toFixed(0):n}const zn="vp8",Zu={audioPreset:kn.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Cn.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:zn,backupCodec:!0,preConnectBuffer:!1},da={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},la={deviceId:{ideal:"default"},resolution:qt.h720.resolution},eh={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Ol,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Jn={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var te;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(te||(te={}));class th{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,i){var s;this.peerConnectionTimeout=Jn.peerConnectionTimeout,this.log=V,this.updateState=()=>{var r,a;const o=this.state,c=this.requiredTransports.map(d=>d.getConnectionState());c.every(d=>d==="connected")?this.state=te.CONNECTED:c.some(d=>d==="failed")?this.state=te.FAILED:c.some(d=>d==="connecting")?this.state=te.CONNECTING:c.every(d=>d==="closed")?this.state=te.CLOSED:c.some(d=>d==="closed")?this.state=te.CLOSING:c.every(d=>d==="new")&&(this.state=te.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(te[o]," to ").concat(te[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),(a=this.subscriber)===null||a===void 0?void 0:a.getConnectionState()))},this.log=Ve((s=i.loggerName)!==null&&s!==void 0?s:Pe.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=t!=="subscriber-primary",this.isSubscriberConnectionRequired=t==="subscriber-primary",this.publisher=new oa(e,i),this._mode=t,t!=="publisher-only"&&(this.subscriber=new oa(e,i),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,we.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,r)},this.subscriber.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,we.PUBLISHER)},this.publisher.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)},this.publisher.onOffer=(r,a)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,r,a)},this.state=te.NEW,this.connectionLock=new he,this.remoteOfferLock=new he}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return p(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const i of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(i)}catch(s){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:s}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return p(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return p(this,void 0,void 0,function*(){var i;t===we.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(i=this.subscriber)===null||i===void 0?void 0:i.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return p(this,void 0,void 0,function*(){var i,s,r;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(i=this.subscriber)===null||i===void 0?void 0:i.getSignallingState().toString()}));const a=yield this.remoteOfferLock.lock();try{return(yield(s=this.subscriber)===null||s===void 0?void 0:s.setRemoteDescription(e,t))?yield(r=this.subscriber)===null||r===void 0?void 0:r.createAndSetAnswer():void 0}finally{a()}})}updateConfiguration(e,t){var i;this.publisher.setConfiguration(e),(i=this.subscriber)===null||i===void 0||i.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return p(this,void 0,void 0,function*(){var i;const s=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return p(this,void 0,void 0,function*(){return new ue((t,i)=>p(this,void 0,void 0,function*(){const s=setTimeout(()=>{i(new yt("negotiation timed out"))},this.peerConnectionTimeout),r=()=>{clearTimeout(s),i(new yt("negotiation aborted"))};e.signal.addEventListener("abort",r),this.publisher.once(wt.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(wt.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(s),a instanceof Error?i(a):i(new Error(String(a)))})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){const i=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(s=>s.receiver===e);return i?.mid}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===we.PUBLISHER?this.publisher.getConnectedAddress():e===we.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(i.getConnectionState()!=="connected")return new Promise((c,d)=>p(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),de.clearTimeout(u),d(F.cancelled("room connection has been cancelled"))};s?.signal.aborted&&l(),s?.signal.addEventListener("abort",l);const u=de.setTimeout(()=>{s?.signal.removeEventListener("abort",l),d(F.internal("could not establish pc connection"))},a);for(;this.state!==te.CONNECTED;)if(yield le(50),s?.signal.aborted){d(F.cancelled("room connection has been cancelled"));return}de.clearTimeout(u),s?.signal.removeEventListener("abort",l),c()}))})()})}}const ua=5e3,ih=3e4;class z{static fetchRegionSettings(e,t,i){return p(this,void 0,void 0,function*(){const s=yield z.fetchLock.lock();try{const r=yield fetch("".concat(nh(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:i});if(r.ok){const a=Ru(r.headers),o=a?a*1e3:ua;return{regionSettings:yield r.json(),updatedAtInMs:Date.now(),maxAgeInMs:o}}else throw r.status===401?F.notAllowed("Could not fetch region settings: ".concat(r.statusText),r.status):F.internal("Could not fetch region settings: ".concat(r.statusText))}catch(r){throw r instanceof F?r:i?.aborted?F.cancelled("Region fetching was aborted"):F.serverUnreachable("Could not fetch region settings, ".concat(r instanceof Error?"".concat(r.name,": ").concat(r.message):r))}finally{s()}})}static scheduleRefetch(e,t,i){return p(this,void 0,void 0,function*(){const s=z.settingsTimeouts.get(e.hostname);clearTimeout(s),z.settingsTimeouts.set(e.hostname,setTimeout(()=>p(this,void 0,void 0,function*(){try{const r=yield z.fetchRegionSettings(e,t);z.updateCachedRegionSettings(e,t,r)}catch(r){if(r instanceof F&&r.reason===Q.NotAllowed){V.debug("token is not valid, cancelling auto region refresh");return}V.debug("auto refetching of region settings failed",{error:r}),z.scheduleRefetch(e,t,i)}}),i))})}static updateCachedRegionSettings(e,t,i){z.cache.set(e.hostname,i),z.scheduleRefetch(e,t,i.maxAgeInMs)}static stopRefetch(e){const t=z.settingsTimeouts.get(e);t&&(clearTimeout(t),z.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=z.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const i=z.connectionTrackers.get(e);i&&i.connectionCount===0&&(V.debug("stopping region refetch after disconnect delay",{hostname:e}),z.stopRefetch(e)),i&&(i.cleanupTimeout=void 0)},ih))}static cancelCleanup(e){const t=z.connectionTrackers.get(e);t?.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=z.connectionTrackers.get(e);t||(t={connectionCount:0},z.connectionTrackers.set(e,t)),t.connectionCount++,z.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=z.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&z.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return St(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return p(this,void 0,void 0,function*(){return z.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return p(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=z.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),z.updateCachedRegionSettings(this.serverUrl,this.token,t));const i=t.regionSettings.regions.filter(s=>!this.attemptedRegions.find(r=>r.url===s.url));if(i.length>0){const s=i[0];return this.attemptedRegions.push(s),V.debug("next region: ".concat(s.region)),s.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){z.updateCachedRegionSettings(this.serverUrl,this.token,e)}}z.cache=new Map,z.settingsTimeouts=new Map,z.connectionTrackers=new Map,z.fetchLock=new he;function nh(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class ie extends Error{constructor(e,t,i){super(t),this.code=e,this.message=pa(t,ie.MAX_MESSAGE_BYTES),this.data=i?pa(i,ie.MAX_DATA_BYTES):void 0}static fromProto(e){return new ie(e.code,e.message,e.data)}toProto(){return new gr({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new ie(ie.ErrorCode[e],ie.ErrorMessage[e],t)}}ie.MAX_MESSAGE_BYTES=256,ie.MAX_DATA_BYTES=15360,ie.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},ie.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const ha=15360;function $n(n){return new TextEncoder().encode(n).length}function pa(n,e){if($n(n)<=e)return n;let t=0,i=n.length;const s=new TextEncoder;for(;t<i;){const r=Math.floor((t+i+1)/2);s.encode(n.slice(0,r)).length<=e?t=r:i=r-1}return n.slice(0,t)}const Qn=2e3;function Pi(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}const Yn=typeof MediaRecorder<"u";class sh{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const rh=Yn?MediaRecorder:sh;class oh extends rh{constructor(e,t){if(!Yn)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let i,s;const r=()=>s===void 0,a=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),s?.close(),s=void 0},o=c=>{s?.error(c),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",a),this.removeEventListener("error",o),s=void 0};this.byteStream=new ReadableStream({start:c=>{s=c,i=d=>p(this,void 0,void 0,function*(){let l;if(d.data.arrayBuffer){const u=yield d.data.arrayBuffer();l=new Uint8Array(u)}else if(d.data.byteArray)l=d.data.byteArray;else throw new Error("no data available!");r()||c.enqueue(l)}),this.addEventListener("dataavailable",i)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}}function ah(){return Yn}const ch=1e3,dh=1e4;class ma extends S{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=Hn(()=>p(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>p(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(w.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new he,this.pauseUpstreamLock=new he,this.trackChangeLock=new he,this.trackChangeLock.lock().then(a=>p(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{a()}})),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==S.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return p(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{kt(this._mediaStreamTrack,r)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let s;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Tt(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{Tt(s??e,r)}))})}waitForDimensions(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ch;return(function*(){var i;if(e.kind===S.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=be())===null||i===void 0?void 0:i.os)==="iOS"&&(yield le(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield le(50)}throw new qe("unable to get track dimensions after timeout")})()})}setDeviceId(e){return p(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Qe(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Qe(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===S.Source.ScreenShare)return;const{deviceId:i,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===S.Kind.Audio?"audioinput":"videoinput";return t?ce.getInstance().normalizeDeviceId(r,i,s):i})()})}mute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return p(this,void 0,void 0,function*(){const i=yield this.trackChangeLock.lock();try{if(!this.sender)throw new qe("unable to replace an unpublished track");let s,r;return typeof t=="boolean"?s=t:t!==void 0&&(s=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=s??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor()),this}finally{i()}})}restart(e){return p(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:s}=e,r=Nl(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===S.Kind.Video?a.video=i||s?{deviceId:i,facingMode:s}:!0:a.audio=i?Object.assign({deviceId:i},r):!0,this.attachedElements.forEach(d=>{kt(this.mediaStreamTrack,d)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===S.Kind.Video&&(yield c.applyConstraints(r)),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(w.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?w.Muted:w.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),jo()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(w.UpstreamPaused,this);const i=be();if(i?.name==="Safari"&&Le(i.version,"12.0")<0)throw new Tn("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(w.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return p(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;const a=yield i.trackChangeLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext};if(yield t.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.internalStopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Tt(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(d=>{d instanceof DOMException&&d.name==="AbortError"?(i.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},i.logContext),{error:d})),setTimeout(()=>{o.play().catch(l=>{i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{err:l}))})},100)):i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:d}))}),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const d of i.attachedElements)d!==i.processorElement&&s&&(kt(i._mediaStreamTrack,d),Tt(i.processor.processedTrack,d));yield(r=i.sender)===null||r===void 0?void 0:r.replaceTrack(i.processor.processedTrack)}i.emit(w.TrackProcessorUpdate,i.processor)}finally{a()}})()})}getProcessor(){return this.processor}stopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const i=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{i()}})()})}internalStopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var i,s;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((s=e.processorElement)===null||s===void 0||s.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(w.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!ah()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new oh(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},dh)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class Ii extends ma{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,S.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=Pi(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(w.AudioTrackFeatureUpdate,this,ae.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(w.AudioTrackFeatureUpdate,this,ae.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===S.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Qe(this._constraints.deviceId);return this.source===S.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return p(this,void 0,void 0,function*(){let t;if(e){const i=Rn({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return p(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){ye()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Qn)))}setProcessor(e){return p(this,void 0,void 0,function*(){var t;const i=yield this.trackChangeLock.lock();try{if(!Me()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const s={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(s),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(w.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(s=>{s.type==="outbound-rtp"&&(i={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),i})}checkForSilence(){return p(this,void 0,void 0,function*(){const e=yield Mo(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(w.AudioSilenceDetected)),e})}}function lh(n,e,t){switch(n.kind){case"audio":return new Ii(n,e,!1,void 0,t);case"video":return new Di(n,e,!1,t);default:throw new qe("unsupported track type: ".concat(n.kind))}}const uh=Object.values(qt),hh=Object.values(Sn),ph=Object.values(Cn),mh=[qt.h180,qt.h360],fh=[Sn.h180,Sn.h360],gh=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,s;return new $(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,n.encoding.priority)}),Xn=["q","h","f"];function Zn(n,e,t,i){var s,r;let a=i?.videoEncoding;n&&(a=i?.screenShareEncoding);const o=i?.simulcast,c=i?.scalabilityMode,d=i?.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=bh(n,e,t,d),V.debug("using video encoding",a));const l=a.maxFramerate,u=new $(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&Ie(d)){const b=new va(c),v=[];if(b.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const R=be();if(Ht()||Me()||R?.name==="Chrome"&&Le(R?.version,"113")<0){const T=b.suffix=="h"?2:3,A=mu(R);for(let x=0;x<b.spatial;x+=1)v.push({rid:Xn[2-x],maxBitrate:a.maxBitrate/Math.pow(T,x),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:A?Math.pow(2,x):void 0});v[0].scalabilityMode=c}else v.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(v[0].priority=u.encoding.priority,v[0].networkPriority=u.encoding.priority),V.debug("using svc encoding",{encodings:v}),v}if(!o)return[a];let h=[];n?h=(s=ga(i?.screenShareSimulcastLayers))!==null&&s!==void 0?s:fa(n,u):h=(r=ga(i?.videoSimulcastLayers))!==null&&r!==void 0?r:fa(n,u);let f;if(h.length>0){const b=h[0];h.length>1&&([,f]=h);const v=Math.max(e,t);if(v>=960&&f)return es(e,t,[b,f,u],l);if(v>=480)return es(e,t,[b,u],l)}return es(e,t,[u])}function vh(n,e,t){var i,s,r,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&V.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),c=(i=o.width)!==null&&i!==void 0?i:(s=n.dimensions)===null||s===void 0?void 0:s.width,d=(r=o.height)!==null&&r!==void 0?r:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===S.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Zn(n.source===S.Source.ScreenShare,c,d,t)}function bh(n,e,t,i){const s=yh(n,e,t);let{encoding:r}=s[0];const a=Math.max(e,t);for(let o=0;o<s.length;o+=1){const c=s[o];if(r=c.encoding,c.width>=a)break}if(i)switch(i){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function yh(n,e,t){if(n)return ph;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?uh:hh}function fa(n,e){if(n)return gh(e);const{width:t,height:i}=e,s=t>i?t/i:i/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?mh:fh}function es(n,e,t,i){const s=[];if(t.forEach((r,a)=>{if(a>=Xn.length)return;const o=Math.min(n,e),d={rid:Xn[a],scaleResolutionDownBy:Math.max(1,o/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},l=i&&r.encoding.maxFramerate?Math.min(i,r.encoding.maxFramerate):r.encoding.maxFramerate;l&&(d.maxFramerate=l);const u=ct()||a===0;r.encoding.priority&&u&&(d.priority=r.encoding.priority,d.networkPriority=r.encoding.priority),s.push(d)}),Me()&&Wo()==="ios"){let r;s.forEach(o=>{r?o.maxFramerate&&o.maxFramerate>r&&(r=o.maxFramerate):r=o.maxFramerate});let a=!0;s.forEach(o=>{var c;o.maxFramerate!=r&&(a&&(a=!1,V.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),V.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),o.maxFramerate=r)})}return s}function ga(n){if(n)return n.sort((e,t)=>{const{encoding:i}=e,{encoding:s}=t;return i.maxBitrate>s.maxBitrate?1:i.maxBitrate<s.maxBitrate?-1:i.maxBitrate===s.maxBitrate&&i.maxFramerate&&s.maxFramerate?i.maxFramerate>s.maxFramerate?1:-1:0})}class va{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function _h(n){return n.source===S.Source.ScreenShare||n.constraints.height&&Qe(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const Th=5e3;class Di extends ma{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,S.Kind.Video,t,i,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const a=new Map(r.map(c=>[c.rid,c])),o=r.some(c=>c.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(w.CpuConstrained)),this.prevStats){let c=0;a.forEach((d,l)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);c+=Pi(d,h)}),this._currentBitrate=c}this.prevStats=a}),this.senderLock=new he}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!ye())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Qn))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return p(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=je(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0)r=d.value,o=!1,yield(a=r.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(l){i={error:l}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return p(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=je(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0){r=d.value,o=!1;const l=r;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){i={error:l}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===S.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===S.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(s=>{var r;if(s.type==="outbound-rtp"){const a={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,framesPerSecond:s.framesPerSecond,framesSent:s.framesSent,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationDurations:s.qualityLimitationDurations,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,targetBitrate:s.targetBitrate,timestamp:s.timestamp},o=i.get(s.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((s,r)=>{var a,o;return((a=r.frameWidth)!==null&&a!==void 0?a:0)-((o=s.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=_e.LOW;i<=_e.HIGH;i+=1)t.push(new rn({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Ie(this.codec),t)}restartTrack(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a;let o;if(e){const u=Rn({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var c=!0,d=je(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;c=!0){r=l.value,c=!1;const u=r;u.sender&&((a=u.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){i={error:u}}finally{try{!c&&!t&&(s=d.return)&&(yield s.call(d))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return p(this,arguments,void 0,function(i){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var a,o,c,d,l,u;if(yield t.setProcessor.call(s,i,r),!((l=s.processor)===null||l===void 0)&&l.processedTrack)try{for(var h=!0,f=je(s.simulcastCodecs.values()),b;b=yield f.next(),a=b.done,!a;h=!0)d=b.value,h=!1,yield(u=d.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(v){o={error:v}}finally{try{!h&&!a&&(c=f.return)&&(yield c.call(f))}finally{if(o)throw o.error}}})()})}setDegradationPreference(e){return p(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Th))}setPublishingCodecs(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a,o,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(Ie(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=je(e);s=yield i.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const l=c;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(Ie(l.codec),l.qualities);else{const u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of l.qualities)if(h.enabled){d.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield ba(u.sender,u.encodings,l.qualities,this.senderLock,Ie(l.codec),this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!r&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return d})}setPublishingLayers(e,t){return p(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield ba(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return p(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const t=this.sender.getParameters();t.encodings=t.encodings.map((i,s)=>{var r;return Object.assign(Object.assign({},i),{active:s===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((r=this.mediaStreamTrack.getSettings().height)!==null&&r!==void 0?r:360)/360)),scalabilityMode:s===0&&Ie(this.codec)?"L1T3":void 0,maxFramerate:s===0?15:0,maxBitrate:s===0?i.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:t.encodings})),this.encodings=t.encodings,yield this.sender.setParameters(t)}catch(t){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:t})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),jo()&&this.isInBackground&&this.source===S.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function ba(n,e,t,i,s,r,a){return p(this,void 0,void 0,function*(){const o=yield i.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:n,qualities:t,senderEncodings:e}));try{const c=n.getParameters(),{encodings:d}=c;if(!d)return;if(d.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:d,senderEncodings:e}));return}let l=!1;!1&&d[0].scalabilityMode||(s&&t.some(f=>f.enabled)&&t.forEach(f=>f.enabled=!0),d.forEach((h,f)=>{var b;let v=(b=h.rid)!==null&&b!==void 0?b:"";v===""&&(v="q");const R=ya(v),T=t.find(A=>A.quality===R);T&&h.active!==T.enabled&&(l=!0,h.active=T.enabled,r.debug("setting layer ".concat(T.quality," to ").concat(h.active?"enabled":"disabled"),a),ct()&&(T.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),l&&(c.encodings=d,r.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:c.encodings})),yield n.setParameters(c))}finally{o()}})}function ya(n){switch(n){case"f":return _e.HIGH;case"h":return _e.MEDIUM;case"q":return _e.LOW;default:return _e.HIGH}}function _a(n,e,t,i){if(!t)return[new ze({quality:_e.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const s=t[0].scalabilityMode,r=new va(s),a=[],o=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let d=0;d<r.spatial;d+=1)a.push(new ze({quality:Math.min(_e.HIGH,r.spatial-1)-d,width:Math.ceil(n/Math.pow(o,d)),height:Math.ceil(e/Math.pow(o,d)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,d)):0,ssrc:0}));return a}return t.map(s=>{var r,a,o;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let d=ya((a=s.rid)!==null&&a!==void 0?a:"");return new ze({quality:d,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(o=s.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const Ta="_lossy",ka="_reliable",kh=2*1e3,ts="leave-reconnect",Sh=3e4,Ch=8*1024,Eh=256*1024;var Ee;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(Ee||(Ee={}));class Rh extends xe.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Jn.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Ee.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=V,this.reliableDataSequence=1,this.reliableMessageBuffer=new ta,this.reliableReceivedState=new Gu(Sh),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=i=>p(this,[i],void 0,function(s){var r=this;let{channel:a}=s;return(function*(){if(a){if(a.label===ka)r.reliableDCSub=a;else if(a.label===Ta)r.lossyDCSub=a;else return;r.log.debug("on data channel ".concat(a.id,", ").concat(a.label),r.logContext),a.onmessage=r.handleDataMessage}})()}),this.handleDataMessage=i=>p(this,void 0,void 0,function*(){var s,r,a,o,c;const d=yield this.dataProcessLock.lock();try{let l;if(i.data instanceof ArrayBuffer)l=i.data;else if(i.data instanceof Blob)l=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const u=pe.fromBinary(new Uint8Array(l));if(u.sequence>0&&u.participantSid!==""){const h=this.reliableReceivedState.get(u.participantSid);if(h&&u.sequence<=h)return;this.reliableReceivedState.set(u.participantSid,u.sequence)}if(((s=u.value)===null||s===void 0?void 0:s.case)==="speaker")this.emit(P.ActiveSpeakersUpdate,u.value.value.speakers);else if(((r=u.value)===null||r===void 0?void 0:r.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up",this.logContext);return}const h=yield(a=this.e2eeManager)===null||a===void 0?void 0:a.handleEncryptedData(u.value.value.encryptedValue,u.value.value.iv,u.participantIdentity,u.value.value.keyIndex),f=pr.fromBinary(h.payload),b=new pe({value:f.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((o=b.value)===null||o===void 0?void 0:o.case)==="user"&&Sa(b,b.value.value),this.emit(P.DataPacketReceived,b,u.value.value.encryptionType)}else((c=u.value)===null||c===void 0?void 0:c.case)==="user"&&Sa(u,u.value.value),this.emit(P.DataPacketReceived,u,se.NONE)}finally{d()}}),this.handleDataError=i=>{const r=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:a}=i.error;this.log.error("DataChannel error on ".concat(r,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:a}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const r=i.currentTarget.maxRetransmits===0?q.LOSSY:q.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(i,s)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(P.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){r(a);return}i===ts&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=de.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,s)=>{this.pcState===Ee.Connected&&i();const r=()=>{this.off(P.Disconnected,a),i()},a=()=>{this.off(P.Restarted,r),s()};this.once(P.Restarted,r),this.once(P.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{if(i===q.RELIABLE){const r=this.dataChannelForKind(i);r&&this.reliableMessageBuffer.alignBufferedAmount(r.bufferedAmount)}const s=this.isBufferStatusLow(i);typeof s<"u"&&s!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,s),this.emit(P.DCBufferStatusChanged,s,i))},this.isBufferStatusLow=i=>{const s=this.dataChannelForKind(i);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>p(this,void 0,void 0,function*(){!this.url||!(yield fetch(zt(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===Y.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===Y.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(rt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>p(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(zt(this.url),{method:"HEAD"}),le(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=Ve((t=e.loggerName)!==null&&t!==void 0?t:Pe.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Vn(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new he,this.dataProcessLock=new he,this.dcBufferStatus=new Map([[q.LOSSY,!0],[q.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(P.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(P.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(P.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(P.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(P.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(P.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(P.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(P.SignalRequestResponse,i)}get logContext(){var e,t,i,s,r,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(s=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||s===void 0?void 0:s.sid,participant:(a=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||a===void 0?void 0:a.identity,pID:this.participantSid}}join(e,t,i,s){return p(this,arguments,void 0,function(r,a,o,c){var d=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){d.url=r,d.token=a,d.signalOpts=o,d.maxJoinAttempts=o.maxRetries;try{d.joinAttempts+=1,d.setupSignalClientCallbacks();const u=yield d.client.join(r,a,o,c,l);return d._isClosed=!1,d.latestJoinResponse=u,d.subscriberPrimary=u.subscriberPrimary,d.pcManager||(yield d.configure(u,!l)),(!d.subscriberPrimary||u.fastPublish)&&d.negotiate().catch(h=>{V.error(h,d.logContext)}),d.registerOnLineListener(),d.clientConfiguration=u.clientConfiguration,d.emit(P.SignalConnected,u),u}catch(u){if(u instanceof F){if(u.reason===Q.ServerUnreachable){if(d.log.warn("Couldn't connect to server, attempt ".concat(d.joinAttempts," of ").concat(d.maxJoinAttempts),d.logContext),d.joinAttempts<d.maxJoinAttempts)return d.join(r,a,o,c,l)}else if(u.reason===Q.ServiceNotFound)return d.log.warn("Initial connection failed: ".concat(u.message," \u2013 Retrying")),d.join(r,a,o,c,!0)}throw u}})()})}close(){return p(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(P.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return p(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new ta,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return p(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new qe("a track with the same ID has already been published");return new Promise((t,i)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(F.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return p(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e,t){return p(this,void 0,void 0,function*(){var i,s;if(this.pcManager&&this.pcManager.currentState!==te.NEW)return;this.participantSid=(i=e.participant)===null||i===void 0?void 0:i.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new th(r,t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions),this.emit(P.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(a,o)=>{this.client.sendIceCandidate(a,o)},this.pcManager.onPublisherOffer=(a,o)=>{this.client.sendOffer(a,o)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(a,o,c)=>p(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(a),this.logContext),["closed","disconnected","failed"].includes(o)&&(this.publisherConnectionPromise=void 0),a===te.CONNECTED){const u=this.pcState===Ee.New;this.pcState=Ee.Connected,u&&this.emit(P.Connected,e)}else a===te.FAILED&&(this.pcState===Ee.Connected||this.pcState===Ee.Reconnecting)&&(this.pcState=Ee.Disconnected,this.handleDisconnect("peerconnection failed",c==="failed"?rt.RR_SUBSCRIBER_FAILED:rt.RR_PUBLISHER_FAILED));const d=this.client.isDisconnected||this.client.currentState===Y.RECONNECTING,l=[te.FAILED,te.CLOSING,te.CLOSED].includes(a);d&&l&&!this._isClosed&&this.emit(P.Offline)}),this.pcManager.onTrack=a=>{a.streams.length!==0&&this.emit(P.MediaTrackAdded,a.track,a.streams[0],a.receiver)},wh((s=e.serverInfo)===null||s===void 0?void 0:s.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,i)=>p(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:i})),this.midToTrackId=i,yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,i)=>p(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=i;const s=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);s&&this.client.sendAnswer(s,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(P.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(P.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{var t;this.token=e,(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(P.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(P.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(P.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{var t,i;const s={direction:"recvonly"};for(let r=0;r<e.numAudios;r++)(t=this.pcManager)===null||t===void 0||t.addPublisherTransceiverOfKind("audio",s);for(let r=0;r<e.numVideos;r++)(i=this.pcManager)===null||i===void 0||i.addPublisherTransceiverOfKind("video",s);this.negotiate()},this.client.onClose=()=>{this.handleDisconnect("signal",rt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e?.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions({updatedAtInMs:Date.now(),maxAgeInMs:ua,regionSettings:e.regions})),e.action){case vt.DISCONNECT:this.emit(P.Disconnected,e?.reason),this.close();break;case vt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(ts);break;case vt.RESUME:this.handleDisconnect(ts)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const s=[];e.iceServers.forEach(r=>{const a={urls:r.urls};r.username&&(a.username=r.username),r.credential&&(a.credential=r.credential),s.push(a)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ut.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Ta,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(ka,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow,this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;const e=this.dataChannelForKind(q.LOSSY);if(e){const t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,Ch),Eh)}},1e3))}createSender(e,t,i){return p(this,void 0,void 0,function*(){if(Pn())return yield this.createTransceiverRTCRtpSender(e,t,i);if(In())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new re("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(Pn())return this.createSimulcastTransceiverSender(e,t,i,s);if(In())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new re("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),Ye(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:s};return i&&(r.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return p(this,void 0,void 0,function*(){var t,i,s;if(!this._isClosed){if(this.attemptingReconnect){V.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Ut.DISABLED||((s=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&s!==void 0?s:te.NEW)===te.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let a=!0;r instanceof re?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),a=!1):r instanceof _t||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",rt.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(P.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return p(this,void 0,void 0,function*(){var t,i,s;try{if(!this.url||!this.token)throw new re("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(P.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new _t;r=yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)}catch(a){throw a instanceof F&&a.reason===Q.NotAllowed?new re("could not reconnect, token might be expired"):new _t}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(P.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==Y.CONNECTED)throw new _t("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(P.Restarted)}catch(r){const a=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return p(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new re("could not reconnect, url or token not saved");if(!this.pcManager)throw new re("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(P.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(s){let r="";throw s instanceof Error&&(r=s.message,this.log.error(s.message,Object.assign(Object.assign({},this.logContext),{error:s}))),s instanceof F&&s.reason===Q.NotAllowed?new re("could not reconnect, token might be expired"):s instanceof F&&s.reason===Q.LeaveRequest?s:new _t(r)}if(this.emit(P.SignalResumed),i){const s=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(s),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Y.CONNECTED)throw new _t("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),i?.lastMessageSeq&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(P.Resumed)})}waitForPCInitialConnection(e,t){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return p(this,void 0,void 0,function*(){this.pcState=Ee.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield le(kh),!this.pcManager)throw new re("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ee.Connected}catch(e){throw this.pcState=Ee.Disconnected,F.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcResponse(e,t,i,s){return p(this,void 0,void 0,function*(){const r=new pe({destinationIdentities:[e],kind:q.RELIABLE,value:{case:"rpcResponse",value:new Yi({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(r,q.RELIABLE)})}publishRpcAck(e,t){return p(this,void 0,void 0,function*(){const i=new pe({destinationIdentities:[e],kind:q.RELIABLE,value:{case:"rpcAck",value:new Qi({requestId:t})}});yield this.sendDataPacket(i,q.RELIABLE)})}sendDataPacket(e,t){return p(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const r=Mu(e);if(r){const a=yield this.e2eeManager.encryptData(r.toBinary());e.value={case:"encryptedPacket",value:new hr({encryptedValue:a.payload,iv:a.iv,keyIndex:a.keyIndex})}}}t===q.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const i=e.toBinary(),s=this.dataChannelForKind(t);if(s){if(t===q.RELIABLE)yield this.waitForBufferStatusLow(t),this.reliableMessageBuffer.push({data:i,sequence:e.sequence});else{if(!this.isBufferStatusLow(t)){this.lossyDataDropCount+=1,this.lossyDataDropCount%100===0&&this.log.warn("dropping lossy data channel messages, total dropped: ".concat(this.lossyDataDropCount),this.logContext);return}this.lossyDataStatCurrentBytes+=i.byteLength}if(this.attemptingReconnect)return;s.send(i)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return p(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(q.RELIABLE);const t=this.dataChannelForKind(q.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(i=>{t.send(i.data)})),this.updateAndEmitDCBufferStatus(q.RELIABLE)})}waitForBufferStatusLow(e){return new ue((t,i)=>p(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>i(new re("engine closed"));for(this.once(P.Closing,s);!this.dcBufferStatus.get(e);)yield le(10);this.off(P.Closing,s),t()}}))}ensureDataTransportConnected(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var r;if(!i.pcManager)throw new re("PC manager is closed");const a=s?i.pcManager.subscriber:i.pcManager.publisher,o=s?"Subscriber":"Publisher";if(!a)throw F.internal("".concat(o," connection not set"));let c=!1;!s&&!i.dataChannelForKind(t,s)&&(i.createDataChannels(),c=!0),!c&&!s&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate().catch(u=>{V.error(u,i.logContext)});const d=i.dataChannelForKind(t,s);if(d?.readyState==="open")return;const l=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<l;){if(a.isICEConnected&&((r=i.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield le(50)}throw F.internal("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()))})()})}ensurePublisherConnected(e){return p(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==te.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return p(this,void 0,void 0,function*(){return new ue((e,t)=>p(this,void 0,void 0,function*(){if(!this.pcManager){t(new yt("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,s=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t(new yt("cannot negotiate on closed engine")),this.on(P.Closing,s),this.pcManager.publisher.once(wt.RTPVideoPayloadTypes,r=>{const a=new Map;r.forEach(o=>{const c=o.codec.toLowerCase();yu(c)&&a.set(o.payload,c)}),this.emit(P.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(r){r instanceof yt&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",rt.RR_UNKNOWN),r instanceof Error?t(r):t(new Error(String(r)))}finally{this.off(P.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===q.LOSSY)return this.lossyDCSub;if(e===q.RELIABLE)return this.reliableDCSub}else{if(e===q.LOSSY)return this.lossyDC;if(e===q.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,s,r,a;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const o=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),d=(i=this.pcManager.subscriber)===null||i===void 0?void 0:i.getRemoteDescription(),l=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getLocalDescription(),u=(a=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&a!==void 0?a:!0,h=new Array,f=new Array;e.forEach(b=>{b.isDesired!==u&&h.push(b.trackSid),b.isEnabled||f.push(b.trackSid)}),this.client.sendSyncState(new on({answer:this.pcManager.mode==="publisher-only"?c?Rt({sdp:c.sdp,type:c.type}):void 0:l?Rt({sdp:l.sdp,type:l.type}):void 0,offer:this.pcManager.mode==="publisher-only"?o?Rt({sdp:o.sdp,type:o.type}):void 0:d?Rt({sdp:d.sdp,type:d.type}):void 0,subscription:new fi({trackSids:h,subscribe:!u,participantTracks:[]}),publishTracks:iu(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((b,v)=>new Ur({publisherSid:v,lastSeq:b}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,s)=>{i?.id!==void 0&&i.id!==null&&e.push(new Fr({label:i.label,id:i.id,target:s}))};return t(this.dataChannelForKind(q.LOSSY),we.PUBLISHER),t(this.dataChannelForKind(q.RELIABLE),we.PUBLISHER),t(this.dataChannelForKind(q.LOSSY,!0),we.SUBSCRIBER),t(this.dataChannelForKind(q.RELIABLE,!0),we.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&de.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){ye()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){ye()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const i=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(i){const s=Object.entries(this.midToTrackId).find(r=>{let[a]=r;return a===i});if(s)return s[1]}}}function wh(n){return n!==void 0&&n>13}function Sa(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}class Ca{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(!(typeof this.totalByteSize!="number"||this.totalByteSize===0)){if(e&&this.bytesReceived<this.totalByteSize)throw new Se("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),me.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Se("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),me.LengthExceeded)}}constructor(e,t,i,s){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=s}}class Ph extends Ca{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();let t=new Ce,i=null,s=null;if(this.signal){const a=this.signal;s=()=>{var o;(o=t.reject)===null||o===void 0||o.call(t,a.reason)},a.addEventListener("abort",s),i=a}const r=()=>{e.releaseLock(),i&&s&&i.removeEventListener("abort",s),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){var a,o;try{const{done:c,value:d}=yield Promise.race([e.read(),t.promise,(o=(a=this.outOfBandFailureRejectingFuture)===null||a===void 0?void 0:a.promise)!==null&&o!==void 0?o:new Promise(()=>{})]);return c?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(d),{done:!1,value:d.content})}catch(c){throw r(),c}}),return(){return p(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,a;let o=new Set;const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=je(c),u;u=yield l.next(),i=u.done,!i;d=!0){a=u.value,d=!1;const h=a;o.add(h)}}catch(h){s={error:h}}finally{try{!d&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return Array.from(o)})()})}}class Ih extends Ca{constructor(e,t,i,s){super(e,t,i,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=wi(e.chunkIndex),s=this.receivedChunks.get(i);if(s&&s.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder("utf-8",{fatal:!0});let i=new Ce,s=null,r=null;if(this.signal){const o=this.signal;r=()=>{var c;(c=i.reject)===null||c===void 0||c.call(i,o.reason)},o.addEventListener("abort",r),s=o}const a=()=>{e.releaseLock(),s&&r&&s.removeEventListener("abort",r),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){var o,c;try{const{done:d,value:l}=yield Promise.race([e.read(),i.promise,(c=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&c!==void 0?c:new Promise(()=>{})]);if(d)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(l);let u;try{u=t.decode(l.content)}catch(h){throw new Se("Cannot decode datastream chunk ".concat(l.chunkIndex," as text: ").concat(h),me.DecodeFailed)}return{done:!1,value:u}}}catch(d){throw a(),d}}),return(){return p(this,void 0,void 0,function*(){return a(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var i,s,r,a;let o="";const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var d=!0,l=je(c),u;u=yield l.next(),i=u.done,!i;d=!0)a=u.value,d=!1,o+=a}catch(h){s={error:h}}finally{try{!d&&!i&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return o})()})}}class Dh{constructor(){this.log=V,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Se('A text stream handler for topic "'.concat(e,'" has already been set.'),me.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Se('A byte stream handler for topic "'.concat(e,'" has already been set.'),me.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,i,s,r;const a=Array.from(this.textStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e),o=Array.from(this.byteStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e);if(a.length>0||o.length>0){const c=new Se("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),me.AbnormalEnd);for(const[d,l]of o)(i=(t=l.outOfBandFailureRejectingFuture).reject)===null||i===void 0||i.call(t,c),this.byteStreamControllers.delete(d);for(const[d,l]of a)(r=(s=l.outOfBandFailureRejectingFuture).reject)===null||r===void 0||r.call(s,c),this.textStreamControllers.delete(d)}}handleDataStreamPacket(e,t){return p(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case"streamChunk":return this.handleStreamChunk(e.value.value,t);case"streamTrailer":return this.handleStreamTrailer(e.value.value,t);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t,i){return p(this,void 0,void 0,function*(){var s;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let a;const o=new Ce;o.promise.catch(l=>{this.log.error(l)});const c={id:e.streamId,name:(s=e.contentHeader.value.name)!==null&&s!==void 0?s:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:wi(e.timestamp),attributes:e.attributes,encryptionType:i},d=new ReadableStream({start:l=>{if(a=l,this.textStreamControllers.has(e.streamId))throw new Se("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),me.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:c,controller:a,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});r(new Ph(c,d,wi(e.totalLength),o),{identity:t})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let a;const o=new Ce;o.promise.catch(l=>{this.log.error(l)});const c={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:i,attachedStreamIds:e.contentHeader.value.attachedStreamIds},d=new ReadableStream({start:l=>{if(a=l,this.textStreamControllers.has(e.streamId))throw new Se("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),me.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:c,controller:a,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:o})}});r(new Ih(c,d,wi(e.totalLength),o),{identity:t})}})}handleStreamChunk(e,t){const i=this.byteStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?(i.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),me.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&i.controller.enqueue(e));const s=this.textStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?(s.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),me.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&s.controller.enqueue(e))}handleStreamTrailer(e,t){const i=this.textStreamControllers.get(e.streamId);i&&(i.info.encryptionType!==t?i.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(i.info.encryptionType),me.EncryptionTypeMismatch)):(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.textStreamControllers.delete(e.streamId)));const s=this.byteStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?s.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),me.EncryptionTypeMismatch)):(s.info.attributes=Object.assign(Object.assign({},s.info.attributes),e.attributes),s.controller.close()),this.byteStreamControllers.delete(e.streamId))}}class Ea{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return p(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class Ah extends Ea{}class Oh extends Ea{}const Ra=15e3;class Nh{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return p(this,void 0,void 0,function*(){var i;const s=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(i=t?.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(o?o.length+1:1).fill(0),d=(u,h)=>{var f;c[h]=u;const b=c.reduce((v,R)=>v+R,0);(f=t?.onProgress)===null||f===void 0||f.call(t,b)},l=yield this.streamText({streamId:s,totalSize:a,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:o,attributes:t?.attributes});return yield l.write(e),d(1,0),yield l.close(),t?.attachments&&o&&(yield Promise.all(t.attachments.map((u,h)=>p(this,void 0,void 0,function*(){return this._sendFile(o[h],u,{topic:t.topic,mimeType:u.type,onProgress:f=>{d(f,h+1)}})})))),l.info})}streamText(e){return p(this,void 0,void 0,function*(){var t,i,s;const r=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e?.topic)!==null&&i!==void 0?i:"",size:e?.totalSize,attributes:e?.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?se.GCM:se.NONE,attachedStreamIds:e?.attachedStreamIds},o=new li({streamId:r,mimeType:a.mimeType,topic:a.topic,timestamp:lt(a.timestamp),totalLength:lt(e?.totalSize),attributes:a.attributes,contentHeader:{case:"textHeader",value:new Er({version:e?.version,attachedStreamIds:a.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?Xi.UPDATE:Xi.CREATE})}}),c=e?.destinationIdentities,d=new pe({destinationIdentities:c,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(d,q.RELIABLE);let l=0;const u=this.engine,h=new WritableStream({write(v){return p(this,void 0,void 0,function*(){for(const R of Eu(v,Ra)){const T=new ui({content:R,streamId:r,chunkIndex:lt(l)}),A=new pe({destinationIdentities:c,value:{case:"streamChunk",value:T}});yield u.sendDataPacket(A,q.RELIABLE),l+=1}})},close(){return p(this,void 0,void 0,function*(){const v=new hi({streamId:r}),R=new pe({destinationIdentities:c,value:{case:"streamTrailer",value:v}});yield u.sendDataPacket(R,q.RELIABLE)})},abort(v){console.log("Sink error:",v)}});let f=()=>p(this,void 0,void 0,function*(){yield b.close()});u.once(P.Closing,f);const b=new Ah(h,a,()=>this.engine.off(P.Closing,f));return b})}sendFile(e,t){return p(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return p(this,void 0,void 0,function*(){var s;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(s=i?.mimeType)!==null&&s!==void 0?s:t.type,topic:i?.topic,destinationIdentities:i?.destinationIdentities}),a=t.stream().getReader();for(;;){const{done:o,value:c}=yield a.read();if(o)break;yield r.write(c)}return yield r.close(),r.info})}streamBytes(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a,o;const c=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),d=e?.destinationIdentities,l={id:c,mimeType:(i=e?.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(s=e?.topic)!==null&&s!==void 0?s:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(r=e?.name)!==null&&r!==void 0?r:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?se.GCM:se.NONE},u=new li({totalLength:lt((o=l.size)!==null&&o!==void 0?o:0),mimeType:l.mimeType,streamId:c,topic:l.topic,timestamp:lt(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new Rr({name:l.name})}}),h=new pe({destinationIdentities:d,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(h,q.RELIABLE);let f=0;const b=new he,v=this.engine,R=this.log,T=new WritableStream({write(x){return p(this,void 0,void 0,function*(){const y=yield b.lock();let _=0;try{for(;_<x.byteLength;){const C=x.slice(_,_+Ra),N=new pe({destinationIdentities:d,value:{case:"streamChunk",value:new ui({content:C,streamId:c,chunkIndex:lt(f)})}});yield v.sendDataPacket(N,q.RELIABLE),f+=1,_+=C.byteLength}}finally{y()}})},close(){return p(this,void 0,void 0,function*(){const x=new hi({streamId:c}),y=new pe({destinationIdentities:d,value:{case:"streamTrailer",value:x}});yield v.sendDataPacket(y,q.RELIABLE)})},abort(x){R.error("Sink error:",x)}});return new Oh(T,l)})}}class wa extends S{constructor(e,t,i,s,r){super(e,i,r),this.sid=t,this.receiver=s}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?w.Muted:w.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(w.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return p(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),Qn)),nu()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:s,rtpTimestamp:r}=i;r&&this.rtpTimestamp!==r&&(this.emit(w.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class xh extends wa{constructor(e,t,i,s,r,a){super(e,t,S.Kind.Audio,i,a),this.monitorReceiver=()=>p(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=Pi(o,this.prevStats)),this.prevStats=o}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Me()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Me())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return p(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Dn(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Dn(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{i.connect(s),i=s}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(w.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(w.AudioPlaybackFailed,s)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}}const is=100;class Mh extends wa{constructor(e,t,i,s,r){super(e,t,S.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>p(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=Pi(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=Hn(()=>{this.updateDimensions()},is),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===S.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?kt(this._mediaStreamTrack,t):Tt(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new Lh(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(i=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&i!==""&&s.get(i)&&(t.mimeType=s.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,i;const s=this.elementInfos.reduce((c,d)=>Math.max(c,d.visibilityChangedAt||0),0),r=!((i=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&i!==void 0)||i?this.isInBackground:!1,a=this.elementInfos.some(c=>c.pictureInPicture),o=this.elementInfos.some(c=>c.visible)&&!r||a;if(!(this.lastVisible===o&&!e)){if(!o&&Date.now()-s<is){de.setTimeout(()=>{this.updateVisibility()},is);return}this.lastVisible=o,this.emit(w.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let i=0,s=0;const r=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*r,c=a.height()*r;o+c>i+s&&(i=o,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:i,height:s},this.emit(w.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Ko():t||(Ko()>2?2:1)}}class Lh{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var s;const{target:r,isIntersecting:a}=i;r===this.element&&(this.isIntersecting=a,this.isPiP=Qt(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var i,s,r;(s=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Qt(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=Qt(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??ns(e),this.isPiP=ye()&&Qt(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=ns(this.element),this.isPiP=Qt(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Go().observe(this.element),Ho().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,s,r;(e=Go())===null||e===void 0||e.unobserve(this.element),(t=Ho())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(r=(s=window.documentPictureInPicture)===null||s===void 0?void 0:s.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function Qt(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?ns(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function ns(n,e){const t=e||window;let i=n.offsetTop,s=n.offsetLeft;const r=n.offsetWidth,a=n.offsetHeight,{hidden:o}=n,{display:c}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,s+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&s<t.pageXOffset+t.innerWidth&&i+a>t.pageYOffset&&s+r>t.pageXOffset&&!o&&c!=="none"}class Ke extends xe.EventEmitter{constructor(e,t,i,s){var r;super(),this.metadataMuted=!1,this.encryption=se.NONE,this.log=V,this.handleMuted=()=>{this.emit(w.Muted)},this.handleUnmuted=()=>{this.emit(w.Unmuted)},this.log=Ve((r=s?.loggerName)!==null&&r!==void 0?r:Pe.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=S.Source.Unknown}setTrack(e){this.track&&(this.track.off(w.Muted,this.handleMuted),this.track.off(w.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(w.Muted,this.handleMuted),e.on(w.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),K(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==se.NONE}get audioTrack(){if(Ue(this.track))return this.track}get videoTrack(){if(Ye(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=S.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===S.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(n.PermissionStatus||(n.PermissionStatus={}))})(Ke||(Ke={}));class ss extends Ke{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(w.Ended)},this.handleCpuConstrained=()=>{this.track&&Ye(this.track)&&this.emit(w.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(w.Ended,this.handleTrackEnded),this.track.off(w.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(w.Ended,this.handleTrackEnded),e.on(w.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Ue(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(ae.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(ae.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(ae.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(ae.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(ae.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(ae.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Ai(n,e){return p(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:s,optionsWithoutProcessor:r}=Uo(n);let a=r.audio,o=r.video;if(i&&typeof r.audio=="object"&&(r.audio.processor=i),s&&typeof r.video=="object"&&(r.video.processor=s),n.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const u=r.audio.deviceId;r.audio.deviceId={exact:u},t=!0,a=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:u}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const u=r.video.deviceId;r.video.deviceId={exact:u},t=!0,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}r.audio===!0?r.audio={deviceId:"default"}:typeof r.audio=="object"&&r.audio!==null&&(r.audio=Object.assign(Object.assign({},r.audio),{deviceId:r.audio.deviceId||"default"})),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const c=xo(r,da,la),d=Rn(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(ce.userMediaPromiseMap.set("audioinput",l),l.catch(()=>ce.userMediaPromiseMap.delete("audioinput"))),r.video&&(ce.userMediaPromiseMap.set("videoinput",l),l.catch(()=>ce.userMediaPromiseMap.delete("videoinput")));try{const u=yield l;return yield Promise.all(u.getTracks().map(h=>p(this,void 0,void 0,function*(){const f=h.kind==="audio";let b=f?c.audio:c.video;(typeof b=="boolean"||!b)&&(b={});let v;const R=f?d.audio:d.video;typeof R!="boolean"&&(v=R);const T=h.getSettings().deviceId;v?.deviceId&&Qe(v.deviceId)!==T?v.deviceId=T:v||(v={deviceId:T});const A=lh(h,v,e);return A.kind===S.Kind.Video?A.source=S.Source.Camera:A.kind===S.Kind.Audio&&(A.source=S.Source.Microphone),A.mediaStream=u,Ue(A)&&i?yield A.setProcessor(i):Ye(A)&&s&&(yield A.setProcessor(s)),A})))}catch(u){if(!t)throw u;return Ai(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function Uh(n){return p(this,void 0,void 0,function*(){return(yield Ai({audio:!1,video:!0}))[0]})}function Fh(n){return p(this,void 0,void 0,function*(){return(yield Ai({audio:!0,video:!1}))[0]})}var it;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(it||(it={}));function Bh(n){switch(n){case Lt.EXCELLENT:return it.Excellent;case Lt.GOOD:return it.Good;case Lt.POOR:return it.Poor;case Lt.LOST:return it.Lost;default:return it.Unknown}}class Pa extends xe.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Ft.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===ft.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,s,r,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Ft.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=it.Unknown,this.log=V,this.log=Ve((c=a?.loggerName)!==null&&c!==void 0?c:Pe.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Ce,this.once(I.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(S.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(S.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(S.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===ft.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==ft.ACTIVE&&this.emit(I.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(I.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(I.ParticipantNameChanged,e)}_setAttributes(e){const t=su(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(I.AttributesChanged,t)}setPermissions(e){var t,i,s,r,a,o;const c=this.permissions,d=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var h;return l!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,d&&this.emit(I.ParticipantPermissionsChanged,c),d}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(I.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=Bh(e),t!==this._connectionQuality&&this.emit(I.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Ue(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(w.Muted,()=>{this.emit(I.TrackMuted,e)}),e.on(w.Unmuted,()=>{this.emit(I.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case S.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case S.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Vh(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Mr({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}class jh extends Pa{constructor(e,t,i,s,r,a){super(e,t,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=se.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Ce)},this.handleReconnected=()=>{var o,c;(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.resolve)===null||c===void 0||c.call(o),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var o,c,d,l,u,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.reject)===null||c===void 0||c.call(o,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((l=(d=this.signalConnectedFuture).reject)===null||l===void 0||l.call(d,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(h=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=o=>{var c,d;o.participant&&this.updateInfo(o.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Ce),(d=(c=this.signalConnectedFuture).resolve)===null||d===void 0||d.call(c)},this.handleSignalRequestResponse=o=>{const{requestId:c,reason:d,message:l}=o,u=this.pendingSignalRequests.get(c);u&&(d!==an.OK&&u.reject(new Oo(l,d)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=o=>{switch(o.value.case){case"rpcResponse":let c=o.value.value,d=null,l=null;c.value.case==="payload"?d=c.value.value:c.value.case==="error"&&(l=ie.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,d,l);break;case"rpcAck":let u=o.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(o=>Vh(o)))},this.onTrackUnmuted=o=>{this.onTrackMuted(o,o.isUpstreamPaused)},this.onTrackMuted=(o,c)=>{if(c===void 0&&(c=!0),!o.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),K(o)));return}this.engine.updateMuteStatus(o.sid,c)},this.onTrackUpstreamPaused=o=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),K(o))),this.onTrackMuted(o,!0)},this.onTrackUpstreamResumed=o=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),K(o))),this.onTrackMuted(o,o.isMuted)},this.onTrackFeatureUpdate=o=>{const c=this.audioTrackPublications.get(o.sid);if(!c){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(o.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(c.trackSid,c.getTrackFeatures())},this.onTrackCpuConstrained=(o,c)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),K(c))),this.emit(I.LocalTrackCpuConstrained,o,c)},this.handleSubscribedQualityUpdate=o=>p(this,void 0,void 0,function*(){var c,d,l,u,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const f=this.videoTrackPublications.get(o.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}if(!f.videoTrack)return;const b=yield f.videoTrack.setPublishingCodecs(o.subscribedCodecs);try{for(var v=!0,R=je(b),T;T=yield R.next(),c=T.done,!c;v=!0){u=T.value,v=!1;const A=u;Zl(A)&&(this.log.debug("publish ".concat(A," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),K(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,A,f.options))}}catch(A){d={error:A}}finally{try{!v&&!c&&(l=R.return)&&(yield l.call(R))}finally{if(d)throw d.error}}}),this.handleLocalTrackUnpublished=o=>{const c=this.trackPublications.get(o.trackSid);if(!c){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}this.unpublishTrack(c.track)},this.handleTrackEnded=o=>p(this,void 0,void 0,function*(){if(o.source===S.Source.ScreenShare||o.source===S.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),K(o))),this.unpublishTrack(o);else if(o.isUserProvided)yield o.mute();else if(We(o)||Xe(o))try{if(ye())try{const c=yield navigator?.permissions.query({name:o.source===S.Source.Camera?"camera":"microphone"});if(c&&c.state==="denied")throw this.log.warn("user has revoked access to ".concat(o.source),Object.assign(Object.assign({},this.logContext),K(o))),c.onchange=()=>{c.state!=="denied"&&(o.isMuted||o.restartTrack(),c.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}o.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),K(o))),We(o)?yield o.restartTrack({deviceId:"default"}):yield o.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),K(o))),yield o.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=s,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r,this.roomOutgoingDataStreamManager=a}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==se.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(P.RemoteMute,(i,s)=>{const r=this.trackPublications.get(i);!r||!r.track||(s?r.mute():r.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(P.Connected,this.handleReconnected).on(P.SignalConnected,this.handleSignalConnected).on(P.SignalRestarted,this.handleReconnected).on(P.SignalResumed,this.handleReconnected).on(P.Restarting,this.handleReconnecting).on(P.Resuming,this.handleReconnecting).on(P.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(P.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(P.Closing,this.handleClosing).on(P.SignalRequestResponse,this.handleSignalRequestResponse).on(P.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return p(this,arguments,void 0,function(t){var i=this;let{metadata:s,name:r,attributes:a}=t;return(function*(){return new ue((o,c)=>p(i,void 0,void 0,function*(){var d,l;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((d=s??this.metadata)!==null&&d!==void 0?d:"",(l=r??this.name)!==null&&l!==void 0?l:"",a),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:b=>{c(b),u=!0},values:{name:r,metadata:s,attributes:a}});performance.now()-f<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!a||Object.entries(a).every(b=>{let[v,R]=b;return this.attributes[v]===R||R===""&&!this.attributes[v]}))){this.pendingSignalRequests.delete(h),o();return}yield le(50)}c(new Oo("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?c(u):c(new Error(String(u)))}}))})()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(S.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(S.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(S.Source.ScreenShare,e,t,i)}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){this.encryptionType=e?se.GCM:se.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,s){return p(this,void 0,void 0,function*(){var r,a;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let c;if(this.pendingPublishing.has(e)){const d=yield this.waitForPendingPublicationOfSource(e);return d||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield d?.unmute(),d}this.pendingPublishing.add(e);try{switch(e){case S.Source.Camera:c=yield this.createTracks({video:(r=i)!==null&&r!==void 0?r:!0});break;case S.Source.Microphone:c=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case S.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new qe(e)}}catch(d){throw c?.forEach(l=>{l.stop()}),d instanceof Error&&this.emit(I.MediaDevicesError,d,wn(e)),this.pendingPublishing.delete(e),d}for(const d of c){const l=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===S.Source.Microphone&&Ue(d)&&l.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),d.startPreConnectBuffer())}try{const d=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),K(u))),d.push(this.publishTrack(u,s));[o]=yield Promise.all(d)}catch(d){throw c?.forEach(l=>{l.stop()}),d}finally{this.pendingPublishing.delete(e)}}else if(!o?.track&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===S.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(S.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return p(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(S.Source.Camera)||this.pendingPublishing.has(S.Source.Microphone))){this.pendingPublishing.add(S.Source.Camera),this.pendingPublishing.add(S.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(S.Source.Camera),this.pendingPublishing.delete(S.Source.Microphone)}}})}createTracks(e){return p(this,void 0,void 0,function*(){var t,i;e??(e={});const s=xo(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield Ai(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Ue(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=S.Source.Microphone,this.emit(I.AudioStreamAcquired)),Ye(o)&&(this.cameraError=void 0,o.source=S.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return p(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Tn("getDisplayMedia not supported");e.resolution===void 0&&!pu()&&(e.resolution=Cn.h1080fps30.resolution);const t=tu(e),i=yield navigator.mediaDevices.getDisplayMedia(t),s=i.getVideoTracks();if(s.length===0)throw new qe("no video track found");const r=new Di(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=S.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(i.getAudioTracks().length>0){this.emit(I.AudioStreamAcquired);const o=new Ii(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=S.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return p(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return(function*(){var o,c,d,l;We(i)&&i.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!a&&(yield r.republishPromise),Ct(i)&&r.pendingPublishPromises.has(i)&&(yield r.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let T;switch(i.source){case S.Source.Microphone:T="audioinput";break;case S.Source.Camera:T="videoinput"}T&&r.activeDeviceMap.has(T)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(T)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Ii(i,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":i=new Di(i,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new qe("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(T=>{T.track&&T.track===i&&(h=T)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),K(h))),h;const f=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s),b="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,v=(c=f.forceStereo)!==null&&c!==void 0?c:b;v&&(f.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),K(i))),f.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(d=f.dtx)!==null&&d!==void 0||(f.dtx=!1),(l=f.red)!==null&&l!==void 0||(f.red=!1)),!fu()&&r.roomOptions.e2ee&&(r.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},r.logContext)),f.simulcast=!1),f.source&&(i.source=f.source);const R=new Promise((T,A)=>p(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Y.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:K(i)}));let x=!1;const y=setTimeout(()=>{x=!0,i.stop(),A(new Ao("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(y),x)return;const _=yield this.publish(i,f,v);T(_)}else try{const x=yield this.publish(i,f,v);T(x)}catch(x){A(x)}}catch(x){A(x)}}));r.pendingPublishPromises.set(i,R);try{return yield R}catch(T){throw T}finally{r.pendingPublishPromises.delete(i)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Ce),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),K(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(s=>ru(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),K(e))),!1)}publish(e,t,i){return p(this,void 0,void 0,function*(){var s,r,a,o,c,d,l,u,h,f;if(!this.hasPermissionsToPublish(e))throw new Ao("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(M=>Ct(e)&&M.source===e.source)&&e.source!==S.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),K(e))),t.stopMicTrackOnMute&&Ue(e)&&(e.stopOnMute=!0),e.source===S.Source.ScreenShare&&ct()&&(t.simulcast=!1),t.videoCodec==="av1"&&!lu()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!uu()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=zn),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(M=>t.videoCodec===Wt(M.mime))||(t.videoCodec=Wt(this.enabledPublishVideoCodecs[0].mime)));const v=t.videoCodec;e.on(w.Muted,this.onTrackMuted),e.on(w.Unmuted,this.onTrackUnmuted),e.on(w.Ended,this.handleTrackEnded),e.on(w.UpstreamPaused,this.onTrackUpstreamPaused),e.on(w.UpstreamResumed,this.onTrackUpstreamResumed),e.on(w.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const R=[],T=!(!((s=t.dtx)!==null&&s!==void 0)||s),A=e.getSourceTrackSettings();A.autoGainControl&&R.push(ae.TF_AUTO_GAIN_CONTROL),A.echoCancellation&&R.push(ae.TF_ECHO_CANCELLATION),A.noiseSuppression&&R.push(ae.TF_NOISE_SUPPRESSION),A.channelCount&&A.channelCount>1&&R.push(ae.TF_STEREO),T&&R.push(ae.TF_NO_DTX),We(e)&&e.hasPreConnectBuffer&&R.push(ae.TF_PRECONNECT_BUFFER);const x=new Bt({cid:e.mediaStreamTrack.id,name:t.name,type:S.kindToProto(e.kind),muted:e.isMuted,source:S.sourceToProto(e.source),disableDtx:T,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:R});let y;if(e.kind===S.Kind.Video){let M={width:0,height:0};try{M=yield e.waitForDimensions()}catch{const L=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:qt.h720.resolution;M={width:L.width,height:L.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{dims:M}))}x.width=M.width,x.height=M.height,Xe(e)&&(Ie(v)&&(e.source===S.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),K(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),x.simulcastCodecs=[new en({codec:v,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:zn}),t.backupCodec&&v!==t.backupCodec.codec&&x.encryption===se.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),x.simulcastCodecs.push(new en({codec:t.backupCodec.codec,cid:""})))),y=Zn(e.source===S.Source.ScreenShare,x.width,x.height,t),x.layers=_a(x.width,x.height,y,Ie(t.videoCodec))}else e.kind===S.Kind.Audio&&(y=[{maxBitrate:(d=t.audioPreset)===null||d===void 0?void 0:d.maxBitrate,priority:(u=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new re("cannot publish track when not connected");const _=()=>p(this,void 0,void 0,function*(){var M,O,L;if(!this.engine.pcManager)throw new re("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,y),this.emit(I.LocalSenderCreated,e.sender,e),Xe(e)&&((M=t.degradationPreference)!==null&&M!==void 0||(t.degradationPreference=_h(e)),e.setDegradationPreference(t.degradationPreference)),y)if(ct()&&e.kind===S.Kind.Audio){let W;for(const Z of this.engine.pcManager.publisher.getTransceivers())if(Z.sender===e.sender){W=Z;break}W&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:W,codec:"opus",maxbr:!((O=y[0])===null||O===void 0)&&O.maxBitrate?y[0].maxBitrate/1e3:0})}else e.codec&&Ie(e.codec)&&(!((L=y[0])===null||L===void 0)&&L.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:x.cid,codec:e.codec,maxbr:y[0].maxBitrate/1e3});yield this.engine.negotiate()});let C;const N=new Promise((M,O)=>p(this,void 0,void 0,function*(){var L;try{C=yield this.engine.addTrack(x),M(C)}catch(W){e.sender&&(!((L=this.engine.pcManager)===null||L===void 0)&&L.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(Z=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{error:Z}))})),O(W)}}));if(this.enabledPublishVideoCodecs.length>0)C=(yield Promise.all([N,_()]))[0];else{C=yield N;let M;if(C.codecs.forEach(O=>{M===void 0&&(M=O.mimeType)}),M&&e.kind===S.Kind.Video){const O=Wt(M);O!==v&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{codec:O})),t.videoCodec=O,y=Zn(e.source===S.Source.ScreenShare,x.width,x.height,t))}yield _()}const U=new ss(e.kind,C,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(U.on(w.CpuConstrained,M=>this.onTrackCpuConstrained(M,U)),U.options=t,e.sid=C.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:y,trackInfo:C})),Xe(e)?e.startMonitor(this.engine.client):We(e)&&e.startMonitor(),this.addTrackPublication(U),this.emit(I.LocalTrackPublished,U),We(e)&&C.audioFeatures.includes(ae.TF_PRECONNECT_BUFFER)){const M=e.getPreConnectBuffer(),O=e.getPreConnectBufferMimeType();this.on(I.LocalTrackSubscribed,L=>{if(L.trackSid===C.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),K(e))),e.stopPreConnectBuffer()}}),M&&new Promise((W,Z)=>p(this,void 0,void 0,function*(){var Te,ut,ge,st,os,as;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),K(e)));const us=setTimeout(()=>{Z(new Error("agent not active within 10 seconds"))},1e4),Ep=yield this.waitUntilActiveAgentPresent();clearTimeout(us),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),K(e)));const Ua=yield this.streamBytes({name:"preconnect-buffer",mimeType:O,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Ep.identity],attributes:{trackId:U.trackSid,sampleRate:String((os=A.sampleRate)!==null&&os!==void 0?os:"48000"),channels:String((as=A.channelCount)!==null&&as!==void 0?as:"1")}});try{for(var cs=!0,ds=je(M),ls;ls=yield ds.next(),Te=ls.done,!Te;cs=!0){st=ls.value,cs=!1;const hs=st;yield Ua.write(hs)}}catch(hs){ut={error:hs}}finally{try{!cs&&!Te&&(ge=ds.return)&&(yield ge.call(ds))}finally{if(ut)throw ut.error}}yield Ua.close(),W()}catch(us){Z(us)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),K(e)))}).catch(W=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{error:W}))})}return U})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return p(this,void 0,void 0,function*(){var s;if(this.encryptionType!==se.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new qe("track is not published");if(!Xe(e))throw new qe("track is not a video track");const a=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),i),o=vh(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),K(e)));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const d=new Bt({cid:c.mediaStreamTrack.id,type:S.kindToProto(e.kind),muted:e.isMuted,source:S.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=_a(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new re("cannot publish track when not connected");const l=()=>p(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(d),l()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:h}))})}unpublishTrack(e,t){return p(this,void 0,void 0,function*(){var i,s;if(Ct(e)){const d=this.pendingPublishPromises.get(e);d&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),K(e))),yield d)}const r=this.getPublicationForTrack(e),a=r?K(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));return}e=r.track,e.off(w.Muted,this.onTrackMuted),e.off(w.Unmuted,this.onTrackUnmuted),e.off(w.Ended,this.handleTrackEnded),e.off(w.UpstreamPaused,this.onTrackUpstreamPaused),e.off(w.UpstreamResumed,this.onTrackUpstreamResumed),e.off(w.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(s=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t?e.stop():e.stopMonitor();let o=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<te.FAILED&&c)try{for(const d of this.engine.pcManager.publisher.getTransceivers())d.sender===c&&(d.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),Xe(e)){for(const[,d]of e.simulcastCodecs)d.sender&&(this.engine.removeTrack(d.sender)&&(o=!0),d.sender=void 0);e.simulcastCodecs.clear()}}catch(d){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:d}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case S.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case S.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(I.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return p(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new ue((r,a)=>p(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),o.push(c))}),yield Promise.all(o.map(c=>p(this,void 0,void 0,function*(){const d=c.track;yield this.unpublishTrack(d,!1),s&&!d.isMuted&&d.source!==S.Source.ScreenShare&&d.source!==S.Source.ScreenShareAudio&&(We(d)||Xe(d))&&!d.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield d.restartTrack()),yield this.publishOrRepublishTrack(d,c.options,!0)}))),r()}catch(o){o instanceof Error?a(o):a(new Error(String(o)))}finally{this.republishPromise=void 0}})),yield i.republishPromise})()})}publishData(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const r=s.reliable?q.RELIABLE:q.LOSSY,a=s.destinationIdentities,o=s.topic;let c=new Ji({participantIdentity:i.identity,payload:t,destinationIdentities:a,topic:o});const d=new pe({kind:r,value:{case:"user",value:c}});yield i.engine.sendDataPacket(d,r)})()})}publishDtmf(e,t){return p(this,void 0,void 0,function*(){const i=new pe({kind:q.RELIABLE,value:{case:"sipDtmf",value:new fr({code:e,digit:t})}});yield this.engine.sendDataPacket(i,q.RELIABLE)})}sendChatMessage(e,t){return p(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},s=new pe({value:{case:"chatMessage",value:new di(Object.assign(Object.assign({},i),{timestamp:X.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(s,q.RELIABLE),this.emit(I.ChatMessage,i),i})}editChatMessage(e,t){return p(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new pe({value:{case:"chatMessage",value:new di(Object.assign(Object.assign({},i),{timestamp:X.parse(i.timestamp),editTimestamp:X.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,q.RELIABLE),this.emit(I.ChatMessage,i),i})}sendText(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){let{destinationIdentity:t,method:i,payload:s,responseTimeout:r=15e3}=e;const a=7e3,o=a+1e3;return new ue((c,d)=>p(this,void 0,void 0,function*(){var l,u,h,f;if($n(s)>ha){d(ie.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((u=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||u===void 0)&&u.version&&Le((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){d(ie.builtIn("UNSUPPORTED_SERVER"));return}const b=Math.max(r,o),v=crypto.randomUUID();yield this.publishRpcRequest(t,v,i,s,b);const R=setTimeout(()=>{this.pendingAcks.delete(v),d(ie.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(v),clearTimeout(T)},a);this.pendingAcks.set(v,{resolve:()=>{clearTimeout(R)},participantIdentity:t});const T=setTimeout(()=>{this.pendingResponses.delete(v),d(ie.builtIn("RESPONSE_TIMEOUT"))},r);this.pendingResponses.set(v,{resolve:(A,x)=>{clearTimeout(T),this.pendingAcks.has(v)&&(this.log.warn("RPC response received before ack",v),this.pendingAcks.delete(v),clearTimeout(R)),x?d(x):c(A??"")},participantIdentity:t})}))}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const s=this.pendingResponses.get(e);s?(s.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,s,r){return p(this,void 0,void 0,function*(){const a=new pe({destinationIdentities:[e],kind:q.RELIABLE,value:{case:"rpcRequest",value:new $i({id:t,method:i,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(a,q.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:s}]of this.pendingResponses)i===e&&(s(null,ie.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var i,s;const r=this.trackPublications.get(t.sid);if(r){const a=r.isMuted||((s=(i=r.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&s!==void 0?s:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),K(r)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}setActiveAgent(e){var t,i,s,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(i=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||i===void 0||i.call(t,e):(r=(s=this.activeAgentFuture)===null||s===void 0?void 0:s.reject)===null||r===void 0||r.call(s,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Ce),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(We(s)||Xe(s))&&s.mediaStreamTrack===e&&(t=i):e===s&&(t=i))}),t}waitForPendingPublicationOfSource(e){return p(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[a]=r;return a.source===e});if(s)return s[1];yield le(20)}})}}class qh extends Ke{constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=r=>{this.setTrack(void 0),this.emit(w.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.visible=r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensionsAdaptiveStream=r,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new fi({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new vr({participantSid:"",trackSids:[this.trackSid]})]});this.emit(w.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?Ke.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ke.SubscriptionStatus.Subscribed:Ke.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ke.PermissionStatus.Allowed:Ke.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.requestedVideoDimensions)===null||i===void 0?void 0:i.height)===e.height||(Ln(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Ln(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:_e.HIGH}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(w.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(w.VisibilityChanged,this.handleVisibilityChange),s.off(w.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(w.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(w.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(w.VisibilityChanged,this.handleVisibilityChange),e.on(w.Ended,this.handleEnded),this.emit(w.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(w.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?w.Muted:w.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(w.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(w.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Ln(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Ar({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===S.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Fo(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const i=ou(this.trackInfo,this.requestedMaxQuality);i&&Fo(this.videoDimensionsAdaptiveStream,i)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream;t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality!==void 0?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:_e.HIGH})),e.quality=_e.HIGH)}this.emit(w.UpdateSettings,e)}}class Oi extends Pa{static fromParticipantInfo(e,t,i){return new Oi(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,s,r,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ft.STANDARD;super(t,i||"",s,r,a,o,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(w.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),K(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(w.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(w.SubscriptionPermissionChanged,t=>{this.emit(I.TrackSubscriptionPermissionChanged,e,t)}),e.on(w.SubscriptionStatusChanged,t=>{this.emit(I.TrackSubscriptionStatusChanged,e,t)}),e.on(w.Subscribed,t=>{this.emit(I.TrackSubscribed,t,e)}),e.on(w.Unsubscribed,t=>{this.emit(I.TrackUnsubscribed,t,e)}),e.on(w.SubscriptionFailed,t=>{this.emit(I.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:S.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:S.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,s,r,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(I.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,s,r,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),K(o))),this.emit(I.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let d;return c?d=new Mh(e,t,s,r):d=new xh(e,t,s,this.audioContext,this.audioOutput),d.source=o.source,d.isMuted=o.isMuted,d.setMediaStream(i),d.start(),o.setTrack(d),this.volumeMap.has(o.source)&&Mn(d)&&Ue(d)&&d.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach(s=>{var r,a;let o=this.getTrackPublicationBySid(s.sid);if(o)o.updateInfo(s);else{const c=S.kindFromProto(s.type);if(!c)return;o=new qh(c,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(s),i.set(s.sid,o);const d=Array.from(this.trackPublications.values()).find(l=>l.source===o?.source);d&&o.source!==S.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:K(d),newTrack:K(o)})),this.addTrackPublication(o)}t.set(s.sid,o)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),K(s))),this.unpublishTrack(s.trackSid,!0))}),i.forEach(s=>{this.emit(I.TrackPublished,s)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:s}=i;switch(s&&(s.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case S.Kind.Audio:this.audioTrackPublications.delete(e);break;case S.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(I.TrackUnpublished,i)}setAudioOutput(e){return p(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var s;Ue(i.track)&&Mn(i.track)&&t.push(i.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var J;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(J||(J={}));const Wh=4*1e3;class Pt extends xe.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,i,s,r,a;if(super(),t=this,this.state=J.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=V,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(o,c,d)=>p(this,void 0,void 0,function*(){var l;if(!hu())throw Me()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const u=yield this.disconnectLock.lock();if(this.state===J.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(J.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==$o(o)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),St(new URL(o))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new z(o,c):this.regionUrlProvider.updateToken(c),this.regionUrlProvider.fetchRegionSettings().then(b=>{var v;(v=this.regionUrlProvider)===null||v===void 0||v.setServerReportedRegions(b)}).catch(b=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:b}))}));const h=(b,v,R)=>p(this,void 0,void 0,function*(){var T,A;this.abortController&&this.abortController.abort();const x=new AbortController;this.abortController=x,u?.();try{if(yield Et.getInstance().getBackOffPromise(o),x.signal.aborted)throw F.cancelled("Connection attempt aborted");yield this.attemptConnection(R??o,c,d,x),this.abortController=void 0,b()}catch(y){if(this.regionUrlProvider&&y instanceof F&&y.reason!==Q.Cancelled&&y.reason!==Q.NotAllowed){let _=null;try{this.log.debug("Fetching next region"),_=yield this.regionUrlProvider.getNextBestRegionUrl((T=this.abortController)===null||T===void 0?void 0:T.signal)}catch(C){if(C instanceof F&&(C.status===401||C.reason===Q.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),v(C);return}}[Q.InternalError,Q.ServerUnreachable,Q.Timeout].includes(y.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Et.getInstance().addFailedConnectionAttempt(o)),_&&!(!((A=this.abortController)===null||A===void 0)&&A.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(y.message,". Retrying with another region: ").concat(_),this.logContext),this.recreateEngine(),yield h(b,v,_)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Jo(y)),v(y))}else{let _=ke.UNKNOWN_REASON;y instanceof F&&(_=Jo(y)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,_),v(y)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ce((b,v)=>{h(b,v,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(o,c,d,l,u,h)=>p(this,void 0,void 0,function*(){var f,b,v;const R=yield d.join(o,c,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},h.signal,!u.singlePeerConnection);let T=R.serverInfo;if(T||(T={version:R.serverVersion,region:R.serverRegion}),this.serverInfo=T,this.log.debug("connected to Livekit Server ".concat(Object.entries(T).map(A=>{let[x,y]=A;return"".concat(x,": ").concat(y)}).join(", ")),{room:(f=R.room)===null||f===void 0?void 0:f.name,roomSid:(b=R.room)===null||b===void 0?void 0:b.sid,identity:(v=R.participant)===null||v===void 0?void 0:v.identity}),!T.version)throw new Jl("unknown server version");return T.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),R}),this.applyJoinResponse=o=>{const c=o.participant;if(this.localParticipant.sid=c.sid,this.localParticipant.identity=c.identity,this.localParticipant.setEnabledPublishCodecs(o.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(o.sifTrailer)}catch(d){this.log.error(d instanceof Error?d.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:d}))}this.handleParticipantUpdates([c,...o.otherParticipants]),o.room&&this.handleRoomUpdate(o.room)},this.attemptConnection=(o,c,d,l)=>p(this,void 0,void 0,function*(){var u,h;this.state===J.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((h=this.regionUrlProvider)===null||h===void 0)&&h.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Jn),d),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const f=yield this.connectSignal(o,c,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();const b=l.signal.aborted?F.cancelled("Signal connection aborted"):F.serverUnreachable("could not establish signal connection");throw f instanceof Error&&(b.message="".concat(b.message,": ").concat(f.message)),f instanceof F&&(b.reason=f.reason,b.status=f.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:f})),b}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),F.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}ye()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),ye()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(J.Connected),this.emit(E.Connected),Et.getInstance().resetFailedConnectionAttempts(o),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var o=arguments.length,c=new Array(o),d=0;d<o;d++)c[d]=arguments[d];return p(t,[...c],void 0,function(){var l=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var h,f,b;const v=yield l.disconnectLock.lock();try{if(l.state===J.Disconnected){l.log.debug("already disconnected",l.logContext);return}if(l.log.info("disconnect from room",Object.assign({},l.logContext)),l.state===J.Connecting||l.state===J.Reconnecting||l.isResuming){const R="Abort connection attempt due to user initiated disconnect";l.log.warn(R,l.logContext),(h=l.abortController)===null||h===void 0||h.abort(R),(b=(f=l.connectFuture)===null||f===void 0?void 0:f.reject)===null||b===void 0||b.call(f,F.cancelled("Client initiated disconnect")),l.connectFuture=void 0}l.engine&&(l.engine.client.isDisconnected||(yield l.engine.client.sendLeave()),yield l.engine.close()),l.handleDisconnect(u,ke.CLIENT_INITIATED),l.engine=void 0}finally{v()}})()})},this.onPageLeave=()=>p(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>p(this,void 0,void 0,function*(){const o=[],c=be();if(c&&c.os==="iOS"){const d="livekit-dummy-audio-el";let l=document.getElementById(d);if(!l){l=document.createElement("audio"),l.id=d,l.autoplay=!0,l.hidden=!0;const u=xn();u.enabled=!0;const h=new MediaStream([u]);l.srcObject=h,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:h,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(E.Disconnected,()=>{l?.remove(),l=null})}o.push(l)}this.remoteParticipants.forEach(d=>{d.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(u=>{o.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...o.map(d=>(d.muted=!1,d.play()))]),this.handleAudioPlaybackStarted()}catch(d){throw this.handleAudioPlaybackFailed(d),d}}),this.startVideo=()=>p(this,void 0,void 0,function*(){const o=[];for(const c of this.remoteParticipants.values())c.videoTrackPublications.forEach(d=>{var l;(l=d.track)===null||l===void 0||l.attachedElements.forEach(u=>{o.includes(u)||o.push(u)})});yield Promise.all(o.map(c=>c.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(c=>{c.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const o of this.remoteParticipants.values())this.handleParticipantDisconnected(o.identity,o);this.setAndEmitConnectionState(J.Reconnecting)&&this.emit(E.Reconnecting)},this.handleSignalRestarted=o=>p(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(o.serverRegion),Object.assign(Object.assign({},this.logContext),{region:o.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(o);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(c){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:c}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:o.serverRegion}))}catch{return}this.setAndEmitConnectionState(J.Connected),this.emit(E.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=o=>{o.forEach(c=>{var d;if(c.identity===this.localParticipant.identity){this.localParticipant.updateInfo(c);return}c.identity===""&&(c.identity=(d=this.sidToIdentity.get(c.sid))!==null&&d!==void 0?d:"");let l=this.remoteParticipants.get(c.identity);c.state===ft.DISCONNECTED?this.handleParticipantDisconnected(c.identity,l):l=this.getOrCreateParticipant(c.identity,c)})},this.handleActiveSpeakersUpdate=o=>{const c=[],d={};o.forEach(l=>{if(d[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),c.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(l.sid);u&&(u.audioLevel=l.level,u.setIsSpeaking(!0),c.push(u))}}),d[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{d[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=c,this.emitWhenConnected(E.ActiveSpeakersChanged,c)},this.handleSpeakersChanged=o=>{const c=new Map;this.activeSpeakers.forEach(l=>{const u=this.remoteParticipants.get(l.identity);u&&u.sid!==l.sid||c.set(l.sid,l)}),o.forEach(l=>{let u=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=l.level,u.setIsSpeaking(l.active),l.active?c.set(l.sid,u):c.delete(l.sid))});const d=Array.from(c.values());d.sort((l,u)=>u.audioLevel-l.audioLevel),this.activeSpeakers=d,this.emitWhenConnected(E.ActiveSpeakersChanged,d)},this.handleStreamStateUpdate=o=>{o.streamStates.forEach(c=>{const d=this.getRemoteParticipantBySid(c.participantSid);if(!d)return;const l=d.getTrackPublicationBySid(c.trackSid);if(!l||!l.track)return;const u=S.streamStateFromProto(c.state);l.track.setStreamState(u),u!==l.track.streamState&&(d.emit(I.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(E.TrackStreamStateChanged,l,l.track.streamState,d))})},this.handleSubscriptionPermissionUpdate=o=>{const c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;const d=c.getTrackPublicationBySid(o.trackSid);d&&d.setAllowed(o.allowed)},this.handleSubscriptionError=o=>{const c=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(o.trackSid));if(!c)return;const d=c.getTrackPublicationBySid(o.trackSid);d&&d.setSubscriptionError(o.err)},this.handleDataPacket=(o,c)=>{const d=this.remoteParticipants.get(o.participantIdentity);if(o.value.case==="user")this.handleUserPacket(d,o.value.value,o.kind,c);else if(o.value.case==="transcription")this.handleTranscription(d,o.value.value);else if(o.value.case==="sipDtmf")this.handleSipDtmf(d,o.value.value);else if(o.value.case==="chatMessage")this.handleChatMessage(d,o.value.value);else if(o.value.case==="metrics")this.handleMetrics(o.value.value,d);else if(o.value.case==="streamHeader"||o.value.case==="streamChunk"||o.value.case==="streamTrailer")this.handleDataStream(o,c);else if(o.value.case==="rpcRequest"){const l=o.value.value;this.handleIncomingRpcRequest(o.participantIdentity,l.id,l.method,l.payload,l.responseTimeoutMs,l.version)}},this.handleUserPacket=(o,c,d,l)=>{this.emit(E.DataReceived,c.payload,o,d,c.topic,l),o?.emit(I.DataReceived,c.payload,d,l)},this.handleSipDtmf=(o,c)=>{this.emit(E.SipDTMFReceived,c,o),o?.emit(I.SipDTMFReceived,c)},this.handleTranscription=(o,c)=>{const d=c.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(c.transcribedParticipantIdentity),l=d?.trackPublications.get(c.trackId),u=Tu(c,this.transcriptionReceivedTimes);l?.emit(w.TranscriptionReceived,u),d?.emit(I.TranscriptionReceived,u,l),this.emit(E.TranscriptionReceived,u,d,l)},this.handleChatMessage=(o,c)=>{const d=ku(c);this.emit(E.ChatMessage,d,o)},this.handleMetrics=(o,c)=>{this.emit(E.MetricsReceived,o,c)},this.handleDataStream=(o,c)=>{this.incomingDataStreamManager.handleDataStreamPacket(o,c)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(E.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=o=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:o})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(E.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(E.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(E.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>p(this,void 0,void 0,function*(){var o;((o=be())===null||o===void 0?void 0:o.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(E.MediaDevicesChanged)}),this.handleRoomUpdate=o=>{const c=this.roomInfo;this.roomInfo=o,c&&c.metadata!==o.metadata&&this.emitWhenConnected(E.RoomMetadataChanged,o.metadata),c?.activeRecording!==o.activeRecording&&this.emitWhenConnected(E.RecordingStatusChanged,o.activeRecording)},this.handleConnectionQualityUpdate=o=>{o.updates.forEach(c=>{if(c.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(c.quality);return}const d=this.getRemoteParticipantBySid(c.participantSid);d&&d.setConnectionQuality(c.quality)})},this.onLocalParticipantMetadataChanged=o=>{this.emit(E.ParticipantMetadataChanged,o,this.localParticipant)},this.onLocalParticipantNameChanged=o=>{this.emit(E.ParticipantNameChanged,o,this.localParticipant)},this.onLocalAttributesChanged=o=>{this.emit(E.ParticipantAttributesChanged,o,this.localParticipant)},this.onLocalTrackMuted=o=>{this.emit(E.TrackMuted,o,this.localParticipant)},this.onLocalTrackUnmuted=o=>{this.emit(E.TrackUnmuted,o,this.localParticipant)},this.onTrackProcessorUpdate=o=>{var c;(c=o?.onPublish)===null||c===void 0||c.call(o,this)},this.onLocalTrackPublished=o=>p(this,void 0,void 0,function*(){var c,d,l,u,h,f;(c=o.track)===null||c===void 0||c.on(w.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=o.track)===null||d===void 0||d.on(w.Restarted,this.onLocalTrackRestarted),(h=(u=(l=o.track)===null||l===void 0?void 0:l.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||h===void 0||h.call(u,this),this.emit(E.LocalTrackPublished,o,this.localParticipant),We(o.track)&&(yield o.track.checkForSilence())&&this.emit(E.LocalAudioSilenceDetected,o);const b=yield(f=o.track)===null||f===void 0?void 0:f.getDeviceId(!1),v=wn(o.source);v&&b&&b!==this.localParticipant.activeDeviceMap.get(v)&&(this.localParticipant.activeDeviceMap.set(v,b),this.emit(E.ActiveDeviceChanged,v,b))}),this.onLocalTrackUnpublished=o=>{var c,d;(c=o.track)===null||c===void 0||c.off(w.TrackProcessorUpdate,this.onTrackProcessorUpdate),(d=o.track)===null||d===void 0||d.off(w.Restarted,this.onLocalTrackRestarted),this.emit(E.LocalTrackUnpublished,o,this.localParticipant)},this.onLocalTrackRestarted=o=>p(this,void 0,void 0,function*(){const c=yield o.getDeviceId(!1),d=wn(o.source);d&&c&&c!==this.localParticipant.activeDeviceMap.get(d)&&(this.log.debug("local track restarted, setting ".concat(d," ").concat(c," active"),this.logContext),this.localParticipant.activeDeviceMap.set(d,c),this.emit(E.ActiveDeviceChanged,d,c))}),this.onLocalConnectionQualityChanged=o=>{this.emit(E.ConnectionQualityChanged,o,this.localParticipant)},this.onMediaDevicesError=(o,c)=>{this.emit(E.MediaDevicesError,o,c)},this.onLocalParticipantPermissionsChanged=o=>{this.emit(E.ParticipantPermissionsChanged,o,this.localParticipant)},this.onLocalChatMessageSent=o=>{this.emit(E.ChatMessage,o,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},eh),e),this.log=Ve((i=this.options.loggerName)!==null&&i!==void 0?i:Pe.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},da),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},la),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Zu),e?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Dh,this.outgoingDataStreamManager=new Nh(this.engine,this.log),this.disconnectLock=new he,this.localParticipant=new jh("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Qe(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Qe(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Qe(this.options.audioOutput.deviceId)).catch(o=>this.log.warn("Could not set audio output: ".concat(o.message),this.logContext)),ye()){const o=new AbortController;(a=(r=navigator.mediaDevices)===null||r===void 0?void 0:r.addEventListener)===null||a===void 0||a.call(r,"devicechange",this.handleDeviceChange,{signal:o.signal}),Pt.cleanupRegistry&&Pt.cleanupRegistry.register(this,()=>{o.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;const t=!!this.options.encryption,i=this.options.encryption||this.options.e2ee;i&&("e2eeManager"in i?(this.e2eeManager=i.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=t):this.e2eeManager=new Lu(i,t),this.e2eeManager.on(et.ParticipantEncryptionStatusChanged,(s,r)=>{Cu(r)&&(this.isE2EEEnabled=s),this.emit(E.ParticipantEncryptionStatusChanged,s,r)}),this.e2eeManager.on(et.EncryptionError,(s,r)=>{const a=r?this.getParticipantByIdentity(r):void 0;this.emit(E.EncryptionError,s,a)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return this.state===J.Disconnected?ue.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?ue.resolve(this.roomInfo.sid):new ue((e,t)=>{const i=s=>{s.sid!==""&&(this.engine.off(P.RoomUpdate,i),e(s.sid))};this.engine.on(P.RoomUpdate,i),this.once(E.Disconnected,()=>{this.engine.off(P.RoomUpdate,i),t(new re("Room disconnected before room server id was available"))})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Rh(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(P.ParticipantUpdate,this.handleParticipantUpdates).on(P.RoomUpdate,this.handleRoomUpdate).on(P.SpeakersChanged,this.handleSpeakersChanged).on(P.StreamStateChanged,this.handleStreamStateUpdate).on(P.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(P.SubscriptionError,this.handleSubscriptionError).on(P.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(P.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(P.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(P.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(P.DataPacketReceived,this.handleDataPacket).on(P.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(J.SignalReconnecting)&&this.emit(E.SignalReconnecting)}).on(P.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(J.Connected)&&this.emit(E.Reconnected)}).on(P.SignalResumed,()=>{this.bufferedEvents=[],(this.state===J.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(P.Restarting,this.handleRestarting).on(P.SignalRestarted,this.handleSignalRestarted).on(P.Offline,()=>{this.setAndEmitConnectionState(J.Reconnecting)&&this.emit(E.Reconnecting)}).on(P.DCBufferStatusChanged,(e,t)=>{this.emit(E.DCBufferStatusChanged,e,t)}).on(P.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:s}=i;return s===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(I.LocalTrackSubscribed,t),this.emitWhenConnected(E.LocalTrackSubscribed,t,this.localParticipant)}).on(P.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(E.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return ce.getInstance().getDevices(e,t)}prepareConnection(e,t){return p(this,void 0,void 0,function*(){if(this.state===J.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(St(new URL(e))&&t){this.regionUrlProvider=new z(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===J.Disconnected&&(this.regionUrl=i,yield fetch(zt(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(zt(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return p(this,void 0,void 0,function*(){let i=()=>p(this,void 0,void 0,function*(){}),s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new Ne({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new Ne({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new Ne({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new Ne({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Ne({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Ne({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":s=new Ne({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>p(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new gi({reason:ke.CLIENT_INITIATED,action:vt.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new Ne({scenario:{case:"subscriberBandwidth",value:lt(t)}});break;case"leave-full-reconnect":s=new Ne({scenario:{case:"leaveRequestFullReconnect",value:!0}})}s&&(yield this.engine.client.sendSimulateScenario(s),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return p(this,arguments,void 0,function(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var o,c,d,l,u,h,f;let b=!0,v=!1;const R=a?{exact:s}:s;if(i==="audioinput"){v=r.localParticipant.audioTrackPublications.size===0;const T=(o=r.getActiveDevice(i))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=R;const A=Array.from(r.localParticipant.audioTrackPublications.values()).filter(y=>y.source===S.Source.Microphone);try{b=(yield Promise.all(A.map(y=>{var _;return(_=y.audioTrack)===null||_===void 0?void 0:_.setDeviceId(R)}))).every(y=>y===!0)}catch(y){throw r.options.audioCaptureDefaults.deviceId=T,y}const x=A.some(y=>{var _,C;return(C=(_=y.track)===null||_===void 0?void 0:_.isMuted)!==null&&C!==void 0?C:!1});b&&x&&(v=!0)}else if(i==="videoinput"){v=r.localParticipant.videoTrackPublications.size===0;const T=(c=r.getActiveDevice(i))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=R;const A=Array.from(r.localParticipant.videoTrackPublications.values()).filter(y=>y.source===S.Source.Camera);try{b=(yield Promise.all(A.map(y=>{var _;return(_=y.videoTrack)===null||_===void 0?void 0:_.setDeviceId(R)}))).every(y=>y===!0)}catch(y){throw r.options.videoCaptureDefaults.deviceId=T,y}const x=A.some(y=>{var _,C;return(C=(_=y.track)===null||_===void 0?void 0:_.isMuted)!==null&&C!==void 0?C:!1});b&&x&&(v=!0)}else if(i==="audiooutput"){if(v=!0,!Dn()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");r.options.webAudioMix&&(s=(d=yield ce.getInstance().normalizeDeviceId("audiooutput",s))!==null&&d!==void 0?d:""),(l=(f=r.options).audioOutput)!==null&&l!==void 0||(f.audioOutput={});const T=(u=r.getActiveDevice(i))!==null&&u!==void 0?u:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=s;try{r.options.webAudioMix&&((h=r.audioContext)===null||h===void 0||h.setSinkId(s)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(A=>A.setAudioOutput({deviceId:s})))}catch(A){throw r.options.audioOutput.deviceId=T,A}}return v&&(r.localParticipant.activeDeviceMap.set(i,s),r.emit(E.ActiveDeviceChanged,i,s)),b})()})}setupLocalParticipantEvents(){this.localParticipant.on(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(I.AttributesChanged,this.onLocalAttributesChanged).on(I.TrackMuted,this.onLocalTrackMuted).on(I.TrackUnmuted,this.onLocalTrackUnmuted).on(I.LocalTrackPublished,this.onLocalTrackPublished).on(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(I.MediaDevicesError,this.onMediaDevicesError).on(I.AudioStreamAcquired,this.startAudio).on(I.ChatMessage,this.onLocalChatMessageSent).on(I.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===J.Connecting||this.state===J.Reconnecting){const u=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(f=>f.id)}),this.onTrackAdded(e,t,i),h()},h=()=>{this.off(E.Reconnected,u),this.off(E.Connected,u),this.off(E.Disconnected,h)};this.once(E.Reconnected,u),this.once(E.Connected,u),this.once(E.Disconnected,h);return}if(this.state===J.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const s=du(t.id),r=s[0];let a=s[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===r);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}if(!o.startsWith("TR")){const u=this.engine.getTrackIdForReceiver(i);if(!u){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(r),this.logContext);return}o=u}o.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(r,", streamId: ").concat(a,", trackId: ").concat(o),Object.assign(Object.assign({},this.logContext),{rpID:r,streamId:a,trackId:o}));let d;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?d=this.options.adaptiveStream:d={});const l=c.addSubscribedMediaTrack(e,o,t,i,d);l?.isEncrypted&&!this.e2eeManager&&this.emit(E.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i,s;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.state!==J.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(a=>{r.unpublishTrack(a.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var a,o,c;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((a=r.track)===null||a===void 0||a.detach(),(o=r.track)===null||o===void 0||o.stop()):(c=r.track)===null||c===void 0||c.stopMonitor()}),this.localParticipant.off(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(I.AttributesChanged,this.onLocalAttributesChanged).off(I.TrackMuted,this.onLocalTrackMuted).off(I.TrackUnmuted,this.onLocalTrackUnmuted).off(I.LocalTrackPublished,this.onLocalTrackPublished).off(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(I.MediaDevicesError,this.onMediaDevicesError).off(I.AudioStreamAcquired,this.startAudio).off(I.ChatMessage,this.onLocalChatMessageSent).off(I.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),ye()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(s=(i=navigator.mediaDevices)===null||i===void 0?void 0:i.removeEventListener)===null||s===void 0||s.call(i,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(J.Disconnected),this.emit(E.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(E.ParticipantDisconnected,t),t.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,i,s,r,a){return p(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,ie.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,ie.builtIn("UNSUPPORTED_METHOD"));return}let c=null,d=null;try{const l=yield o({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});$n(l)>ha?(c=ie.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),this.log.warn("RPC Response payload too large for ".concat(i))):d=l}catch(l){l instanceof ie?c=l:(this.log.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),l),c=ie.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,d,c)})}selectDefaultDevices(){return p(this,void 0,void 0,function*(){var e,t,i;const s=ce.getInstance().previousDevices,r=yield ce.getInstance().getDevices(void 0,!1),a=be();if(a?.name==="Chrome"&&a.os!=="iOS")for(let c of r){const d=s.find(l=>l.deviceId===c.deviceId);d&&d.label!==""&&d.kind===c.kind&&d.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(E.ActiveDeviceChanged,c.kind,c.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let c of o){const d=eu(c),l=this.localParticipant.getTrackPublication(d);if(l&&(!((e=l.track)===null||e===void 0)&&e.isUserProvided))continue;const u=r.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((t=s.filter(f=>f.kind===c)[0])===null||t===void 0?void 0:t.deviceId)&&u.length>0&&((i=u[0])===null||i===void 0?void 0:i.deviceId)!==h){yield this.switchActiveDevice(c,u[0].deviceId);continue}c==="audioinput"&&!Ht()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Ht())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return p(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Lo())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),le(200)])}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(E.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let s;return t?s=Oi.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new Oi(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(E.ParticipantConnected,i),i.on(I.TrackPublished,s=>{this.emitWhenConnected(E.TrackPublished,s,i)}).on(I.TrackSubscribed,(s,r)=>{s.kind===S.Kind.Audio?(s.on(w.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(w.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===S.Kind.Video&&(s.on(w.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(w.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(E.TrackSubscribed,s,r,i)}).on(I.TrackUnpublished,s=>{this.emit(E.TrackUnpublished,s,i)}).on(I.TrackUnsubscribed,(s,r)=>{this.emit(E.TrackUnsubscribed,s,r,i)}).on(I.TrackMuted,s=>{this.emitWhenConnected(E.TrackMuted,s,i)}).on(I.TrackUnmuted,s=>{this.emitWhenConnected(E.TrackUnmuted,s,i)}).on(I.ParticipantMetadataChanged,s=>{this.emitWhenConnected(E.ParticipantMetadataChanged,s,i)}).on(I.ParticipantNameChanged,s=>{this.emitWhenConnected(E.ParticipantNameChanged,s,i)}).on(I.AttributesChanged,s=>{this.emitWhenConnected(E.ParticipantAttributesChanged,s,i)}).on(I.ConnectionQualityChanged,s=>{this.emitWhenConnected(E.ConnectionQualityChanged,s,i)}).on(I.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(E.ParticipantPermissionsChanged,s,i)}).on(I.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(E.TrackSubscriptionStatusChanged,s,r,i)}).on(I.TrackSubscriptionFailed,(s,r)=>{this.emit(E.TrackSubscriptionFailed,s,i,r)}).on(I.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(E.TrackSubscriptionPermissionChanged,s,r,i)}).on(I.Active,()=>{this.emitWhenConnected(E.ParticipantActive,i),i.kind===Ft.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,s)=>(i.push(...s.getTrackPublications()),i),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Su(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=de.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ke.STATE_MISMATCH))):e=0},Wh)}clearConnectionReconcile(){this.connectionReconcileInterval&&de.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(E.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(this.state===J.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===J.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return p(this,void 0,void 0,function*(){var t,i,s,r;const a=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new ai({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:X.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new ot({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(E.SignalConnected),this.emit(E.Connected),this.setAndEmitConnectionState(J.Connected),a.video){const c=new ss(S.Kind.Video,new gt({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO,name:"video-dummy"}),new Di(a.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:zo(160*((i=o.aspectRatios[0])!==null&&i!==void 0?i:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(I.LocalTrackPublished,c)}if(a.audio){const c=new ss(S.Kind.Audio,new gt({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO}),new Ii(a.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:xn(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(c),this.localParticipant.emit(I.LocalTrackPublished,c)}for(let c=0;c<o.count-1;c+=1){let d=new ot({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(c),state:ft.ACTIVE,tracks:[],joinedAt:X.parse(Date.now())});const l=this.getOrCreateParticipant(d.identity,d);if(o.video){const u=zo(160*((r=o.aspectRatios[c%o.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),h=new gt({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}if(o.audio){const u=xn(),h=new gt({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Re.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),d.tracks=[...d.tracks,h]}l.updateInfo(d)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(e!==E.ActiveSpeakersChanged&&e!==E.TranscriptionReceived){const r=Ia(i).filter(a=>a!==void 0);(e===E.TrackSubscribed||e===E.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r})),this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...i)}}Pt.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function Ia(n){return n.map(e=>{if(e)return Array.isArray(e)?Ia(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Ae;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(Ae||(Ae={}));class nt extends xe.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Ae.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Pt(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return p(this,void 0,void 0,function*(){if(this.status!==Ae.IDLE)throw Error("check is running already");this.setStatus(Ae.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==Ae.SKIPPED&&this.setStatus(this.isSuccess()?Ae.SUCCESS:Ae.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return p(this,void 0,void 0,function*(){return this.room.state===J.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return p(this,void 0,void 0,function*(){this.room&&this.room.state!==J.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Ae.SKIPPED)}switchProtocol(e){return p(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(E.Reconnecting,()=>{t=!0}),this.room.once(E.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(i)return;yield le(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Kh extends nt{get description(){return"Cloud regions"}perform(){return p(this,void 0,void 0,function*(){const e=new z(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let r=0;r<3;r++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((r,a)=>(r.duration-a.duration)*.5+(r.rtt-a.rtt)*.5);const s=t[0];this.bestStats=s,this.appendMessage("best Cloud region: ".concat(s.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return p(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const s=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!s)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,c=1e6/a,d="A".repeat(a),l=Date.now();for(let b=0;b<c;b++)yield r.write(d);yield r.close();const u=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:s,rtt:1e4,duration:u-l};return h?.forEach(b=>{b.type==="candidate-pair"&&b.nominated&&(f.rtt=b.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const rs=1e4;class Hh extends nt{get description(){return"Connection via UDP vs TCP"}perform(){return p(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(rs/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(rs/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return p(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let s=0;const r=()=>{s=(s+1)%360,i.fillStyle="hsl(".concat(s,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const o=t.captureStream(30).getVideoTracks()[0],d=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>p(this,void 0,void 0,function*(){const h=yield d.getRTCStatsReport();h?.forEach(f=>{f.type==="outbound-rtp"?(l.packetsSent=f.packetsSent,l.qualityLimitationDurations=f.qualityLimitationDurations,l.bitrateTotal+=f.targetBitrate,l.count++):f.type==="remote-inbound-rtp"&&(l.packetsLost=f.packetsLost,l.rttTotal+=f.roundTripTime,l.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,rs)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}}class Gh extends nt{get description(){return"Can publish audio"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield Fh();if(yield Mo(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let a=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class zh extends nt{get description(){return"Can publish video"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield Uh();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(r+=a.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return p(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,i.autoplay=!0,i.playsInline=!0,i.setAttribute("playsinline","true"),document.body.appendChild(i),yield new Promise(s=>{i.onplay=()=>{setTimeout(()=>{var r,a,o,c;const d=document.createElement("canvas"),l=e.getSettings(),u=(a=(r=l.width)!==null&&r!==void 0?r:i.videoWidth)!==null&&a!==void 0?a:1280,h=(c=(o=l.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&c!==void 0?c:720;d.width=u,d.height=h;const f=d.getContext("2d");f.drawImage(i,0,0);const v=f.getImageData(0,0,d.width,d.height).data;let R=!0;for(let T=0;T<v.length;T+=4)if(v[T]!==0||v[T+1]!==0||v[T+2]!==0){R=!1;break}R?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},i.play()}),t.getTracks().forEach(s=>s.stop()),i.remove()})}}class Jh extends nt{get description(){return"Resuming connection after interruption"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,s=!1,r;const a=new Promise(d=>{setTimeout(d,5e3),r=d}),o=()=>{i=!0};t.on(E.SignalReconnecting,o).on(E.Reconnecting,o).on(E.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield a,i){if(!s||t.state!==J.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class $h extends nt{get description(){return"Can connect via TURN"}perform(){return p(this,void 0,void 0,function*(){var e,t,i;St(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new z(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const s=new Vn,r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let a=!1,o=!1,c=!1;for(let d of r.iceServers)for(let l of d.urls)l.startsWith("turn:")?(o=!0,c=!0):l.startsWith("turns:")&&(o=!0,c=!0,a=!0),l.startsWith("stun:")&&(c=!0);c?o&&!a&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield s.close(),!((i=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||i===void 0)&&i.iceServers||o?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(d=>setTimeout(d,0)))})}}class Qh extends nt{get description(){return"Establishing WebRTC connection"}perform(){return p(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(E.SignalConnected,()=>{var i;const s=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,a)=>{if(r.candidate){const o=new RTCIceCandidate(r);let c="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(Yh(o.address)?c+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,c+=" (passive)"):o.protocol==="udp"&&(t=!0)),this.appendMessage(c)}s&&s(r,a)},!((i=this.room.engine.pcManager)===null||i===void 0)&&i.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),V.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function Yh(n){const e=n.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class Xh extends nt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return p(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new Vn,r;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(St(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));const c=yield new z(this.url,this.token).getNextBestRegionUrl();c&&(r=yield s.join(c,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),this.appendMessage("Fallback to region worked. To avoid initial connections failing, ensure you're calling room.prepareConnection() ahead of time"))}}r?(this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===yr.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=r.serverInfo)===null||i===void 0?void 0:i.region))):this.appendError("Websocket connection could not be established"),yield s.close()})}}class Pp extends xe.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Ae.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==Ae.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return p(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),s=a=>{this.updateCheck(t,a)};i.on("update",s);const r=yield i.run();return i.off("update",s),r})}checkWebsocket(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Xh)})}checkWebRTC(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Qh)})}checkTURN(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck($h)})}checkReconnect(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Jh)})}checkPublishAudio(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Gh)})}checkPublishVideo(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(zh)})}checkConnectionProtocol(){return p(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Hh);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Kh)})}}function H(n,e,t){return(e=ep(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function Zh(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var i=t.call(n,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function ep(n){var e=Zh(n,"string");return typeof e=="symbol"?e:e+""}new TextEncoder,new TextDecoder;class fe extends Error{constructor(e,t){var i;super(e,t),H(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(i=Error.captureStackTrace)===null||i===void 0||i.call(Error,this,this.constructor)}}H(fe,"code","ERR_JOSE_GENERIC");class tp extends fe{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),H(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),H(this,"claim",void 0),H(this,"reason",void 0),H(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}H(tp,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class ip extends fe{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:i,reason:s,payload:t}}),H(this,"code","ERR_JWT_EXPIRED"),H(this,"claim",void 0),H(this,"reason",void 0),H(this,"payload",void 0),this.claim=i,this.reason=s,this.payload=t}}H(ip,"code","ERR_JWT_EXPIRED");class np extends fe{constructor(){super(...arguments),H(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}H(np,"code","ERR_JOSE_ALG_NOT_ALLOWED");class sp extends fe{constructor(){super(...arguments),H(this,"code","ERR_JOSE_NOT_SUPPORTED")}}H(sp,"code","ERR_JOSE_NOT_SUPPORTED");class rp extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),H(this,"code","ERR_JWE_DECRYPTION_FAILED")}}H(rp,"code","ERR_JWE_DECRYPTION_FAILED");class op extends fe{constructor(){super(...arguments),H(this,"code","ERR_JWE_INVALID")}}H(op,"code","ERR_JWE_INVALID");class ap extends fe{constructor(){super(...arguments),H(this,"code","ERR_JWS_INVALID")}}H(ap,"code","ERR_JWS_INVALID");class cp extends fe{constructor(){super(...arguments),H(this,"code","ERR_JWT_INVALID")}}H(cp,"code","ERR_JWT_INVALID");class dp extends fe{constructor(){super(...arguments),H(this,"code","ERR_JWK_INVALID")}}H(dp,"code","ERR_JWK_INVALID");class lp extends fe{constructor(){super(...arguments),H(this,"code","ERR_JWKS_INVALID")}}H(lp,"code","ERR_JWKS_INVALID");class up extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),H(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}H(up,"code","ERR_JWKS_NO_MATCHING_KEY");class hp extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),H(this,Symbol.asyncIterator,void 0),H(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}H(hp,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class pp extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),H(this,"code","ERR_JWKS_TIMEOUT")}}H(pp,"code","ERR_JWKS_TIMEOUT");class mp extends fe{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),H(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}H(mp,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");var Da;(function(n){n[n.Reserved=0]="Reserved",n[n.TooLarge=1]="TooLarge"})(Da||(Da={}));var Aa;(function(n){n[n.TooShort=0]="TooShort",n[n.HeaderOverrun=1]="HeaderOverrun",n[n.MissingExtWords=2]="MissingExtWords",n[n.UnsupportedVersion=3]="UnsupportedVersion",n[n.InvalidHandle=4]="InvalidHandle",n[n.MalformedExt=5]="MalformedExt"})(Aa||(Aa={}));var Oa;(function(n){n[n.TooSmallForHeader=0]="TooSmallForHeader",n[n.TooSmallForPayload=1]="TooSmallForPayload"})(Oa||(Oa={}));var Ni;(function(n){n[n.UserTimestamp=2]="UserTimestamp",n[n.E2ee=1]="E2ee"})(Ni||(Ni={})),Ni.UserTimestamp,Ni.E2ee;var Na;(function(n){n[n.Start=0]="Start",n[n.Inter=1]="Inter",n[n.Final=2]="Final",n[n.Single=3]="Single"})(Na||(Na={}));class fp extends j{constructor(e){super(),this._room=null,this._context=e,this._trackRegistry=new jc,this._eventAdapter=new qc(e,this._trackRegistry),this._maxAttempts=e.options.reconnect?.maxAttempts||It,this._maxDelay=(e.options.reconnect?.delay??Mi)*Dt,m.info("LiveKit Service created")}async connect(e,t,i,s){if(this.ensureNotDisposed(),this._room&&this._room.isConnected()){m.warn("Already connected to LiveKit room");return}try{m.info(`Connecting to LiveKit room: ${i} at ${e}`);const r=new Pt({reconnectPolicy:{nextRetryDelayInMs:a=>a.elapsedMs<this._maxDelay?Math.min(Dt*Math.pow(2,a.retryCount),this._maxDelay):null}});r.prepareConnection(e,t),r.on(E.TrackSubscribed,(a,o,c)=>{this._handleTrackSubscribed(a,o,c)}),r.on(E.TrackUnsubscribed,(a,o,c)=>{this._handleTrackUnsubscribed(a,o,c)}),r.on(E.TrackMuted,(a,o)=>{this._handleTrackMuted(a,o)}),r.on(E.TrackUnmuted,(a,o)=>{this._handleTrackUnmuted(a,o)}),r.on(E.Connected,()=>{m.info("Connected to LiveKit room"),this._context.eventBus.emit("inner:rtc:connected",void 0)}),r.on(E.Disconnected,a=>{a?m.info(`LiveKit room disconnected: ${a}`):m.info("LiveKit room disconnected"),a!==ke.CLIENT_INITIATED&&this._context.eventBus.emit("inner:rtc:disconnected",{reason:a?String(a):void 0}),this._room=null}),m.info("Connecting to LiveKit room..."),await r.connect(e,t,{autoSubscribe:!0,maxRetries:this._context.options.reconnect?.maxAttempts||It}),this._eventAdapter.setRoom(r),this._room=r}catch(r){throw G.fromError(r,B.LIVEKIT_CONNECT_FAILED)}}_handleTrackSubscribed(e,t,i){try{if(!e.mediaStreamTrack){m.warn("Track does not have MediaStreamTrack");return}e.kind==="audio"&&i.on(I.IsSpeakingChanged,o=>{console.log("\u8F68\u9053 \u8BF4\u8BDD\u72B6\u6001:",o)});const r=t.trackSid,a=i.identity;this._eventAdapter.handleTrackSubscribed(e,r,a)}catch(s){m.error("Error handling track subscribed:",s)}}_handleTrackUnsubscribed(e,t,i){try{const s=t,r=i,a=s.trackSid,o=r.identity;this._trackRegistry.getTrack(a)?.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:unavailable",void 0),this._eventAdapter.handleTrackUnsubscribed(a,o)}catch(s){m.error("Error handling track unsubscribed:",s)}}_handleTrackMuted(e,t){try{e.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:unavailable",void 0)}catch(i){m.error("Error handling track muted:",i)}}_handleTrackUnmuted(e,t){try{e.kind==="video"&&this._context.eventBus.emit("inner:rtc:video:available",void 0)}catch(i){m.error("Error handling track unmuted:",i)}}async disconnect(){if(this._room)try{await this._room.disconnect(),this._room=null,this._context.eventBus.emit("inner:rtc:disconnected",{reason:"Disconnected from LiveKit room"}),m.info("Disconnected from LiveKit room")}catch(e){m.error("Error disconnecting from LiveKit room:",e),this._room=null}}isConnected(){return this._room?this._room.state===J.Connected:!1}getTrackRegistry(){return this._trackRegistry}get trackRegistry(){return this._trackRegistry}getEventAdapter(){return this._eventAdapter}onDispose(){this.disconnect(),this._trackRegistry.dispose(),this._eventAdapter.dispose(),m.info("LiveKit Service disposed")}}class gp extends j{constructor(e){super(),this._conversationManager=null,this._context=e,m.info("WebSocket Dispatcher created")}setConversationManager(e){this._conversationManager=e,m.debug("Conversation manager set in dispatcher")}dispatch(e){this.ensureNotDisposed();try{if(e.type==="ws"){this._handleWSServerMessage(e);return}if(e.type==="text"){this._handleServerTextMessage(e);return}}catch(t){m.error("Error dispatching message:",t)}}_handleWSServerMessage(e){e.code===101?(this._conversationManager?.handleServerPong(),m.debug("Received pingpong response")):e.code===102&&(m.warn("Server will disconnect"),this._conversationManager?.willDisconnect())}_handleServerTextMessage(e){if(!this._conversationManager){m.warn("Conversation manager not set, text message ignored");return}const{uid:t,payload:i,code:s}=e;s===200?(this._conversationManager.handleAnswerChunk(t,i,!1),m.debug(`Answer received (code 200) for uid: ${t}`)):s===201?(this._conversationManager.handleAnswerChunk(t,"",!0),m.debug(`Answer completed (code 201) for uid: ${t}`)):s===300?(this._conversationManager.handleAsrTextReceived(t,i),m.debug(`ASR text chunk received (code 300) for uid: ${t}`)):s===400?(this._conversationManager.handleServerInitiatedMessage(t,i),m.debug(`Server initiated message received (code 300) for uid: ${t}`)):s===500&&(this._conversationManager.handleServerCommand(s,i),m.debug(`Server command received (code 500) for uid: ${t}`))}onDispose(){m.info("WebSocket Dispatcher disposed")}}class vp extends j{constructor(e){super(),this._ws=null,this._dispatcher=null,this._isConnecting=!1,this._activeTimers=new Set,this._retryCount=0,this._maxRetries=It,this._pingTimer=void 0,this._pongTimer=void 0,this._isExplicitDisconnect=!1,this._context=e,this._maxRetries=e.options.reconnect?.maxAttempts??It,this._maxDelay=(e.options.reconnect?.delay??Mi)*Dt,this._dispatcher=new gp(e)}setConversationManager(e){this._dispatcher&&this._dispatcher.setConversationManager(e)}async connect(){if(this.ensureNotDisposed(),this._stopHeartbeat(),!(this._isConnecting||this.isConnected||this._ws?.readyState===WebSocket.OPEN)){this._isConnecting=!0,this._isExplicitDisconnect=!1;try{return this._ws=new WebSocket(this._context.wsUrl),new Promise((e,t)=>{this._ws.onopen=()=>{this._isConnecting=!1,this._retryCount=0,this.sendPing(),this._context.eventBus.emit("inner:ws:connected",void 0),m.info("Conversation transport connected"),e()},this._ws.onerror=i=>{this._isConnecting=!1,m.error("Conversation transport error:",i),this._context.eventBus.emit("inner:sdk:error",{error:new G("WebSocket connection error",B.WS_CONNECT_ERROR,i)}),t(new G("WebSocket connection error",B.WS_CONNECT_ERROR,i))},this._ws.onclose=i=>{const s=i.code,r=i.reason?i.reason:i.wasClean?"Clean close":"Closed by remote";this._handleDisconnect(s,r)},this._ws.onmessage=i=>{this._handleMessage(i.data)}})}catch(e){throw this._isConnecting=!1,this._context.emitError(e,B.WS_CONNECT_FAILED)}}}disconnect(){this._isExplicitDisconnect=!0,this._stopHeartbeat(),this._ws&&(this._ws.close(),this._ws=null),this._context.eventBus.emit("inner:ws:disconnected",{reason:"Client disconnect"}),m.info("Conversation transport disconnected")}_handleDisconnect(e,t){if(this._stopHeartbeat(),this._isConnecting=!1,e!==void 0&&new Set([1e3,1001,1002,1003,1007,1008]).has(e)){this._isExplicitDisconnect=!0;const s=`WebSocket closed (code ${e}): ${t??""}`;this._context.eventBus.emit("inner:ws:disconnected",{reason:s}),m.info(`Conversation transport closed with non-retry code ${e}: ${t??""}`);return}if(!this._isExplicitDisconnect&&this._retryCount<this._maxRetries){this._retryCount++;const s=Math.min(Dt*Math.pow(2,this._retryCount-1),this._maxDelay);m.warn(`Connection lost. Retry ${this._retryCount} in ${s}ms`);const r=setTimeout(()=>{!this._isExplicitDisconnect&&!this.isDisposed&&this.connect().catch(()=>{})},s);this._registerTimer(r)}else this._context.eventBus.emit("inner:ws:disconnected",{reason:"Closed"})}_registerTimer(e){return this._activeTimers.add(e),e}_clearTimer(e){e&&(clearTimeout(e),this._activeTimers.delete(e))}sendPing(){if(!this.isConnected)return;const e={type:"ws",code:101,payload:"ping"};this._ws?.send(JSON.stringify(e)),clearTimeout(this._pongTimer),this._pongTimer=setTimeout(()=>{m.error(`Pong timeout (${fs/Dt}s). Reconnecting...`),this._ws?.close()},fs)}handlePongReceived(){clearTimeout(this._pongTimer),this._clearTimer(this._pingTimer),this._pingTimer=setTimeout(()=>{this.sendPing()},ja)}willDisconnect(){if(this.ensureNotDisposed(),this._ws&&this._ws.readyState===WebSocket.OPEN){const t=JSON.stringify({type:"ws",code:102,payload:"will disconnect"});this._ws.send(t),this._isExplicitDisconnect=!0,this._ws.close(),this._ws=null,this._context.eventBus.emit("inner:ws:disconnected",{reason:"Client responsive to server's disconnect message."})}}sendText(e,t,i=200,s){if(this.ensureNotDisposed(),!this._ws||this._ws.readyState!==WebSocket.OPEN)throw new G("WebSocket is not connected",B.WS_NOT_CONNECTED);try{const a=JSON.stringify({type:"text",code:i,uid:e,metadata:s,payload:t});this._ws.send(a),m.debug("Text message sent via transport:",e)}catch(r){throw this._context.emitError(r,B.WS_TEXT_SEND_FAILED)}}_handleMessage(e){try{if(typeof e!="string")return;const t=JSON.parse(e);m.debug("Message received:",t.type),this._dispatcher?this._dispatcher.dispatch(t):m.warn("Dispatcher not set, message ignored")}catch(t){m.error("Error parsing message:",t),this._context.emitError(t,B.WS_PARSE_ERROR)}}sendBinary(e){if(this.ensureNotDisposed(),!this._ws||this._ws.readyState!==WebSocket.OPEN){m.debug("WebSocket not connected, binary data dropped");return}try{this._ws.send(e),m.debug("Binary data sent via transport")}catch(t){m.error("Error sending binary data:",t)}}get isConnected(){return this._ws?.readyState===WebSocket.OPEN}_stopHeartbeat(){this._clearTimer(this._pingTimer),this._clearTimer(this._pongTimer)}onDispose(){this._stopHeartbeat(),this.disconnect(),this._dispatcher&&(this._dispatcher.dispose(),this._dispatcher=null),m.info("Conversation transport disposed")}}const xi=["sdk:connected","sdk:disconnected","sdk:error","media:video:available","media:video:unavailable","media:video:trackAdded","media:video:trackRemoved","media:audio:trackAdded","media:audio:trackRemoved","media:audio:captureStarted","media:audio:captureStopped","media:camera:started","media:camera:stopped","media:audio:volumeChanged","media:audio:muted","media:audio:unmuted","conversation:question:sent","conversation:answer:waiting","conversation:server:message","conversation:asr:received","conversation:answer:chunk","conversation:answer:completed"],xa=/^[a-z]+:[a-zA-z]+(:[a-zA-Z]+)?$/;class bp{constructor(e){this.inner=e,this.listeners=new Map,this.forwardedVideoTrackIds=new Set,this.wsConnected=!1,this.livekitConnected=!1,this.httpConnected=!1,this.internalMap={"inner:sdk:error":{public:"sdk:error",sanitizer:t=>({message:t?.error?.message,code:t?.error?.code})},"inner:rtc:video:available":{public:"media:video:available"},"inner:rtc:video:unavailable":{public:"media:video:unavailable"},"inner:video:track:added":{public:"media:video:trackAdded"},"inner:video:track:removed":{public:"media:video:trackRemoved"},"inner:audio:track:added":{public:"media:audio:trackAdded"},"inner:audio:track:removed":{public:"media:audio:trackRemoved"},"inner:audio:input:started":{public:"media:audio:captureStarted"},"inner:audio:input:stopped":{public:"media:audio:captureStopped"},"inner:camera:started":{public:"media:camera:started"},"inner:camera:stopped":{public:"media:camera:stopped"},"inner:audio:volume:changed":{public:"media:audio:volumeChanged",sanitizer:t=>({volume:t?.volume})},"inner:audio:muted":{public:"media:audio:muted"},"inner:audio:unmuted":{public:"media:audio:unmuted"},"inner:conversation:question:sent":{public:"conversation:question:sent",sanitizer:t=>({questionId:t?.questionId,text:String(t?.text||"")})},"inner:conversation:answer:waiting":{public:"conversation:answer:waiting",sanitizer:t=>({questionId:t?.questionId})},"inner:conversation:server:message":{public:"conversation:server:message",sanitizer:t=>({questionId:t?.questionId,message:String(t?.message||""),type:String(t?.type||"")})},"inner:conversation:asr:received":{public:"conversation:asr:received",sanitizer:t=>({questionId:t?.questionId,text:String(t?.text||"")})},"inner:conversation:answer:chunk":{public:"conversation:answer:chunk",sanitizer:t=>({questionId:t?.questionId,chunk:String(t?.chunk||"")})},"inner:conversation:answer:completed":{public:"conversation:answer:completed",sanitizer:t=>({questionId:t?.questionId,fullAnswer:String(t?.fullAnswer||"")})}},Object.keys(this.internalMap).forEach(t=>{this.inner.on(t,i=>this.handleInternalEvent(t,i))}),this.inner.on("inner:sdk:connected",t=>this.handleConnected(t,!0)),this.inner.on("inner:sdk:disconnected",t=>this.handleConnected(t,!1)),xi.forEach(t=>{this.inner.on(t,i=>this.handlePublicEvent(t,i))})}publicAPI(){return{on:this.on.bind(this),off:this.off.bind(this),once:this.once.bind(this)}}on(e,t){const i=String(e);return this.assertAllowed(i),this.listeners.has(i)||this.listeners.set(i,new Set),this.listeners.get(i).add(t),()=>this.off(e,t)}once(e,t){const i=String(e);this.assertAllowed(i);const s=r=>{try{t(r)}finally{this.off(e,s)}};return this.on(e,s)}off(e,t){const i=String(e);this.assertAllowed(i);const s=this.listeners.get(i);s&&(s.delete(t),s.size===0&&this.listeners.delete(i))}handleInternalEvent(e,t){const i=this.internalMap[e];if(!i)return;const s=i.public;if(xi.indexOf(s)===-1)return;if(s==="media:video:trackAdded"){const o=t?.trackId||t?.id;if(typeof o=="string"){if(this.forwardedVideoTrackIds.has(o))return;this.forwardedVideoTrackIds.add(o)}}const r=i.sanitizer?i.sanitizer(t):t;if(!xa.test(s))return;const a=this.listeners.get(s);!a||a.size===0||a.forEach(o=>{try{o(r)}catch(c){console.error("PublicEventEmitter listener error",c)}})}handlePublicEvent(e,t){if(xi.indexOf(e)===-1)return;const i=Object.values(this.internalMap).find(a=>a.public===e),s=i&&i.sanitizer?i.sanitizer(t):t;if(e==="media:video:trackAdded"){const a=t?.trackId||t?.id;if(typeof a=="string"){if(this.forwardedVideoTrackIds.has(a))return;this.forwardedVideoTrackIds.add(a)}}const r=this.listeners.get(e);!r||r.size===0||r.forEach(a=>{try{a(s)}catch(o){console.error("PublicEventEmitter listener error",o)}})}handleConnected(e,t){e.source==="livekit"?this.livekitConnected=t:e.source==="ws"?this.wsConnected=t:e.source==="http"&&(this.httpConnected=t),this.maybeEmitSdkConnected(t?"connected":"disconnected")}maybeEmitSdkConnected(e){const t=e==="connected",i=t?!!this.livekitConnected:!this.livekitConnected,s=t?!!this.wsConnected:!this.wsConnected,r=t?!!this.httpConnected:!this.httpConnected,a={livekit:i,ws:s,http:r,all:i&&s&&r},o=JSON.stringify(a);this.lastConnectedPayloadJson!==o&&(this.lastConnectedPayloadJson=o,this.inner.emit(`sdk:${e}`,a))}assertAllowed(e){if(xi.indexOf(e)===-1)throw new Error(`Event "${e}" is not allowed for public consumers`);if(!xa.test(e))throw new Error(`Event name "${e}" does not follow namespace:domain[:action] naming`)}}class yp extends j{constructor(e,t,i){super(),this._requestCounter=0,this._context=e,this._baseURL=t||"",this._defaultHeaders=i||{},m.info(`HTTP Service created with baseURL: ${this._baseURL||"none"}`)}setAuthToken(e){this._defaultHeaders.Authorization=`Bearer ${e}`}request(e){this.ensureNotDisposed();const t=e.requestId||`req_${Date.now()}_${++this._requestCounter}`,i=this._buildURL(e.url,e.params),s=this._mergeHeaders(e.headers),r={method:e.method||"GET",headers:s};e.data!==void 0&&(e.method||"GET")!=="GET"&&(typeof e.data=="string"?r.body=e.data:(r.body=JSON.stringify(e.data),!s["Content-Type"]&&!s["content-type"]&&(s["Content-Type"]="application/json")));const a=e.timeout||3e4,o=new AbortController;return r.signal=o.signal,new Promise((c,d)=>{const l=setTimeout(()=>o.abort(),a);fetch(i,r).then(async u=>{clearTimeout(l);const h={};u.headers.forEach((R,T)=>{h[T]=R});let f;const b=u.headers.get("content-type");b&&b.includes("application/json")?f=await u.json():f=await u.text();const v={requestId:t,status:u.status,headers:h,data:f,config:e};m.debug(`HTTP request succeeded: ${e.method} ${i} [${t}]`),c(v)}).catch(u=>{clearTimeout(l);const h=u&&u.name==="AbortError",f={requestId:t,status:u&&u.status||void 0,message:h?"Request aborted (timeout)":u&&u.message||"HTTP request failed",error:u,config:e};m.error(`HTTP request failed: ${e.method} ${i} [${t}]`,u),d(f)})})}get(e,t,i){return this.request({...i,url:e,method:"GET",params:t})}post(e,t,i){return this.request({...i,url:e,method:"POST",data:t})}put(e,t,i){return this.request({...i,url:e,method:"PUT",data:t})}delete(e,t){return this.request({...t,url:e,method:"DELETE"})}patch(e,t,i){return this.request({...i,url:e,method:"PATCH",data:t})}_buildURL(e,t){if(e.startsWith("http://")||e.startsWith("https://"))return this._appendParams(e,t);let i=this._baseURL;return i&&!i.endsWith("/")&&!e.startsWith("/")?i+="/":i&&i.endsWith("/")&&e.startsWith("/")&&(i=i.slice(0,-1)),i+=e,this._appendParams(i,t)}_appendParams(e,t){if(!t||Object.keys(t).length===0)return e;const i=new URLSearchParams;for(const[r,a]of Object.entries(t))i.append(r,String(a));const s=e.includes("?")?"&":"?";return`${e}${s}${i.toString()}`}_mergeHeaders(e){const t={...this._defaultHeaders};return e&&Object.assign(t,e),t}onDispose(){m.info("HTTP Service disposed")}}function _p(n,e="https"){return n.startsWith(e)?n:`${e}://${n}`}class Tp extends j{constructor(e,t){super(),this._context=e,this._httpService=new yp(e,t||Ka)}getAuthToken(){return this.ensureNotDisposed(),this._httpService?.request({url:"/auth/login",method:"GET",data:{}}).then(e=>{e.data.code===At&&this._httpService?.setAuthToken(e.data.data.token)}).catch(e=>{throw this._context.emitError(e,B.SDK_AUTH_TOKEN_FAILED)})}getLivekitConfig(){return this.ensureNotDisposed(),this._httpService?.request({url:"/stream/v1/start",method:"POST",data:{avatarName:this._context.options.avatarName,voice:this._context.options.avatarVoice||""}}).then(e=>{if(e.data.code===At){const t=e.data.data;return this._context.setLivekitConfig(_p(t.livekitUrl,"wss"),t.roomToken,t.roomId),this._context.setWsUrl(`${this._context.options.wsUrlPrefix||Ga}/${t.roomId}/${this._context.options.avatarName}`),this._context.setVideoOptions({renderMode:t.greenScreen.enabled?"processed":"raw",greenScreen:t.greenScreen||{}}),this._context.eventBus.emit("inner:sdk:connected",{source:"http"}),!0}else throw new G(e.data.msg,B.SDK_GET_LIVEKIT_CONFIG_FAILED)}).catch(e=>{throw this._context.eventBus.emit("inner:sdk:error",{error:new G(e.message,B.SDK_GET_LIVEKIT_CONFIG_FAILED)}),G.fromError(e,B.SDK_GET_LIVEKIT_CONFIG_FAILED)})}switchVideo({onceActions:e,loopActions:t}){return this.ensureNotDisposed(),this._httpService?.request({url:"/avatar/v1/switch-video",method:"POST",data:{roomId:this._context.roomId,onceActions:e,loopActions:t}}).then(i=>{if(i.data.code===At)return!0;throw this._context.emitError(i.data.message,B.SDK_SWITCH_VIDEO_FAILED)})}interruptConversation(){return this.ensureNotDisposed(),this._httpService?.request({url:"/stream/v1/interrupt",method:"POST",data:{roomId:this._context.roomId}}).then(e=>{if(e.data.code===At)return!0;throw this._context.emitError(e.data.message,B.SDK_INTERRUPT_CONVERSATION_FAILED)}).finally(()=>{this._context.eventBus.emit("inner:sdk:disconnected",{source:"http"})})}disconnectConversation(){return this.ensureNotDisposed(),this._httpService?.request({url:"/stream/v1/stop",method:"POST",data:{roomId:this._context.roomId}}).then(e=>e.data.code===At).finally(()=>{this._context.eventBus.emit("inner:sdk:disconnected",{source:"http"})})}onDispose(){this._httpService.dispose()}}class Ma extends j{constructor(e){super(),this._videoController=null,this._audioController=null,this._conversationController=null,this._cameraController=null,this._liveKitService=null,this._conversationTransport=null,this._connectionCoordinator=null,this._httpController=null,this._preConnectPromise=null,this._lastPreConnectSuccessAt=null,this._context=new Ja(e),m.info("SDK Client created")}get events(){return this.ensureNotDisposed(),this._publicEventAPI||(this._publicEmitter=new bp(this._context.eventBus),this._publicEventAPI=this._publicEmitter.publicAPI()),this._publicEventAPI}pushActions({onceActions:e,loopActions:t}){return this.ensureNotDisposed(),this._ensureConnected(),this._httpController?.switchVideo({onceActions:e,loopActions:t})}interruptConnection(){return this.ensureNotDisposed(),this._ensureConnected(),this._httpController?.interruptConversation()}sendTextQuestion(e){if(this.ensureNotDisposed(),this._ensureConnected(),this._conversationController)return this._conversationController.sendQuestion(e);throw new G("Conversation controller is not available",B.CONVERSATION_CONTROLLER_NOT_AVAILABLE)}setRenderFitMode(e){this.ensureNotDisposed(),this._ensureConnected(),this._videoController&&this._videoController.setRenderFitMode(e)}async startAudioCapture(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new G("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);await this._audioController.startCapture()}async stopAudioCapture(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new G("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);await this._audioController.stopCapture()}setVolume(e){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new G("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);this._audioController.setVolume(e)}getVolume(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new G("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);return this._audioController?.getVolume()||1}mute(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new G("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);this._audioController.mute()}unmute(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new G("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);this._audioController.unmute()}get isMuted(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._audioController)throw new G("Audio controller is not available",B.AUDIO_CONTROLLER_NOT_AVAILABLE);return this._audioController.isMuted()}get isAudioCapturing(){return this.ensureNotDisposed(),this._ensureConnected(),this._audioController?this._audioController.isCapturing:!1}async startCamera(){if(this.ensureNotDisposed(),this._ensureConnected(),!this._cameraController)throw new G("Camera controller is not available",B.CAMERA_CONTROLLER_NOT_AVAILABLE);await this._cameraController.startCamera()}stopCamera(){this.ensureNotDisposed(),this._ensureConnected(),this._cameraController&&this._cameraController.stopCamera()}getCameraStream(){return this.ensureNotDisposed(),this._ensureConnected(),this._cameraController?.getStream()??null}getCameraTrack(){return this.ensureNotDisposed(),this._ensureConnected(),this._cameraController?.getTrack()??null}attachCameraTo(e){if(this.ensureNotDisposed(),this._ensureConnected(),!this._cameraController)throw new G("Camera controller is not available",B.CAMERA_CONTROLLER_NOT_AVAILABLE);this._cameraController.attachTo(e)}async preConnect(){if(this.ensureNotDisposed(),this._preConnectPromise)return this._preConnectPromise;const e=Date.now();return this._lastPreConnectSuccessAt!==null&&e-this._lastPreConnectSuccessAt<za?Promise.resolve(!0):(this._preConnectPromise=(async()=>{try{if(m.info("Creating HTTP controller..."),this._httpController=this._httpController??new Tp(this._context,this._context.options.http?.baseURL),m.info("Getting auth token..."),await this._httpController.getAuthToken(),m.info("Getting livekit config..."),!!!await this._httpController?.getLivekitConfig())throw new Error("Config missing");return this._lastPreConnectSuccessAt=Date.now(),!0}catch(t){throw this._context.emitError(t,B.SDK_PRECONNECT_FAILED)}finally{this._preConnectPromise=null}})(),this._preConnectPromise)}async connect(){if(this.ensureNotDisposed(),this._connectionCoordinator&&this._context.sessionState.isConnected){m.warn("SDK already initialized");return}try{if(!await this.preConnect())throw new G("PreConnect failed without explicit error",B.SDK_CONNECT_FAILED)}catch(e){throw this._context.emitError(e,B.SDK_CONNECT_FAILED)}try{if(m.info("Initializing SDK..."),this._connectionCoordinator=new Qa(this._context),this._connectionCoordinator.start(),this._connectionCoordinator.startConnecting(),this._videoController=new ic(this._context,this._context.options.video),this._audioController=new kc(this._context,this._context.options.audio),this._cameraController=new Mc(this._context),this._conversationController=new Vc(this._context),this._liveKitService=new fp(this._context),this._conversationTransport=new vp(this._context),this._liveKitService&&this._videoController&&this._audioController){const e=this._liveKitService.getEventAdapter();e&&(typeof e.setVideoController=="function"&&e.setVideoController(this._videoController),typeof e.setAudioController=="function"&&e.setAudioController(this._audioController))}if(this._conversationTransport){const e={sendBinary:t=>{this._conversationTransport.sendBinary(t)},isConnected:()=>this._conversationTransport.isConnected};this._audioController&&this._audioController.setWebSocketSender(e),this._cameraController&&this._cameraController.setWebSocketSender(e)}this._conversationTransport&&this._conversationController&&(this._conversationTransport.setConversationManager(this._conversationController.manager),this._conversationController.setTransport(this._conversationTransport)),await this._liveKitService.connect(this._context.livekitUrl,this._context.token,this._context.options.avatarName),this._conversationTransport&&await this._conversationTransport.connect(),m.info("SDK initialized and connected")}catch(e){throw this._connectionCoordinator&&this._connectionCoordinator.transitionToIdle(),await this._cleanup(),this._context.emitError(e,B.SDK_INITIALIZATION_FAILED)}}async disconnect(){if(this.ensureNotDisposed(),!(!this._connectionCoordinator||this._connectionCoordinator.getState()==="idle"||this._connectionCoordinator.getState()==="disposed")){m.info("Disconnecting SDK..."),this._connectionCoordinator.startDisconnecting();try{this._conversationTransport&&this._conversationTransport.disconnect(),this._liveKitService&&await this._liveKitService.disconnect(),this._audioController&&this._audioController.stopCapture(),this._cameraController&&this._cameraController.stopCamera(),this._httpController&&await this._httpController.disconnectConversation(),this._preConnectPromise=null,this._connectionCoordinator.completeDisconnecting(),m.info("SDK disconnected")}catch(e){throw m.error("Error during disconnect:",e),this._context.emitError(e,B.SDK_DISCONNECT_FAILED)}}}async reconnect(){this.ensureNotDisposed();const e=this._connectionCoordinator;if(!e?.canStartReconnectingManual()){const i=e?e.getSnapshot():this.connectionSnapshot;return m.warn("SDK reconnect not allowed in current state, returning current snapshot"),i}const t=e.captureSnapshotAndStartReconnectingManual();try{if(this._audioController&&this._audioController.stopCapture(),t.rtc.connected&&!t.rtc.hasVideoTrack&&(await this._liveKitService?.disconnect(),await this._conversationTransport?.disconnect()),this._conversationTransport&&!this._conversationTransport.isConnected){if(!await this.preConnect())throw new G("PreConnect failed without explicit error",B.SDK_CONNECT_FAILED);await this._conversationTransport.connect()}return this._liveKitService&&!this._liveKitService.isConnected()&&await this._liveKitService.connect(this._context.livekitUrl,this._context.token,this._context.options.avatarName),t}catch(i){throw m.error("Error during reconnect:",i),this._context.emitError(i,B.SDK_RECONNECT_FAILED)}}get connectionSnapshot(){return this.ensureNotDisposed(),this._connectionCoordinator?this._connectionCoordinator.getSnapshot():bs(vs("idle"))}async _cleanup(){if(this._conversationTransport&&this._conversationTransport.disconnect(),this._liveKitService)try{await this._liveKitService.disconnect()}catch(e){m.error("Error disconnecting LiveKit:",e)}this._audioController&&this._audioController.stopCapture(),this._cameraController&&this._cameraController.stopCamera()}get isConnected(){return this.ensureNotDisposed(),this._context.sessionState.isConnected}_ensureConnected(){if(!this._context.sessionState.isConnected)throw new G("SDK is not connected. Call connect() first.",B.SDK_NOT_CONNECTED)}onDispose(){this.disconnect().catch(e=>{m.error("Error during disconnect in dispose:",e)}),this._videoController&&(this._videoController.dispose(),this._videoController=null),this._audioController&&(this._audioController.dispose(),this._audioController=null),this._cameraController&&(this._cameraController.dispose(),this._cameraController=null),this._conversationController&&(this._conversationController.dispose(),this._conversationController=null),this._liveKitService&&(this._liveKitService.dispose(),this._liveKitService=null),this._conversationTransport&&(this._conversationTransport.dispose(),this._conversationTransport=null),this._httpController&&(this._httpController.dispose(),this._httpController=null),this._connectionCoordinator&&(this._connectionCoordinator.transitionToDisposed(),this._connectionCoordinator.dispose(),this._connectionCoordinator=null),this._context.dispose(),m.info("SDK Client disposed")}}function kp(n){if(!n.avatarName)throw new G("avatarName is required",B.NO_AVATARNAME);return m.info("Creating SDK client with options:",{avatarName:n.avatarName}),new Ma(n)}class La extends j{constructor(e,t){super(),this._videoElement=null,this._videoUrl=null,this._isPlaying=!1,this._frameCallbackId=null,this._videoUrl=e,t?this._videoElement=t:(this._videoElement=document.createElement("video"),this._videoElement.style.opacity="0",this._videoElement.muted=!0,this._videoElement.playsInline=!0,this._videoElement.loop=!0,document.querySelector("#video-container")?.appendChild(this._videoElement)),m.info("Local Video Debug Source created")}get videoElement(){return this._videoElement}async load(){if(!this._videoElement)throw new Error("Video element or URL not set");return new Promise((e,t)=>{const i=this._videoElement,s=()=>{i.removeEventListener("loadedmetadata",s),i.removeEventListener("error",r),m.info(`Video loaded: ${i.videoWidth}x${i.videoHeight}`),e()},r=a=>{i.removeEventListener("loadedmetadata",s),i.removeEventListener("error",r),t(new Error(`Failed to load video: ${a}`))};i.addEventListener("loadedmetadata",s),i.addEventListener("error",r),i.src=this._videoUrl||"",i.load()})}async play(){if(!this._videoElement)throw new Error("Video element not set");if(!this._isPlaying)try{await this._videoElement.play(),this._videoElement.style.opacity="0",this._videoElement.setAttribute("loop","true"),this._isPlaying=!0,m.info("Video playback started")}catch(e){throw m.error("Failed to play video:",e),e}}pause(){this._videoElement&&this._isPlaying&&(this._videoElement.pause(),this._isPlaying=!1,m.info("Video playback paused"))}stop(){this._videoElement&&(this._videoElement.pause(),this._videoElement.currentTime=0,this._isPlaying=!1,m.info("Video playback stopped"))}get isPlaying(){return this._isPlaying&&this._videoElement!==null&&!this._videoElement.paused}get videoWidth(){return this._videoElement?.videoWidth||0}get videoHeight(){return this._videoElement?.videoHeight||0}async captureFrame(){if(!this._videoElement||this._videoElement.readyState<2)return null;try{if("VideoFrame"in window&&typeof window.VideoFrame=="function")try{return new VideoFrame(this._videoElement,{timestamp:this._videoElement.currentTime*1e6})}catch(i){m.error("",i)}const e=await createImageBitmap(this._videoElement),t=new VideoFrame(e,{timestamp:this._videoElement.currentTime*1e6});return e.close(),t}catch(e){return m.error("Failed to capture video frame:",e),null}}onFrame(e){if(!this._videoElement)return;this.offFrame();const t=this._videoElement;if("requestVideoFrameCallback"in t){const i=(s,r)=>{!this._isPlaying||!this._videoElement||this.captureFrame().then(a=>{a&&(e(a),a.close()),this._isPlaying&&this._videoElement&&(this._frameCallbackId=t.requestVideoFrameCallback(i))}).catch(a=>{m.error("Error in frame callback:",a)})};this._frameCallbackId=t.requestVideoFrameCallback(i)}else{const i=()=>{!this._isPlaying||!this._videoElement||this.captureFrame().then(s=>{s&&(e(s),s.close()),this._isPlaying&&this._videoElement&&(this._frameCallbackId=requestAnimationFrame(i))}).catch(s=>{m.error("Error in frame callback:",s)})};this._frameCallbackId=requestAnimationFrame(i)}}offFrame(){this._frameCallbackId!==null&&(this._videoElement&&"cancelVideoFrameCallback"in this._videoElement?this._videoElement.cancelVideoFrameCallback(this._frameCallbackId):cancelAnimationFrame(this._frameCallbackId),this._frameCallbackId=null)}onDispose(){this.stop(),this.offFrame(),this._videoElement&&this._videoElement.parentElement===document.body&&document.body.removeChild(this._videoElement),this._videoElement=null,this._videoUrl=null,m.info("Local Video Debug Source disposed")}}class Sp extends j{constructor(e,t,i){super(),this._outputCanvas=null,this._outputRenderer=null,this._source=new _s;const s={...e,renderMode:"processed"};this._pipeline=new Ss(this._source,s),this._outputRenderer=new Ui(i,t),this._pipeline.setRenderer(this._outputRenderer),this._outputCanvas=this._outputRenderer.getCanvas(),m.info("Video Pipeline Runner created")}get outputCanvas(){return this._outputCanvas}get processor(){return this._pipeline.strategy.getProcessors()[0]||null}setProcessor(e){this._pipeline.setProcessor(e),m.info("Processor set on pipeline")}async processFrame(e){if(this.ensureNotDisposed(),!this._outputRenderer){m.error("Output renderer not available"),e.close();return}try{const t=this._pipeline.strategy.getProcessors()[0]||null;let i=null;if(t){try{i=t.process(e)}catch(s){m.error("Error processing frame:",s),i=e}if(i===null&&"getImageData"in t){const s=t.getImageData();if(s&&this._outputCanvas&&this._outputRenderer.getContext()){const r=this._outputRenderer.getContext();r&&((this._outputCanvas.width!==s.width||this._outputCanvas.height!==s.height)&&(this._outputCanvas.width=s.width,this._outputCanvas.height=s.height),r.putImageData(s,0,0))}e.close();return}i&&i!==e?(this._outputRenderer.render(i),e.close()):i===e?this._outputRenderer.render(e):e.close()}else this._outputRenderer.render(e)}catch(t){m.error("Error in processFrame:",t),e.close()}}setOutputSize(e,t){this._outputCanvas&&(this._outputCanvas.width=e,this._outputCanvas.height=t,m.info(`Output canvas size set to ${e}x${t}`))}onDispose(){this._pipeline.dispose(),this._outputRenderer&&(this._outputRenderer.dispose(),this._outputRenderer=null),this._outputCanvas&&this._outputCanvas.parentElement===document.body&&document.body.removeChild(this._outputCanvas),this._outputCanvas=null,m.info("Video Pipeline Runner disposed")}}class Cp extends j{constructor(e,t,i,s){if(super(),this._isRunning=!1,this._videoSource=new La(e,t),this._options={renderMode:"processed",containerElement:t,...s},this._pipelineRunner=new Sp(this._options,t,i),this._options.greenScreen?.enabled){const r=new Fi(this._options.greenScreen);this._pipelineRunner.setProcessor(r),m.info("Green screen processor enabled in debugger")}m.info("Standalone Video Debugger created")}async switchSource(e,t){this.ensureNotDisposed();const i=this._videoSource,s=this._isRunning,r=new La(e,t);try{await r.load(),s&&await r.play(),r.onFrame(c=>{this._pipelineRunner.processFrame(c).catch(d=>{m.error("Error processing frame:",d)})}),this._videoSource=r;try{i.offFrame(),i.stop(),i.dispose()}catch(c){console.warn("Error disposing old video source during switch:",c)}const a=this._videoSource.videoWidth,o=this._videoSource.videoHeight;a>0&&o>0&&this._pipelineRunner.setOutputSize(a,o)}catch(a){m.error("Failed to switch video source:",a);try{r.dispose()}catch(o){console.warn("Error disposing new video source after failed switch:",o)}throw a}}get outputCanvas(){return this._pipelineRunner.outputCanvas}get videoSource(){return this._videoSource}get processor(){return this._pipelineRunner.processor}setProcessor(e){this._pipelineRunner.setProcessor(e)}updateGreenScreenOptions(e){const t=this._pipelineRunner.processor;if(t&&"updateOptions"in t&&typeof t.updateOptions=="function")t.updateOptions(e),m.info("Green screen options updated");else{const i=this._options.greenScreen||{enabled:!1},s={...i,...e,enabled:e.enabled!==void 0?e.enabled:i.enabled},r=new Fi(s);this._pipelineRunner.setProcessor(r),this._options.greenScreen=s,m.info("Green screen processor recreated with new options")}}async initialize(){this.ensureNotDisposed();try{await this._videoSource.load();const e=this._videoSource.videoWidth,t=this._videoSource.videoHeight;e>0&&t>0&&this._pipelineRunner.setOutputSize(e,t),m.info("Video debugger initialized")}catch(e){throw m.error("Failed to initialize video debugger:",e),e}}async start(){if(this.ensureNotDisposed(),this._isRunning){m.warn("Debugger is already running");return}try{this._videoSource.videoWidth===0&&await this.initialize(),await this._videoSource.play(),this._videoSource.onFrame(e=>{this._pipelineRunner.processFrame(e).catch(t=>{m.error("Error processing frame:",t)})}),this._isRunning=!0,m.info("Video debugger started")}catch(e){throw m.error("Failed to start video debugger:",e),e}}stop(){this._isRunning&&(this._videoSource.stop(),this._videoSource.offFrame(),this._isRunning=!1,m.info("Video debugger stopped"))}pause(){this._isRunning&&(this._videoSource.pause(),m.info("Video debugger paused"))}async resume(){this._isRunning&&(await this._videoSource.play(),m.info("Video debugger resumed"))}get isRunning(){return this._isRunning}onDispose(){this.stop(),this._videoSource.dispose(),this._pipelineRunner.dispose(),m.info("Standalone Video Debugger disposed")}}D.DEFAULT_AUDIO_BUFFER_SIZE=Wa,D.DEFAULT_AUDIO_CHANNELS=qa,D.DEFAULT_AUDIO_SAMPLE_RATE=Li,D.DEFAULT_RECONNECT_ATTEMPTS=It,D.DEFAULT_RECONNECT_DELAY=Mi,D.DEFAULT_WS_TIMEOUT=Va,D.Disposable=j,D.EventBus=ps,D.Logger=m,D.SDKClient=Ma,D.SDKError=G,D.SessionState=ms,D.StandaloneVideoDebugger=Cp,D.createClient=kp}));