obi-sdk 0.13.3 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.umd.js CHANGED
@@ -39,7 +39,7 @@ a=extmap-allow-mixed`)!==-1){const r=i.sdp.split(`
39
39
  `).filter(s=>s.trim()!=="a=extmap-allow-mixed").join(`
40
40
  `);A.RTCSessionDescription&&i instanceof A.RTCSessionDescription?arguments[0]=new A.RTCSessionDescription({type:i.type,sdp:r}):i.sdp=r}return t.apply(this,arguments)}}function rs(A,e){if(!(A.RTCPeerConnection&&A.RTCPeerConnection.prototype))return;const t=A.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(A.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 ss(A,e){if(!(A.RTCPeerConnection&&A.RTCPeerConnection.prototype))return;const t=A.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(A.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return t.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?t.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(s=>t.apply(this,[s]))})}var AC=Object.freeze({__proto__:null,removeExtmapAllowMixed:$a,shimAddIceCandidateNullOrEmpty:rs,shimConnectionState:Ka,shimMaxMessageSize:ns,shimParameterlessSetLocalDescription:ss,shimRTCIceCandidate:As,shimRTCIceCandidateRelayProtocol:Na,shimSendThrowTypeError:is});function nC(){let{window:A}=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=Zu,n=YB(A),i={browserDetails:n,commonShim:AC,extractVersion:ts,disableLog:qB,disableWarnings:zB,sdp:tC};switch(n.browser){case"chrome":if(!uh||!Oa||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),i;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),i;t("adapter.js shimming chrome."),i.browserShim=uh,rs(A,n),ss(A),ih(A,n),rh(A),Oa(A,n),sh(A),lh(A,n),oh(A),ah(A),dh(A,n),As(A),Na(A),Ka(A),ns(A,n),is(A),$a(A,n);break;case"firefox":if(!yh||!Ha||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),i;t("adapter.js shimming firefox."),i.browserShim=yh,rs(A,n),ss(A),hh(A,n),Ha(A,n),fh(A),mh(A),ph(A),gh(A),vh(A),Bh(A),Ch(A),bh(A),wh(A),As(A),Ka(A),ns(A,n),is(A);break;case"safari":if(!xh||!e.shimSafari)return t("Safari shim is not included in this adapter release."),i;t("adapter.js shimming safari."),i.browserShim=xh,rs(A,n),ss(A),Fh(A),Ih(A),Uh(A),Eh(A),Sh(A),Qh(A),Th(A),_h(A),As(A),Na(A),ns(A,n),is(A),$a(A,n);break;default:t("Unsupported browser!");break}return i}nC({window:typeof window>"u"?void 0:window});const iC=10,os="lk_e2ee",rC={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:iC,keyringSize:16};var hA;(function(A){A.SetKey="setKey",A.RatchetRequest="ratchetRequest",A.KeyRatcheted="keyRatcheted"})(hA||(hA={}));var Lh;(function(A){A.KeyRatcheted="keyRatcheted"})(Lh||(Lh={}));var fA;(function(A){A.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",A.EncryptionError="encryptionError"})(fA||(fA={}));var Dh;(function(A){A.Error="cryptorError"})(Dh||(Dh={}));function sC(){return oC()||Va()}function Va(){return typeof window.RTCRtpScriptTransform<"u"}function oC(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class b2 extends Ot.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,n,i)=>{j.debug("key ratcheted event received",{ratchetResult:t,participantId:n,keyIndex:i})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},rC),e),this.on(hA.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,n){const i={key:e,participantIdentity:t,keyIndex:n};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(n??0),i),this.emit(hA.SetKey,i)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(hA.RatchetRequest,e,t)}}class pA extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var J;(function(A){A[A.NotAllowed=0]="NotAllowed",A[A.ServerUnreachable=1]="ServerUnreachable",A[A.InternalError=2]="InternalError",A[A.Cancelled=3]="Cancelled",A[A.LeaveRequest=4]="LeaveRequest"})(J||(J={}));class oe extends pA{constructor(e,t,n,i){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=i,this.reasonName=J[t]}}class Ga extends pA{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class zt extends pA{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class aC extends pA{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class Te extends pA{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class ja extends pA{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Wa extends pA{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Oh extends pA{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:Ra[t]}}var as;(function(A){A.PermissionDenied="PermissionDenied",A.NotFound="NotFound",A.DeviceInUse="DeviceInUse",A.Other="Other"})(as||(as={})),function(A){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?A.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?A.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?A.DeviceInUse:A.Other}A.getFailure=e}(as||(as={}));var Hh;(function(A){A[A.InvalidKey=0]="InvalidKey",A[A.MissingKey=1]="MissingKey",A[A.InternalError=2]="InternalError"})(Hh||(Hh={}));var F;(function(A){A.Connected="connected",A.Reconnecting="reconnecting",A.SignalReconnecting="signalReconnecting",A.Reconnected="reconnected",A.Disconnected="disconnected",A.ConnectionStateChanged="connectionStateChanged",A.Moved="moved",A.MediaDevicesChanged="mediaDevicesChanged",A.ParticipantConnected="participantConnected",A.ParticipantDisconnected="participantDisconnected",A.TrackPublished="trackPublished",A.TrackSubscribed="trackSubscribed",A.TrackSubscriptionFailed="trackSubscriptionFailed",A.TrackUnpublished="trackUnpublished",A.TrackUnsubscribed="trackUnsubscribed",A.TrackMuted="trackMuted",A.TrackUnmuted="trackUnmuted",A.LocalTrackPublished="localTrackPublished",A.LocalTrackUnpublished="localTrackUnpublished",A.LocalAudioSilenceDetected="localAudioSilenceDetected",A.ActiveSpeakersChanged="activeSpeakersChanged",A.ParticipantMetadataChanged="participantMetadataChanged",A.ParticipantNameChanged="participantNameChanged",A.ParticipantAttributesChanged="participantAttributesChanged",A.ParticipantActive="participantActive",A.RoomMetadataChanged="roomMetadataChanged",A.DataReceived="dataReceived",A.SipDTMFReceived="sipDTMFReceived",A.TranscriptionReceived="transcriptionReceived",A.ConnectionQualityChanged="connectionQualityChanged",A.TrackStreamStateChanged="trackStreamStateChanged",A.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",A.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",A.AudioPlaybackStatusChanged="audioPlaybackChanged",A.VideoPlaybackStatusChanged="videoPlaybackChanged",A.MediaDevicesError="mediaDevicesError",A.ParticipantPermissionsChanged="participantPermissionsChanged",A.SignalConnected="signalConnected",A.RecordingStatusChanged="recordingStatusChanged",A.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",A.EncryptionError="encryptionError",A.DCBufferStatusChanged="dcBufferStatusChanged",A.ActiveDeviceChanged="activeDeviceChanged",A.ChatMessage="chatMessage",A.LocalTrackSubscribed="localTrackSubscribed",A.MetricsReceived="metricsReceived"})(F||(F={}));var R;(function(A){A.TrackPublished="trackPublished",A.TrackSubscribed="trackSubscribed",A.TrackSubscriptionFailed="trackSubscriptionFailed",A.TrackUnpublished="trackUnpublished",A.TrackUnsubscribed="trackUnsubscribed",A.TrackMuted="trackMuted",A.TrackUnmuted="trackUnmuted",A.LocalTrackPublished="localTrackPublished",A.LocalTrackUnpublished="localTrackUnpublished",A.ParticipantMetadataChanged="participantMetadataChanged",A.ParticipantNameChanged="participantNameChanged",A.DataReceived="dataReceived",A.SipDTMFReceived="sipDTMFReceived",A.TranscriptionReceived="transcriptionReceived",A.IsSpeakingChanged="isSpeakingChanged",A.ConnectionQualityChanged="connectionQualityChanged",A.TrackStreamStateChanged="trackStreamStateChanged",A.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",A.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",A.MediaDevicesError="mediaDevicesError",A.AudioStreamAcquired="audioStreamAcquired",A.ParticipantPermissionsChanged="participantPermissionsChanged",A.PCTrackAdded="pcTrackAdded",A.AttributesChanged="attributesChanged",A.LocalTrackSubscribed="localTrackSubscribed",A.ChatMessage="chatMessage",A.Active="active"})(R||(R={}));var _;(function(A){A.TransportsCreated="transportsCreated",A.Connected="connected",A.Disconnected="disconnected",A.Resuming="resuming",A.Resumed="resumed",A.Restarting="restarting",A.Restarted="restarted",A.SignalResumed="signalResumed",A.SignalRestarted="signalRestarted",A.Closing="closing",A.MediaTrackAdded="mediaTrackAdded",A.ActiveSpeakersUpdate="activeSpeakersUpdate",A.DataPacketReceived="dataPacketReceived",A.RTPVideoMapUpdate="rtpVideoMapUpdate",A.DCBufferStatusChanged="dcBufferStatusChanged",A.ParticipantUpdate="participantUpdate",A.RoomUpdate="roomUpdate",A.SpeakersChanged="speakersChanged",A.StreamStateChanged="streamStateChanged",A.ConnectionQualityUpdate="connectionQualityUpdate",A.SubscriptionError="subscriptionError",A.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",A.RemoteMute="remoteMute",A.SubscribedQualityUpdate="subscribedQualityUpdate",A.LocalTrackUnpublished="localTrackUnpublished",A.LocalTrackSubscribed="localTrackSubscribed",A.Offline="offline",A.SignalRequestResponse="signalRequestResponse",A.SignalConnected="signalConnected",A.RoomMoved="roomMoved"})(_||(_={}));var I;(function(A){A.Message="message",A.Muted="muted",A.Unmuted="unmuted",A.Restarted="restarted",A.Ended="ended",A.Subscribed="subscribed",A.Unsubscribed="unsubscribed",A.UpdateSettings="updateSettings",A.UpdateSubscription="updateSubscription",A.AudioPlaybackStarted="audioPlaybackStarted",A.AudioPlaybackFailed="audioPlaybackFailed",A.AudioSilenceDetected="audioSilenceDetected",A.VisibilityChanged="visibilityChanged",A.VideoDimensionsChanged="videoDimensionsChanged",A.VideoPlaybackStarted="videoPlaybackStarted",A.VideoPlaybackFailed="videoPlaybackFailed",A.ElementAttached="elementAttached",A.ElementDetached="elementDetached",A.UpstreamPaused="upstreamPaused",A.UpstreamResumed="upstreamResumed",A.SubscriptionPermissionChanged="subscriptionPermissionChanged",A.SubscriptionStatusChanged="subscriptionStatusChanged",A.SubscriptionFailed="subscriptionFailed",A.TrackProcessorUpdate="trackProcessorUpdate",A.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",A.TranscriptionReceived="transcriptionReceived",A.TimeSyncUpdate="timeSyncUpdate"})(I||(I={}));function cC(A){return typeof A>"u"?A:typeof structuredClone=="function"?structuredClone(A):JSON.parse(JSON.stringify(A))}const lC=/version\/(\d+(\.?_?\d+)+)/i;let Ja;function St(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof A>"u"&&typeof navigator>"u")return;const t=(A??navigator.userAgent).toLowerCase();if(Ja===void 0||e){const n=dC.find(i=>{let{test:r}=i;return r.test(t)});Ja=n?.describe(t)}return Ja}const dC=[{test:/firefox|iceweasel|fxios/i,describe(A){return{name:"Firefox",version:cs(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,A),os:A.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Xa(A)}}},{test:/chrom|crios|crmo/i,describe(A){return{name:"Chrome",version:cs(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,A),os:A.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Xa(A)}}},{test:/safari|applewebkit/i,describe(A){return{name:"Safari",version:cs(lC,A),os:A.includes("mobile/")?"iOS":"macOS",osVersion:Xa(A)}}}];function cs(A,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const n=e.match(A);return n&&n.length>=t&&n[t]||""}function Xa(A){return A.includes("mac os")?cs(/\(.+?(\d+_\d+(:?_\d+)?)/,A,1).replace(/_/g,"."):void 0}var uC="2.13.0";const hC=uC,fC=16;class _e{}_e.setTimeout=function(){return setTimeout(...arguments)},_e.setInterval=function(){return setInterval(...arguments)},_e.clearTimeout=function(){return clearTimeout(...arguments)},_e.clearInterval=function(){return clearInterval(...arguments)};const pC=5e3,Li=[];var ut;(function(A){A[A.LOW=0]="LOW",A[A.MEDIUM=1]="MEDIUM",A[A.HIGH=2]="HIGH"})(ut||(ut={}));class T extends Ot.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var i;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=T.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=j,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),pC):this.handleAppVisibilityChanged()},this.log=qt((i=n.loggerName)!==null&&i!==void 0?i:Et.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=T.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),te(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===T.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===T.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Li.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&Li.splice(Li.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Nn(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),i=n.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(i?I.AudioPlaybackStarted:I.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(i?I.AudioPlaybackFailed:I.VideoPlaybackFailed,r):r.name==="AbortError"?j.debug("".concat(i?"audio":"video"," playback aborted, likely due to new play request")):j.warn("could not playback ".concat(i?"audio":"video"),r),i&&e&&n.some(s=>s.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(I.ElementAttached,e),e}detach(e){try{if(e){Kn(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(I.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(n=>{Kn(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(I.ElementDetached,n)}),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=qt(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Li.forEach(n=>{n.parentElement||(t=!1)}),t&&Li.push(e)}}handleAppVisibilityChanged(){return m(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===T.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){tt()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){tt()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Nn(A,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let n;A.kind==="audio"?n=t.getAudioTracks():n=t.getVideoTracks(),n.includes(A)||(n.forEach(i=>{t.removeTrack(i)}),t.addTrack(A)),(!gA()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(gA()||$n())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Kn(A,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(A),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(A){let e;(function(c){c.Audio="audio",c.Video="video",c.Unknown="unknown"})(e=A.Kind||(A.Kind={}));let t;(function(c){c.Camera="camera",c.Microphone="microphone",c.ScreenShare="screen_share",c.ScreenShareAudio="screen_share_audio",c.Unknown="unknown"})(t=A.Source||(A.Source={}));let n;(function(c){c.Active="active",c.Paused="paused",c.Unknown="unknown"})(n=A.StreamState||(A.StreamState={}));function i(c){switch(c){case e.Audio:return Ct.AUDIO;case e.Video:return Ct.VIDEO;default:return Ct.DATA}}A.kindToProto=i;function r(c){switch(c){case Ct.AUDIO:return e.Audio;case Ct.VIDEO:return e.Video;default:return e.Unknown}}A.kindFromProto=r;function s(c){switch(c){case t.Camera:return Ee.CAMERA;case t.Microphone:return Ee.MICROPHONE;case t.ScreenShare:return Ee.SCREEN_SHARE;case t.ScreenShareAudio:return Ee.SCREEN_SHARE_AUDIO;default:return Ee.UNKNOWN}}A.sourceToProto=s;function o(c){switch(c){case Ee.CAMERA:return t.Camera;case Ee.MICROPHONE:return t.Microphone;case Ee.SCREEN_SHARE:return t.ScreenShare;case Ee.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}A.sourceFromProto=o;function a(c){switch(c){case Ta.ACTIVE:return n.Active;case Ta.PAUSED:return n.Paused;default:return n.Unknown}}A.streamStateFromProto=a})(T||(T={}));class se{constructor(e,t,n,i,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&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:i,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 gC=["vp8","h264"],mC=["vp8","h264","vp9","av1"];function vC(A){return!!gC.find(e=>e===A)}var Mh;(function(A){A[A.PREFER_REGRESSION=0]="PREFER_REGRESSION",A[A.SIMULCAST=1]="SIMULCAST",A[A.REGRESSION=2]="REGRESSION"})(Mh||(Mh={}));var qa;(function(A){A.telephone={maxBitrate:12e3},A.speech={maxBitrate:24e3},A.music={maxBitrate:48e3},A.musicStereo={maxBitrate:64e3},A.musicHighQuality={maxBitrate:96e3},A.musicHighQualityStereo={maxBitrate:128e3}})(qa||(qa={}));const Di={h90:new se(160,90,9e4,20),h180:new se(320,180,16e4,20),h216:new se(384,216,18e4,20),h360:new se(640,360,45e4,20),h540:new se(960,540,8e5,25),h720:new se(1280,720,17e5,30),h1080:new se(1920,1080,3e6,30),h1440:new se(2560,1440,5e6,30),h2160:new se(3840,2160,8e6,30)},za={h120:new se(160,120,7e4,20),h180:new se(240,180,125e3,20),h240:new se(320,240,14e4,20),h360:new se(480,360,33e4,20),h480:new se(640,480,5e5,20),h540:new se(720,540,6e5,25),h720:new se(960,720,13e5,30),h1080:new se(1440,1080,23e5,30),h1440:new se(1920,1440,38e5,30)},Ya={h360fps3:new se(640,360,2e5,3,"medium"),h360fps15:new se(640,360,4e5,15,"medium"),h720fps5:new se(1280,720,8e5,5,"medium"),h720fps15:new se(1280,720,15e5,15,"medium"),h720fps30:new se(1280,720,2e6,30,"medium"),h1080fps15:new se(1920,1080,25e5,15,"medium"),h1080fps30:new se(1920,1080,5e6,30,"medium"),original:new se(0,0,7e6,30,"medium")},BC="|",Nh="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function CC(A){const e=A.split(BC);return e.length>1?[e[0],A.substr(e[0].length+1)]:[A,""]}function et(A){return m(this,void 0,void 0,function*(){return new Promise(e=>_e.setTimeout(e,A))})}function Za(){return"addTransceiver"in RTCPeerConnection.prototype}function ec(){return"addTrack"in RTCPeerConnection.prototype}function bC(){if(!("getCapabilities"in RTCRtpSender)||gA())return!1;const A=RTCRtpSender.getCapabilities("video");let e=!1;if(A){for(const t of A.codecs)if(t.mimeType==="video/AV1"){e=!0;break}}return e}function wC(){if(!("getCapabilities"in RTCRtpSender)||$n())return!1;if(gA()){const t=St();if(t?.version&&An(t.version,"16")<0)return!1}const A=RTCRtpSender.getCapabilities("video");let e=!1;if(A){for(const t of A.codecs)if(t.mimeType==="video/VP9"){e=!0;break}}return e}function Oi(A){return A==="av1"||A==="vp9"}function tc(A){return document?(A||(A=document.createElement("audio")),"setSinkId"in A):!1}function yC(){return typeof RTCPeerConnection>"u"?!1:Za()||ec()}function $n(){var A;return((A=St())===null||A===void 0?void 0:A.name)==="Firefox"}function gA(){var A;return((A=St())===null||A===void 0?void 0:A.name)==="Safari"}function EC(){const A=St();return A?.name==="Safari"&&A.version.startsWith("17.")}function Kh(){var A,e;return tt()?(e=(A=navigator.userAgentData)===null||A===void 0?void 0:A.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function SC(){const A=St(),e="17.2";if(A)return A.name!=="Safari"&&A.os!=="iOS"||A.os==="iOS"&&A.osVersion&&An(e,A.osVersion)>=0?!0:A.name==="Safari"&&An(e,A.version)>=0}function tt(){return typeof document<"u"}function Ht(){return navigator.product=="ReactNative"}function Ac(A){return A.hostname.endsWith(".livekit.cloud")||A.hostname.endsWith(".livekit.run")}function $h(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Vh(){if(!Ht())return;let A=$h();if(A)return A.platform}function Gh(){if(tt())return window.devicePixelRatio;if(Ht()){let A=$h();if(A)return A.devicePixelRatio}return 1}function An(A,e){const t=A.split("."),n=e.split("."),i=Math.min(t.length,n.length);for(let r=0;r<i;++r){const s=parseInt(t[r],10),o=parseInt(n[r],10);if(s>o)return 1;if(s<o)return-1;if(r===i-1&&s===o)return 0}return A===""&&e!==""?-1:e===""?1:t.length==n.length?0:t.length<n.length?-1:1}function UC(A){for(const e of A)e.target.handleResize(e)}function TC(A){for(const e of A)e.target.handleVisibilityChanged(e)}let nc=null;const jh=()=>(nc||(nc=new ResizeObserver(UC)),nc);let ic=null;const Wh=()=>(ic||(ic=new IntersectionObserver(TC,{root:null,rootMargin:"0px"})),ic);function kC(){var A;const e=new mB({sdk:Iu.JS,protocol:fC,version:hC});return Ht()&&(e.os=(A=Vh())!==null&&A!==void 0?A:""),e}function Jh(){let A=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,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const i=document.createElement("canvas");i.width=A,i.height=e;const r=i.getContext("2d");r?.fillRect(0,0,i.width,i.height),n&&r&&(r.beginPath(),r.arc(A/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const s=i.captureStream(),[o]=s.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let Hi;function rc(){if(!Hi){const A=new AudioContext,e=A.createOscillator(),t=A.createGain();t.gain.setValueAtTime(0,0);const n=A.createMediaStreamDestination();if(e.connect(t),t.connect(n),e.start(),[Hi]=n.stream.getAudioTracks(),!Hi)throw Error("Could not get empty media stream audio track");Hi.enabled=!1}return Hi.clone()}class sc{constructor(e,t){this.onFinally=t,this.promise=new Promise((n,i)=>m(this,void 0,void 0,function*(){this.resolve=n,this.reject=i,e&&(yield e(n,i))})).finally(()=>{var n;return(n=this.onFinally)===null||n===void 0?void 0:n.call(this)})}}function FC(A){return mC.includes(A)}function mA(A){if(typeof A=="string"||typeof A=="number")return A;if(Array.isArray(A))return A[0];if(A.exact)return Array.isArray(A.exact)?A.exact[0]:A.exact;if(A.ideal)return Array.isArray(A.ideal)?A.ideal[0]:A.ideal;throw Error("could not unwrap constraint")}function QC(A){return A.startsWith("http")?A.replace(/^(http)/,"ws"):A}function oc(A){return A.startsWith("ws")?A.replace(/^(ws)/,"http"):A}function IC(A,e){return A.segments.map(t=>{let{id:n,text:i,language:r,startTime:s,endTime:o,final:a}=t;var c;const l=(c=e.get(n))!==null&&c!==void 0?c:Date.now(),d=Date.now();return a?e.delete(n):e.set(n,l),{id:n,text:i,startTime:Number.parseInt(s.toString()),endTime:Number.parseInt(o.toString()),final:a,language:r,firstReceivedTime:l,lastReceivedTime:d}})}function _C(A){const{id:e,timestamp:t,message:n,editTimestamp:i}=A;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:n}}function Xh(A){switch(A.reason){case J.LeaveRequest:return A.context;case J.Cancelled:return bt.CLIENT_INITIATED;case J.NotAllowed:return bt.USER_REJECTED;case J.ServerUnreachable:return bt.JOIN_FAILURE;default:return bt.UNKNOWN_REASON}}function ls(A){return A!==void 0?Number(A):void 0}function nn(A){return A!==void 0?BigInt(A):void 0}function Vn(A){return!!A&&!(A instanceof MediaStreamTrack)&&A.isLocal}function Yt(A){return!!A&&A.kind==T.Kind.Audio}function Gn(A){return!!A&&A.kind==T.Kind.Video}function vA(A){return Vn(A)&&Gn(A)}function rn(A){return Vn(A)&&Yt(A)}function ac(A){return!!A&&!A.isLocal}function xC(A){return!!A&&!A.isLocal}function cc(A){return ac(A)&&Gn(A)}function RC(A){return A.isLocal}function PC(A,e){const t=[];let n=new TextEncoder().encode(A);for(;n.length>e;){let i=e;for(;i>0;){const r=n[i];if(r!==void 0&&(r&192)!==128)break;i--}t.push(n.slice(0,i)),n=n.slice(i)}return n.length>0&&t.push(n),t}function qh(A,e,t){var n,i,r,s;const{optionsWithoutProcessor:o,audioProcessor:a,videoProcessor:c}=ef(A??{}),l=e?.processor,d=t?.processor,u=o??{};return u.audio===!0&&(u.audio={}),u.video===!0&&(u.video={}),u.audio&&(lc(u.audio,e),(n=(r=u.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"}),(a||l)&&(u.audio.processor=a??l)),u.video&&(lc(u.video,t),(i=(s=u.video).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||d)&&(u.video.processor=c??d)),u}function lc(A,e){return Object.keys(e).forEach(t=>{A[t]===void 0&&(A[t]=e[t])}),A}function dc(A){var e,t,n,i;const r={};if(A.video)if(typeof A.video=="object"){const s={},o=s,a=A.video;Object.keys(a).forEach(c=>{switch(c){case"resolution":lc(o,a.resolution);break;default:o[c]=a[c]}}),r.video=s,(e=(n=r.video).deviceId)!==null&&e!==void 0||(n.deviceId={ideal:"default"})}else r.video=A.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return A.audio?typeof A.audio=="object"?(r.audio=A.audio,(t=(i=r.audio).deviceId)!==null&&t!==void 0||(i.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function zh(A){return m(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const n=Yh();if(n){const i=n.createAnalyser();i.fftSize=2048;const r=i.frequencyBinCount,s=new Uint8Array(r);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(i),yield et(t),i.getByteTimeDomainData(s);const a=s.some(c=>c!==128&&c!==0);return n.close(),!a}return!1}()})}function Yh(){var A;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((A=window.document)===null||A===void 0)&&A.body)){const n=()=>m(this,void 0,void 0,function*(){var i;try{t.state==="suspended"&&(yield t.resume())}catch(r){console.warn("Error trying to auto-resume audio context",r)}(i=window.document.body)===null||i===void 0||i.removeEventListener("click",n)});window.document.body.addEventListener("click",n)}return t}}function LC(A){return A==="audioinput"?T.Source.Microphone:A==="videoinput"?T.Source.Camera:T.Source.Unknown}function Zh(A){return A===T.Source.Microphone?"audioinput":A===T.Source.Camera?"videoinput":void 0}function DC(A){var e,t;let n=(e=A.video)!==null&&e!==void 0?e:!0;return A.resolution&&A.resolution.width>0&&A.resolution.height>0&&(n=typeof n=="boolean"?{}:n,gA()?n=Object.assign(Object.assign({},n),{width:{max:A.resolution.width},height:{max:A.resolution.height},frameRate:A.resolution.frameRate}):n=Object.assign(Object.assign({},n),{width:{ideal:A.resolution.width},height:{ideal:A.resolution.height},frameRate:A.resolution.frameRate})),{audio:(t=A.audio)!==null&&t!==void 0?t:!1,video:n,controller:A.controller,selfBrowserSurface:A.selfBrowserSurface,surfaceSwitching:A.surfaceSwitching,systemAudio:A.systemAudio,preferCurrentTab:A.preferCurrentTab}}function ds(A){return A.split("/")[1].toLowerCase()}function OC(A){const e=[];return A.forEach(t=>{t.track!==void 0&&e.push(new _a({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function te(A){return"mediaStreamTrack"in A?{trackID:A.sid,source:A.source,muted:A.isMuted,enabled:A.mediaStreamTrack.enabled,kind:A.kind,streamID:A.mediaStreamID,streamTrackID:A.mediaStreamTrack.id}:{trackID:A.trackSid,enabled:A.isEnabled,muted:A.isMuted,trackInfo:Object.assign({mimeType:A.mimeType,name:A.trackName,encrypted:A.isEncrypted,kind:A.kind,source:A.source},A.track?te(A.track):{})}}function HC(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function MC(A,e){var t;A===void 0&&(A={}),e===void 0&&(e={});const n=[...Object.keys(e),...Object.keys(A)],i={};for(const r of n)A[r]!==e[r]&&(i[r]=(t=e[r])!==null&&t!==void 0?t:"");return i}function ef(A){const e=Object.assign({},A);let t,n;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&&(n=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:n,optionsWithoutProcessor:cC(e)}}function NC(A){switch(A){case Ee.CAMERA:return T.Source.Camera;case Ee.MICROPHONE:return T.Source.Microphone;case Ee.SCREEN_SHARE:return T.Source.ScreenShare;case Ee.SCREEN_SHARE_AUDIO:return T.Source.ScreenShareAudio;default:return T.Source.Unknown}}class KC extends Ot.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var n,i;const{kind:r,data:s}=t.data;switch(r){case"error":j.error(s.error.message),this.emit(fA.EncryptionError,s.error);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)}),this.encryptionEnabled!==s.enabled&&s.participantIdentity===((n=this.room)===null||n===void 0?void 0:n.localParticipant.identity))this.emit(fA.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const o=(i=this.room)===null||i===void 0?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(fA.ParticipantEncryptionStatusChanged,s.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(hA.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break}},this.onWorkerError=t=>{j.error("e2ee worker encountered an error:",{error:t.error}),this.emit(fA.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!sC())throw new Ga("tried to setup end-to-end encryption on an unsupported browser");if(j.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:GB.getLevel()}};this.worker&&(j.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){j.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?j.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(_.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(F.TrackPublished,(n,i)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==st.NONE,i.identity)),e.on(F.ConnectionStateChanged,n=>{n===Z.Connected&&e.remoteParticipants.forEach(i=>{i.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==st.NONE,i.identity)})})}).on(F.TrackUnsubscribed,(n,i,r)=>{var s;const o={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:n.mediaStreamID}};(s=this.worker)===null||s===void 0||s.postMessage(o)}).on(F.TrackSubscribed,(n,i,r)=>{this.setupE2EEReceiver(n,r.identity,i.trackInfo)}).on(F.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(n=>{this.postKey(n)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(R.LocalTrackPublished,n=>m(this,void 0,void 0,function*(){this.setupE2EESender(n.track,n.track.sender)})),t.on(hA.SetKey,n=>this.postKey(n)).on(hA.RatchetRequest,(n,i)=>this.postRatchetRequest(n,i))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e){let{key:t,participantIdentity:n,keyIndex:i}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const s={kind:"setKey",data:{participantIdentity:n,isPublisher:n===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:i}};this.worker.postMessage(s)}postEnable(e,t){if(this.worker){const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}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 n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}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,n){if(e.receiver){if(!n?.mimeType||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?ds(n.mimeType):void 0)}}setupE2EESender(e,t){if(!Vn(e)||!t){t||j.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,i){return m(this,void 0,void 0,function*(){if(this.worker){if(Va()){const r={kind:"decode",participantIdentity:n,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(os in e&&i){const a={kind:"updateCodec",data:{trackId:t,codec:i,participantIdentity:n}};this.worker.postMessage(a);return}let r=e.writableStream,s=e.readableStream;if(!r||!s){const a=e.createEncodedStreams();e.writableStream=a.writable,r=a.writable,e.readableStream=a.readable,s=a.readable}const o={kind:"decode",data:{readableStream:s,writableStream:r,trackId:t,codec:i,participantIdentity:n}};this.worker.postMessage(o,[s,r])}e[os]=!0}})}handleSender(e,t,n){var i;if(!(os in e||!this.worker)){if(!(!((i=this.room)===null||i===void 0)&&i.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Va()){j.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{j.info("initialize encoded streams");const r=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s,[r.readable,r.writable])}e[os]=!0}}}const uc="default";class Fe{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new Fe),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var r;if(((r=Fe.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){j.debug("awaiting getUserMedia promise");try{t?yield Fe.userMediaPromiseMap.get(t):yield Promise.all(Fe.userMediaPromiseMap.values())}catch{j.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&!(gA()&&n.hasDeviceInUse(t))&&(s.filter(a=>a.kind===t).length===0||s.some(a=>{const c=a.label==="",l=t?a.kind===t:!0;return c&&l}))){const a={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},c=yield navigator.mediaDevices.getUserMedia(a);s=yield navigator.mediaDevices.enumerateDevices(),c.getTracks().forEach(l=>{l.stop()})}return n._previousDevices=s,t&&(s=s.filter(o=>o.kind===t)),s}()})}normalizeDeviceId(e,t,n){return m(this,void 0,void 0,function*(){if(t!==uc)return t;const i=yield this.getDevices(e),r=i.find(o=>o.deviceId===uc);if(!r){j.warn("could not reliably determine default device");return}const s=i.find(o=>o.deviceId!==uc&&o.groupId===(n??r.groupId));if(!s){j.warn("could not reliably determine default device");return}return s?.deviceId})}hasDeviceInUse(e){return e?Fe.userMediaPromiseMap.has(e):Fe.userMediaPromiseMap.size>0}}Fe.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Fe.userMediaPromiseMap=new Map;var Mi;(function(A){A[A.WAITING=0]="WAITING",A[A.RUNNING=1]="RUNNING",A[A.COMPLETED=2]="COMPLETED"})(Mi||(Mi={}));class $C{constructor(){this.pendingTasks=new Map,this.taskMutex=new ze,this.nextTaskIndex=0}run(e){return m(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Mi.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Mi.RUNNING,yield e()}finally{t.status=Mi.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return m(this,void 0,void 0,function*(){return this.run(()=>m(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function VC(A,e){const t=new URL(QC(A));return e.forEach((n,i)=>{t.searchParams.set(i,n)}),tf(t,"rtc")}function GC(A){const e=new URL(oc(A));return tf(e,"validate")}function jC(A){return A.endsWith("/")?A:"".concat(A,"/")}function tf(A,e){return A.pathname="".concat(jC(A.pathname)).concat(e),A.toString()}const WC=["syncState","trickle","offer","answer","simulate","leave"];function JC(A){const e=WC.indexOf(A.case)>=0;return j.trace("request allowed to bypass queue:",{canPass:e,req:A}),e}var ce;(function(A){A[A.CONNECTING=0]="CONNECTING",A[A.CONNECTED=1]="CONNECTED",A[A.RECONNECTING=2]="RECONNECTING",A[A.DISCONNECTING=3]="DISCONNECTING",A[A.DISCONNECTED=4]="DISCONNECTED"})(ce||(ce={}));class hc{get currentState(){return this.state}get isDisconnected(){return this.state===ce.DISCONNECTING||this.state===ce.DISCONNECTED}get isEstablishingConnection(){return this.state===ce.CONNECTING||this.state===ce.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 n;this.rtt=0,this.state=ce.DISCONNECTED,this.log=j,this._requestId=0,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.log=qt((n=t.loggerName)!==null&&n!==void 0?n:Et.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new $C,this.queuedRequests=[],this.closingLock=new ze,this.connectionLock=new ze,this.state=ce.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,n,i){return m(this,void 0,void 0,function*(){return this.state=ce.CONNECTING,this.options=n,yield this.connect(e,t,n,i)})}reconnect(e,t,n,i){return m(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=ce.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:i}))})}connect(e,t,n,i){this.connectOptions=n;const r=kC(),s=XC(t,r,n),o=VC(e,s),a=GC(o);return new Promise((c,l)=>m(this,void 0,void 0,function*(){const d=yield this.connectionLock.lock();try{const u=()=>m(this,void 0,void 0,function*(){this.close(),clearTimeout(h),l(new oe("room connection has been cancelled (signal)",J.Cancelled))}),h=setTimeout(()=>{this.close(),l(new oe("room connection has timed out (signal)",J.ServerUnreachable))},n.websocketTimeout);i?.aborted&&u(),i?.addEventListener("abort",u);const f=new URL(o);f.searchParams.has("access_token")&&f.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(f),Object.assign({reconnect:n.reconnect,reconnectReason:n.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(h)},this.ws.onerror=p=>m(this,void 0,void 0,function*(){if(this.state!==ce.CONNECTED){this.state=ce.DISCONNECTED,clearTimeout(h);try{const g=yield fetch(a);if(g.status.toFixed(0).startsWith("4")){const v=yield g.text();l(new oe(v,J.NotAllowed,g.status))}else l(new oe("Encountered unknown websocket error during connection: ".concat(p.toString()),J.InternalError,g.status))}catch(g){l(new oe(g instanceof Error?g.message:"server was not reachable",J.ServerUnreachable))}return}this.handleWSError(p)}),this.ws.onmessage=p=>m(this,void 0,void 0,function*(){var g,v,w;let y;if(typeof p.data=="string"){const B=JSON.parse(p.data);y=Du.fromJson(B,{ignoreUnknownFields:!0})}else if(p.data instanceof ArrayBuffer)y=Du.fromBinary(new Uint8Array(p.data));else{this.log.error("could not decode websocket message: ".concat(typeof p.data),this.logContext);return}if(this.state!==ce.CONNECTED){let B=!1;if(((g=y.message)===null||g===void 0?void 0:g.case)==="join"?(this.state=ce.CONNECTED,i?.removeEventListener("abort",u),this.pingTimeoutDuration=y.message.value.pingTimeout,this.pingIntervalDuration=y.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})),this.startPingInterval()),c(y.message.value)):this.state===ce.RECONNECTING&&y.message.case!=="leave"?(this.state=ce.CONNECTED,i?.removeEventListener("abort",u),this.startPingInterval(),((v=y.message)===null||v===void 0?void 0:v.case)==="reconnect"?c(y.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),c(void 0),B=!0)):this.isEstablishingConnection&&y.message.case==="leave"?l(new oe("Received leave request while trying to (re)connect",J.LeaveRequest,void 0,y.message.value.reason)):n.reconnect||l(new oe("did not receive join response, got ".concat((w=y.message)===null||w===void 0?void 0:w.case," instead"),J.InternalError)),!B)return}this.signalLatency&&(yield et(this.signalLatency)),this.handleSignalResponse(y)}),this.ws.onclose=p=>{this.isEstablishingConnection&&l(new oe("Websocket got closed during a (re)connection attempt",J.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:p.reason,code:p.code,wasClean:p.wasClean,state:this.state})),this.handleOnClose(p.reason)}}finally{d()}}))}close(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const n=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=ce.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const i=new Promise(r=>{e.ws?e.ws.onclose=()=>{r()}:r()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([i,et(250)])),e.ws=void 0}}finally{t&&(e.state=ce.DISCONNECTED),n()}}()})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:us(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:us(e)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new Qa({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Ia({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return m(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const o=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new Nu({requestId:o,metadata:n,name:i,attributes:s})}),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 Mu({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Vu({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:he.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Wu({timestamp:he.parse(Date.now()),rtt:he.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Hu({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new zr({reason:bt.CLIENT_INITIATED,action:Hn.DISCONNECT})})}sendRequest(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!i&&!JC(t)&&n.state===ce.RECONNECTING){n.queuedRequests.push(()=>m(n,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(i||(yield n.requestQueue.flush()),n.signalLatency&&(yield et(n.signalLatency)),!n.ws||n.ws.readyState!==n.ws.OPEN){n.log.error("cannot send signal request before connected, type: ".concat(t?.case),n.logContext);return}const s=new CB({message:t});try{n.useJSON?n.ws.send(s.toJsonString()):n.ws.send(s.toBinary())}catch(o){n.log.error("error sending signal message",Object.assign(Object.assign({},n.logContext),{error:o}))}}()})}handleSignalResponse(e){var t,n;const i=e.message;if(i==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(i.case==="answer"){const s=Af(i.value);this.onAnswer&&this.onAnswer(s)}else if(i.case==="offer"){const s=Af(i.value);this.onOffer&&this.onOffer(s)}else if(i.case==="trickle"){const s=JSON.parse(i.value.candidateInit);this.onTrickle&&this.onTrickle(s,i.value.target)}else i.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=i.value.participants)!==null&&t!==void 0?t:[]):i.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(i.value):i.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((n=i.value.speakers)!==null&&n!==void 0?n:[]):i.case==="leave"?this.onLeave&&this.onLeave(i.value):i.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(i.value.sid,i.value.muted):i.case==="roomUpdate"?this.onRoomUpdate&&i.value.room&&this.onRoomUpdate(i.value.room):i.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(i.value):i.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(i.value):i.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(i.value):i.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(i.value):i.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(i.value):i.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(i.value):i.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(i.value):i.case==="pong"||(i.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(i.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):i.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(i.value):i.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(i.value.trackSid):i.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(i.value.token),this.onRoomMoved&&this.onRoomMoved(i.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:i.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return m(this,void 0,void 0,function*(){if(this.state===ce.DISCONNECTED)return;const t=this.onClose;yield this.close(),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=_e.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&&_e.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=_e.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&_e.clearInterval(this.pingInterval)}}function Af(A){const e={type:"offer",sdp:A.sdp};switch(A.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=A.type;break}return e}function us(A){return new en({sdp:A.sdp,type:A.type})}function XC(A,e,t){var n;const i=new URLSearchParams;return i.set("access_token",A),t.reconnect&&(i.set("reconnect","1"),t.sid&&i.set("sid",t.sid)),i.set("auto_subscribe",t.autoSubscribe?"1":"0"),i.set("sdk",Ht()?"reactnative":"js"),i.set("version",e.version),i.set("protocol",e.protocol.toString()),e.deviceModel&&i.set("device_model",e.deviceModel),e.os&&i.set("os",e.os),e.osVersion&&i.set("os_version",e.osVersion),e.browser&&i.set("browser",e.browser),e.browserVersion&&i.set("browser_version",e.browserVersion),t.adaptiveStream&&i.set("adaptive_stream","1"),t.reconnectReason&&i.set("reconnect_reason",t.reconnectReason.toString()),!((n=navigator.connection)===null||n===void 0)&&n.type&&i.set("network",navigator.connection.type),i}var Ut={},fc={},pc={exports:{}},nf;function gc(){if(nf)return pc.exports;nf=1;var A=pc.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(A).forEach(function(e){var t=A[e];t.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),pc.exports}var rf;function qC(){return rf||(rf=1,function(A){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,a,c,l){if(l&&!c)a[l]=e(o[1]);else for(var d=0;d<c.length;d+=1)o[d+1]!=null&&(a[c[d]]=e(o[d+1]))},n=function(o,a,c){var l=o.name&&o.names;o.push&&!a[o.push]?a[o.push]=[]:l&&!a[o.name]&&(a[o.name]={});var d=o.push?{}:l?a[o.name]:a;t(c.match(o.reg),d,o.names,o.name),o.push&&a[o.push].push(d)},i=gc(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);A.parse=function(o){var a={},c=[],l=a;return o.split(/(\r\n|\r|\n)/).filter(r).forEach(function(d){var u=d[0],h=d.slice(2);u==="m"&&(c.push({rtp:[],fmtp:[]}),l=c[c.length-1]);for(var f=0;f<(i[u]||[]).length;f+=1){var p=i[u][f];if(p.reg.test(h))return n(p,l,h)}}),a.media=c,a};var s=function(o,a){var c=a.split(/=(.+)/,2);return c.length===2?o[c[0]]=e(c[1]):c.length===1&&a.length>1&&(o[c[0]]=void 0),o};A.parseParams=function(o){return o.split(/;\s?/).reduce(s,{})},A.parseFmtpConfig=A.parseParams,A.parsePayloads=function(o){return o.toString().split(" ").map(Number)},A.parseRemoteCandidates=function(o){for(var a=[],c=o.split(" ").map(e),l=0;l<c.length;l+=3)a.push({component:c[l],ip:c[l+1],port:c[l+2]});return a},A.parseImageAttributes=function(o){return o.split(" ").map(function(a){return a.substring(1,a.length-1).split(",").reduce(s,{})})},A.parseSimulcastStreamList=function(o){return o.split(";").map(function(a){return a.split(",").map(function(c){var l,d=!1;return c[0]!=="~"?l=e(c):(l=e(c.substring(1,c.length)),d=!0),{scid:l,paused:d}})})}}(fc)),fc}var mc,sf;function zC(){if(sf)return mc;sf=1;var A=gc(),e=/%[sdv%]/g,t=function(s){var o=1,a=arguments,c=a.length;return s.replace(e,function(l){if(o>=c)return l;var d=a[o];switch(o+=1,l){case"%%":return"%";case"%s":return String(d);case"%d":return Number(d);case"%v":return""}})},n=function(s,o,a){var c=o.format instanceof Function?o.format(o.push?a:a[o.name]):o.format,l=[s+"="+c];if(o.names)for(var d=0;d<o.names.length;d+=1){var u=o.names[d];o.name?l.push(a[o.name][u]):l.push(a[o.names[d]])}else l.push(a[o.name]);return t.apply(null,l)},i=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return mc=function(s,o){o=o||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(d){d.payloads==null&&(d.payloads="")});var a=o.outerOrder||i,c=o.innerOrder||r,l=[];return a.forEach(function(d){A[d].forEach(function(u){u.name in s&&s[u.name]!=null?l.push(n(d,u,s)):u.push in s&&s[u.push]!=null&&s[u.push].forEach(function(h){l.push(n(d,u,h))})})}),s.media.forEach(function(d){l.push(n("m",A.m[0],d)),c.forEach(function(u){A[u].forEach(function(h){h.name in d&&d[h.name]!=null?l.push(n(u,h,d)):h.push in d&&d[h.push]!=null&&d[h.push].forEach(function(f){l.push(n(u,h,f))})})})}),l.join(`\r
41
41
  `)+`\r
42
- `},mc}var of;function YC(){if(of)return Ut;of=1;var A=qC(),e=zC(),t=gc();return Ut.grammar=t,Ut.write=e,Ut.parse=A.parse,Ut.parseParams=A.parseParams,Ut.parseFmtpConfig=A.parseFmtpConfig,Ut.parsePayloads=A.parsePayloads,Ut.parseRemoteCandidates=A.parseRemoteCandidates,Ut.parseImageAttributes=A.parseImageAttributes,Ut.parseSimulcastStreamList=A.parseSimulcastStreamList,Ut}var BA=YC();function vc(A,e,t){var n,i,r;e===void 0&&(e=50),t===void 0&&(t={});var s=(n=t.isImmediate)!=null&&n,o=(i=t.callback)!=null&&i,a=t.maxWait,c=Date.now(),l=[];function d(){if(a!==void 0){var h=Date.now()-c;if(h+e>=a)return a-h}return e}var u=function(){var h=[].slice.call(arguments),f=this;return new Promise(function(p,g){var v=s&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,c=Date.now(),!s){var y=A.apply(f,h);o&&o(y),l.forEach(function(B){return(0,B.resolve)(y)}),l=[]}},d()),v){var w=A.apply(f,h);return o&&o(w),p(w)}l.push({resolve:p,reject:g})})};return u.cancel=function(h){r!==void 0&&clearTimeout(r),l.forEach(function(f){return(0,f.reject)(h)}),l=[]},u}const ZC=.7,eb=20,jn={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class af extends Ot.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 n;super(),this.log=j,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=vc(i=>m(this,void 0,void 0,function*(){this.emit(jn.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(i)i(r);else throw r}}),eb),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=qt((n=t.loggerName)!==null&&n!==void 0?n:Et.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.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 n;(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.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 m(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return m(this,void 0,void 0,function*(){var t;let n;if(e.type==="offer"){let{stereoMids:i,nackMids:r}=tb(e);this.remoteStereoMids=i,this.remoteNackMids=r}else if(e.type==="answer"){const i=BA.parse((t=e.sdp)!==null&&t!==void 0?t:"");i.media.forEach(r=>{r.type==="audio"&&this.trackBitrates.some(s=>{if(!s.transceiver||r.mid!=s.transceiver.mid)return!1;let o=0;if(r.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0)return!0;let a=!1;for(const c of r.fmtp)if(c.payload===o){c.config=c.config.split(";").filter(l=>!l.includes("maxaveragebitrate")).join(";"),s.maxbr>0&&(c.config+=";maxaveragebitrate=".concat(s.maxbr*1e3)),a=!0;break}return a||s.maxbr>0&&r.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(s.maxbr*1e3)}),!0})}),n=BA.write(i)}yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(i=>{this.pc.addIceCandidate(i)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(jn.NegotiationComplete),e.sdp&&BA.parse(e.sdp).media.forEach(r=>{r.type==="video"&&this.emit(jn.RTPVideoPayloadTypes,r.rtp)}))})}createAndSendOffer(e){return m(this,void 0,void 0,function*(){var t;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 r=this._pc.remoteDescription;if(e?.iceRestart&&r)yield this._pc.setRemoteDescription(r);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 n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));const i=BA.parse((t=n.sdp)!==null&&t!==void 0?t:"");i.media.forEach(r=>{lf(r),r.type==="audio"?cf(r,[],[]):r.type==="video"&&this.trackBitrates.some(s=>{if(!r.msid||!s.cid||!r.msid.includes(s.cid))return!1;let o=0;if(r.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0||(Oi(s.codec)&&this.ensureVideoDDExtensionForSVC(r,i),s.codec!=="av1"))return!0;const a=Math.round(s.maxbr*ZC);for(const c of r.fmtp)if(c.payload===o){c.config.includes("x-google-start-bitrate")||(c.config+=";x-google-start-bitrate=".concat(a));break}return!0})}),yield this.setMungedSDP(n,BA.write(i)),this.onOffer(n)})}createAndSetAnswer(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),n=BA.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(i=>{lf(i),i.type==="audio"&&cf(i,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,BA.write(n)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Te("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 Te("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 m(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const n=new Map,i=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),n.set(o.id,o);break;case"remote-candidate":i.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const s=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(s!==void 0)return i.get(s)})}setMungedSDP(e,t,n){return m(this,void 0,void 0,function*(){if(t){const i=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?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=i}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(i){let r="unknown error";i instanceof Error?r=i.message:typeof i=="string"&&(r=i);const s={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new ja(r)}})}ensureVideoDDExtensionForSVC(e,t){var n,i;if(!((n=e.ext)===null||n===void 0?void 0:n.some(s=>s.uri===Nh))){if(this.ddExtID===0){let s=0;t.media.forEach(o=>{var a;o.type==="video"&&((a=o.ext)===null||a===void 0||a.forEach(c=>{c.value>s&&(s=c.value)}))}),this.ddExtID=s+1}(i=e.ext)===null||i===void 0||i.push({value:this.ddExtID,uri:Nh})}}}function cf(A,e,t){let n=0;A.rtp.some(i=>i.codec==="opus"?(n=i.payload,!0):!1),n>0&&(A.rtcpFb||(A.rtcpFb=[]),t.includes(A.mid)&&!A.rtcpFb.some(i=>i.payload===n&&i.type==="nack")&&A.rtcpFb.push({payload:n,type:"nack"}),e.includes(A.mid)&&A.fmtp.some(i=>i.payload===n?(i.config.includes("stereo=1")||(i.config+=";stereo=1"),!0):!1))}function tb(A){var e;const t=[],n=[],i=BA.parse((e=A.sdp)!==null&&e!==void 0?e:"");let r=0;return i.media.forEach(s=>{var o;s.type==="audio"&&(s.rtp.some(a=>a.codec==="opus"?(r=a.payload,!0):!1),!((o=s.rtcpFb)===null||o===void 0)&&o.some(a=>a.payload===r&&a.type==="nack")&&n.push(s.mid),s.fmtp.some(a=>a.payload===r?(a.config.includes("sprop-stereo=1")&&t.push(s.mid),!0):!1))}),{stereoMids:t,nackMids:n}}function lf(A){if(A.connection){const e=A.connection.ip.indexOf(":")>=0;(A.connection.version===4&&e||A.connection.version===6&&!e)&&(A.connection.ip="0.0.0.0",A.connection.version=4)}}const Bc="vp8",Ab={audioPreset:qa.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ya.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Bc,backupCodec:!0},df={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},uf={deviceId:{ideal:"default"},resolution:Di.h720.resolution},nb={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new WB,disconnectOnPageLeave:!0,webAudioMix:!1},Cc={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ge;(function(A){A[A.NEW=0]="NEW",A[A.CONNECTING=1]="CONNECTING",A[A.CONNECTED=2]="CONNECTED",A[A.FAILED=3]="FAILED",A[A.CLOSING=4]="CLOSING",A[A.CLOSED=5]="CLOSED"})(ge||(ge={}));class ib{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,n){var i;this.peerConnectionTimeout=Cc.peerConnectionTimeout,this.log=j,this.updateState=()=>{var r;const s=this.state,o=this.requiredTransports.map(a=>a.getConnectionState());o.every(a=>a==="connected")?this.state=ge.CONNECTED:o.some(a=>a==="failed")?this.state=ge.FAILED:o.some(a=>a==="connecting")?this.state=ge.CONNECTING:o.every(a=>a==="closed")?this.state=ge.CLOSED:o.some(a=>a==="closed")?this.state=ge.CLOSING:o.every(a=>a==="new")&&(this.state=ge.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(ge[s]," to ").concat(ge[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=qt((i=n.loggerName)!==null&&i!==void 0?i:Et.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new af(e,n),this.subscriber=new af(e,n),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,r,yt.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,r,yt.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var s;(s=this.onDataChannel)===null||s===void 0||s.call(this,r)},this.subscriber.onTrack=r=>{var s;(s=this.onTrack)===null||s===void 0||s.call(this,r)},this.publisher.onOffer=r=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,r)},this.state=ge.NEW,this.connectionLock=new ze,this.remoteOfferLock=new ze}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()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return m(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(n){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:n}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return m(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return m(this,void 0,void 0,function*(){t===yt.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return m(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return m(this,void 0,void 0,function*(){var n;const i=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((n=this.requiredTransports)===null||n===void 0?void 0:n.map(r=>this.ensureTransportConnected(r,e,t)))}finally{i()}})}negotiate(e){return m(this,void 0,void 0,function*(){return new Promise((t,n)=>m(this,void 0,void 0,function*(){const i=setTimeout(()=>{n("negotiation timed out")},this.peerConnectionTimeout),r=()=>{clearTimeout(i),n("negotiation aborted")};e.signal.addEventListener("abort",r),this.publisher.once(jn.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(jn.NegotiationComplete,()=>{clearTimeout(i),t()})}),yield this.publisher.negotiate(s=>{clearTimeout(i),n(s)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===yt.PUBLISHER?this.publisher.getConnectedAddress():e===yt.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return m(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(n.getConnectionState()!=="connected")return new Promise((a,c)=>m(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),_e.clearTimeout(d),c(new oe("room connection has been cancelled",J.Cancelled))};i?.signal.aborted&&l(),i?.signal.addEventListener("abort",l);const d=_e.setTimeout(()=>{i?.signal.removeEventListener("abort",l),c(new oe("could not establish pc connection",J.InternalError))},s);for(;this.state!==ge.CONNECTED;)if(yield et(50),i?.signal.aborted){c(new oe("room connection has been cancelled",J.Cancelled));return}_e.clearTimeout(d),i?.signal.removeEventListener("abort",l),a()}))}()})}}class me extends Error{constructor(e,t,n){super(t),this.code=e,this.message=ff(t,me.MAX_MESSAGE_BYTES),this.data=n?ff(n,me.MAX_DATA_BYTES):void 0}static fromProto(e){return new me(e.code,e.message,e.data)}toProto(){return new ku({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new me(me.ErrorCode[e],me.ErrorMessage[e],t)}}me.MAX_MESSAGE_BYTES=256,me.MAX_DATA_BYTES=15360,me.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},me.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 hf=15360;function bc(A){return new TextEncoder().encode(A).length}function ff(A,e){if(bc(A)<=e)return A;let t=0,n=A.length;const i=new TextEncoder;for(;t<n;){const r=Math.floor((t+n+1)/2);i.encode(A.slice(0,r)).length<=e?t=r:n=r-1}return A.slice(0,t)}const wc=2e3;function hs(A,e){if(!e)return 0;let t,n;return"bytesReceived"in A?(t=A.bytesReceived,n=e.bytesReceived):"bytesSent"in A&&(t=A.bytesSent,n=e.bytesSent),t===void 0||n===void 0||A.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(A.timestamp-e.timestamp)}const rb=1e3;class pf extends T{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,n){let i=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=vc(()=>m(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>m(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(I.Ended,this)},this.reacquireTrack=!1,this.providedByUser=i,this.muteLock=new ze,this.pauseUpstreamLock=new ze,this.processorLock=new ze,this.restartLock=new ze,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==T.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 m(this,void 0,void 0,function*(){var n;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{Kn(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 i;if(this.processor&&e){const r=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Nn(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}finally{r()}}this.sender&&((n=this.sender.transport)===null||n===void 0?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(i??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=>{Nn(i??e,r)}))})}waitForDimensions(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:rb;return function*(){var n;if(e.kind===T.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=St())===null||n===void 0?void 0:n.os)==="iOS"&&(yield et(10));const i=Date.now();for(;Date.now()-i<t;){const r=e.dimensions;if(r)return r;yield et(50)}throw new zt("unable to get track dimensions after timeout")}()})}setDeviceId(e){return m(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===mA(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),mA(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return m(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===T.Source.ScreenShare)return;const{deviceId:n,groupId:i}=e._mediaStreamTrack.getSettings(),r=e.kind===T.Kind.Audio?"audioinput":"videoinput";return t?Fe.getInstance().normalizeDeviceId(r,n,i):n}()})}mute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return m(this,void 0,void 0,function*(){if(!this.sender)throw new zt("unable to replace an unpublished track");let n,i;return typeof t=="boolean"?n=t:t!==void 0&&(n=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=n??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return m(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:n,facingMode:i}=e,r=JB(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===T.Kind.Video?s.video=n||i?{deviceId:n,facingMode:i}:!0:s.audio=n?{deviceId:n}:!0,this.attachedElements.forEach(c=>{Kn(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const a=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return yield a.applyConstraints(r),a.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(a),this._constraints=e,this.emit(I.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?I.Muted:I.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 m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Kh()&&(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 m(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(I.UpstreamPaused,this);const n=St();if(n?.name==="Safari"&&An(n.version,"12.0")<0)throw new Ga("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 m(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(I.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 m(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 m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var r;const s=yield n.processorLock.lock();try{n.log.debug("setting up processor",n.logContext);const o=document.createElement(n.kind),a={kind:n.kind,track:n._mediaStreamTrack,element:o,audioContext:n.audioContext};if(yield t.init(a),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.stopProcessor()),n.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Nn(n._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:c}))),n.processor=t,n.processorElement=o,n.processor.processedTrack){for(const c of n.attachedElements)c!==n.processorElement&&i&&(Kn(n._mediaStreamTrack,c),Nn(n.processor.processedTrack,c));yield(r=n.sender)===null||r===void 0?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(I.TrackProcessorUpdate,n.processor)}finally{s()}}()})}getProcessor(){return this.processor}stopProcessor(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,i;e.processor&&(e.log.debug("stopping processor",e.logContext),(n=e.processor.processedTrack)===null||n===void 0||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((i=e.processorElement)===null||i===void 0||i.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(I.TrackProcessorUpdate))}()})}}class fs extends pf{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,T.Kind.Audio,t,n,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}s&&this.prevStats&&(this._currentBitrate=hs(s,this.prevStats)),this.prevStats=s}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(I.AudioTrackFeatureUpdate,this,wt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(I.AudioTrackFeatureUpdate,this,wt.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(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===T.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 m(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 n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==mA(this._constraints.deviceId);return this.source===T.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return m(this,void 0,void 0,function*(){let t;if(e){const n=dc({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return m(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){tt()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},wc)))}setProcessor(e){return m(this,void 0,void 0,function*(){var t;const n=yield this.processorLock.lock();try{if(!Ht()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),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(I.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return m(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 n;return t.forEach(i=>{i.type==="outbound-rtp"&&(n={type:"audio",streamId:i.id,packetsSent:i.packetsSent,packetsLost:i.packetsLost,bytesSent:i.bytesSent,timestamp:i.timestamp,roundTripTime:i.roundTripTime,jitter:i.jitter})}),n})}checkForSilence(){return m(this,void 0,void 0,function*(){const e=yield zh(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(I.AudioSilenceDetected)),e})}}function sb(A,e,t){switch(A.kind){case"audio":return new fs(A,e,!1,void 0,t);case"video":return new gs(A,e,!1,t);default:throw new zt("unsupported track type: ".concat(A.kind))}}const ob=Object.values(Di),ab=Object.values(za),cb=Object.values(Ya),lb=[Di.h180,Di.h360],db=[za.h180,za.h360],ub=A=>[{scaleResolutionDownBy:2,fps:A.encoding.maxFramerate}].map(t=>{var n,i;return new se(Math.floor(A.width/t.scaleResolutionDownBy),Math.floor(A.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(A.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((n=A.encoding.maxFramerate)!==null&&n!==void 0?n:30)/((i=t.fps)!==null&&i!==void 0?i:30))))),t.fps,A.encoding.priority)}),yc=["q","h","f"];function Ec(A,e,t,n){var i,r;let s=n?.videoEncoding;A&&(s=n?.screenShareEncoding);const o=n?.simulcast,a=n?.scalabilityMode,c=n?.videoCodec;if(!s&&!o&&!a||!e||!t)return[{}];s||(s=fb(A,e,t,c),j.debug("using video encoding",s));const l=s.maxFramerate,d=new se(e,t,s.maxBitrate,s.maxFramerate,s.priority);if(a&&Oi(c)){const f=new ps(a),p=[];if(f.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(a));const g=St();if(gA()||Ht()||g?.name==="Chrome"&&An(g?.version,"113")<0){const v=f.suffix=="h"?2:3;for(let w=0;w<f.spatial;w+=1)p.push({rid:yc[2-w],maxBitrate:s.maxBitrate/Math.pow(v,w),maxFramerate:d.encoding.maxFramerate});p[0].scalabilityMode=a}else p.push({maxBitrate:s.maxBitrate,maxFramerate:d.encoding.maxFramerate,scalabilityMode:a});return d.encoding.priority&&(p[0].priority=d.encoding.priority,p[0].networkPriority=d.encoding.priority),j.debug("using svc encoding",{encodings:p}),p}if(!o)return[s];let u=[];A?u=(i=mf(n?.screenShareSimulcastLayers))!==null&&i!==void 0?i:gf(A,d):u=(r=mf(n?.videoSimulcastLayers))!==null&&r!==void 0?r:gf(A,d);let h;if(u.length>0){const f=u[0];u.length>1&&([,h]=u);const p=Math.max(e,t);if(p>=960&&h)return Sc(e,t,[f,h,d],l);if(p>=480)return Sc(e,t,[f,d],l)}return Sc(e,t,[d])}function hb(A,e,t){var n,i,r,s;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&j.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=A.mediaStreamTrack.getSettings(),a=(n=o.width)!==null&&n!==void 0?n:(i=A.dimensions)===null||i===void 0?void 0:i.width,c=(r=o.height)!==null&&r!==void 0?r:(s=A.dimensions)===null||s===void 0?void 0:s.height;return A.source===T.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Ec(A.source===T.Source.ScreenShare,a,c,t)}function fb(A,e,t,n){const i=pb(A,e,t);let{encoding:r}=i[0];const s=Math.max(e,t);for(let o=0;o<i.length;o+=1){const a=i[o];if(r=a.encoding,a.width>=s)break}if(n)switch(n){case"av1":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 pb(A,e,t){if(A)return cb;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?ob:ab}function gf(A,e){if(A)return ub(e);const{width:t,height:n}=e,i=t>n?t/n:n/t;return Math.abs(i-16/9)<Math.abs(i-4/3)?lb:db}function Sc(A,e,t,n){const i=[];if(t.forEach((r,s)=>{if(s>=yc.length)return;const o=Math.min(A,e),c={rid:yc[s],scaleResolutionDownBy:Math.max(1,o/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},l=n&&r.encoding.maxFramerate?Math.min(n,r.encoding.maxFramerate):r.encoding.maxFramerate;l&&(c.maxFramerate=l);const d=$n()||s===0;r.encoding.priority&&d&&(c.priority=r.encoding.priority,c.networkPriority=r.encoding.priority),i.push(c)}),Ht()&&Vh()==="ios"){let r;i.forEach(o=>{r?o.maxFramerate&&o.maxFramerate>r&&(r=o.maxFramerate):r=o.maxFramerate});let s=!0;i.forEach(o=>{var a;o.maxFramerate!=r&&(s&&(s=!1,j.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),j.info('Setting framerate of encoding "'.concat((a=o.rid)!==null&&a!==void 0?a:"",'" to ').concat(r)),o.maxFramerate=r)})}return i}function mf(A){if(A)return A.sort((e,t)=>{const{encoding:n}=e,{encoding:i}=t;return n.maxBitrate>i.maxBitrate?1:n.maxBitrate<i.maxBitrate?-1:n.maxBitrate===i.maxBitrate&&n.maxFramerate&&i.maxFramerate?n.maxFramerate>i.maxFramerate?1:-1:0})}class ps{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 gb(A){return A.source===T.Source.ScreenShare||A.constraints.height&&mA(A.constraints.height)>=1080?"maintain-resolution":"balanced"}const mb=5e3;class gs extends pf{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0;super(e,T.Kind.Video,t,n,i),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}const s=new Map(r.map(o=>[o.rid,o]));if(this.prevStats){let o=0;s.forEach((a,c)=>{var l;const d=(l=this.prevStats)===null||l===void 0?void 0:l.get(c);o+=hs(a,d)}),this._currentBitrate=o}this.prevStats=s}),this.senderLock=new ze}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!tt())return;const n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},wc))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return m(this,void 0,void 0,function*(){var t,n,i,r,s;yield e.pauseUpstream.call(this);try{for(var o=!0,a=uA(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0)r=c.value,o=!1,yield(s=r.sender)===null||s===void 0?void 0:s.replaceTrack(null)}catch(l){n={error:l}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return m(this,void 0,void 0,function*(){var t,n,i,r,s;yield e.resumeUpstream.call(this);try{for(var o=!0,a=uA(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0){r=c.value,o=!1;const l=r;yield(s=l.sender)===null||s===void 0?void 0:s.replaceTrack(l.mediaStreamTrack)}}catch(l){n={error:l}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(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===T.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 m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===T.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 m(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach(i=>{var r;if(i.type==="outbound-rtp"){const s={type:"video",streamId:i.id,frameHeight:i.frameHeight,frameWidth:i.frameWidth,framesPerSecond:i.framesPerSecond,framesSent:i.framesSent,firCount:i.firCount,pliCount:i.pliCount,nackCount:i.nackCount,packetsSent:i.packetsSent,bytesSent:i.bytesSent,qualityLimitationReason:i.qualityLimitationReason,qualityLimitationDurations:i.qualityLimitationDurations,qualityLimitationResolutionChanges:i.qualityLimitationResolutionChanges,rid:(r=i.rid)!==null&&r!==void 0?r:i.id,retransmittedPacketsSent:i.retransmittedPacketsSent,targetBitrate:i.targetBitrate,timestamp:i.timestamp},o=n.get(i.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}}),t.sort((i,r)=>{var s,o;return((s=r.frameWidth)!==null&&s!==void 0?s:0)-((o=i.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let n=ut.LOW;n<=ut.HIGH;n+=1)t.push(new xa({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return m(this,void 0,void 0,function*(){var t,n,i,r,s;let o;if(e){const d=dc({video:e});typeof d.video!="boolean"&&(o=d.video)}yield this.restart(o);try{for(var a=!0,c=uA(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;a=!0){r=l.value,a=!1;const d=r;d.sender&&((s=d.sender.transport)===null||s===void 0?void 0:s.state)!=="closed"&&(d.mediaStreamTrack=this.mediaStreamTrack.clone(),yield d.sender.replaceTrack(d.mediaStreamTrack))}}catch(d){n={error:d}}finally{try{!a&&!t&&(i=c.return)&&(yield i.call(c))}finally{if(n)throw n.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return m(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s,o,a,c,l,d;if(yield t.setProcessor.call(i,n,r),!((l=i.processor)===null||l===void 0)&&l.processedTrack)try{for(var u=!0,h=uA(i.simulcastCodecs.values()),f;f=yield h.next(),s=f.done,!s;u=!0)c=f.value,u=!1,yield(d=c.sender)===null||d===void 0?void 0:d.replaceTrack(i.processor.processedTrack)}catch(p){o={error:p}}finally{try{!u&&!s&&(a=h.return)&&(yield a.call(h))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return m(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 n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},mb))}setPublishingCodecs(e){return m(this,void 0,void 0,function*(){var t,n,i,r,s,o,a;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(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,n=uA(e);i=yield n.next(),r=i.done,!r;t=!0){a=i.value,t=!1;const l=a;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(l.qualities);else{const d=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:d})),!d||!d.sender){for(const u of l.qualities)if(u.enabled){c.push(l.codec);break}}else d.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield vf(d.sender,d.encodings,l.qualities,this.senderLock,this.log,this.logContext))}}}catch(l){s={error:l}}finally{try{!t&&!r&&(o=n.return)&&(yield o.call(n))}finally{if(s)throw s.error}}return c})}setPublishingLayers(e){return m(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield vf(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Kh()&&this.isInBackground&&this.source===T.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function vf(A,e,t,n,i,r){return m(this,void 0,void 0,function*(){const s=yield n.lock();i.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:A,qualities:t,senderEncodings:e}));try{const o=A.getParameters(),{encodings:a}=o;if(!a)return;if(a.length!==e.length){i.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:a,senderEncodings:e}));return}let c=!1;const l=St();if(l?.name==="Chrome"&&An(l?.version,"133")>0&&a[0].scalabilityMode){const u=a[0],h=new ps(u.scalabilityMode);let f=Pn.OFF;if(t.forEach(p=>{p.enabled&&(f===Pn.OFF||p.quality>f)&&(f=p.quality)}),f===Pn.OFF)u.active&&(u.active=!1,c=!0);else if(!u.active||h.spatial!==f+1){c=!0,u.active=!0;const p=new ps(e[0].scalabilityMode);h.spatial=f+1,h.suffix=p.suffix,h.spatial===1&&(h.suffix=void 0),u.scalabilityMode=h.toString(),u.scaleResolutionDownBy=Math.pow(2,2-f),e[0].maxBitrate&&(u.maxBitrate=e[0].maxBitrate/(u.scaleResolutionDownBy*u.scaleResolutionDownBy))}}else a.forEach((u,h)=>{var f;let p=(f=u.rid)!==null&&f!==void 0?f:"";p===""&&(p="q");const g=Bf(p),v=t.find(w=>w.quality===g);v&&u.active!==v.enabled&&(c=!0,u.active=v.enabled,i.debug("setting layer ".concat(v.quality," to ").concat(u.active?"enabled":"disabled"),r),$n()&&(v.enabled?(u.scaleResolutionDownBy=e[h].scaleResolutionDownBy,u.maxBitrate=e[h].maxBitrate,u.maxFrameRate=e[h].maxFrameRate):(u.scaleResolutionDownBy=4,u.maxBitrate=10,u.maxFrameRate=2)))});c&&(o.encodings=a,i.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:o.encodings})),yield A.setParameters(o))}finally{s()}})}function Bf(A){switch(A){case"f":return ut.HIGH;case"h":return ut.MEDIUM;case"q":return ut.LOW;default:return ut.HIGH}}function Cf(A,e,t,n){if(!t)return[new ZA({quality:ut.HIGH,width:A,height:e,bitrate:0,ssrc:0})];if(n){const i=t[0].scalabilityMode,r=new ps(i),s=[],o=r.suffix=="h"?1.5:2,a=r.suffix=="h"?2:3;for(let c=0;c<r.spatial;c+=1)s.push(new ZA({quality:Math.min(ut.HIGH,r.spatial-1)-c,width:Math.ceil(A/Math.pow(o,c)),height:Math.ceil(e/Math.pow(o,c)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(a,c)):0,ssrc:0}));return s}return t.map(i=>{var r,s,o;const a=(r=i.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let c=Bf((s=i.rid)!==null&&s!==void 0?s:"");return new ZA({quality:c,width:Math.ceil(A/a),height:Math.ceil(e/a),bitrate:(o=i.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const bf="_lossy",wf="_reliable",vb=2*1e3,Uc="leave-reconnect";var Tt;(function(A){A[A.New=0]="New",A[A.Connected=1]="Connected",A[A.Disconnected=2]="Disconnected",A[A.Reconnecting=3]="Reconnecting",A[A.Closed=4]="Closed"})(Tt||(Tt={}));class Bb extends Ot.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Cc.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Tt.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=j,this.handleDataChannel=n=>m(this,[n],void 0,function(i){var r=this;let{channel:s}=i;return function*(){if(s){if(s.label===wf)r.reliableDCSub=s;else if(s.label===bf)r.lossyDCSub=s;else return;r.log.debug("on data channel ".concat(s.id,", ").concat(s.label),r.logContext),s.onmessage=r.handleDataMessage}}()}),this.handleDataMessage=n=>m(this,void 0,void 0,function*(){var i,r;const s=yield this.dataProcessLock.lock();try{let o;if(n.data instanceof ArrayBuffer)o=n.data;else if(n.data instanceof Blob)o=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:n.data}));return}const a=Ze.fromBinary(new Uint8Array(o));((i=a.value)===null||i===void 0?void 0:i.case)==="speaker"?this.emit(_.ActiveSpeakersUpdate,a.value.value.speakers):(((r=a.value)===null||r===void 0?void 0:r.case)==="user"&&bb(a,a.value.value),this.emit(_.DataPacketReceived,a))}finally{s()}}),this.handleDataError=n=>{const r=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(n instanceof ErrorEvent&&n.error){const{error:s}=n.error;this.log.error("DataChannel error on ".concat(r,": ").concat(n.message),Object.assign(Object.assign({},this.logContext),{error:s}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:n}))},this.handleBufferedAmountLow=n=>{const r=n.currentTarget.maxRetransmits===0?Y.LOSSY:Y.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(n,i)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=a=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(a,"ms. giving up"),this.logContext),this.emit(_.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});if(o===null){r(s);return}n===Uc&&(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=_e.setTimeout(()=>this.attemptReconnect(i).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((n,i)=>{this.pcState===Tt.Connected&&n();const r=()=>{this.off(_.Disconnected,s),n()},s=()=>{this.off(_.Restarted,r),i()};this.once(_.Restarted,r),this.once(_.Disconnected,s)}),this.updateAndEmitDCBufferStatus=n=>{const i=this.isBufferStatusLow(n);typeof i<"u"&&i!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,i),this.emit(_.DCBufferStatusChanged,i,n))},this.isBufferStatusLow=n=>{const i=this.dataChannelForKind(n);if(i)return i.bufferedAmount<=i.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ce.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Ln.RR_SIGNAL_DISCONNECTED))},this.log=qt((t=e.loggerName)!==null&&t!==void 0?t:Et.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new hc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new ze,this.dataProcessLock=new ze,this.dcBufferStatus=new Map([[Y.LOSSY,!0],[Y.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(_.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(_.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(_.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(_.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(_.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(_.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(_.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(_.SignalRequestResponse,n)}get logContext(){var e,t,n,i,r,s,o,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(i=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.room)===null||i===void 0?void 0:i.sid,participant:(s=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||s===void 0?void 0:s.identity,pID:(a=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||a===void 0?void 0:a.sid}}join(e,t,n,i){return m(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,t,n,i);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),(!this.subscriberPrimary||r.fastPublish)&&this.negotiate(),this.clientConfiguration=r.clientConfiguration,setTimeout(()=>{this.emit(_.SignalConnected)},10),r}catch(r){if(r instanceof oe&&r.reason===J.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,n,i);throw r}})}close(){return m(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(_.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return m(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=n=>{n&&(n.close(),n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.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})}cleanupClient(){return m(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new zt("a track with the same ID has already been published");return new Promise((t,n)=>{const i=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(new oe("publication of local track timed out, no response from server",J.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(i),t(r)},reject:()=>{clearTimeout(i),n(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 m(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){return m(this,void 0,void 0,function*(){var t,n;if(this.pcManager&&this.pcManager.currentState!==ge.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const i=this.makeRTCConfiguration(e);this.pcManager=new ib(i,e.subscriberPrimary,this.loggerOptions),this.emit(_.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,s)=>{this.client.sendIceCandidate(r,s)},this.pcManager.onPublisherOffer=r=>{this.client.sendOffer(r)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,s,o)=>m(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r),this.logContext),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),r===ge.CONNECTED){const l=this.pcState===Tt.New;this.pcState=Tt.Connected,l&&this.emit(_.Connected,e)}else r===ge.FAILED&&this.pcState===Tt.Connected&&(this.pcState=Tt.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?Ln.RR_SUBSCRIBER_FAILED:Ln.RR_PUBLISHER_FAILED));const a=this.client.isDisconnected||this.client.currentState===ce.RECONNECTING,c=[ge.FAILED,ge.CLOSING,ge.CLOSED].includes(r);a&&c&&!this._isClosed&&this.emit(_.Offline)}),this.pcManager.onTrack=r=>{this.emit(_.MediaTrackAdded,r.track,r.streams[0],r.receiver)},Cb((n=e.serverInfo)===null||n===void 0?void 0:n.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>m(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))}),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=>m(this,void 0,void 0,function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(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:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(_.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(_.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(_.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(_.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.emit(_.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Ln.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(e.regions)),e.action){case Hn.DISCONNECT:this.emit(_.Disconnected,e?.reason),this.close();break;case Hn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Uc);break;case Hn.RESUME:this.handleDisconnect(Uc)}}}makeRTCConfiguration(e){var t;const n=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),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const i=[];e.iceServers.forEach(r=>{const s={urls:r.urls};r.username&&(s.username=r.username),r.credential&&(s.credential=r.credential),i.push(s)}),n.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ri.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}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(bf,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(wf,{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)}createSender(e,t,n){return m(this,void 0,void 0,function*(){if(Za())return yield this.createTransceiverRTCRtpSender(e,t,n);if(ec())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Te("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,i){return m(this,void 0,void 0,function*(){if(Za())return this.createSimulcastTransceiverSender(e,t,n,i);if(ec())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Te("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new Te("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),Gn(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:i};return n&&(r.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,n,i){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new Te("publisher is closed");const r={direction:"sendonly"};i&&(r.sendEncodings=i);const s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new Te("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return m(this,void 0,void 0,function*(){var t,n,i;if(!this._isClosed){if(this.attemptingReconnect){j.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Ri.DISABLED||((i=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&i!==void 0?i:ge.NEW)===ge.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 s=!0;r instanceof Te?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),s=!1):r instanceof Wn||(this.fullReconnectOnNext=!0),s?this.handleDisconnect("reconnect",Ln.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(_.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 m(this,void 0,void 0,function*(){var t,n,i;try{if(!this.url||!this.token)throw new Te("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(_.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 Wn;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(s){throw s instanceof oe&&s.reason===J.NotAllowed?new Te("could not reconnect, token might be expired"):new Wn}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(_.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==ce.CONNECTED)throw new Wn("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(_.Restarted)}catch(r){const s=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(s){yield this.restartConnection(s);return}else throw(i=this.regionUrlProvider)===null||i===void 0||i.resetAttempts(),r}})}resumeConnection(e){return m(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new Te("could not reconnect, url or token not saved");if(!this.pcManager)throw new Te("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(_.Resuming);let n;try{this.setupSignalClientCallbacks(),n=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(i){let r="";throw i instanceof Error&&(r=i.message,this.log.error(i.message,Object.assign(Object.assign({},this.logContext),{error:i}))),i instanceof oe&&i.reason===J.NotAllowed?new Te("could not reconnect, token might be expired"):i instanceof oe&&i.reason===J.LeaveRequest?i:new Wn(r)}if(this.emit(_.SignalResumed),n){const i=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(i)}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!==ce.CONNECTED)throw new Wn("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(),this.emit(_.Resumed)})}waitForPCInitialConnection(e,t){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new Te("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return m(this,void 0,void 0,function*(){this.pcState=Tt.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield et(vb),!this.pcManager)throw new Te("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Tt.Connected}catch(e){throw this.pcState=Tt.Disconnected,new oe("could not establish PC connection, ".concat(e.message),J.InternalError)}})}publishRpcResponse(e,t,n,i){return m(this,void 0,void 0,function*(){const r=new Ze({destinationIdentities:[e],kind:Y.RELIABLE,value:{case:"rpcResponse",value:new Tu({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:n??""}})}});yield this.sendDataPacket(r,Y.RELIABLE)})}publishRpcAck(e,t){return m(this,void 0,void 0,function*(){const n=new Ze({destinationIdentities:[e],kind:Y.RELIABLE,value:{case:"rpcAck",value:new Uu({requestId:t})}});yield this.sendDataPacket(n,Y.RELIABLE)})}sendDataPacket(e,t){return m(this,void 0,void 0,function*(){const n=e.toBinary();yield this.ensurePublisherConnected(t);const i=this.dataChannelForKind(t);i&&i.send(n),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,n)=>m(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const i=()=>n("Engine closed");for(this.once(_.Closing,i);!this.dcBufferStatus.get(e);)yield et(10);this.off(_.Closing,i),t()}}))}ensureDataTransportConnected(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var r;if(!n.pcManager)throw new Te("PC manager is closed");const s=i?n.pcManager.subscriber:n.pcManager.publisher,o=i?"Subscriber":"Publisher";if(!s)throw new oe("".concat(o," connection not set"),J.InternalError);let a=!1;!i&&!n.dataChannelForKind(t,i)&&(n.createDataChannels(),a=!0),!a&&!i&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(a=!0),a&&n.negotiate();const c=n.dataChannelForKind(t,i);if(c?.readyState==="open")return;const l=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<l;){if(s.isICEConnected&&((r=n.dataChannelForKind(t,i))===null||r===void 0?void 0:r.readyState)==="open")return;yield et(50)}throw new oe("could not establish ".concat(o," connection, state: ").concat(s.getICEConnectionState()),J.InternalError)}()})}ensurePublisherConnected(e){return m(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==ge.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return m(this,void 0,void 0,function*(){return new Promise((e,t)=>m(this,void 0,void 0,function*(){if(!this.pcManager){t(new ja("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const n=new AbortController,i=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(_.Closing,i),this.pcManager.publisher.once(jn.RTPVideoPayloadTypes,r=>{const s=new Map;r.forEach(o=>{const a=o.codec.toLowerCase();FC(a)&&s.set(o.payload,a)}),this.emit(_.RTPVideoMapUpdate,s)});try{yield this.pcManager.negotiate(n),e()}catch(r){r instanceof ja&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Ln.RR_UNKNOWN),t(r)}finally{this.off(_.Closing,i)}}))})}dataChannelForKind(e,t){if(t){if(e===Y.LOSSY)return this.lossyDCSub;if(e===Y.RELIABLE)return this.reliableDCSub}else{if(e===Y.LOSSY)return this.lossyDC;if(e===Y.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,i;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const r=this.pcManager.subscriber.getLocalDescription(),s=this.pcManager.subscriber.getRemoteDescription(),o=(i=(n=this.signalOpts)===null||n===void 0?void 0:n.autoSubscribe)!==null&&i!==void 0?i:!0,a=new Array,c=new Array;e.forEach(l=>{l.isDesired!==o&&a.push(l.trackSid),l.isEnabled||c.push(l.trackSid)}),this.client.sendSyncState(new Gu({answer:r?us({sdp:r.sdp,type:r.type}):void 0,offer:s?us({sdp:s.sdp,type:s.type}):void 0,subscription:new qr({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:OC(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(n,i)=>{n?.id!==void 0&&n.id!==null&&e.push(new ju({label:n.label,id:n.id,target:i}))};return t(this.dataChannelForKind(Y.LOSSY),yt.PUBLISHER),t(this.dataChannelForKind(Y.RELIABLE),yt.PUBLISHER),t(this.dataChannelForKind(Y.LOSSY,!0),yt.SUBSCRIBER),t(this.dataChannelForKind(Y.RELIABLE,!0),yt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&_e.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){tt()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){tt()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Wn extends Error{}function Cb(A){return A!==void 0&&A>13}function bb(A,e){const t=A.participantIdentity?A.participantIdentity:e.participantIdentity;A.participantIdentity=t,e.participantIdentity=t;const n=A.destinationIdentities.length!==0?A.destinationIdentities:e.destinationIdentities;A.destinationIdentities=n,e.destinationIdentities=n}class Tc{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Ac(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return m(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter(n=>!this.attemptedRegions.find(i=>i.url===n.url));if(t.length>0){const n=t[0];return this.attemptedRegions.push(n),j.debug("next region: ".concat(n.region)),n.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return m(this,void 0,void 0,function*(){const t=yield fetch("".concat(wb(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const n=yield t.json();return this.lastUpdateAt=Date.now(),n}else throw new oe("Could not fetch region settings: ".concat(t.statusText),t.status===401?J.NotAllowed:J.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function wb(A){return"".concat(A.protocol.replace("ws","http"),"//").concat(A.host,"/settings")}class yf{get info(){return this._info}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}}class yb extends yf{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,n)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>m(this,void 0,void 0,function*(){try{const{done:t,value:n}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(n),{done:!1,value:n.content})}catch{return{done:!0,value:void 0}}}),return(){return m(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return m(this,void 0,void 0,function*(){var e,t,n,i;let r=new Set;try{for(var s=!0,o=uA(this),a;a=yield o.next(),e=a.done,!e;s=!0){i=a.value,s=!1;const c=i;r.add(c)}}catch(c){t={error:c}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return Array.from(r)})}}class Eb extends yf{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=ls(e.chunkIndex),i=this.receivedChunks.get(n);if(i&&i.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength;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;return{next:()=>m(this,void 0,void 0,function*(){try{const{done:n,value:i}=yield e.read();return n?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:t.decode(i.content)})}catch{return{done:!0,value:void 0}}}),return(){return m(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return m(this,void 0,void 0,function*(){var e,t,n,i;let r="";try{for(var s=!0,o=uA(this),a;a=yield o.next(),e=a.done,!e;s=!0)i=a.value,s=!1,r+=i}catch(c){t={error:c}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return r})}}class Ef{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return m(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 Sb extends Ef{}class Ub extends Ef{}class Sf extends T{constructor(e,t,n,i,r){super(e,n,r),this.sid=t,this.receiver=i}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?I.Muted:I.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=n=>{n.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(I.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return m(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(),wc)),HC()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const n=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(n){const{timestamp:i,rtpTimestamp:r}=n;r&&this.rtpTimestamp!==r&&(this.emit(I.TimeSyncUpdate,{timestamp:i,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Tb extends Sf{constructor(e,t,n,i,r,s){super(e,t,T.Kind.Audio,n,s),this.monitorReceiver=()=>m(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=hs(o,this.prevStats)),this.prevStats=o}),this.audioContext=i,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;Ht()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Ht())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return m(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(tc(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&tc(e)&&e.setSinkId(this.sinkId).catch(n=>{this.log.error("Failed to set sink id on remote audio track",n,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 n=this.sourceNode;this.webAudioPluginNodes.forEach(i=>{n.connect(i),n=i}),this.gainNode=e.createGain(),n.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(I.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(i=>{this.emit(I.AudioPlaybackFailed,i)})}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 m(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(n=>{n.type==="inbound-rtp"&&(t={type:"audio",streamId:n.id,timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),t})}}const kc=100;class kb extends Sf{constructor(e,t,n,i,r){super(e,t,T.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>m(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const s=yield this.getReceiverStats();s&&this.prevStats&&this.receiver&&(this._currentBitrate=hs(s,this.prevStats)),this.prevStats=s}),this.debouncedHandleResize=vc(()=>{this.updateDimensions()},kc),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Kn(this._mediaStreamTrack,t):Nn(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 Fb(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(n=>n===e);for(const n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return m(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",i=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(n=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"&&i.set(r.id,r)}),t&&n!==""&&i.get(n)&&(t.mimeType=i.get(n).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(n=>n.element===e);for(const n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const n=this.elementInfos.reduce((o,a)=>Math.max(o,a.visibilityChangedAt||0),0),i=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,r=this.elementInfos.some(o=>o.pictureInPicture),s=this.elementInfos.some(o=>o.visible)&&!i||r;if(this.lastVisible!==s){if(!s&&Date.now()-n<kc){_e.setTimeout(()=>{this.updateVisibility()},kc);return}this.lastVisible=s,this.emit(I.VisibilityChanged,s,this)}}updateDimensions(){var e,t;let n=0,i=0;const r=this.getPixelDensity();for(const s of this.elementInfos){const o=s.width()*r,a=s.height()*r;o+a>n+i&&(n=o,i=a)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===i||(this.lastDimensions={width:n,height:i},this.emit(I.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Gh():t||(Gh()>2?2:1)}}class Fb{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var i;const{target:r,isIntersecting:s}=n;r===this.element&&(this.isIntersecting=s,this.isPiP=Ni(this.element),this.visibilityChangedAt=Date.now(),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this))},this.onEnterPiP=()=>{var n,i,r;(i=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Ni(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=Ni(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??Fc(e),this.isPiP=tt()&&Ni(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=Fc(this.element),this.isPiP=Ni(this.element),this.element.handleResize=()=>{var i;(i=this.handleResize)===null||i===void 0||i.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Wh().observe(this.element),jh().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),(n=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||n===void 0||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,i,r;(e=Wh())===null||e===void 0||e.unobserve(this.element),(t=jh())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(n=window.documentPictureInPicture)===null||n===void 0||n.removeEventListener("enter",this.onEnterPiP),(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function Ni(A){var e,t;return document.pictureInPictureElement===A?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Fc(A,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Fc(A,e){const t=e||window;let n=A.offsetTop,i=A.offsetLeft;const r=A.offsetWidth,s=A.offsetHeight,{hidden:o}=A,{display:a}=getComputedStyle(A);for(;A.offsetParent;)A=A.offsetParent,n+=A.offsetTop,i+=A.offsetLeft;return n<t.pageYOffset+t.innerHeight&&i<t.pageXOffset+t.innerWidth&&n+s>t.pageYOffset&&i+r>t.pageXOffset&&!o&&a!=="none"}class Zt extends Ot.EventEmitter{constructor(e,t,n,i){var r;super(),this.metadataMuted=!1,this.encryption=st.NONE,this.log=j,this.handleMuted=()=>{this.emit(I.Muted)},this.handleUnmuted=()=>{this.emit(I.Unmuted)},this.log=qt((r=i?.loggerName)!==null&&r!==void 0?r:Et.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=T.Source.Unknown}setTrack(e){this.track&&(this.track.off(I.Muted,this.handleMuted),this.track.off(I.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(I.Muted,this.handleMuted),e.on(I.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),te(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==st.NONE}get audioTrack(){if(Yt(this.track))return this.track}get videoTrack(){if(Gn(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=T.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===T.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(A){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(A.SubscriptionStatus||(A.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(A.PermissionStatus||(A.PermissionStatus={}))})(Zt||(Zt={}));class Qc extends Zt{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n,i){super(e,t.sid,t.name,i),this.track=void 0,this.handleTrackEnded=()=>{this.emit(I.Ended)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&this.track.off(I.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(I.Ended,this.handleTrackEnded)}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 m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Yt(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(wt.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(wt.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(wt.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(wt.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(wt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(wt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}function ms(A,e){return m(this,void 0,void 0,function*(){A??(A={});let t=!1;const{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:r}=ef(A);let s=r.audio,o=r.video;if(n&&typeof r.audio=="object"&&(r.audio.processor=n),i&&typeof r.video=="object"&&(r.video.processor=i),A.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const d=r.audio.deviceId;r.audio.deviceId={exact:d},t=!0,s=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:d}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const d=r.video.deviceId;r.video.deviceId={exact:d},t=!0,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:d}})}(r.audio===!0||typeof r.audio=="object"&&!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 a=qh(r,df,uf),c=dc(a),l=navigator.mediaDevices.getUserMedia(c);r.audio&&(Fe.userMediaPromiseMap.set("audioinput",l),l.catch(()=>Fe.userMediaPromiseMap.delete("audioinput"))),r.video&&(Fe.userMediaPromiseMap.set("videoinput",l),l.catch(()=>Fe.userMediaPromiseMap.delete("videoinput")));try{const d=yield l;return yield Promise.all(d.getTracks().map(u=>m(this,void 0,void 0,function*(){const h=u.kind==="audio";let f=h?a.audio:a.video;(typeof f=="boolean"||!f)&&(f={});let p;const g=h?c.audio:c.video;typeof g!="boolean"&&(p=g);const v=u.getSettings().deviceId;p?.deviceId&&mA(p.deviceId)!==v?p.deviceId=v:p||(p={deviceId:v});const w=sb(u,p,e);return w.kind===T.Kind.Video?w.source=T.Source.Camera:w.kind===T.Kind.Audio&&(w.source=T.Source.Microphone),w.mediaStream=d,Yt(w)&&n?yield w.setProcessor(n):Gn(w)&&i&&(yield w.setProcessor(i)),w})))}catch(d){if(!t)throw d;return ms(Object.assign(Object.assign({},A),{audio:s,video:o}),e)}})}function Qb(A){return m(this,void 0,void 0,function*(){return(yield ms({audio:!1,video:A??!0}))[0]})}function Ib(A){return m(this,void 0,void 0,function*(){return(yield ms({audio:A??!0,video:!1}))[0]})}var CA;(function(A){A.Excellent="excellent",A.Good="good",A.Poor="poor",A.Lost="lost",A.Unknown="unknown"})(CA||(CA={}));function _b(A){switch(A){case xi.EXCELLENT:return CA.Excellent;case xi.GOOD:return CA.Good;case xi.POOR:return CA.Poor;case xi.LOST:return CA.Lost;default:return CA.Unknown}}class Uf extends Ot.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===Xr.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Dn.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,i,r,s){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Xr.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=CA.Unknown,this.log=j,this.log=qt((a=s?.loggerName)!==null&&a!==void 0?a:Et.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=i,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 sc,this.once(R.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(T.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(T.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(T.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===Dn.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Dn.ACTIVE&&this.emit(R.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(R.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(R.ParticipantNameChanged,e)}_setAttributes(e){const t=MC(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(R.AttributesChanged,t)}setPermissions(e){var t,n,i,r,s,o;const a=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((i=this.permissions)===null||i===void 0?void 0:i.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((s=this.permissions)===null||s===void 0?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,d)=>{var u;return l!==((u=this.permissions)===null||u===void 0?void 0:u.canPublishSources[d])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(R.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(R.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=_b(e),t!==this._connectionQuality&&this.emit(R.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=>Yt(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(I.Muted,()=>{this.emit(R.TrackMuted,e)}),e.on(I.Unmuted,()=>{this.emit(R.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case T.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case T.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function xb(A){var e,t,n;if(!A.participantSid&&!A.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new $u({participantIdentity:(e=A.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=A.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=A.allowAll)!==null&&n!==void 0?n:!1,trackSids:A.allowedTrackSids||[]})}const Tf=15e3;class Rb extends Uf{constructor(e,t,n,i,r){super(e,t,void 0,void 0,void 0,{loggerName:i.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=st.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new sc)},this.handleReconnected=()=>{var s,o;(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.resolve)===null||o===void 0||o.call(s),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var s,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(a=>this.log.warn(a.message,this.logContext)),(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.reject)===null||o===void 0||o.call(s,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=s=>{const{requestId:o,reason:a,message:c}=s,l=this.pendingSignalRequests.get(o);l&&(a!==Ra.OK&&l.reject(new Oh(c,a)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=s=>{switch(s.value.case){case"rpcResponse":let o=s.value.value,a=null,c=null;o.value.case==="payload"?a=o.value.value:o.value.case==="error"&&(c=me.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,a,c);break;case"rpcAck":let l=s.value.value;this.handleIncomingRpcAck(l.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(s=>xb(s)))},this.onTrackUnmuted=s=>{this.onTrackMuted(s,s.isUpstreamPaused)},this.onTrackMuted=(s,o)=>{if(o===void 0&&(o=!0),!s.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),te(s)));return}this.engine.updateMuteStatus(s.sid,o)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),te(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),te(s))),this.onTrackMuted(s,s.isMuted)},this.onTrackFeatureUpdate=s=>{const o=this.audioTrackPublications.get(s.sid);if(!o){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(s.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.handleSubscribedQualityUpdate=s=>m(this,void 0,void 0,function*(){var o,a,c,l,d,u;if(!(!((d=this.roomOptions)===null||d===void 0)&&d.dynacast))return;const h=this.videoTrackPublications.get(s.trackSid);if(!h){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}if(s.subscribedCodecs.length>0){if(!h.videoTrack)return;const v=yield h.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var f=!0,p=uA(v),g;g=yield p.next(),o=g.done,!o;f=!0){l=g.value,f=!1;const w=l;vC(w)&&(this.log.debug("publish ".concat(w," for ").concat(h.videoTrack.sid),Object.assign(Object.assign({},this.logContext),te(h))),yield this.publishAdditionalCodecForTrack(h.videoTrack,w,h.options))}}catch(w){a={error:w}}finally{try{!f&&!o&&(c=p.return)&&(yield c.call(p))}finally{if(a)throw a.error}}}else s.subscribedQualities.length>0&&(yield(u=h.videoTrack)===null||u===void 0?void 0:u.setPublishingLayers(s.subscribedQualities))}),this.handleLocalTrackUnpublished=s=>{const o=this.trackPublications.get(s.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=s=>m(this,void 0,void 0,function*(){if(s.source===T.Source.ScreenShare||s.source===T.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),te(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(rn(s)||vA(s))try{if(tt())try{const o=yield navigator?.permissions.query({name:s.source===T.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(s.source),Object.assign(Object.assign({},this.logContext),te(s))),o.onchange=()=>{o.state!=="denied"&&(s.isMuted||s.restartTrack(),o.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}s.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),te(s))),rn(s)?yield s.restartTrack({deviceId:"default"}):yield s.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),te(s))),yield s.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=i,this.setupEngine(n),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==st.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){this.engine=e,this.engine.on(_.RemoteMute,(t,n)=>{const i=this.trackPublications.get(t);!i||!i.track||(n?i.mute():i.unmute())}),this.engine.on(_.Connected,this.handleReconnected).on(_.SignalRestarted,this.handleReconnected).on(_.SignalResumed,this.handleReconnected).on(_.Restarting,this.handleReconnecting).on(_.Resuming,this.handleReconnecting).on(_.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(_.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(_.Disconnected,this.handleDisconnected).on(_.SignalRequestResponse,this.handleSignalRequestResponse).on(_.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return m(this,arguments,void 0,function(t){var n=this;let{metadata:i,name:r,attributes:s}=t;return function*(){return new Promise((o,a)=>m(n,void 0,void 0,function*(){var c,l;try{let d=!1;const u=yield this.engine.client.sendUpdateLocalMetadata((c=i??this.metadata)!==null&&c!==void 0?c:"",(l=r??this.name)!==null&&l!==void 0?l:"",s),h=performance.now();for(this.pendingSignalRequests.set(u,{resolve:o,reject:f=>{a(f),d=!0},values:{name:r,metadata:i,attributes:s}});performance.now()-h<5e3&&!d;){if((!r||this.name===r)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every(f=>{let[p,g]=f;return this.attributes[p]===g||g===""&&!this.attributes[p]}))){this.pendingSignalRequests.delete(u),o();return}yield et(50)}a(new Oh("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error&&a(d)}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(T.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(T.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(T.Source.ScreenShare,e,t,n)}setPermissions(e){const t=this.permissions,n=super.setPermissions(e);return n&&t&&this.emit(R.ParticipantPermissionsChanged,t),n}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){this.encryptionType=e?st.GCM:st.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,i){return m(this,void 0,void 0,function*(){var r,s;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 a;if(this.pendingPublishing.has(e)){const c=yield this.waitForPendingPublicationOfSource(e);return c||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield c?.unmute(),c}this.pendingPublishing.add(e);try{switch(e){case T.Source.Camera:a=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case T.Source.Microphone:a=yield this.createTracks({audio:(s=n)!==null&&s!==void 0?s:!0});break;case T.Source.ScreenShare:a=yield this.createScreenTracks(Object.assign({},n));break;default:throw new zt(e)}}catch(c){throw a?.forEach(l=>{l.stop()}),c instanceof Error&&this.emit(R.MediaDevicesError,c),this.pendingPublishing.delete(e),c}try{const c=[];for(const d of a)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),te(d))),c.push(this.publishTrack(d,i));[o]=yield Promise.all(c)}catch(c){throw a?.forEach(l=>{l.stop()}),c}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===T.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const a=this.getTrackPublication(T.Source.ScreenShareAudio);a&&a.track&&this.unpublishTrack(a.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return m(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(T.Source.Camera)||this.pendingPublishing.has(T.Source.Microphone))){this.pendingPublishing.add(T.Source.Camera),this.pendingPublishing.add(T.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(T.Source.Camera),this.pendingPublishing.delete(T.Source.Microphone)}}})}createTracks(e){return m(this,void 0,void 0,function*(){var t,n;e??(e={});const i=qh(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults);try{return(yield ms(i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Yt(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=T.Source.Microphone,this.emit(R.AudioStreamAcquired)),Gn(o)&&(this.cameraError=void 0,o.source=T.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return m(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Ga("getDisplayMedia not supported");e.resolution===void 0&&!EC()&&(e.resolution=Ya.h1080fps30.resolution);const t=DC(e),n=yield navigator.mediaDevices.getDisplayMedia(t),i=n.getVideoTracks();if(i.length===0)throw new zt("no video track found");const r=new gs(i[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=T.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const s=[r];if(n.getAudioTracks().length>0){this.emit(R.AudioStreamAcquired);const o=new fs(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=T.Source.ScreenShareAudio,s.push(o)}return s})}publishTrack(e,t){return m(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return m(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,a,c,l;rn(n)&&n.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!s&&(yield r.republishPromise),Vn(n)&&r.pendingPublishPromises.has(n)&&(yield r.pendingPublishPromises.get(n));let d;if(n instanceof MediaStreamTrack)d=n.getConstraints();else{d=n.constraints;let v;switch(n.source){case T.Source.Microphone:v="audioinput";break;case T.Source.Camera:v="videoinput"}v&&r.activeDeviceMap.has(v)&&(d=Object.assign(Object.assign({},d),{deviceId:r.activeDeviceMap.get(v)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new fs(n,d,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":n=new gs(n,d,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new zt("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let u;if(r.trackPublications.forEach(v=>{v.track&&v.track===n&&(u=v)}),u)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),te(u))),u;const h="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.mediaStreamTrack.getConstraints().channelCount===2,f=(a=i?.forceStereo)!==null&&a!==void 0?a:h;f&&(i||(i={}),i.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),te(n))),i.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(c=i.dtx)!==null&&c!==void 0||(i.dtx=!1),(l=i.red)!==null&&l!==void 0||(i.red=!1));const p=Object.assign(Object.assign({},r.roomOptions.publishDefaults),i);!SC()&&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)),p.simulcast=!1),p.source&&(n.source=p.source);const g=new Promise((v,w)=>m(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ce.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:te(n)}));const y=()=>m(this,void 0,void 0,function*(){try{const B=yield this.publish(n,p,f);v(B)}catch(B){w(B)}});setTimeout(()=>{this.engine.off(_.SignalConnected,y),w(new Wa("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(_.SignalConnected,y),this.engine.on(_.Closing,()=>{this.engine.off(_.SignalConnected,y),w(new Wa("publishing rejected as engine closed",499))})}else try{const y=yield this.publish(n,p,f);v(y)}catch(y){w(y)}}catch(y){w(y)}}));r.pendingPublishPromises.set(n,g);try{return yield g}catch(v){throw v}finally{r.pendingPublishPromises.delete(n)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),te(e))),!1;const{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(i=>NC(i)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),te(e))),!1)}publish(e,t,n){return m(this,void 0,void 0,function*(){var i,r,s,o,a,c,l,d,u,h;if(!this.hasPermissionsToPublish(e))throw new Wa("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(C=>Vn(e)&&C.source===e.source)&&e.source!==T.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),te(e))),t.stopMicTrackOnMute&&Yt(e)&&(e.stopOnMute=!0),e.source===T.Source.ScreenShare&&$n()&&(t.simulcast=!1),t.videoCodec==="av1"&&!bC()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!wC()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Bc),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(C=>t.videoCodec===ds(C.mime))||(t.videoCodec=ds(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(I.Muted,this.onTrackMuted),e.on(I.Unmuted,this.onTrackUnmuted),e.on(I.Ended,this.handleTrackEnded),e.on(I.UpstreamPaused,this.onTrackUpstreamPaused),e.on(I.UpstreamResumed,this.onTrackUpstreamResumed),e.on(I.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const g=new Fa({cid:e.mediaStreamTrack.id,name:t.name,type:T.kindToProto(e.kind),muted:e.isMuted,source:T.sourceToProto(e.source),disableDtx:!(!((i=t.dtx)!==null&&i!==void 0)||i),encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy});let v;if(e.kind===T.Kind.Video){let C={width:0,height:0};try{C=yield e.waitForDimensions()}catch{const U=(o=(s=this.roomOptions.videoCaptureDefaults)===null||s===void 0?void 0:s.resolution)!==null&&o!==void 0?o:Di.h720.resolution;C={width:U.width,height:U.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),te(e)),{dims:C}))}g.width=C.width,g.height=C.height,vA(e)&&(Oi(p)&&(e.source===T.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),te(e))))),t.scalabilityMode=(a=t.scalabilityMode)!==null&&a!==void 0?a:"L3T3_KEY"),g.simulcastCodecs=[new ka({codec:p,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Bc}),t.backupCodec&&p!==t.backupCodec.codec&&g.encryption===st.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),g.simulcastCodecs.push(new ka({codec:t.backupCodec.codec,cid:""})))),v=Ec(e.source===T.Source.ScreenShare,g.width,g.height,t),g.layers=Cf(g.width,g.height,v,Oi(t.videoCodec))}else e.kind===T.Kind.Audio&&(v=[{maxBitrate:(c=t.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(d=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&d!==void 0?d:"high",networkPriority:(h=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&h!==void 0?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new Te("cannot publish track when not connected");const w=()=>m(this,void 0,void 0,function*(){var C,b,U;if(!this.engine.pcManager)throw new Te("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,v),vA(e)&&((C=t.degradationPreference)!==null&&C!==void 0||(t.degradationPreference=gb(e)),e.setDegradationPreference(t.degradationPreference)),v)if($n()&&e.kind===T.Kind.Audio){let Q;for(const x of this.engine.pcManager.publisher.getTransceivers())if(x.sender===e.sender){Q=x;break}Q&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:Q,codec:"opus",maxbr:!((b=v[0])===null||b===void 0)&&b.maxBitrate?v[0].maxBitrate/1e3:0})}else e.codec&&Oi(e.codec)&&(!((U=v[0])===null||U===void 0)&&U.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:g.cid,codec:e.codec,maxbr:v[0].maxBitrate/1e3});yield this.engine.negotiate()});let y;if(this.enabledPublishVideoCodecs.length>0)y=(yield Promise.all([this.engine.addTrack(g),w()]))[0];else{y=yield this.engine.addTrack(g);let C;if(y.codecs.forEach(b=>{C===void 0&&(C=b.mimeType)}),C&&e.kind===T.Kind.Video){const b=ds(C);b!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),te(e)),{codec:b})),t.videoCodec=b,v=Ec(e.source===T.Source.ScreenShare,g.width,g.height,t))}yield w()}const B=new Qc(e.kind,y,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return B.options=t,e.sid=y.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:v,trackInfo:y})),vA(e)?e.startMonitor(this.engine.client):rn(e)&&e.startMonitor(),this.addTrackPublication(B),this.emit(R.LocalTrackPublished,B),B})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return m(this,void 0,void 0,function*(){var i;if(this.encryptionType!==st.NONE)return;let r;if(this.trackPublications.forEach(h=>{h.track&&h.track===e&&(r=h)}),!r)throw new zt("track is not published");if(!vA(e))throw new zt("track is not a video track");const s=Object.assign(Object.assign({},(i=this.roomOptions)===null||i===void 0?void 0:i.publishDefaults),n),o=hb(e,t,s);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),te(e)));return}const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new Fa({cid:a.mediaStreamTrack.id,type:T.kindToProto(e.kind),muted:e.isMuted,source:T.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=Cf(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new Te("cannot publish track when not connected");const l=()=>m(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,s,o),yield this.engine.negotiate()}),u=(yield Promise.all([this.engine.addTrack(c),l()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:u}))})}unpublishTrack(e,t){return m(this,void 0,void 0,function*(){var n,i;if(Vn(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),te(e))),yield c)}const r=this.getPublicationForTrack(e),s=r?te(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),s)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),s));return}e=r.track,e.off(I.Muted,this.onTrackMuted),e.off(I.Unmuted,this.onTrackUnmuted),e.off(I.Ended,this.handleTrackEnded),e.off(I.UpstreamPaused,this.onTrackUpstreamPaused),e.off(I.UpstreamResumed,this.onTrackUpstreamResumed),e.off(I.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(i=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&i!==void 0?i:!0),t?e.stop():e.stopMonitor();let o=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ge.FAILED&&a)try{for(const c of this.engine.pcManager.publisher.getTransceivers())c.sender===a&&(c.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),vA(e)){for(const[,c]of e.simulcastCodecs)c.sender&&(this.engine.removeTrack(c.sender)&&(o=!0),c.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),s),{error:c}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case T.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case T.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(R.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return m(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new Promise((r,s)=>m(n,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(a=>{a.track&&(t&&(a.options=Object.assign(Object.assign({},a.options),t)),o.push(a))}),yield Promise.all(o.map(a=>m(this,void 0,void 0,function*(){const c=a.track;yield this.unpublishTrack(c,!1),i&&!c.isMuted&&c.source!==T.Source.ScreenShare&&c.source!==T.Source.ScreenShareAudio&&(rn(c)||vA(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:a.trackSid})),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,a.options,!0)}))),r()}catch(o){s(o)}finally{this.republishPromise=void 0}})),yield n.republishPromise}()})}publishData(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const r=i.reliable?Y.RELIABLE:Y.LOSSY,s=i.destinationIdentities,o=i.topic,a=new Ze({kind:r,value:{case:"user",value:new yu({participantIdentity:n.identity,payload:t,destinationIdentities:s,topic:o})}});yield n.engine.sendDataPacket(a,r)}()})}publishDtmf(e,t){return m(this,void 0,void 0,function*(){const n=new Ze({kind:Y.RELIABLE,value:{case:"sipDtmf",value:new Eu({code:e,digit:t})}});yield this.engine.sendDataPacket(n,Y.RELIABLE)})}sendChatMessage(e,t){return m(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},i=new Ze({value:{case:"chatMessage",value:new wa(Object.assign(Object.assign({},n),{timestamp:he.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(i,Y.RELIABLE),this.emit(R.ChatMessage,n),n})}editChatMessage(e,t){return m(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),i=new Ze({value:{case:"chatMessage",value:new wa(Object.assign(Object.assign({},n),{timestamp:he.parse(n.timestamp),editTimestamp:he.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(i,Y.RELIABLE),this.emit(R.ChatMessage,n),n})}sendText(e,t){return m(this,void 0,void 0,function*(){var n;const i=crypto.randomUUID(),s=new TextEncoder().encode(e).byteLength,o=(n=t?.attachments)===null||n===void 0?void 0:n.map(()=>crypto.randomUUID()),a=new Array(o?o.length+1:1).fill(0),c=(d,u)=>{var h;a[u]=d;const f=a.reduce((p,g)=>p+g,0);(h=t?.onProgress)===null||h===void 0||h.call(t,f)},l=yield this.streamText({streamId:i,totalSize:s,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:o,attributes:t?.attributes});return yield l.write(e),c(1,0),yield l.close(),t?.attachments&&o&&(yield Promise.all(t.attachments.map((d,u)=>m(this,void 0,void 0,function*(){return this._sendFile(o[u],d,{topic:t.topic,mimeType:d.type,onProgress:h=>{c(h,u+1)}})})))),l.info})}streamText(e){return m(this,void 0,void 0,function*(){var t,n;const i=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),r={id:i,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e?.topic)!==null&&n!==void 0?n:"",size:e?.totalSize,attributes:e?.attributes},s=new Ea({streamId:i,mimeType:r.mimeType,topic:r.topic,timestamp:nn(r.timestamp),totalLength:nn(e?.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new Pu({version:e?.version,attachedStreamIds:e?.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?ya.UPDATE:ya.CREATE})}}),o=e?.destinationIdentities,a=new Ze({destinationIdentities:o,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(a,Y.RELIABLE);let c=0;const l=this,d=new WritableStream({write(f){return m(this,void 0,void 0,function*(){for(const p of PC(f,Tf)){yield l.engine.waitForBufferStatusLow(Y.RELIABLE);const g=new Sa({content:p,streamId:i,chunkIndex:nn(c)}),v=new Ze({destinationIdentities:o,value:{case:"streamChunk",value:g}});yield l.engine.sendDataPacket(v,Y.RELIABLE),c+=1}})},close(){return m(this,void 0,void 0,function*(){const f=new Ua({streamId:i}),p=new Ze({destinationIdentities:o,value:{case:"streamTrailer",value:f}});yield l.engine.sendDataPacket(p,Y.RELIABLE)})},abort(f){console.log("Sink error:",f)}});let u=()=>m(this,void 0,void 0,function*(){yield h.close()});l.engine.once(_.Closing,u);const h=new Sb(d,r,()=>this.engine.off(_.Closing,u));return h})}sendFile(e,t){return m(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return m(this,void 0,void 0,function*(){var i;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(i=n?.mimeType)!==null&&i!==void 0?i:t.type,topic:n?.topic,destinationIdentities:n?.destinationIdentities}),s=t.stream().getReader();for(;;){const{done:o,value:a}=yield s.read();if(o)break;yield r.write(a)}return yield r.close(),r.info})}streamBytes(e){return m(this,void 0,void 0,function*(){var t,n,i,r,s;const o=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a=e?.destinationIdentities,c={id:o,mimeType:(n=e?.mimeType)!==null&&n!==void 0?n:"application/octet-stream",topic:(i=e?.topic)!==null&&i!==void 0?i:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(r=e?.name)!==null&&r!==void 0?r:"unknown"},l=new Ea({totalLength:nn((s=c.size)!==null&&s!==void 0?s:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:nn(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Lu({name:c.name})}}),d=new Ze({destinationIdentities:a,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(d,Y.RELIABLE);let u=0;const h=new ze,f=this.engine,p=this.log,g=new WritableStream({write(w){return m(this,void 0,void 0,function*(){const y=yield h.lock();let B=0;try{for(;B<w.byteLength;){const C=w.slice(B,B+Tf);yield f.waitForBufferStatusLow(Y.RELIABLE);const b=new Ze({destinationIdentities:a,value:{case:"streamChunk",value:new Sa({content:C,streamId:o,chunkIndex:nn(u)})}});yield f.sendDataPacket(b,Y.RELIABLE),u+=1,B+=C.byteLength}}finally{y()}})},close(){return m(this,void 0,void 0,function*(){const w=new Ua({streamId:o}),y=new Ze({destinationIdentities:a,value:{case:"streamTrailer",value:w}});yield f.sendDataPacket(y,Y.RELIABLE)})},abort(w){p.error("Sink error:",w)}});return new Ub(g,c)})}performRpc(e){return m(this,arguments,void 0,function(t){var n=this;let{destinationIdentity:i,method:r,payload:s,responseTimeout:o=1e4}=t;return function*(){return new Promise((c,l)=>m(n,void 0,void 0,function*(){var d,u,h,f;if(bc(s)>hf){l(me.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((u=(d=this.engine.latestJoinResponse)===null||d===void 0?void 0:d.serverInfo)===null||u===void 0)&&u.version&&An((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){l(me.builtIn("UNSUPPORTED_SERVER"));return}const p=crypto.randomUUID();yield this.publishRpcRequest(i,p,r,s,o-2e3);const g=setTimeout(()=>{this.pendingAcks.delete(p),l(me.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(p),clearTimeout(v)},2e3);this.pendingAcks.set(p,{resolve:()=>{clearTimeout(g)},participantIdentity:i});const v=setTimeout(()=>{this.pendingResponses.delete(p),l(me.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(p,{resolve:(w,y)=>{clearTimeout(v),this.pendingAcks.has(p)&&(console.warn("RPC response received before ack",p),this.pendingAcks.delete(p),clearTimeout(g)),y?l(y):c(w??"")},participantIdentity:i})}))}()})}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,n){const i=this.pendingResponses.get(e);i?(i.resolve(t,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,n,i,r){return m(this,void 0,void 0,function*(){const s=new Ze({destinationIdentities:[e],kind:Y.RELIABLE,value:{case:"rpcRequest",value:new Su({id:t,method:n,payload:i,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(s,Y.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:n,resolve:i}]of this.pendingResponses)n===e&&(i(null,me.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 n,i;const r=this.trackPublications.get(t.sid);if(r){const s=r.isMuted||((i=(n=r.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&i!==void 0?i:!1);s!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),te(r)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(t.sid,s))}}),!0):!1}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(rn(i)||vA(i))&&i.mediaStreamTrack===e&&(t=n):e===i&&(t=n))}),t}waitForPendingPublicationOfSource(e){return m(this,void 0,void 0,function*(){const n=Date.now();for(;Date.now()<n+1e4;){const i=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[s]=r;return s.source===e});if(i)return i[1];yield et(20)}})}}class Pb extends Zt{constructor(e,t,n,i){super(e,t.sid,t.name,i),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=ut.HIGH,this.handleEnded=r=>{this.setTrack(void 0),this.emit(I.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.disabled=!r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensions=r,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const i=new qr({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Fu({participantSid:"",trackSids:[this.trackSid]})]});this.emit(I.UpdateSubscription,i),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?Zt.SubscriptionStatus.Unsubscribed:super.isSubscribed?Zt.SubscriptionStatus.Subscribed:Zt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Zt.PermissionStatus.Allowed:Zt.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,n;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((n=this.videoDimensions)===null||n===void 0?void 0:n.height)===e.height||(cc(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&cc(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,i=this.track;i!==e&&(i&&(i.off(I.VideoDimensionsChanged,this.handleVideoDimensionsChange),i.off(I.VisibilityChanged,this.handleVisibilityChange),i.off(I.Ended,this.handleEnded),i.detach(),i.stopMonitor(),this.emit(I.Unsubscribed,i)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(I.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(I.VisibilityChanged,this.handleVisibilityChange),e.on(I.Ended,this.handleEnded),this.emit(I.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(I.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?I.Muted:I.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(I.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(I.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===T.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return cc(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Ou({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=ut.HIGH,this.emit(I.UpdateSettings,e)}}class vs extends Uf{static fromParticipantInfo(e,t,n){return new vs(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,i,r,s,o){let a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Xr.STANDARD;super(t,n||"",i,r,s,o,a),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(I.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),te(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(I.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(I.SubscriptionPermissionChanged,t=>{this.emit(R.TrackSubscriptionPermissionChanged,e,t)}),e.on(I.SubscriptionStatusChanged,t=>{this.emit(R.TrackSubscriptionStatusChanged,e,t)}),e.on(I.Subscribed,t=>{this.emit(R.TrackSubscribed,t,e)}),e.on(I.Unsubscribed,t=>{this.emit(R.TrackUnsubscribed,t,e)}),e.on(I.SubscriptionFailed,t=>{this.emit(R.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]:T.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:T.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,i,r,s){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(s===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(R.TrackSubscriptionFailed,t);return}s===void 0&&(s=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,i,r,s-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),te(o))),this.emit(R.TrackSubscriptionFailed,t);return}const a=e.kind==="video";let c;return a?c=new kb(e,t,i,r):c=new Tb(e,t,i,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(n),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&ac(c)&&Yt(c)&&c.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,n=new Map;return e.tracks.forEach(i=>{var r,s;let o=this.getTrackPublicationBySid(i.sid);if(o)o.updateInfo(i);else{const a=T.kindFromProto(i.type);if(!a)return;o=new Pb(a,i,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(s=this.loggerOptions)===null||s===void 0?void 0:s.loggerName}),o.updateInfo(i),n.set(i.sid,o);const c=Array.from(this.trackPublications.values()).find(l=>l.source===o?.source);c&&o.source!==T.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:te(c),newTrack:te(o)})),this.addTrackPublication(o)}t.set(i.sid,o)}),this.trackPublications.forEach(i=>{t.has(i.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),te(i))),this.unpublishTrack(i.trackSid,!0))}),n.forEach(i=>{this.emit(R.TrackPublished,i)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const{track:i}=n;switch(i&&(i.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case T.Kind.Audio:this.audioTrackPublications.delete(e);break;case T.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(R.TrackUnpublished,n)}setAudioOutput(e){return m(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var i;Yt(n.track)&&ac(n.track)&&t.push(n.track.setSinkId((i=e.deviceId)!==null&&i!==void 0?i:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var Z;(function(A){A.Disconnected="disconnected",A.Connecting="connecting",A.Connected="connected",A.Reconnecting="reconnecting",A.SignalReconnecting="signalReconnecting"})(Z||(Z={}));const Lb=4*1e3;class sn extends Ot.EventEmitter{constructor(e){var t,n,i,r;if(super(),t=this,this.state=Z.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=j,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(s,o,a)=>m(this,void 0,void 0,function*(){var c;if(!yC())throw Ht()?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 l=yield this.disconnectLock.lock();if(this.state===Z.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),l(),Promise.resolve();if(this.connectFuture)return l(),this.connectFuture.promise;this.setAndEmitConnectionState(Z.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==s&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Ac(new URL(s))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Tc(s,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(h=>{var f;(f=this.regionUrlProvider)===null||f===void 0||f.setServerReportedRegions(h)}).catch(h=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:h}))}));const d=(h,f,p)=>m(this,void 0,void 0,function*(){var g,v;this.abortController&&this.abortController.abort();const w=new AbortController;this.abortController=w,l?.();try{yield this.attemptConnection(p??s,o,a,w),this.abortController=void 0,h()}catch(y){if(this.regionUrlProvider&&y instanceof oe&&y.reason!==J.Cancelled&&y.reason!==J.NotAllowed){let B=null;try{B=yield this.regionUrlProvider.getNextBestRegionUrl((g=this.abortController)===null||g===void 0?void 0:g.signal)}catch(C){if(C instanceof oe&&(C.status===401||C.reason===J.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),f(C);return}}B&&!(!((v=this.abortController)===null||v===void 0)&&v.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(y.message,". Retrying with another region: ").concat(B),this.logContext),this.recreateEngine(),yield d(h,f,B)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Xh(y)),f(y))}else{let B=bt.UNKNOWN_REASON;y instanceof oe&&(B=Xh(y)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,B),f(y)}}}),u=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new sc((h,f)=>{d(h,f,u)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(s,o,a,c,l,d)=>m(this,void 0,void 0,function*(){var u,h,f;const p=yield a.join(s,o,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof l.adaptiveStream=="object"?!0:l.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},d.signal);let g=p.serverInfo;if(g||(g={version:p.serverVersion,region:p.serverRegion}),this.serverInfo=g,this.log.debug("connected to Livekit Server ".concat(Object.entries(g).map(v=>{let[w,y]=v;return"".concat(w,": ").concat(y)}).join(", ")),{room:(u=p.room)===null||u===void 0?void 0:u.name,roomSid:(h=p.room)===null||h===void 0?void 0:h.sid,identity:(f=p.participant)===null||f===void 0?void 0:f.identity}),!g.version)throw new aC("unknown server version");return g.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),l.dynacast=!1),p}),this.applyJoinResponse=s=>{const o=s.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(s.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(s.sifTrailer)}catch(a){this.log.error(a instanceof Error?a.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:a}))}this.handleParticipantUpdates([o,...s.otherParticipants]),s.room&&this.handleRoomUpdate(s.room)},this.attemptConnection=(s,o,a,c)=>m(this,void 0,void 0,function*(){var l,d;this.state===Z.Reconnecting||this.isResuming||!((l=this.engine)===null||l===void 0)&&l.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((d=this.regionUrlProvider)===null||d===void 0)&&d.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Cc),a),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const u=yield this.connectSignal(s,o,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(u),this.setupLocalParticipantEvents(),this.emit(F.SignalConnected)}catch(u){yield this.engine.close(),this.recreateEngine();const h=new oe("could not establish signal connection",J.ServerUnreachable);throw u instanceof Error&&(h.message="".concat(h.message,": ").concat(u.message)),u instanceof oe&&(h.reason=u.reason,h.status=u.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:u})),h}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new oe("Connection attempt aborted",J.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(u){throw yield this.engine.close(),this.recreateEngine(),u}tt()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),tt()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Z.Connected),this.emit(F.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];return m(t,[...o],void 0,function(){var c=this;let l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var d,u,h,f;const p=yield c.disconnectLock.lock();try{if(c.state===Z.Disconnected){c.log.debug("already disconnected",c.logContext);return}c.log.info("disconnect from room",Object.assign({},c.logContext)),(c.state===Z.Connecting||c.state===Z.Reconnecting||c.isResuming)&&(c.log.warn("abort connection attempt",c.logContext),(d=c.abortController)===null||d===void 0||d.abort(),(h=(u=c.connectFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,new oe("Client initiated disconnect",J.Cancelled)),c.connectFuture=void 0),!((f=c.engine)===null||f===void 0)&&f.client.isDisconnected||(yield c.engine.client.sendLeave()),c.engine&&(yield c.engine.close()),c.handleDisconnect(l,bt.CLIENT_INITIATED),c.engine=void 0}finally{p()}}()})},this.onPageLeave=()=>m(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>m(this,void 0,void 0,function*(){const s=[],o=St();if(o&&o.os==="iOS"){const a="livekit-dummy-audio-el";let c=document.getElementById(a);if(!c){c=document.createElement("audio"),c.id=a,c.autoplay=!0,c.hidden=!0;const l=rc();l.enabled=!0;const d=new MediaStream([l]);c.srcObject=d,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:d,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(c),this.once(F.Disconnected,()=>{c?.remove(),c=null})}s.push(c)}this.remoteParticipants.forEach(a=>{a.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(l=>{s.push(l)})})});try{yield Promise.all([this.acquireAudioContext(),...s.map(a=>(a.muted=!1,a.play()))]),this.handleAudioPlaybackStarted()}catch(a){throw this.handleAudioPlaybackFailed(a),a}}),this.startVideo=()=>m(this,void 0,void 0,function*(){const s=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(a=>{var c;(c=a.track)===null||c===void 0||c.attachedElements.forEach(l=>{s.includes(l)||s.push(l)})});yield Promise.all(s.map(o=>o.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(o=>{o.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 s of this.remoteParticipants.values())this.handleParticipantDisconnected(s.identity,s);this.setAndEmitConnectionState(Z.Reconnecting)&&this.emit(F.Reconnecting)},this.handleSignalRestarted=s=>m(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(s.serverRegion),Object.assign(Object.assign({},this.logContext),{region:s.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(s);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(o){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:o}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:s.serverRegion}))}catch{return}this.setAndEmitConnectionState(Z.Connected),this.emit(F.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=s=>{s.forEach(o=>{var a;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(a=this.sidToIdentity.get(o.sid))!==null&&a!==void 0?a:"");let c=this.remoteParticipants.get(o.identity);o.state===Dn.DISCONNECTED?this.handleParticipantDisconnected(o.identity,c):c=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=s=>{const o=[],a={};s.forEach(c=>{if(a[c.sid]=!0,c.sid===this.localParticipant.sid)this.localParticipant.audioLevel=c.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const l=this.getRemoteParticipantBySid(c.sid);l&&(l.audioLevel=c.level,l.setIsSpeaking(!0),o.push(l))}}),a[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{a[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(F.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=s=>{const o=new Map;this.activeSpeakers.forEach(c=>{const l=this.remoteParticipants.get(c.identity);l&&l.sid!==c.sid||o.set(c.sid,c)}),s.forEach(c=>{let l=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(l=this.localParticipant),l&&(l.audioLevel=c.level,l.setIsSpeaking(c.active),c.active?o.set(c.sid,l):o.delete(c.sid))});const a=Array.from(o.values());a.sort((c,l)=>l.audioLevel-c.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(F.ActiveSpeakersChanged,a)},this.handleStreamStateUpdate=s=>{s.streamStates.forEach(o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);if(!c||!c.track)return;const l=T.streamStateFromProto(o.state);l!==c.track.streamState&&(c.track.streamState=l,a.emit(R.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(F.TrackStreamStateChanged,c,c.track.streamState,a))})},this.handleSubscriptionPermissionUpdate=s=>{const o=this.getRemoteParticipantBySid(s.participantSid);if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setAllowed(s.allowed)},this.handleSubscriptionError=s=>{const o=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(s.trackSid));if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setSubscriptionError(s.err)},this.handleDataPacket=s=>{const o=this.remoteParticipants.get(s.participantIdentity);if(s.value.case==="user")this.handleUserPacket(o,s.value.value,s.kind);else if(s.value.case==="transcription")this.handleTranscription(o,s.value.value);else if(s.value.case==="sipDtmf")this.handleSipDtmf(o,s.value.value);else if(s.value.case==="chatMessage")this.handleChatMessage(o,s.value.value);else if(s.value.case==="metrics")this.handleMetrics(s.value.value,o);else if(s.value.case==="streamHeader")this.handleStreamHeader(s.value.value,s.participantIdentity);else if(s.value.case==="streamChunk")this.handleStreamChunk(s.value.value);else if(s.value.case==="streamTrailer")this.handleStreamTrailer(s.value.value);else if(s.value.case==="rpcRequest"){const a=s.value.value;this.handleIncomingRpcRequest(s.participantIdentity,a.id,a.method,a.payload,a.responseTimeoutMs,a.version)}},this.handleUserPacket=(s,o,a)=>{this.emit(F.DataReceived,o.payload,s,a,o.topic),s?.emit(R.DataReceived,o.payload,a)},this.handleSipDtmf=(s,o)=>{this.emit(F.SipDTMFReceived,o,s),s?.emit(R.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(s,o)=>{const a=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),c=a?.trackPublications.get(o.trackId),l=IC(o,this.transcriptionReceivedTimes);c?.emit(I.TranscriptionReceived,l),a?.emit(R.TranscriptionReceived,l,c),this.emit(F.TranscriptionReceived,l,a,c)},this.handleChatMessage=(s,o)=>{const a=_C(o);this.emit(F.ChatMessage,a,s)},this.handleMetrics=(s,o)=>{this.emit(F.MetricsReceived,s,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(F.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=s=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:s})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(F.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(F.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(F.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>m(this,void 0,void 0,function*(){var s,o,a;const c=Fe.getInstance().previousDevices,l=yield Fe.getInstance().getDevices(void 0,!1),d=St();if(d?.name==="Chrome"&&d.os!=="iOS")for(let h of l){const f=c.find(p=>p.deviceId===h.deviceId);f&&f.label!==""&&f.kind===h.kind&&f.label!==h.label&&this.getActiveDevice(h.kind)==="default"&&this.emit(F.ActiveDeviceChanged,h.kind,h.deviceId)}const u=["audiooutput","audioinput","videoinput"];for(let h of u){const f=LC(h),p=this.localParticipant.getTrackPublication(f);if(p&&(!((s=p.track)===null||s===void 0)&&s.isUserProvided))continue;const g=l.filter(w=>w.kind===h),v=this.getActiveDevice(h);if(v===((o=c.filter(w=>w.kind===h)[0])===null||o===void 0?void 0:o.deviceId)&&g.length>0&&((a=g[0])===null||a===void 0?void 0:a.deviceId)!==v){yield this.switchActiveDevice(h,g[0].deviceId);continue}h==="audioinput"&&!gA()||h==="videoinput"||g.length>0&&!g.find(w=>w.deviceId===this.getActiveDevice(h))&&(yield this.switchActiveDevice(h,g[0].deviceId))}this.emit(F.MediaDevicesChanged)}),this.handleRoomUpdate=s=>{const o=this.roomInfo;this.roomInfo=s,o&&o.metadata!==s.metadata&&this.emitWhenConnected(F.RoomMetadataChanged,s.metadata),o?.activeRecording!==s.activeRecording&&this.emitWhenConnected(F.RecordingStatusChanged,s.activeRecording)},this.handleConnectionQualityUpdate=s=>{s.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const a=this.getRemoteParticipantBySid(o.participantSid);a&&a.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=s=>{this.emit(F.ParticipantMetadataChanged,s,this.localParticipant)},this.onLocalParticipantNameChanged=s=>{this.emit(F.ParticipantNameChanged,s,this.localParticipant)},this.onLocalAttributesChanged=s=>{this.emit(F.ParticipantAttributesChanged,s,this.localParticipant)},this.onLocalTrackMuted=s=>{this.emit(F.TrackMuted,s,this.localParticipant)},this.onLocalTrackUnmuted=s=>{this.emit(F.TrackUnmuted,s,this.localParticipant)},this.onTrackProcessorUpdate=s=>{var o;(o=s?.onPublish)===null||o===void 0||o.call(s,this)},this.onLocalTrackPublished=s=>m(this,void 0,void 0,function*(){var o,a,c,l,d,u;(o=s.track)===null||o===void 0||o.on(I.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.on(I.Restarted,this.onLocalTrackRestarted),(d=(l=(c=s.track)===null||c===void 0?void 0:c.getProcessor())===null||l===void 0?void 0:l.onPublish)===null||d===void 0||d.call(l,this),this.emit(F.LocalTrackPublished,s,this.localParticipant),rn(s.track)&&(yield s.track.checkForSilence())&&this.emit(F.LocalAudioSilenceDetected,s);const h=yield(u=s.track)===null||u===void 0?void 0:u.getDeviceId(!1),f=Zh(s.source);f&&h&&h!==this.localParticipant.activeDeviceMap.get(f)&&(this.localParticipant.activeDeviceMap.set(f,h),this.emit(F.ActiveDeviceChanged,f,h))}),this.onLocalTrackUnpublished=s=>{var o,a;(o=s.track)===null||o===void 0||o.off(I.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.off(I.Restarted,this.onLocalTrackRestarted),this.emit(F.LocalTrackUnpublished,s,this.localParticipant)},this.onLocalTrackRestarted=s=>m(this,void 0,void 0,function*(){const o=yield s.getDeviceId(!1),a=Zh(s.source);a&&o&&o!==this.localParticipant.activeDeviceMap.get(a)&&(this.log.debug("local track restarted, setting ".concat(a," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(a,o),this.emit(F.ActiveDeviceChanged,a,o))}),this.onLocalConnectionQualityChanged=s=>{this.emit(F.ConnectionQualityChanged,s,this.localParticipant)},this.onMediaDevicesError=s=>{this.emit(F.MediaDevicesError,s)},this.onLocalParticipantPermissionsChanged=s=>{this.emit(F.ParticipantPermissionsChanged,s,this.localParticipant)},this.onLocalChatMessageSent=s=>{this.emit(F.ChatMessage,s,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},nb),e),this.log=qt((n=this.options.loggerName)!==null&&n!==void 0?n:Et.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},df),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},uf),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Ab),e?.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new ze,this.localParticipant=new Rb("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",mA(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",mA(this.options.audioCaptureDefaults.deviceId)),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&this.switchActiveDevice("audiooutput",mA(this.options.audioOutput.deviceId)).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),tt()){const s=new AbortController;(r=navigator.mediaDevices)===null||r===void 0||r.addEventListener("devicechange",this.handleDeviceChange,{signal:s.signal}),sn.cleanupRegistry&&sn.cleanupRegistry.register(this,()=>{s.abort()})}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(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)}handleIncomingRpcRequest(e,t,n,i,r,s){return m(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),s!==1){yield this.engine.publishRpcResponse(e,t,null,me.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(n);if(!o){yield this.engine.publishRpcResponse(e,t,null,me.builtIn("UNSUPPORTED_METHOD"));return}let a=null,c=null;try{const l=yield o({requestId:t,callerIdentity:e,payload:i,responseTimeout:r});bc(l)>hf?(a=me.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(n))):c=l}catch(l){l instanceof me?a=l:(console.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),l),a=me.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)})}setE2EEEnabled(e){return m(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;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new KC(this.options.e2ee),this.e2eeManager.on(fA.ParticipantEncryptionStatusChanged,(t,n)=>{RC(n)&&(this.isE2EEEnabled=t),this.emit(F.ParticipantEncryptionStatusChanged,t,n)}),this.e2eeManager.on(fA.EncryptionError,t=>this.emit(F.EncryptionError,t)),(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 m(this,void 0,void 0,function*(){return this.state===Z.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const n=i=>{i.sid!==""&&(this.engine.off(_.RoomUpdate,n),e(i.sid))};this.engine.on(_.RoomUpdate,n),this.once(F.Disconnected,()=>{this.engine.off(_.RoomUpdate,n),t("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 Bb(this.options),this.engine.on(_.ParticipantUpdate,this.handleParticipantUpdates).on(_.RoomUpdate,this.handleRoomUpdate).on(_.SpeakersChanged,this.handleSpeakersChanged).on(_.StreamStateChanged,this.handleStreamStateUpdate).on(_.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(_.SubscriptionError,this.handleSubscriptionError).on(_.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(_.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(_.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(_.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(_.DataPacketReceived,this.handleDataPacket).on(_.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Z.SignalReconnecting)&&this.emit(F.SignalReconnecting)}).on(_.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Z.Connected)&&this.emit(F.Reconnected)}).on(_.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Z.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(_.Restarting,this.handleRestarting).on(_.SignalRestarted,this.handleSignalRestarted).on(_.Offline,()=>{this.setAndEmitConnectionState(Z.Reconnecting)&&this.emit(F.Reconnecting)}).on(_.DCBufferStatusChanged,(e,t)=>{this.emit(F.DCBufferStatusChanged,e,t)}).on(_.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(n=>{let{trackSid:i}=n;return i===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(R.LocalTrackSubscribed,t),this.emitWhenConnected(F.LocalTrackSubscribed,t,this.localParticipant)}).on(_.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,n)=>{this.handleParticipantDisconnected(n,t)}),this.emit(F.Moved,e.room.name,e.token),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))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Fe.getInstance().getDevices(e,t)}prepareConnection(e,t){return m(this,void 0,void 0,function*(){if(this.state===Z.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Ac(new URL(e))&&t){this.regionUrlProvider=new Tc(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===Z.Disconnected&&(this.regionUrl=n,yield fetch(oc(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(oc(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:n}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return m(this,void 0,void 0,function*(){let n=()=>{},i;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new Dt({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new Dt({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new Dt({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new Dt({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":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new Dt({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new Dt({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":i=new Dt({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>m(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new zr({reason:bt.CLIENT_INITIATED,action:Hn.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");i=new Dt({scenario:{case:"subscriberBandwidth",value:nn(t)}});break;case"leave-full-reconnect":i=new Dt({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return m(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,a,c,l,d,u,h,f;let p=!0,g=!1;const v=s?{exact:i}:i;if(n==="audioinput"){g=r.localParticipant.audioTrackPublications.size===0;const w=(o=r.getActiveDevice(n))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=v;const y=Array.from(r.localParticipant.audioTrackPublications.values()).filter(B=>B.source===T.Source.Microphone);try{p=(yield Promise.all(y.map(B=>{var C;return(C=B.audioTrack)===null||C===void 0?void 0:C.setDeviceId(v)}))).every(B=>B===!0)}catch(B){throw r.options.audioCaptureDefaults.deviceId=w,B}}else if(n==="videoinput"){g=r.localParticipant.videoTrackPublications.size===0;const w=(a=r.getActiveDevice(n))!==null&&a!==void 0?a:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=v;const y=Array.from(r.localParticipant.videoTrackPublications.values()).filter(B=>B.source===T.Source.Camera);try{p=(yield Promise.all(y.map(B=>{var C;return(C=B.videoTrack)===null||C===void 0?void 0:C.setDeviceId(v)}))).every(B=>B===!0)}catch(B){throw r.options.videoCaptureDefaults.deviceId=w,B}}else if(n==="audiooutput"){if(!tc()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");r.options.webAudioMix&&(i=(c=yield Fe.getInstance().normalizeDeviceId("audiooutput",i))!==null&&c!==void 0?c:""),(l=(f=r.options).audioOutput)!==null&&l!==void 0||(f.audioOutput={});const w=(d=r.getActiveDevice(n))!==null&&d!==void 0?d:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=i;try{r.options.webAudioMix&&((u=r.audioContext)===null||u===void 0||u.setSinkId(i)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(y=>y.setAudioOutput({deviceId:i})))}catch(y){throw r.options.audioOutput.deviceId=w,y}}return(g||n==="audiooutput")&&(r.localParticipant.activeDeviceMap.set(n,n==="audiooutput"&&((h=r.options.audioOutput)===null||h===void 0?void 0:h.deviceId)||i),r.emit(F.ActiveDeviceChanged,n,i)),p}()})}setupLocalParticipantEvents(){this.localParticipant.on(R.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(R.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(R.AttributesChanged,this.onLocalAttributesChanged).on(R.TrackMuted,this.onLocalTrackMuted).on(R.TrackUnmuted,this.onLocalTrackUnmuted).on(R.LocalTrackPublished,this.onLocalTrackPublished).on(R.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(R.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(R.MediaDevicesError,this.onMediaDevicesError).on(R.AudioStreamAcquired,this.startAudio).on(R.ChatMessage,this.onLocalChatMessageSent).on(R.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,n){if(this.state===Z.Connecting||this.state===Z.Reconnecting){const l=()=>{this.onTrackAdded(e,t,n),d()},d=()=>{this.off(F.Reconnected,l),this.off(F.Connected,l),this.off(F.Disconnected,d)};this.once(F.Reconnected,l),this.once(F.Connected,l),this.once(F.Disconnected,d);return}if(this.state===Z.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 i=CC(t.id),r=i[0];let s=i[1],o=e.id;if(s&&s.startsWith("TR")&&(o=s),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const a=Array.from(this.remoteParticipants.values()).find(l=>l.sid===r);if(!a){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={}),a.addSubscribedMediaTrack(e,o,t,n,c)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==Z.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(i=>{i.trackPublications.forEach(r=>{i.unpublishTrack(r.trackSid)})}),this.localParticipant.trackPublications.forEach(i=>{var r,s,o;i.track&&this.localParticipant.unpublishTrack(i.track,e),e?((r=i.track)===null||r===void 0||r.detach(),(s=i.track)===null||s===void 0||s.stop()):(o=i.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(R.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(R.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(R.AttributesChanged,this.onLocalAttributesChanged).off(R.TrackMuted,this.onLocalTrackMuted).off(R.TrackUnmuted,this.onLocalTrackUnmuted).off(R.LocalTrackPublished,this.onLocalTrackPublished).off(R.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(R.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(R.MediaDevicesError,this.onMediaDevicesError).off(R.AudioStreamAcquired,this.startAudio).off(R.ChatMessage,this.onLocalChatMessageSent).off(R.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),tt()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(n=navigator.mediaDevices)===null||n===void 0||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Z.Disconnected),this.emit(F.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(i=>{t.unpublishTrack(i.trackSid,!0)}),this.emit(F.ParticipantDisconnected,t),t.setDisconnected(),(n=this.localParticipant)===null||n===void 0||n.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return m(this,void 0,void 0,function*(){var n;if(e.contentHeader.case==="byteHeader"){const i=this.byteStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let r;const s={id:e.streamId,name:(n=e.contentHeader.value.name)!==null&&n!==void 0?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:ls(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{r=a,this.byteStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now()})}});i(new yb(s,o,ls(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const i=this.textStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let r;const s={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{r=a,this.textStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now()})}});i(new Eb(s,o,ls(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const n=this.textStreamControllers.get(e.streamId);n&&e.content.length>0&&n.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return m(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=Yh())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(i=>i.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),et(200)])}catch(i){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:i}))}const n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(F.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let i;return t?i=vs.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):i=new vs(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&i.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),i}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}const n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(F.ParticipantConnected,n),n.on(R.TrackPublished,i=>{this.emitWhenConnected(F.TrackPublished,i,n)}).on(R.TrackSubscribed,(i,r)=>{i.kind===T.Kind.Audio?(i.on(I.AudioPlaybackStarted,this.handleAudioPlaybackStarted),i.on(I.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):i.kind===T.Kind.Video&&(i.on(I.VideoPlaybackFailed,this.handleVideoPlaybackFailed),i.on(I.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(F.TrackSubscribed,i,r,n)}).on(R.TrackUnpublished,i=>{this.emit(F.TrackUnpublished,i,n)}).on(R.TrackUnsubscribed,(i,r)=>{this.emit(F.TrackUnsubscribed,i,r,n)}).on(R.TrackMuted,i=>{this.emitWhenConnected(F.TrackMuted,i,n)}).on(R.TrackUnmuted,i=>{this.emitWhenConnected(F.TrackUnmuted,i,n)}).on(R.ParticipantMetadataChanged,i=>{this.emitWhenConnected(F.ParticipantMetadataChanged,i,n)}).on(R.ParticipantNameChanged,i=>{this.emitWhenConnected(F.ParticipantNameChanged,i,n)}).on(R.AttributesChanged,i=>{this.emitWhenConnected(F.ParticipantAttributesChanged,i,n)}).on(R.ConnectionQualityChanged,i=>{this.emitWhenConnected(F.ConnectionQualityChanged,i,n)}).on(R.ParticipantPermissionsChanged,i=>{this.emitWhenConnected(F.ParticipantPermissionsChanged,i,n)}).on(R.TrackSubscriptionStatusChanged,(i,r)=>{this.emitWhenConnected(F.TrackSubscriptionStatusChanged,i,r,n)}).on(R.TrackSubscriptionFailed,(i,r)=>{this.emit(F.TrackSubscriptionFailed,i,n,r)}).on(R.TrackSubscriptionPermissionChanged,(i,r)=>{this.emitWhenConnected(F.TrackSubscriptionPermissionChanged,i,r,n)}).on(R.Active,()=>{this.emitWhenConnected(F.ParticipantActive,n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((n,i)=>(n.push(...i.getTrackPublications()),n),[]),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&&xC(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=_e.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,bt.STATE_MISMATCH))):e=0},Lb)}clearConnectionReconcile(){this.connectionReconcileInterval&&_e.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(F.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];if(this.state===Z.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===Z.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return m(this,void 0,void 0,function*(){var t,n;const i=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Wr({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:he.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new YA({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(F.SignalConnected),this.emit(F.Connected),this.setAndEmitConnectionState(Z.Connected),i.video){const s=new Qc(T.Kind.Video,new On({source:Ee.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ct.AUDIO,name:"video-dummy"}),new gs(i.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Jh(160*((t=r.aspectRatios[0])!==null&&t!==void 0?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(R.LocalTrackPublished,s)}if(i.audio){const s=new Qc(T.Kind.Audio,new On({source:Ee.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ct.AUDIO}),new fs(i.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:rc(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(R.LocalTrackPublished,s)}for(let s=0;s<r.count-1;s+=1){let o=new YA({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(s),state:Dn.ACTIVE,tracks:[],joinedAt:he.parse(Date.now())});const a=this.getOrCreateParticipant(o.identity,o);if(r.video){const c=Jh(160*((n=r.aspectRatios[s%r.aspectRatios.length])!==null&&n!==void 0?n:1),160,!1,!0),l=new On({source:Ee.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ct.AUDIO});a.addSubscribedMediaTrack(c,l.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,l]}if(r.audio){const c=rc(),l=new On({source:Ee.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ct.AUDIO});a.addSubscribedMediaTrack(c,l.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,l]}a.updateInfo(o)}})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];if(e!==F.ActiveSpeakersChanged&&e!==F.TranscriptionReceived){const r=kf(n).filter(s=>s!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...n)}}sn.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(A=>{A()});function kf(A){return A.map(e=>{if(e)return Array.isArray(e)?kf(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var kt;(function(A){A[A.IDLE=0]="IDLE",A[A.RUNNING=1]="RUNNING",A[A.SKIPPED=2]="SKIPPED",A[A.SUCCESS=3]="SUCCESS",A[A.FAILED=4]="FAILED"})(kt||(kt={}));class bA extends Ot.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=kt.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new sn(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return m(this,void 0,void 0,function*(){if(this.status!==kt.IDLE)throw Error("check is running already");this.setStatus(kt.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!==kt.SKIPPED&&this.setStatus(this.isSuccess()?kt.SUCCESS:kt.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return m(this,void 0,void 0,function*(){return this.room.state===Z.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return m(this,void 0,void 0,function*(){this.room&&this.room.state!==Z.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(kt.SKIPPED)}switchProtocol(e){return m(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(F.Reconnecting,()=>{t=!0}),this.room.once(F.Reconnected,()=>{n=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const i=Date.now()+1e4;for(;Date.now()<i;){if(n)return;yield et(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 Db extends bA{get description(){return"Cloud regions"}perform(){return m(this,void 0,void 0,function*(){const e=new Tc(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],n=new Set;for(let r=0;r<3;r++){const s=yield e.getNextBestRegionUrl();if(!s)break;if(n.has(s))continue;n.add(s);const o=yield this.checkCloudRegion(s);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((r,s)=>(r.duration-s.duration)*.5+(r.rtt-s.rtt)*.5);const i=t[0];this.bestStats=i,this.appendMessage("best Cloud region: ".concat(i.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return m(this,void 0,void 0,function*(){var t,n;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const i=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!i)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),s=1e3,a=1e6/s,c="A".repeat(s),l=Date.now();for(let f=0;f<a;f++)yield r.write(c);yield r.close();const d=Date.now(),u=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),h={region:i,rtt:1e4,duration:d-l};return u?.forEach(f=>{f.type==="candidate-pair"&&f.nominated&&(h.rtt=f.currentRoundTripTime*1e3)}),yield this.disconnect(),h})}}const Ic=1e4;class Ob extends bA{get description(){return"Connection via UDP vs TCP"}perform(){return m(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 n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/(Ic/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(Ic/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return m(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 n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let i=0;const r=()=>{i=(i+1)%360,n.fillStyle="hsl(".concat(i,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const o=t.captureStream(30).getVideoTracks()[0],c=(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},d=setInterval(()=>m(this,void 0,void 0,function*(){const u=yield c.getRTCStatsReport();u?.forEach(h=>{h.type==="outbound-rtp"?(l.packetsSent=h.packetsSent,l.qualityLimitationDurations=h.qualityLimitationDurations,l.bitrateTotal+=h.targetBitrate,l.count++):h.type==="remote-inbound-rtp"&&(l.packetsLost=h.packetsLost,l.rttTotal+=h.roundTripTime,l.jitterTotal+=h.jitter)})}),1e3);return yield new Promise(u=>setTimeout(u,Ic)),clearInterval(d),o.stop(),t.remove(),yield this.disconnect(),l})}}class Hb extends bA{get description(){return"Can publish audio"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Ib();if(yield zh(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise(o=>setTimeout(o,3e3));const r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(s=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," audio packets"))})}}class Mb extends bA{get description(){return"Can publish video"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Qb();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise(s=>setTimeout(s,5e3));const i=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let r=0;if(i.forEach(s=>{s.type==="outbound-rtp"&&(s.kind==="video"||!s.kind&&s.mediaType==="video")&&(r+=s.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return m(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const n=document.createElement("video");n.srcObject=t,n.muted=!0,yield new Promise(i=>{n.onplay=()=>{setTimeout(()=>{var r,s,o,a;const c=document.createElement("canvas"),l=e.getSettings(),d=(s=(r=l.width)!==null&&r!==void 0?r:n.videoWidth)!==null&&s!==void 0?s:1280,u=(a=(o=l.height)!==null&&o!==void 0?o:n.videoHeight)!==null&&a!==void 0?a:720;c.width=d,c.height=u;const h=c.getContext("2d");h.drawImage(n,0,0);const p=h.getImageData(0,0,c.width,c.height).data;let g=!0;for(let v=0;v<p.length;v+=4)if(p[v]!==0||p[v+1]!==0||p[v+2]!==0){g=!1;break}g?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),i()},1e3)},n.play()}),n.remove()})}}class Nb extends bA{get description(){return"Resuming connection after interruption"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect();let n=!1,i=!1,r;const s=new Promise(c=>{setTimeout(c,5e3),r=c}),o=()=>{n=!0};t.on(F.SignalReconnecting,o).on(F.Reconnecting,o).on(F.Reconnected,()=>{i=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const a=t.engine.client.onClose;if(a&&a(""),yield s,n){if(!i||t.state!==Z.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 Kb extends bA{get description(){return"Can connect via TURN"}perform(){return m(this,void 0,void 0,function*(){var e,t;const n=new hc,i=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,s=!1,o=!1;for(let a of i.iceServers)for(let c of a.urls)c.startsWith("turn:")?(s=!0,o=!0):c.startsWith("turns:")&&(s=!0,o=!0,r=!0),c.startsWith("stun:")&&(o=!0);o?s&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield n.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(a=>setTimeout(a,0)))})}}class $b extends bA{get description(){return"Establishing WebRTC connection"}perform(){return m(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(F.SignalConnected,()=>{const n=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,r)=>{if(i.candidate){const s=new RTCIceCandidate(i);let o="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(Vb(s.address)?o+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,o+=" (passive)"):s.protocol==="udp"&&(t=!0)),this.appendMessage(o)}n&&n(i,r)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=i=>{i instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(i.errorCode," ").concat(i.errorText," ").concat(i.url))})});try{yield this.connect(),j.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}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 Vb(A){const e=A.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 Gb extends bA{get description(){return"Connecting to signal connection via WebSocket"}perform(){return m(this,void 0,void 0,function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new hc;const r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===Qu.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=r.serverInfo)===null||n===void 0?void 0:n.region)),yield i.close()})}}class w2 extends Ot.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:kt.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!==kt.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return m(this,void 0,void 0,function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),i=s=>{this.updateCheck(t,s)};n.on("update",i);const r=yield n.run();return n.off("update",i),r})}checkWebsocket(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Gb)})}checkWebRTC(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck($b)})}checkTURN(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Kb)})}checkReconnect(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Nb)})}checkPublishAudio(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Hb)})}checkPublishVideo(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Mb)})}checkConnectionProtocol(){return m(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Ob);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Db)})}}const At=Symbol.for("@ts-pattern/matcher"),Ff=Symbol.for("@ts-pattern/isVariadic"),Bs="@ts-pattern/anonymous-select-key",_c=A=>!!(A&&typeof A=="object"),Cs=A=>A&&!!A[At],xe=(A,e,t)=>{if(Cs(A)){const n=A[At](),{matched:i,selections:r}=n.match(e);return i&&r&&Object.keys(r).forEach(s=>t(s,r[s])),i}if(_c(A)){if(!_c(e))return!1;if(Array.isArray(A)){if(!Array.isArray(e))return!1;let n=[],i=[],r=[];for(const s of A.keys()){const o=A[s];Cs(o)&&o[Ff]?r.push(o):r.length?i.push(o):n.push(o)}if(r.length){if(r.length>1)throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(e.length<n.length+i.length)return!1;const s=e.slice(0,n.length),o=i.length===0?[]:e.slice(-i.length),a=e.slice(n.length,i.length===0?1/0:-i.length);return n.every((c,l)=>xe(c,s[l],t))&&i.every((c,l)=>xe(c,o[l],t))&&(r.length===0||xe(r[0],a,t))}return A.length===e.length&&A.every((s,o)=>xe(s,e[o],t))}return Reflect.ownKeys(A).every(n=>{const i=A[n];return(n in e||Cs(r=i)&&r[At]().matcherType==="optional")&&xe(i,e[n],t);var r})}return Object.is(e,A)},ot=A=>{var e,t,n;return _c(A)?Cs(A)?(e=(t=(n=A[At]()).getSelectionKeys)==null?void 0:t.call(n))!=null?e:[]:Array.isArray(A)?Ki(A,ot):Ki(Object.values(A),ot):[]},Ki=(A,e)=>A.reduce((t,n)=>t.concat(e(n)),[]);function jb(...A){if(A.length===1){const[e]=A;return t=>xe(e,t,()=>{})}if(A.length===2){const[e,t]=A;return xe(e,t,()=>{})}throw new Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${A.length}.`)}function Re(A){return Object.assign(A,{optional:()=>Rc(A),and:e=>le(A,e),or:e=>Qf(A,e),select:e=>e===void 0?$i(A):$i(e,A)})}function xc(A){return Object.assign((e=>Object.assign(e,{[Symbol.iterator](){let t=0;const n=[{value:Object.assign(e,{[Ff]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var i;return(i=n[t++])!=null?i:n.at(-1)}}}}))(A),{optional:()=>xc(Rc(A)),select:e=>xc(e===void 0?$i(A):$i(e,A))})}function Rc(A){return Re({[At]:()=>({match:e=>{let t={};const n=(i,r)=>{t[i]=r};return e===void 0?(ot(A).forEach(i=>n(i,void 0)),{matched:!0,selections:t}):{matched:xe(A,e,n),selections:t}},getSelectionKeys:()=>ot(A),matcherType:"optional"})})}const Wb=(A,e)=>{for(const t of A)if(!e(t))return!1;return!0},Jb=(A,e)=>{for(const[t,n]of A.entries())if(!e(n,t))return!1;return!0};function le(...A){return Re({[At]:()=>({match:e=>{let t={};const n=(i,r)=>{t[i]=r};return{matched:A.every(i=>xe(i,e,n)),selections:t}},getSelectionKeys:()=>Ki(A,ot),matcherType:"and"})})}function Qf(...A){return Re({[At]:()=>({match:e=>{let t={};const n=(i,r)=>{t[i]=r};return Ki(A,ot).forEach(i=>n(i,void 0)),{matched:A.some(i=>xe(i,e,n)),selections:t}},getSelectionKeys:()=>Ki(A,ot),matcherType:"or"})})}function X(A){return{[At]:()=>({match:e=>({matched:!!A(e)})})}}function $i(...A){const e=typeof A[0]=="string"?A[0]:void 0,t=A.length===2?A[1]:typeof A[0]=="string"?void 0:A[0];return Re({[At]:()=>({match:n=>{let i={[e??Bs]:n};return{matched:t===void 0||xe(t,n,(r,s)=>{i[r]=s}),selections:i}},getSelectionKeys:()=>[e??Bs].concat(t===void 0?[]:ot(t))})})}function Mt(A){return typeof A=="number"}function wA(A){return typeof A=="string"}function yA(A){return typeof A=="bigint"}const If=Re(X(function(A){return!0})),Xb=If,EA=A=>Object.assign(Re(A),{startsWith:e=>{return EA(le(A,(t=e,X(n=>wA(n)&&n.startsWith(t)))));var t},endsWith:e=>{return EA(le(A,(t=e,X(n=>wA(n)&&n.endsWith(t)))));var t},minLength:e=>EA(le(A,(t=>X(n=>wA(n)&&n.length>=t))(e))),length:e=>EA(le(A,(t=>X(n=>wA(n)&&n.length===t))(e))),maxLength:e=>EA(le(A,(t=>X(n=>wA(n)&&n.length<=t))(e))),includes:e=>{return EA(le(A,(t=e,X(n=>wA(n)&&n.includes(t)))));var t},regex:e=>{return EA(le(A,(t=e,X(n=>wA(n)&&!!n.match(t)))));var t}}),qb=EA(X(wA)),Nt=A=>Object.assign(Re(A),{between:(e,t)=>Nt(le(A,((n,i)=>X(r=>Mt(r)&&n<=r&&i>=r))(e,t))),lt:e=>Nt(le(A,(t=>X(n=>Mt(n)&&n<t))(e))),gt:e=>Nt(le(A,(t=>X(n=>Mt(n)&&n>t))(e))),lte:e=>Nt(le(A,(t=>X(n=>Mt(n)&&n<=t))(e))),gte:e=>Nt(le(A,(t=>X(n=>Mt(n)&&n>=t))(e))),int:()=>Nt(le(A,X(e=>Mt(e)&&Number.isInteger(e)))),finite:()=>Nt(le(A,X(e=>Mt(e)&&Number.isFinite(e)))),positive:()=>Nt(le(A,X(e=>Mt(e)&&e>0))),negative:()=>Nt(le(A,X(e=>Mt(e)&&e<0)))}),zb=Nt(X(Mt)),SA=A=>Object.assign(Re(A),{between:(e,t)=>SA(le(A,((n,i)=>X(r=>yA(r)&&n<=r&&i>=r))(e,t))),lt:e=>SA(le(A,(t=>X(n=>yA(n)&&n<t))(e))),gt:e=>SA(le(A,(t=>X(n=>yA(n)&&n>t))(e))),lte:e=>SA(le(A,(t=>X(n=>yA(n)&&n<=t))(e))),gte:e=>SA(le(A,(t=>X(n=>yA(n)&&n>=t))(e))),positive:()=>SA(le(A,X(e=>yA(e)&&e>0))),negative:()=>SA(le(A,X(e=>yA(e)&&e<0)))}),Yb=SA(X(yA)),Zb=Re(X(function(A){return typeof A=="boolean"})),ew=Re(X(function(A){return typeof A=="symbol"})),tw=Re(X(function(A){return A==null})),Aw=Re(X(function(A){return A!=null}));var nw={__proto__:null,matcher:At,optional:Rc,array:function(...A){return xc({[At]:()=>({match:e=>{if(!Array.isArray(e))return{matched:!1};if(A.length===0)return{matched:!0};const t=A[0];let n={};if(e.length===0)return ot(t).forEach(r=>{n[r]=[]}),{matched:!0,selections:n};const i=(r,s)=>{n[r]=(n[r]||[]).concat([s])};return{matched:e.every(r=>xe(t,r,i)),selections:n}},getSelectionKeys:()=>A.length===0?[]:ot(A[0])})})},set:function(...A){return Re({[At]:()=>({match:e=>{if(!(e instanceof Set))return{matched:!1};let t={};if(e.size===0)return{matched:!0,selections:t};if(A.length===0)return{matched:!0};const n=(r,s)=>{t[r]=(t[r]||[]).concat([s])},i=A[0];return{matched:Wb(e,r=>xe(i,r,n)),selections:t}},getSelectionKeys:()=>A.length===0?[]:ot(A[0])})})},map:function(...A){return Re({[At]:()=>({match:e=>{if(!(e instanceof Map))return{matched:!1};let t={};if(e.size===0)return{matched:!0,selections:t};const n=(o,a)=>{t[o]=(t[o]||[]).concat([a])};if(A.length===0)return{matched:!0};var i;if(A.length===1)throw new Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(i=A[0])==null?void 0:i.toString()}`);const[r,s]=A;return{matched:Jb(e,(o,a)=>{const c=xe(r,a,n),l=xe(s,o,n);return c&&l}),selections:t}},getSelectionKeys:()=>A.length===0?[]:[...ot(A[0]),...ot(A[1])]})})},intersection:le,union:Qf,not:function(A){return Re({[At]:()=>({match:e=>({matched:!xe(A,e,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:X,select:$i,any:If,_:Xb,string:qb,number:zb,bigint:Yb,boolean:Zb,symbol:ew,nullish:tw,nonNullable:Aw,instanceOf:function(A){return Re(X(function(e){return t=>t instanceof e}(A)))},shape:function(A){return Re(X(jb(A)))}};let iw=class extends Error{constructor(e){let t;try{t=JSON.stringify(e)}catch{t=e}super(`Pattern matching error: no pattern matches value ${t}`),this.input=void 0,this.input=e}};const Pc={matched:!1,value:void 0};function Vi(A){return new rw(A,Pc)}let rw=class Hd{constructor(e,t){this.input=void 0,this.state=void 0,this.input=e,this.state=t}with(...e){if(this.state.matched)return this;const t=e[e.length-1],n=[e[0]];let i;e.length===3&&typeof e[1]=="function"?i=e[1]:e.length>2&&n.push(...e.slice(1,e.length-1));let r=!1,s={};const o=(c,l)=>{r=!0,s[c]=l},a=!n.some(c=>xe(c,this.input,o))||i&&!i(this.input)?Pc:{matched:!0,value:t(r?Bs in s?s[Bs]:s:this.input,this.input)};return new Hd(this.input,a)}when(e,t){if(this.state.matched)return this;const n=!!e(this.input);return new Hd(this.input,n?{matched:!0,value:t(this.input,this.input)}:Pc)}otherwise(e){return this.state.matched?this.state.value:e(this.input)}exhaustive(e=sw){return this.state.matched?this.state.value:e(this.input)}run(){return this.exhaustive()}returnType(){return this}};function sw(A){throw new iw(A)}const ow=/\{[^{}]+\}/g;function aw(){return Math.random().toString(36).slice(2,11)}function cw(A){let{baseUrl:e="",Request:t=globalThis.Request,fetch:n=globalThis.fetch,querySerializer:i,bodySerializer:r,headers:s,...o}={...A};e=Pf(e);const a=[];async function c(l,d){const{baseUrl:u,fetch:h=n,Request:f=t,headers:p,params:g={},parseAs:v="json",querySerializer:w,bodySerializer:y=r??dw,body:B,...C}=d||{};u&&(e=Pf(u));let b=typeof i=="function"?i:Rf(i);w&&(b=typeof w=="function"?w:Rf({...typeof i=="object"?i:{},...w}));const U=B===void 0?void 0:y(B),Q=U===void 0||U instanceof FormData?{}:{"Content-Type":"application/json"},x={redirect:"follow",...o,...C,body:U,headers:hw(Q,s,p,g.header)};let O,M,N=new t(uw(l,{baseUrl:e,params:g,querySerializer:b}),x);for(const V in C)V in N||(N[V]=C[V]);if(a.length){O=aw(),M=Object.freeze({baseUrl:e,fetch:h,parseAs:v,querySerializer:b,bodySerializer:y});for(const V of a)if(V&&typeof V=="object"&&typeof V.onRequest=="function"){const z=await V.onRequest({request:N,schemaPath:l,params:g,options:M,id:O});if(z){if(!(z instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");N=z}}}let $=await h(N);if(a.length)for(let V=a.length-1;V>=0;V--){const z=a[V];if(z&&typeof z=="object"&&typeof z.onResponse=="function"){const rt=await z.onResponse({request:N,response:$,schemaPath:l,params:g,options:M,id:O});if(rt){if(!(rt instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");$=rt}}}if($.status===204||$.headers.get("Content-Length")==="0")return $.ok?{data:{},response:$}:{error:{},response:$};if($.ok)return v==="stream"?{data:$.body,response:$}:{data:await $[v](),response:$};let He=await $.text();try{He=JSON.parse(He)}catch{}return{error:He,response:$}}return{GET(l,d){return c(l,{...d,method:"GET"})},PUT(l,d){return c(l,{...d,method:"PUT"})},POST(l,d){return c(l,{...d,method:"POST"})},DELETE(l,d){return c(l,{...d,method:"DELETE"})},OPTIONS(l,d){return c(l,{...d,method:"OPTIONS"})},HEAD(l,d){return c(l,{...d,method:"HEAD"})},PATCH(l,d){return c(l,{...d,method:"PATCH"})},TRACE(l,d){return c(l,{...d,method:"TRACE"})},use(...l){for(const d of l)if(d){if(typeof d!="object"||!("onRequest"in d||"onResponse"in d))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");a.push(d)}},eject(...l){for(const d of l){const u=a.indexOf(d);u!==-1&&a.splice(u,1)}}}}function bs(A,e,t){if(e==null)return"";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${A}=${t?.allowReserved===!0?e:encodeURIComponent(e)}`}function _f(A,e,t){if(!e||typeof e!="object")return"";const n=[],i={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(const o in e)n.push(o,t.allowReserved===!0?e[o]:encodeURIComponent(e[o]));const s=n.join(",");switch(t.style){case"form":return`${A}=${s}`;case"label":return`.${s}`;case"matrix":return`;${A}=${s}`;default:return s}}for(const s in e){const o=t.style==="deepObject"?`${A}[${s}]`:s;n.push(bs(o,e[s],t))}const r=n.join(i);return t.style==="label"||t.style==="matrix"?`${i}${r}`:r}function xf(A,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){const r={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",s=(t.allowReserved===!0?e:e.map(o=>encodeURIComponent(o))).join(r);switch(t.style){case"simple":return s;case"label":return`.${s}`;case"matrix":return`;${A}=${s}`;default:return`${A}=${s}`}}const n={simple:",",label:".",matrix:";"}[t.style]||"&",i=[];for(const r of e)t.style==="simple"||t.style==="label"?i.push(t.allowReserved===!0?r:encodeURIComponent(r)):i.push(bs(A,r,t));return t.style==="label"||t.style==="matrix"?`${n}${i.join(n)}`:i.join(n)}function Rf(A){return function(t){const n=[];if(t&&typeof t=="object")for(const i in t){const r=t[i];if(r!=null){if(Array.isArray(r)){if(r.length===0)continue;n.push(xf(i,r,{style:"form",explode:!0,...A?.array,allowReserved:A?.allowReserved||!1}));continue}if(typeof r=="object"){n.push(_f(i,r,{style:"deepObject",explode:!0,...A?.object,allowReserved:A?.allowReserved||!1}));continue}n.push(bs(i,r,A))}}return n.join("&")}}function lw(A,e){let t=A;for(const n of A.match(ow)??[]){let i=n.substring(1,n.length-1),r=!1,s="simple";if(i.endsWith("*")&&(r=!0,i=i.substring(0,i.length-1)),i.startsWith(".")?(s="label",i=i.substring(1)):i.startsWith(";")&&(s="matrix",i=i.substring(1)),!e||e[i]===void 0||e[i]===null)continue;const o=e[i];if(Array.isArray(o)){t=t.replace(n,xf(i,o,{style:s,explode:r}));continue}if(typeof o=="object"){t=t.replace(n,_f(i,o,{style:s,explode:r}));continue}if(s==="matrix"){t=t.replace(n,`;${bs(i,o)}`);continue}t=t.replace(n,s==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function dw(A){return A instanceof FormData?A:JSON.stringify(A)}function uw(A,e){let t=`${e.baseUrl}${A}`;e.params?.path&&(t=lw(t,e.params.path));let n=e.querySerializer(e.params.query??{});return n.startsWith("?")&&(n=n.substring(1)),n&&(t+=`?${n}`),t}function hw(...A){const e=new Headers;for(const t of A){if(!t||typeof t!="object")continue;const n=t instanceof Headers?t.entries():Object.entries(t);for(const[i,r]of n)if(r===null)e.delete(i);else if(Array.isArray(r))for(const s of r)e.append(i,s);else r!==void 0&&e.set(i,r)}return e}function Pf(A){return A.endsWith("/")?A.substring(0,A.length-1):A}class Lf{constructor(e){this.client=cw({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch})}setAuthToken(e){this.client.use({onRequest({request:t}){return t.headers.set("Authorization",`Bearer ${e}`),t}})}setApiToken(e){this.client.use({onRequest({request:t}){return t.headers.set("Authorization",`Token ${e}`),t}})}async getAuthUrl(e){return await this.client.GET("/api/auth/{type}",{params:{path:{type:e}}})}async getConnectUrl(e){return await this.client.GET("/api/connect/{type}",{params:{path:{type:e}}})}async logout(){return await this.client.POST("/api/logout")}async getCurrentUser(){return await this.client.GET("/api/me")}async createPresignedUploadUrl(e){return await this.client.POST("/api/files",{body:e})}async createKnowledgeBlock(e){return await this.client.POST("/api/knowledge",{body:e})}async listOnboardees(){return await this.client.GET("/api/onboardees")}async getOnboardee(e){return await this.client.GET("/api/onboardees/{id}",{params:{path:{id:e}}})}async getOnboardeeWidgetConfig(e,t){return await this.client.GET("/api/onboardees/{id}/config",{params:{path:{id:e}},signal:t})}async listPlans(){return await this.client.GET("/api/plans")}async listProducts(){return await this.client.GET("/api/products")}async getProduct(e){return await this.client.GET("/api/products/{id}",{params:{path:{id:e}}})}async createProduct(e){return await this.client.POST("/api/products",{body:e})}async updateProduct(e,t){return await this.client.PATCH("/api/products/{id}",{params:{path:{id:e}},body:t})}async createPlan(e){return await this.client.POST("/api/plans",{body:e})}async getPlan(e){return await this.client.GET("/api/plans/{id}",{params:{path:{id:e}}})}async replacePlan(e,t){return await this.client.PUT("/api/plans/{id}",{params:{path:{id:e}},body:t})}async updatePlan(e,t){return await this.client.PATCH("/api/plans/{id}",{params:{path:{id:e}},body:t})}async getPlanVideoUrl(e){return await this.client.GET("/api/plans/{id}/video-url",{params:{path:{id:e}}})}async deletePlan(e){return await this.client.DELETE("/api/admin/plans/{id}",{params:{path:{id:e}}})}async publishPlanRevision(e,t){return await this.client.POST("/api/plans/{id}/publish",{params:{path:{id:e}},body:t})}async listPlanRevisions(e){return await this.client.GET("/api/plans/{id}/revisions",{params:{path:{id:e}}})}async getRevisionNavigationIndex(e){return await this.client.GET("/api/revisions/{id}/navigation-index",{params:{path:{id:e}}})}async replaceRevisionNavigationIndex(e,t){return await this.client.PUT("/api/revisions/{id}/navigation-index",{params:{path:{id:e}},body:t})}async getRevisionFAQ(e){return await this.client.GET("/api/revisions/{id}/faq",{params:{path:{id:e}}})}async replaceRevisionFAQ(e,t){return await this.client.PUT("/api/revisions/{id}/faq",{params:{path:{id:e}},body:t})}async listRevisionKnowledgeBlocks(e){return await this.client.GET("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}}})}async getRevisionSteps(e){return await this.client.GET("/api/revisions/{id}/steps",{params:{path:{id:e}}})}async replaceRevisionKnowledgeBlocks(e,t){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async createRevisionKnowledgeBlock(e,t){return await this.client.POST("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async updateRevisionKnowledgeBlock(e,t,n){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:n})}async deleteRevisionKnowledgeBlock(e,t){return await this.client.DELETE("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async listSessions(e){return await this.client.GET("/api/sessions",{params:{query:{token:e}}})}async createSession(e){return await this.client.POST("/api/sessions",{body:e})}async getSession(e){return await this.client.GET("/api/sessions/{id}",{params:{path:{id:e}}})}async startSession(e,t){return await this.client.GET("/api/sessions/{id}/start-session",{params:{path:{id:e},query:{token:t}}})}async getSessionRecording(e){return await this.client.GET("/api/sessions/{id}/recording",{params:{path:{id:e}}})}async getSessionProductUrl(e){return await this.client.GET("/api/sessions/{id}/product-url",{params:{path:{id:e}}})}async updateSession(e,t){return await this.client.PATCH("/api/sessions/{id}",{params:{path:{id:e}},body:t})}async getJoinToken(e,{skipIntro:t,user:n}={}){return await this.client.GET("/api/join-token",{params:{query:{token:e,...t&&{skip_intro:"true"},...n&&{user:encodeURIComponent(n)}}}})}async trackEvent(e){return await this.client.POST("/api/track",{body:e})}getClient(){return this.client}}const fw="https://app.coragents.ai";var H;(function(A){A.READY="ready",A.ERROR="error",A.PAUSED="paused",A.LOADING="loading",A.THINKING="thinking",A.RESEARCHING="researching",A.AGENT_SPEAKING="agent_speaking",A.USER_SPEAKING="user_speaking",A.AWAITING_USER_INPUT="awaiting_user_input"})(H||(H={}));class pw{constructor({sessionId:e,apiBaseUrl:t,embedded:n,user:i}){this.currentState=H.READY,this.livekitState="speaking",this.embedded=!1,this.agentHasSpoken=!1,this.assistantAudioContext=null,this.userAudioContext=null,this._assistantAudioTimer=null,this._userAudioTimer=null,this.user=void 0,this.sessionId=e,this.apiBaseUrl=t||fw,this.embedded=n??!0,this.client=new Lf({baseUrl:this.apiBaseUrl}),this.emitter=new uv,this.user=i}emit(e,t){this.emitter.emit(e,t)}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}setupRoomEventListeners(){this.room&&(this.room.on(F.LocalTrackUnpublished,e=>{e.source===T.Source.ScreenShare&&(this.screenStream=void 0)}),this.room.on(F.Disconnected,()=>{this.disconnect()}),this.room.on(F.ParticipantDisconnected,()=>{this.disconnect()}),this.room.on(F.TrackSubscribed,(e,t,n)=>{if(e.kind==="audio"&&e.attach(),e.source===T.Source.Microphone&&n.identity.includes("agent-")){const i=e.mediaStream;if(!i){console.error("No media stream available for assistant track");return}const r=new AudioContext,s=r.createAnalyser();r.createMediaStreamSource(i).connect(s),s.fftSize=2048;const a=new Uint8Array(s.frequencyBinCount);this.analyzeAudio(s,a,"ASSISTANT"),this.assistantAudioContext=r}}),this.room.on(F.ParticipantAttributesChanged,e=>{if(!e["lk.agent.state"]||this.currentState===H.RESEARCHING||this.currentState===H.PAUSED)return;const t=e["lk.agent.state"];if(t==="speaking"&&(this.agentHasSpoken=!0),!this.agentHasSpoken)return;const n=Vi(t).with("listening",()=>H.USER_SPEAKING).with("speaking",()=>H.AGENT_SPEAKING).with("thinking",()=>H.THINKING).otherwise(()=>{});n&&(this.setState(n),this.livekitState=t)}),this.room.on(F.DataReceived,async e=>{console.debug("[obi] data received",e);try{const t=JSON.parse(new TextDecoder().decode(e)),n=t.status||t.request;Vi(n).with("using_tool",()=>{this.currentState=H.RESEARCHING,this.emitter.emit("stateChanged",H.RESEARCHING)}).with("using_tool_ended",()=>{this.currentState=H.AGENT_SPEAKING,this.emitter.emit("stateChanged",H.AGENT_SPEAKING)}).with("share_mic",()=>{this.emitter.emit("micShareRequested")}).with("share_screen",()=>{this.emitter.emit("screenShareRequested")}).with("prompt_user",()=>{this.emitter.emit("promptUser")}).with("capture_page_html",()=>{this.emitter.emit("capturePageHTML")}).with("fill",()=>{this.emitter.emit("fill",t.value)}).otherwise(()=>{console.warn("Unknown data received:",t)})}catch(t){console.error("Error parsing data:",t)}}),this.room.localParticipant.registerRpcMethod("screen_capture",async e=>(this.emitter.emit("screenCaptureRequested"),new Promise(t=>{this.emitter.once("screenCaptureComplete",async n=>{if(n==="error"){t("error");return}try{await this.room.localParticipant.sendFile(new File([n],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),t("ok")}catch{t("error")}})}))))}async connect(){if(!this.sessionId){console.error("[obi] no session ID found"),this.emitter.emit("error",new Error("No session ID provided"));return}try{this.room=new sn({adaptiveStream:!0,dynacast:!0}),this.setupRoomEventListeners();const e=await this.client.getJoinToken(this.sessionId,{skipIntro:this.embedded,...this.user&&{user:JSON.stringify(this.user)}});return await this.room.connect(e.data.url,e.data.token),this.emitter.emit("connected"),{url:e.data.url,token:e.data.token}}catch(e){throw console.error("Failed to connect to LiveKit:",e),this.disconnect(),this.emitter.emit("error",e instanceof Error?e:new Error(String(e))),e}}async disconnect(){this.room&&(this.room.disconnect(!0),this.room.removeAllListeners(),this.room=void 0),this.screenStream?.track&&this.screenStream.track.stop(),this.microphoneStream&&this.microphoneStream.getTracks().forEach(e=>e.stop()),this._userAudioTimer&&(window.clearTimeout(this._userAudioTimer),this._userAudioTimer=null),this._assistantAudioTimer&&(window.clearTimeout(this._assistantAudioTimer),this._assistantAudioTimer=null),await this.userAudioContext?.close().catch(()=>{}),this.userAudioContext=null,await this.assistantAudioContext?.close().catch(()=>{}),this.assistantAudioContext=null,this.setState(H.READY),this.emitter.emit("disconnected")}setState(e){e!==this.currentState&&(this.currentState=e,this.emitter.emit("stateChanged",e))}getCurrentState(){return this.currentState}async requestMicrophone(){try{const e=await navigator.mediaDevices.getUserMedia({audio:!0});this.microphoneStream=e;const t=new AudioContext;this.userAudioContext=t;const n=t.createAnalyser(),i=t.createMediaStreamSource(e),r=t.createGain();r.gain.value=1.5,i.connect(r),r.connect(n),n.fftSize=2048;const s=new Uint8Array(n.frequencyBinCount);this.analyzeAudio(n,s,"USER")}catch(e){throw console.error("Microphone permission denied:",e),new Error("Microphone permission denied")}}async shareMic(){if(!this.room){console.warn("[obi] shareMic called while not connected");return}this.emitter.emit("preMicShare");try{if(await this.requestMicrophone(),!this.microphoneStream){console.warn("[obi] failed to share microphone");return}const e=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(e,{name:"microphone",source:T.Source.Microphone}),await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"share_mic",success:!0})),{reliable:!0}),this.emitter.emit("micShared")}catch(e){console.error("[obi] error sharing microphone:",e),this.emitter.emit("error",e instanceof Error?e:new Error(String(e)))}}async shareScreen(){if(!this.room){console.warn("[obi] shareScreen called while not connected");return}this.emitter.emit("preScreenShare");try{if(this.screenStream=await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),!this.screenStream){console.warn("Failed to share screen");return}await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"share_screen",success:!0})),{reliable:!0}),this.emitter.emit("screenShared")}catch(e){console.error("Error sharing screen:",e),this.emitter.emit("error",e instanceof Error?e:new Error(String(e)))}}pauseRecording(){this.room&&(this.setState(H.PAUSED),this.room.localParticipant.getTrackPublications().forEach(e=>{e.handleMuted(),e.track?.mediaStream?.getTracks().forEach(t=>t.enabled=!1)}),this.microphoneStream?.getTracks().forEach(e=>e.enabled=!1),this.screenStream?.track?.mute())}resumeRecording(){if(!this.room)return;const e=Vi(this.livekitState).with("listening",()=>H.USER_SPEAKING).with("speaking",()=>H.AGENT_SPEAKING).otherwise(()=>H.THINKING);this.setState(e),this.room.localParticipant.getTrackPublications().forEach(t=>{t.handleUnmuted(),t.track?.mediaStream?.getTracks().forEach(n=>n.enabled=!0)}),this.microphoneStream?.getTracks().forEach(t=>t.enabled=!0),this.screenStream?.track?.unmute()}async promptContinue(){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"prompt_user",success:!0})),{reliable:!0})}async analyzeAudio(e,t,n){if(n==="USER"&&this.currentState===H.USER_SPEAKING||n==="ASSISTANT"&&this.currentState===H.AGENT_SPEAKING){e.getByteFrequencyData(t);const i=t.reduce((o,a)=>o+a,0)/t.length,r=Math.max(.01,Math.min(1,i/128));let s;n==="USER"&&this.currentState===H.USER_SPEAKING?s="USER":n==="ASSISTANT"&&this.currentState===H.AGENT_SPEAKING&&(s="ASSISTANT"),s&&this.emitter.emit("volume",{speaker:s,spectrum:Array.from(t),volume:r})}n==="USER"?this._userAudioTimer=window.setTimeout(()=>this.analyzeAudio(e,t,n),200):this._assistantAudioTimer=window.setTimeout(()=>this.analyzeAudio(e,t,n),200)}async sendHTML(e){if(!this.room){console.log("Cannot send HTML: Not connected to room");return}try{const t={type:"page_content",html:e,timestamp:new Date().toISOString()},n=JSON.stringify(t),r=new TextEncoder().encode(n);await this.room.localParticipant.publishData(r,{reliable:!0})}catch(t){console.error("Error sending HTML to LiveKit:",t),this.emitter.emit("error",t instanceof Error?t:new Error(String(t)))}}async reconnect(e,t,n){try{if(!e||!t)return console.error("Missing room URL or token for reconnection"),this.emitter.emit("error",new Error("Missing room URL or token for reconnection")),!1;if(this.agentHasSpoken=!0,await this.requestMicrophone(),this.room=new sn({adaptiveStream:!0,dynacast:!0}),this.setupRoomEventListeners(),await this.room.connect(e,t),this.microphoneStream){const i=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(i,{name:"microphone",source:T.Source.Microphone})}return this.setState(n),n===H.PAUSED&&this.pauseRecording(),!0}catch(i){return console.error("Failed to reconnect to room:",i),this.disconnect(),this.emitter.emit("error",i instanceof Error?i:new Error(String(i))),!1}}async updateUser(e){if(!this.room)throw new Error("Cannot update user: No active session");const t=this.user;this.user=e;try{if(await this.client.updateSession(this.sessionId,{user:e?JSON.stringify(e):void 0}),this.room&&this.room.localParticipant){const n={type:"user_updated",user:e,timestamp:new Date().toISOString()},i=JSON.stringify(n),s=new TextEncoder().encode(i);await this.room.localParticipant.publishData(s,{reliable:!0})}this.emitter.emit("userUpdated",e)}catch(n){throw this.user=t,console.error("Failed to update user:",n),this.emitter.emit("error",n instanceof Error?n:new Error(String(n))),n}}}/**
42
+ `},mc}var of;function YC(){if(of)return Ut;of=1;var A=qC(),e=zC(),t=gc();return Ut.grammar=t,Ut.write=e,Ut.parse=A.parse,Ut.parseParams=A.parseParams,Ut.parseFmtpConfig=A.parseFmtpConfig,Ut.parsePayloads=A.parsePayloads,Ut.parseRemoteCandidates=A.parseRemoteCandidates,Ut.parseImageAttributes=A.parseImageAttributes,Ut.parseSimulcastStreamList=A.parseSimulcastStreamList,Ut}var BA=YC();function vc(A,e,t){var n,i,r;e===void 0&&(e=50),t===void 0&&(t={});var s=(n=t.isImmediate)!=null&&n,o=(i=t.callback)!=null&&i,a=t.maxWait,c=Date.now(),l=[];function d(){if(a!==void 0){var h=Date.now()-c;if(h+e>=a)return a-h}return e}var u=function(){var h=[].slice.call(arguments),f=this;return new Promise(function(p,g){var v=s&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,c=Date.now(),!s){var y=A.apply(f,h);o&&o(y),l.forEach(function(B){return(0,B.resolve)(y)}),l=[]}},d()),v){var w=A.apply(f,h);return o&&o(w),p(w)}l.push({resolve:p,reject:g})})};return u.cancel=function(h){r!==void 0&&clearTimeout(r),l.forEach(function(f){return(0,f.reject)(h)}),l=[]},u}const ZC=.7,eb=20,jn={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class af extends Ot.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 n;super(),this.log=j,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=vc(i=>m(this,void 0,void 0,function*(){this.emit(jn.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(i)i(r);else throw r}}),eb),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=qt((n=t.loggerName)!==null&&n!==void 0?n:Et.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.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 n;(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.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 m(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return m(this,void 0,void 0,function*(){var t;let n;if(e.type==="offer"){let{stereoMids:i,nackMids:r}=tb(e);this.remoteStereoMids=i,this.remoteNackMids=r}else if(e.type==="answer"){const i=BA.parse((t=e.sdp)!==null&&t!==void 0?t:"");i.media.forEach(r=>{r.type==="audio"&&this.trackBitrates.some(s=>{if(!s.transceiver||r.mid!=s.transceiver.mid)return!1;let o=0;if(r.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0)return!0;let a=!1;for(const c of r.fmtp)if(c.payload===o){c.config=c.config.split(";").filter(l=>!l.includes("maxaveragebitrate")).join(";"),s.maxbr>0&&(c.config+=";maxaveragebitrate=".concat(s.maxbr*1e3)),a=!0;break}return a||s.maxbr>0&&r.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(s.maxbr*1e3)}),!0})}),n=BA.write(i)}yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(i=>{this.pc.addIceCandidate(i)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(jn.NegotiationComplete),e.sdp&&BA.parse(e.sdp).media.forEach(r=>{r.type==="video"&&this.emit(jn.RTPVideoPayloadTypes,r.rtp)}))})}createAndSendOffer(e){return m(this,void 0,void 0,function*(){var t;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 r=this._pc.remoteDescription;if(e?.iceRestart&&r)yield this._pc.setRemoteDescription(r);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 n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));const i=BA.parse((t=n.sdp)!==null&&t!==void 0?t:"");i.media.forEach(r=>{lf(r),r.type==="audio"?cf(r,[],[]):r.type==="video"&&this.trackBitrates.some(s=>{if(!r.msid||!s.cid||!r.msid.includes(s.cid))return!1;let o=0;if(r.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0||(Oi(s.codec)&&this.ensureVideoDDExtensionForSVC(r,i),s.codec!=="av1"))return!0;const a=Math.round(s.maxbr*ZC);for(const c of r.fmtp)if(c.payload===o){c.config.includes("x-google-start-bitrate")||(c.config+=";x-google-start-bitrate=".concat(a));break}return!0})}),yield this.setMungedSDP(n,BA.write(i)),this.onOffer(n)})}createAndSetAnswer(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),n=BA.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(i=>{lf(i),i.type==="audio"&&cf(i,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,BA.write(n)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Te("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 Te("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 m(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const n=new Map,i=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),n.set(o.id,o);break;case"remote-candidate":i.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const s=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(s!==void 0)return i.get(s)})}setMungedSDP(e,t,n){return m(this,void 0,void 0,function*(){if(t){const i=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?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=i}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(i){let r="unknown error";i instanceof Error?r=i.message:typeof i=="string"&&(r=i);const s={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new ja(r)}})}ensureVideoDDExtensionForSVC(e,t){var n,i;if(!((n=e.ext)===null||n===void 0?void 0:n.some(s=>s.uri===Nh))){if(this.ddExtID===0){let s=0;t.media.forEach(o=>{var a;o.type==="video"&&((a=o.ext)===null||a===void 0||a.forEach(c=>{c.value>s&&(s=c.value)}))}),this.ddExtID=s+1}(i=e.ext)===null||i===void 0||i.push({value:this.ddExtID,uri:Nh})}}}function cf(A,e,t){let n=0;A.rtp.some(i=>i.codec==="opus"?(n=i.payload,!0):!1),n>0&&(A.rtcpFb||(A.rtcpFb=[]),t.includes(A.mid)&&!A.rtcpFb.some(i=>i.payload===n&&i.type==="nack")&&A.rtcpFb.push({payload:n,type:"nack"}),e.includes(A.mid)&&A.fmtp.some(i=>i.payload===n?(i.config.includes("stereo=1")||(i.config+=";stereo=1"),!0):!1))}function tb(A){var e;const t=[],n=[],i=BA.parse((e=A.sdp)!==null&&e!==void 0?e:"");let r=0;return i.media.forEach(s=>{var o;s.type==="audio"&&(s.rtp.some(a=>a.codec==="opus"?(r=a.payload,!0):!1),!((o=s.rtcpFb)===null||o===void 0)&&o.some(a=>a.payload===r&&a.type==="nack")&&n.push(s.mid),s.fmtp.some(a=>a.payload===r?(a.config.includes("sprop-stereo=1")&&t.push(s.mid),!0):!1))}),{stereoMids:t,nackMids:n}}function lf(A){if(A.connection){const e=A.connection.ip.indexOf(":")>=0;(A.connection.version===4&&e||A.connection.version===6&&!e)&&(A.connection.ip="0.0.0.0",A.connection.version=4)}}const Bc="vp8",Ab={audioPreset:qa.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ya.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Bc,backupCodec:!0},df={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},uf={deviceId:{ideal:"default"},resolution:Di.h720.resolution},nb={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new WB,disconnectOnPageLeave:!0,webAudioMix:!1},Cc={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ge;(function(A){A[A.NEW=0]="NEW",A[A.CONNECTING=1]="CONNECTING",A[A.CONNECTED=2]="CONNECTED",A[A.FAILED=3]="FAILED",A[A.CLOSING=4]="CLOSING",A[A.CLOSED=5]="CLOSED"})(ge||(ge={}));class ib{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,n){var i;this.peerConnectionTimeout=Cc.peerConnectionTimeout,this.log=j,this.updateState=()=>{var r;const s=this.state,o=this.requiredTransports.map(a=>a.getConnectionState());o.every(a=>a==="connected")?this.state=ge.CONNECTED:o.some(a=>a==="failed")?this.state=ge.FAILED:o.some(a=>a==="connecting")?this.state=ge.CONNECTING:o.every(a=>a==="closed")?this.state=ge.CLOSED:o.some(a=>a==="closed")?this.state=ge.CLOSING:o.every(a=>a==="new")&&(this.state=ge.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(ge[s]," to ").concat(ge[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=qt((i=n.loggerName)!==null&&i!==void 0?i:Et.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new af(e,n),this.subscriber=new af(e,n),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,r,yt.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,r,yt.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var s;(s=this.onDataChannel)===null||s===void 0||s.call(this,r)},this.subscriber.onTrack=r=>{var s;(s=this.onTrack)===null||s===void 0||s.call(this,r)},this.publisher.onOffer=r=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,r)},this.state=ge.NEW,this.connectionLock=new ze,this.remoteOfferLock=new ze}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()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return m(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(n){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:n}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return m(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return m(this,void 0,void 0,function*(){t===yt.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return m(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return m(this,void 0,void 0,function*(){var n;const i=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((n=this.requiredTransports)===null||n===void 0?void 0:n.map(r=>this.ensureTransportConnected(r,e,t)))}finally{i()}})}negotiate(e){return m(this,void 0,void 0,function*(){return new Promise((t,n)=>m(this,void 0,void 0,function*(){const i=setTimeout(()=>{n("negotiation timed out")},this.peerConnectionTimeout),r=()=>{clearTimeout(i),n("negotiation aborted")};e.signal.addEventListener("abort",r),this.publisher.once(jn.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(jn.NegotiationComplete,()=>{clearTimeout(i),t()})}),yield this.publisher.negotiate(s=>{clearTimeout(i),n(s)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===yt.PUBLISHER?this.publisher.getConnectedAddress():e===yt.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return m(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(n.getConnectionState()!=="connected")return new Promise((a,c)=>m(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),_e.clearTimeout(d),c(new oe("room connection has been cancelled",J.Cancelled))};i?.signal.aborted&&l(),i?.signal.addEventListener("abort",l);const d=_e.setTimeout(()=>{i?.signal.removeEventListener("abort",l),c(new oe("could not establish pc connection",J.InternalError))},s);for(;this.state!==ge.CONNECTED;)if(yield et(50),i?.signal.aborted){c(new oe("room connection has been cancelled",J.Cancelled));return}_e.clearTimeout(d),i?.signal.removeEventListener("abort",l),a()}))}()})}}class me extends Error{constructor(e,t,n){super(t),this.code=e,this.message=ff(t,me.MAX_MESSAGE_BYTES),this.data=n?ff(n,me.MAX_DATA_BYTES):void 0}static fromProto(e){return new me(e.code,e.message,e.data)}toProto(){return new ku({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new me(me.ErrorCode[e],me.ErrorMessage[e],t)}}me.MAX_MESSAGE_BYTES=256,me.MAX_DATA_BYTES=15360,me.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},me.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 hf=15360;function bc(A){return new TextEncoder().encode(A).length}function ff(A,e){if(bc(A)<=e)return A;let t=0,n=A.length;const i=new TextEncoder;for(;t<n;){const r=Math.floor((t+n+1)/2);i.encode(A.slice(0,r)).length<=e?t=r:n=r-1}return A.slice(0,t)}const wc=2e3;function hs(A,e){if(!e)return 0;let t,n;return"bytesReceived"in A?(t=A.bytesReceived,n=e.bytesReceived):"bytesSent"in A&&(t=A.bytesSent,n=e.bytesSent),t===void 0||n===void 0||A.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(A.timestamp-e.timestamp)}const rb=1e3;class pf extends T{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,n){let i=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=vc(()=>m(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>m(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(I.Ended,this)},this.reacquireTrack=!1,this.providedByUser=i,this.muteLock=new ze,this.pauseUpstreamLock=new ze,this.processorLock=new ze,this.restartLock=new ze,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==T.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 m(this,void 0,void 0,function*(){var n;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{Kn(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 i;if(this.processor&&e){const r=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Nn(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}finally{r()}}this.sender&&((n=this.sender.transport)===null||n===void 0?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(i??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=>{Nn(i??e,r)}))})}waitForDimensions(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:rb;return function*(){var n;if(e.kind===T.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=St())===null||n===void 0?void 0:n.os)==="iOS"&&(yield et(10));const i=Date.now();for(;Date.now()-i<t;){const r=e.dimensions;if(r)return r;yield et(50)}throw new zt("unable to get track dimensions after timeout")}()})}setDeviceId(e){return m(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===mA(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),mA(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return m(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===T.Source.ScreenShare)return;const{deviceId:n,groupId:i}=e._mediaStreamTrack.getSettings(),r=e.kind===T.Kind.Audio?"audioinput":"videoinput";return t?Fe.getInstance().normalizeDeviceId(r,n,i):n}()})}mute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return m(this,void 0,void 0,function*(){if(!this.sender)throw new zt("unable to replace an unpublished track");let n,i;return typeof t=="boolean"?n=t:t!==void 0&&(n=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=n??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return m(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:n,facingMode:i}=e,r=JB(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===T.Kind.Video?s.video=n||i?{deviceId:n,facingMode:i}:!0:s.audio=n?{deviceId:n}:!0,this.attachedElements.forEach(c=>{Kn(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const a=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return yield a.applyConstraints(r),a.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(a),this._constraints=e,this.emit(I.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?I.Muted:I.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 m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Kh()&&(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 m(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(I.UpstreamPaused,this);const n=St();if(n?.name==="Safari"&&An(n.version,"12.0")<0)throw new Ga("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 m(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(I.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 m(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 m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var r;const s=yield n.processorLock.lock();try{n.log.debug("setting up processor",n.logContext);const o=document.createElement(n.kind),a={kind:n.kind,track:n._mediaStreamTrack,element:o,audioContext:n.audioContext};if(yield t.init(a),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.stopProcessor()),n.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Nn(n._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:c}))),n.processor=t,n.processorElement=o,n.processor.processedTrack){for(const c of n.attachedElements)c!==n.processorElement&&i&&(Kn(n._mediaStreamTrack,c),Nn(n.processor.processedTrack,c));yield(r=n.sender)===null||r===void 0?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(I.TrackProcessorUpdate,n.processor)}finally{s()}}()})}getProcessor(){return this.processor}stopProcessor(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,i;e.processor&&(e.log.debug("stopping processor",e.logContext),(n=e.processor.processedTrack)===null||n===void 0||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((i=e.processorElement)===null||i===void 0||i.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(I.TrackProcessorUpdate))}()})}}class fs extends pf{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,T.Kind.Audio,t,n,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}s&&this.prevStats&&(this._currentBitrate=hs(s,this.prevStats)),this.prevStats=s}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(I.AudioTrackFeatureUpdate,this,wt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(I.AudioTrackFeatureUpdate,this,wt.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(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===T.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 m(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 n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==mA(this._constraints.deviceId);return this.source===T.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return m(this,void 0,void 0,function*(){let t;if(e){const n=dc({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return m(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){tt()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},wc)))}setProcessor(e){return m(this,void 0,void 0,function*(){var t;const n=yield this.processorLock.lock();try{if(!Ht()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),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(I.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return m(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 n;return t.forEach(i=>{i.type==="outbound-rtp"&&(n={type:"audio",streamId:i.id,packetsSent:i.packetsSent,packetsLost:i.packetsLost,bytesSent:i.bytesSent,timestamp:i.timestamp,roundTripTime:i.roundTripTime,jitter:i.jitter})}),n})}checkForSilence(){return m(this,void 0,void 0,function*(){const e=yield zh(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(I.AudioSilenceDetected)),e})}}function sb(A,e,t){switch(A.kind){case"audio":return new fs(A,e,!1,void 0,t);case"video":return new gs(A,e,!1,t);default:throw new zt("unsupported track type: ".concat(A.kind))}}const ob=Object.values(Di),ab=Object.values(za),cb=Object.values(Ya),lb=[Di.h180,Di.h360],db=[za.h180,za.h360],ub=A=>[{scaleResolutionDownBy:2,fps:A.encoding.maxFramerate}].map(t=>{var n,i;return new se(Math.floor(A.width/t.scaleResolutionDownBy),Math.floor(A.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(A.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((n=A.encoding.maxFramerate)!==null&&n!==void 0?n:30)/((i=t.fps)!==null&&i!==void 0?i:30))))),t.fps,A.encoding.priority)}),yc=["q","h","f"];function Ec(A,e,t,n){var i,r;let s=n?.videoEncoding;A&&(s=n?.screenShareEncoding);const o=n?.simulcast,a=n?.scalabilityMode,c=n?.videoCodec;if(!s&&!o&&!a||!e||!t)return[{}];s||(s=fb(A,e,t,c),j.debug("using video encoding",s));const l=s.maxFramerate,d=new se(e,t,s.maxBitrate,s.maxFramerate,s.priority);if(a&&Oi(c)){const f=new ps(a),p=[];if(f.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(a));const g=St();if(gA()||Ht()||g?.name==="Chrome"&&An(g?.version,"113")<0){const v=f.suffix=="h"?2:3;for(let w=0;w<f.spatial;w+=1)p.push({rid:yc[2-w],maxBitrate:s.maxBitrate/Math.pow(v,w),maxFramerate:d.encoding.maxFramerate});p[0].scalabilityMode=a}else p.push({maxBitrate:s.maxBitrate,maxFramerate:d.encoding.maxFramerate,scalabilityMode:a});return d.encoding.priority&&(p[0].priority=d.encoding.priority,p[0].networkPriority=d.encoding.priority),j.debug("using svc encoding",{encodings:p}),p}if(!o)return[s];let u=[];A?u=(i=mf(n?.screenShareSimulcastLayers))!==null&&i!==void 0?i:gf(A,d):u=(r=mf(n?.videoSimulcastLayers))!==null&&r!==void 0?r:gf(A,d);let h;if(u.length>0){const f=u[0];u.length>1&&([,h]=u);const p=Math.max(e,t);if(p>=960&&h)return Sc(e,t,[f,h,d],l);if(p>=480)return Sc(e,t,[f,d],l)}return Sc(e,t,[d])}function hb(A,e,t){var n,i,r,s;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&j.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=A.mediaStreamTrack.getSettings(),a=(n=o.width)!==null&&n!==void 0?n:(i=A.dimensions)===null||i===void 0?void 0:i.width,c=(r=o.height)!==null&&r!==void 0?r:(s=A.dimensions)===null||s===void 0?void 0:s.height;return A.source===T.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Ec(A.source===T.Source.ScreenShare,a,c,t)}function fb(A,e,t,n){const i=pb(A,e,t);let{encoding:r}=i[0];const s=Math.max(e,t);for(let o=0;o<i.length;o+=1){const a=i[o];if(r=a.encoding,a.width>=s)break}if(n)switch(n){case"av1":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 pb(A,e,t){if(A)return cb;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?ob:ab}function gf(A,e){if(A)return ub(e);const{width:t,height:n}=e,i=t>n?t/n:n/t;return Math.abs(i-16/9)<Math.abs(i-4/3)?lb:db}function Sc(A,e,t,n){const i=[];if(t.forEach((r,s)=>{if(s>=yc.length)return;const o=Math.min(A,e),c={rid:yc[s],scaleResolutionDownBy:Math.max(1,o/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},l=n&&r.encoding.maxFramerate?Math.min(n,r.encoding.maxFramerate):r.encoding.maxFramerate;l&&(c.maxFramerate=l);const d=$n()||s===0;r.encoding.priority&&d&&(c.priority=r.encoding.priority,c.networkPriority=r.encoding.priority),i.push(c)}),Ht()&&Vh()==="ios"){let r;i.forEach(o=>{r?o.maxFramerate&&o.maxFramerate>r&&(r=o.maxFramerate):r=o.maxFramerate});let s=!0;i.forEach(o=>{var a;o.maxFramerate!=r&&(s&&(s=!1,j.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),j.info('Setting framerate of encoding "'.concat((a=o.rid)!==null&&a!==void 0?a:"",'" to ').concat(r)),o.maxFramerate=r)})}return i}function mf(A){if(A)return A.sort((e,t)=>{const{encoding:n}=e,{encoding:i}=t;return n.maxBitrate>i.maxBitrate?1:n.maxBitrate<i.maxBitrate?-1:n.maxBitrate===i.maxBitrate&&n.maxFramerate&&i.maxFramerate?n.maxFramerate>i.maxFramerate?1:-1:0})}class ps{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 gb(A){return A.source===T.Source.ScreenShare||A.constraints.height&&mA(A.constraints.height)>=1080?"maintain-resolution":"balanced"}const mb=5e3;class gs extends pf{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0;super(e,T.Kind.Video,t,n,i),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}const s=new Map(r.map(o=>[o.rid,o]));if(this.prevStats){let o=0;s.forEach((a,c)=>{var l;const d=(l=this.prevStats)===null||l===void 0?void 0:l.get(c);o+=hs(a,d)}),this._currentBitrate=o}this.prevStats=s}),this.senderLock=new ze}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!tt())return;const n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},wc))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return m(this,void 0,void 0,function*(){var t,n,i,r,s;yield e.pauseUpstream.call(this);try{for(var o=!0,a=uA(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0)r=c.value,o=!1,yield(s=r.sender)===null||s===void 0?void 0:s.replaceTrack(null)}catch(l){n={error:l}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return m(this,void 0,void 0,function*(){var t,n,i,r,s;yield e.resumeUpstream.call(this);try{for(var o=!0,a=uA(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0){r=c.value,o=!1;const l=r;yield(s=l.sender)===null||s===void 0?void 0:s.replaceTrack(l.mediaStreamTrack)}}catch(l){n={error:l}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(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===T.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 m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===T.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 m(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach(i=>{var r;if(i.type==="outbound-rtp"){const s={type:"video",streamId:i.id,frameHeight:i.frameHeight,frameWidth:i.frameWidth,framesPerSecond:i.framesPerSecond,framesSent:i.framesSent,firCount:i.firCount,pliCount:i.pliCount,nackCount:i.nackCount,packetsSent:i.packetsSent,bytesSent:i.bytesSent,qualityLimitationReason:i.qualityLimitationReason,qualityLimitationDurations:i.qualityLimitationDurations,qualityLimitationResolutionChanges:i.qualityLimitationResolutionChanges,rid:(r=i.rid)!==null&&r!==void 0?r:i.id,retransmittedPacketsSent:i.retransmittedPacketsSent,targetBitrate:i.targetBitrate,timestamp:i.timestamp},o=n.get(i.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}}),t.sort((i,r)=>{var s,o;return((s=r.frameWidth)!==null&&s!==void 0?s:0)-((o=i.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let n=ut.LOW;n<=ut.HIGH;n+=1)t.push(new xa({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return m(this,void 0,void 0,function*(){var t,n,i,r,s;let o;if(e){const d=dc({video:e});typeof d.video!="boolean"&&(o=d.video)}yield this.restart(o);try{for(var a=!0,c=uA(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;a=!0){r=l.value,a=!1;const d=r;d.sender&&((s=d.sender.transport)===null||s===void 0?void 0:s.state)!=="closed"&&(d.mediaStreamTrack=this.mediaStreamTrack.clone(),yield d.sender.replaceTrack(d.mediaStreamTrack))}}catch(d){n={error:d}}finally{try{!a&&!t&&(i=c.return)&&(yield i.call(c))}finally{if(n)throw n.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return m(this,arguments,void 0,function(n){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s,o,a,c,l,d;if(yield t.setProcessor.call(i,n,r),!((l=i.processor)===null||l===void 0)&&l.processedTrack)try{for(var u=!0,h=uA(i.simulcastCodecs.values()),f;f=yield h.next(),s=f.done,!s;u=!0)c=f.value,u=!1,yield(d=c.sender)===null||d===void 0?void 0:d.replaceTrack(i.processor.processedTrack)}catch(p){o={error:p}}finally{try{!u&&!s&&(a=h.return)&&(yield a.call(h))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return m(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 n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},mb))}setPublishingCodecs(e){return m(this,void 0,void 0,function*(){var t,n,i,r,s,o,a;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(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,n=uA(e);i=yield n.next(),r=i.done,!r;t=!0){a=i.value,t=!1;const l=a;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(l.qualities);else{const d=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:d})),!d||!d.sender){for(const u of l.qualities)if(u.enabled){c.push(l.codec);break}}else d.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield vf(d.sender,d.encodings,l.qualities,this.senderLock,this.log,this.logContext))}}}catch(l){s={error:l}}finally{try{!t&&!r&&(o=n.return)&&(yield o.call(n))}finally{if(s)throw s.error}}return c})}setPublishingLayers(e){return m(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield vf(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Kh()&&this.isInBackground&&this.source===T.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function vf(A,e,t,n,i,r){return m(this,void 0,void 0,function*(){const s=yield n.lock();i.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:A,qualities:t,senderEncodings:e}));try{const o=A.getParameters(),{encodings:a}=o;if(!a)return;if(a.length!==e.length){i.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:a,senderEncodings:e}));return}let c=!1;const l=St();if(l?.name==="Chrome"&&An(l?.version,"133")>0&&a[0].scalabilityMode){const u=a[0],h=new ps(u.scalabilityMode);let f=Pn.OFF;if(t.forEach(p=>{p.enabled&&(f===Pn.OFF||p.quality>f)&&(f=p.quality)}),f===Pn.OFF)u.active&&(u.active=!1,c=!0);else if(!u.active||h.spatial!==f+1){c=!0,u.active=!0;const p=new ps(e[0].scalabilityMode);h.spatial=f+1,h.suffix=p.suffix,h.spatial===1&&(h.suffix=void 0),u.scalabilityMode=h.toString(),u.scaleResolutionDownBy=Math.pow(2,2-f),e[0].maxBitrate&&(u.maxBitrate=e[0].maxBitrate/(u.scaleResolutionDownBy*u.scaleResolutionDownBy))}}else a.forEach((u,h)=>{var f;let p=(f=u.rid)!==null&&f!==void 0?f:"";p===""&&(p="q");const g=Bf(p),v=t.find(w=>w.quality===g);v&&u.active!==v.enabled&&(c=!0,u.active=v.enabled,i.debug("setting layer ".concat(v.quality," to ").concat(u.active?"enabled":"disabled"),r),$n()&&(v.enabled?(u.scaleResolutionDownBy=e[h].scaleResolutionDownBy,u.maxBitrate=e[h].maxBitrate,u.maxFrameRate=e[h].maxFrameRate):(u.scaleResolutionDownBy=4,u.maxBitrate=10,u.maxFrameRate=2)))});c&&(o.encodings=a,i.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:o.encodings})),yield A.setParameters(o))}finally{s()}})}function Bf(A){switch(A){case"f":return ut.HIGH;case"h":return ut.MEDIUM;case"q":return ut.LOW;default:return ut.HIGH}}function Cf(A,e,t,n){if(!t)return[new ZA({quality:ut.HIGH,width:A,height:e,bitrate:0,ssrc:0})];if(n){const i=t[0].scalabilityMode,r=new ps(i),s=[],o=r.suffix=="h"?1.5:2,a=r.suffix=="h"?2:3;for(let c=0;c<r.spatial;c+=1)s.push(new ZA({quality:Math.min(ut.HIGH,r.spatial-1)-c,width:Math.ceil(A/Math.pow(o,c)),height:Math.ceil(e/Math.pow(o,c)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(a,c)):0,ssrc:0}));return s}return t.map(i=>{var r,s,o;const a=(r=i.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let c=Bf((s=i.rid)!==null&&s!==void 0?s:"");return new ZA({quality:c,width:Math.ceil(A/a),height:Math.ceil(e/a),bitrate:(o=i.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const bf="_lossy",wf="_reliable",vb=2*1e3,Uc="leave-reconnect";var Tt;(function(A){A[A.New=0]="New",A[A.Connected=1]="Connected",A[A.Disconnected=2]="Disconnected",A[A.Reconnecting=3]="Reconnecting",A[A.Closed=4]="Closed"})(Tt||(Tt={}));class Bb extends Ot.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Cc.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Tt.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=j,this.handleDataChannel=n=>m(this,[n],void 0,function(i){var r=this;let{channel:s}=i;return function*(){if(s){if(s.label===wf)r.reliableDCSub=s;else if(s.label===bf)r.lossyDCSub=s;else return;r.log.debug("on data channel ".concat(s.id,", ").concat(s.label),r.logContext),s.onmessage=r.handleDataMessage}}()}),this.handleDataMessage=n=>m(this,void 0,void 0,function*(){var i,r;const s=yield this.dataProcessLock.lock();try{let o;if(n.data instanceof ArrayBuffer)o=n.data;else if(n.data instanceof Blob)o=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:n.data}));return}const a=Ze.fromBinary(new Uint8Array(o));((i=a.value)===null||i===void 0?void 0:i.case)==="speaker"?this.emit(_.ActiveSpeakersUpdate,a.value.value.speakers):(((r=a.value)===null||r===void 0?void 0:r.case)==="user"&&bb(a,a.value.value),this.emit(_.DataPacketReceived,a))}finally{s()}}),this.handleDataError=n=>{const r=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(n instanceof ErrorEvent&&n.error){const{error:s}=n.error;this.log.error("DataChannel error on ".concat(r,": ").concat(n.message),Object.assign(Object.assign({},this.logContext),{error:s}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:n}))},this.handleBufferedAmountLow=n=>{const r=n.currentTarget.maxRetransmits===0?Y.LOSSY:Y.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(n,i)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=a=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(a,"ms. giving up"),this.logContext),this.emit(_.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});if(o===null){r(s);return}n===Uc&&(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=_e.setTimeout(()=>this.attemptReconnect(i).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((n,i)=>{this.pcState===Tt.Connected&&n();const r=()=>{this.off(_.Disconnected,s),n()},s=()=>{this.off(_.Restarted,r),i()};this.once(_.Restarted,r),this.once(_.Disconnected,s)}),this.updateAndEmitDCBufferStatus=n=>{const i=this.isBufferStatusLow(n);typeof i<"u"&&i!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,i),this.emit(_.DCBufferStatusChanged,i,n))},this.isBufferStatusLow=n=>{const i=this.dataChannelForKind(n);if(i)return i.bufferedAmount<=i.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ce.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Ln.RR_SIGNAL_DISCONNECTED))},this.log=qt((t=e.loggerName)!==null&&t!==void 0?t:Et.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new hc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new ze,this.dataProcessLock=new ze,this.dcBufferStatus=new Map([[Y.LOSSY,!0],[Y.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(_.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(_.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(_.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(_.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(_.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(_.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(_.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(_.SignalRequestResponse,n)}get logContext(){var e,t,n,i,r,s,o,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(i=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.room)===null||i===void 0?void 0:i.sid,participant:(s=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||s===void 0?void 0:s.identity,pID:(a=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||a===void 0?void 0:a.sid}}join(e,t,n,i){return m(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,t,n,i);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),(!this.subscriberPrimary||r.fastPublish)&&this.negotiate(),this.clientConfiguration=r.clientConfiguration,setTimeout(()=>{this.emit(_.SignalConnected)},10),r}catch(r){if(r instanceof oe&&r.reason===J.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,n,i);throw r}})}close(){return m(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(_.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return m(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=n=>{n&&(n.close(),n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.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})}cleanupClient(){return m(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new zt("a track with the same ID has already been published");return new Promise((t,n)=>{const i=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(new oe("publication of local track timed out, no response from server",J.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(i),t(r)},reject:()=>{clearTimeout(i),n(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 m(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){return m(this,void 0,void 0,function*(){var t,n;if(this.pcManager&&this.pcManager.currentState!==ge.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const i=this.makeRTCConfiguration(e);this.pcManager=new ib(i,e.subscriberPrimary,this.loggerOptions),this.emit(_.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,s)=>{this.client.sendIceCandidate(r,s)},this.pcManager.onPublisherOffer=r=>{this.client.sendOffer(r)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,s,o)=>m(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r),this.logContext),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),r===ge.CONNECTED){const l=this.pcState===Tt.New;this.pcState=Tt.Connected,l&&this.emit(_.Connected,e)}else r===ge.FAILED&&this.pcState===Tt.Connected&&(this.pcState=Tt.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?Ln.RR_SUBSCRIBER_FAILED:Ln.RR_PUBLISHER_FAILED));const a=this.client.isDisconnected||this.client.currentState===ce.RECONNECTING,c=[ge.FAILED,ge.CLOSING,ge.CLOSED].includes(r);a&&c&&!this._isClosed&&this.emit(_.Offline)}),this.pcManager.onTrack=r=>{this.emit(_.MediaTrackAdded,r.track,r.streams[0],r.receiver)},Cb((n=e.serverInfo)===null||n===void 0?void 0:n.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>m(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))}),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=>m(this,void 0,void 0,function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(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:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(_.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(_.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(_.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(_.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.emit(_.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Ln.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(e.regions)),e.action){case Hn.DISCONNECT:this.emit(_.Disconnected,e?.reason),this.close();break;case Hn.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Uc);break;case Hn.RESUME:this.handleDisconnect(Uc)}}}makeRTCConfiguration(e){var t;const n=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),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const i=[];e.iceServers.forEach(r=>{const s={urls:r.urls};r.username&&(s.username=r.username),r.credential&&(s.credential=r.credential),i.push(s)}),n.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ri.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}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(bf,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(wf,{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)}createSender(e,t,n){return m(this,void 0,void 0,function*(){if(Za())return yield this.createTransceiverRTCRtpSender(e,t,n);if(ec())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Te("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,i){return m(this,void 0,void 0,function*(){if(Za())return this.createSimulcastTransceiverSender(e,t,n,i);if(ec())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Te("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new Te("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),Gn(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:i};return n&&(r.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,n,i){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new Te("publisher is closed");const r={direction:"sendonly"};i&&(r.sendEncodings=i);const s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new Te("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return m(this,void 0,void 0,function*(){var t,n,i;if(!this._isClosed){if(this.attemptingReconnect){j.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Ri.DISABLED||((i=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&i!==void 0?i:ge.NEW)===ge.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 s=!0;r instanceof Te?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),s=!1):r instanceof Wn||(this.fullReconnectOnNext=!0),s?this.handleDisconnect("reconnect",Ln.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(_.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 m(this,void 0,void 0,function*(){var t,n,i;try{if(!this.url||!this.token)throw new Te("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(_.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 Wn;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(s){throw s instanceof oe&&s.reason===J.NotAllowed?new Te("could not reconnect, token might be expired"):new Wn}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(_.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==ce.CONNECTED)throw new Wn("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(_.Restarted)}catch(r){const s=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(s){yield this.restartConnection(s);return}else throw(i=this.regionUrlProvider)===null||i===void 0||i.resetAttempts(),r}})}resumeConnection(e){return m(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new Te("could not reconnect, url or token not saved");if(!this.pcManager)throw new Te("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(_.Resuming);let n;try{this.setupSignalClientCallbacks(),n=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(i){let r="";throw i instanceof Error&&(r=i.message,this.log.error(i.message,Object.assign(Object.assign({},this.logContext),{error:i}))),i instanceof oe&&i.reason===J.NotAllowed?new Te("could not reconnect, token might be expired"):i instanceof oe&&i.reason===J.LeaveRequest?i:new Wn(r)}if(this.emit(_.SignalResumed),n){const i=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(i)}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!==ce.CONNECTED)throw new Wn("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(),this.emit(_.Resumed)})}waitForPCInitialConnection(e,t){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new Te("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return m(this,void 0,void 0,function*(){this.pcState=Tt.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield et(vb),!this.pcManager)throw new Te("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Tt.Connected}catch(e){throw this.pcState=Tt.Disconnected,new oe("could not establish PC connection, ".concat(e.message),J.InternalError)}})}publishRpcResponse(e,t,n,i){return m(this,void 0,void 0,function*(){const r=new Ze({destinationIdentities:[e],kind:Y.RELIABLE,value:{case:"rpcResponse",value:new Tu({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:n??""}})}});yield this.sendDataPacket(r,Y.RELIABLE)})}publishRpcAck(e,t){return m(this,void 0,void 0,function*(){const n=new Ze({destinationIdentities:[e],kind:Y.RELIABLE,value:{case:"rpcAck",value:new Uu({requestId:t})}});yield this.sendDataPacket(n,Y.RELIABLE)})}sendDataPacket(e,t){return m(this,void 0,void 0,function*(){const n=e.toBinary();yield this.ensurePublisherConnected(t);const i=this.dataChannelForKind(t);i&&i.send(n),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,n)=>m(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const i=()=>n("Engine closed");for(this.once(_.Closing,i);!this.dcBufferStatus.get(e);)yield et(10);this.off(_.Closing,i),t()}}))}ensureDataTransportConnected(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var r;if(!n.pcManager)throw new Te("PC manager is closed");const s=i?n.pcManager.subscriber:n.pcManager.publisher,o=i?"Subscriber":"Publisher";if(!s)throw new oe("".concat(o," connection not set"),J.InternalError);let a=!1;!i&&!n.dataChannelForKind(t,i)&&(n.createDataChannels(),a=!0),!a&&!i&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(a=!0),a&&n.negotiate();const c=n.dataChannelForKind(t,i);if(c?.readyState==="open")return;const l=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<l;){if(s.isICEConnected&&((r=n.dataChannelForKind(t,i))===null||r===void 0?void 0:r.readyState)==="open")return;yield et(50)}throw new oe("could not establish ".concat(o," connection, state: ").concat(s.getICEConnectionState()),J.InternalError)}()})}ensurePublisherConnected(e){return m(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==ge.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return m(this,void 0,void 0,function*(){return new Promise((e,t)=>m(this,void 0,void 0,function*(){if(!this.pcManager){t(new ja("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const n=new AbortController,i=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(_.Closing,i),this.pcManager.publisher.once(jn.RTPVideoPayloadTypes,r=>{const s=new Map;r.forEach(o=>{const a=o.codec.toLowerCase();FC(a)&&s.set(o.payload,a)}),this.emit(_.RTPVideoMapUpdate,s)});try{yield this.pcManager.negotiate(n),e()}catch(r){r instanceof ja&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Ln.RR_UNKNOWN),t(r)}finally{this.off(_.Closing,i)}}))})}dataChannelForKind(e,t){if(t){if(e===Y.LOSSY)return this.lossyDCSub;if(e===Y.RELIABLE)return this.reliableDCSub}else{if(e===Y.LOSSY)return this.lossyDC;if(e===Y.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,i;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const r=this.pcManager.subscriber.getLocalDescription(),s=this.pcManager.subscriber.getRemoteDescription(),o=(i=(n=this.signalOpts)===null||n===void 0?void 0:n.autoSubscribe)!==null&&i!==void 0?i:!0,a=new Array,c=new Array;e.forEach(l=>{l.isDesired!==o&&a.push(l.trackSid),l.isEnabled||c.push(l.trackSid)}),this.client.sendSyncState(new Gu({answer:r?us({sdp:r.sdp,type:r.type}):void 0,offer:s?us({sdp:s.sdp,type:s.type}):void 0,subscription:new qr({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:OC(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(n,i)=>{n?.id!==void 0&&n.id!==null&&e.push(new ju({label:n.label,id:n.id,target:i}))};return t(this.dataChannelForKind(Y.LOSSY),yt.PUBLISHER),t(this.dataChannelForKind(Y.RELIABLE),yt.PUBLISHER),t(this.dataChannelForKind(Y.LOSSY,!0),yt.SUBSCRIBER),t(this.dataChannelForKind(Y.RELIABLE,!0),yt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&_e.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){tt()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){tt()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Wn extends Error{}function Cb(A){return A!==void 0&&A>13}function bb(A,e){const t=A.participantIdentity?A.participantIdentity:e.participantIdentity;A.participantIdentity=t,e.participantIdentity=t;const n=A.destinationIdentities.length!==0?A.destinationIdentities:e.destinationIdentities;A.destinationIdentities=n,e.destinationIdentities=n}class Tc{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Ac(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return m(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter(n=>!this.attemptedRegions.find(i=>i.url===n.url));if(t.length>0){const n=t[0];return this.attemptedRegions.push(n),j.debug("next region: ".concat(n.region)),n.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return m(this,void 0,void 0,function*(){const t=yield fetch("".concat(wb(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const n=yield t.json();return this.lastUpdateAt=Date.now(),n}else throw new oe("Could not fetch region settings: ".concat(t.statusText),t.status===401?J.NotAllowed:J.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function wb(A){return"".concat(A.protocol.replace("ws","http"),"//").concat(A.host,"/settings")}class yf{get info(){return this._info}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}}class yb extends yf{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,n)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>m(this,void 0,void 0,function*(){try{const{done:t,value:n}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(n),{done:!1,value:n.content})}catch{return{done:!0,value:void 0}}}),return(){return m(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return m(this,void 0,void 0,function*(){var e,t,n,i;let r=new Set;try{for(var s=!0,o=uA(this),a;a=yield o.next(),e=a.done,!e;s=!0){i=a.value,s=!1;const c=i;r.add(c)}}catch(c){t={error:c}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return Array.from(r)})}}class Eb extends yf{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=ls(e.chunkIndex),i=this.receivedChunks.get(n);if(i&&i.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength;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;return{next:()=>m(this,void 0,void 0,function*(){try{const{done:n,value:i}=yield e.read();return n?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:t.decode(i.content)})}catch{return{done:!0,value:void 0}}}),return(){return m(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return m(this,void 0,void 0,function*(){var e,t,n,i;let r="";try{for(var s=!0,o=uA(this),a;a=yield o.next(),e=a.done,!e;s=!0)i=a.value,s=!1,r+=i}catch(c){t={error:c}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(t)throw t.error}}return r})}}class Ef{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return m(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 Sb extends Ef{}class Ub extends Ef{}class Sf extends T{constructor(e,t,n,i,r){super(e,n,r),this.sid=t,this.receiver=i}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?I.Muted:I.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=n=>{n.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(I.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return m(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(),wc)),HC()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const n=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(n){const{timestamp:i,rtpTimestamp:r}=n;r&&this.rtpTimestamp!==r&&(this.emit(I.TimeSyncUpdate,{timestamp:i,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Tb extends Sf{constructor(e,t,n,i,r,s){super(e,t,T.Kind.Audio,n,s),this.monitorReceiver=()=>m(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=hs(o,this.prevStats)),this.prevStats=o}),this.audioContext=i,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;Ht()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Ht())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return m(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(tc(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&tc(e)&&e.setSinkId(this.sinkId).catch(n=>{this.log.error("Failed to set sink id on remote audio track",n,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 n=this.sourceNode;this.webAudioPluginNodes.forEach(i=>{n.connect(i),n=i}),this.gainNode=e.createGain(),n.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(I.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(i=>{this.emit(I.AudioPlaybackFailed,i)})}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 m(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(n=>{n.type==="inbound-rtp"&&(t={type:"audio",streamId:n.id,timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),t})}}const kc=100;class kb extends Sf{constructor(e,t,n,i,r){super(e,t,T.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>m(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const s=yield this.getReceiverStats();s&&this.prevStats&&this.receiver&&(this._currentBitrate=hs(s,this.prevStats)),this.prevStats=s}),this.debouncedHandleResize=vc(()=>{this.updateDimensions()},kc),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Kn(this._mediaStreamTrack,t):Nn(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 Fb(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(n=>n===e);for(const n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return m(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",i=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(n=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"&&i.set(r.id,r)}),t&&n!==""&&i.get(n)&&(t.mimeType=i.get(n).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(n=>n.element===e);for(const n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const n=this.elementInfos.reduce((o,a)=>Math.max(o,a.visibilityChangedAt||0),0),i=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,r=this.elementInfos.some(o=>o.pictureInPicture),s=this.elementInfos.some(o=>o.visible)&&!i||r;if(this.lastVisible!==s){if(!s&&Date.now()-n<kc){_e.setTimeout(()=>{this.updateVisibility()},kc);return}this.lastVisible=s,this.emit(I.VisibilityChanged,s,this)}}updateDimensions(){var e,t;let n=0,i=0;const r=this.getPixelDensity();for(const s of this.elementInfos){const o=s.width()*r,a=s.height()*r;o+a>n+i&&(n=o,i=a)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===i||(this.lastDimensions={width:n,height:i},this.emit(I.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Gh():t||(Gh()>2?2:1)}}class Fb{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var i;const{target:r,isIntersecting:s}=n;r===this.element&&(this.isIntersecting=s,this.isPiP=Ni(this.element),this.visibilityChangedAt=Date.now(),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this))},this.onEnterPiP=()=>{var n,i,r;(i=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Ni(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=Ni(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??Fc(e),this.isPiP=tt()&&Ni(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=Fc(this.element),this.isPiP=Ni(this.element),this.element.handleResize=()=>{var i;(i=this.handleResize)===null||i===void 0||i.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Wh().observe(this.element),jh().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),(n=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||n===void 0||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,i,r;(e=Wh())===null||e===void 0||e.unobserve(this.element),(t=jh())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(n=window.documentPictureInPicture)===null||n===void 0||n.removeEventListener("enter",this.onEnterPiP),(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function Ni(A){var e,t;return document.pictureInPictureElement===A?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Fc(A,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Fc(A,e){const t=e||window;let n=A.offsetTop,i=A.offsetLeft;const r=A.offsetWidth,s=A.offsetHeight,{hidden:o}=A,{display:a}=getComputedStyle(A);for(;A.offsetParent;)A=A.offsetParent,n+=A.offsetTop,i+=A.offsetLeft;return n<t.pageYOffset+t.innerHeight&&i<t.pageXOffset+t.innerWidth&&n+s>t.pageYOffset&&i+r>t.pageXOffset&&!o&&a!=="none"}class Zt extends Ot.EventEmitter{constructor(e,t,n,i){var r;super(),this.metadataMuted=!1,this.encryption=st.NONE,this.log=j,this.handleMuted=()=>{this.emit(I.Muted)},this.handleUnmuted=()=>{this.emit(I.Unmuted)},this.log=qt((r=i?.loggerName)!==null&&r!==void 0?r:Et.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=T.Source.Unknown}setTrack(e){this.track&&(this.track.off(I.Muted,this.handleMuted),this.track.off(I.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(I.Muted,this.handleMuted),e.on(I.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),te(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==st.NONE}get audioTrack(){if(Yt(this.track))return this.track}get videoTrack(){if(Gn(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=T.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===T.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(A){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(A.SubscriptionStatus||(A.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(A.PermissionStatus||(A.PermissionStatus={}))})(Zt||(Zt={}));class Qc extends Zt{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n,i){super(e,t.sid,t.name,i),this.track=void 0,this.handleTrackEnded=()=>{this.emit(I.Ended)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&this.track.off(I.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(I.Ended,this.handleTrackEnded)}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 m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Yt(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(wt.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(wt.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(wt.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(wt.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(wt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(wt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}function ms(A,e){return m(this,void 0,void 0,function*(){A??(A={});let t=!1;const{audioProcessor:n,videoProcessor:i,optionsWithoutProcessor:r}=ef(A);let s=r.audio,o=r.video;if(n&&typeof r.audio=="object"&&(r.audio.processor=n),i&&typeof r.video=="object"&&(r.video.processor=i),A.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const d=r.audio.deviceId;r.audio.deviceId={exact:d},t=!0,s=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:d}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const d=r.video.deviceId;r.video.deviceId={exact:d},t=!0,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:d}})}(r.audio===!0||typeof r.audio=="object"&&!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 a=qh(r,df,uf),c=dc(a),l=navigator.mediaDevices.getUserMedia(c);r.audio&&(Fe.userMediaPromiseMap.set("audioinput",l),l.catch(()=>Fe.userMediaPromiseMap.delete("audioinput"))),r.video&&(Fe.userMediaPromiseMap.set("videoinput",l),l.catch(()=>Fe.userMediaPromiseMap.delete("videoinput")));try{const d=yield l;return yield Promise.all(d.getTracks().map(u=>m(this,void 0,void 0,function*(){const h=u.kind==="audio";let f=h?a.audio:a.video;(typeof f=="boolean"||!f)&&(f={});let p;const g=h?c.audio:c.video;typeof g!="boolean"&&(p=g);const v=u.getSettings().deviceId;p?.deviceId&&mA(p.deviceId)!==v?p.deviceId=v:p||(p={deviceId:v});const w=sb(u,p,e);return w.kind===T.Kind.Video?w.source=T.Source.Camera:w.kind===T.Kind.Audio&&(w.source=T.Source.Microphone),w.mediaStream=d,Yt(w)&&n?yield w.setProcessor(n):Gn(w)&&i&&(yield w.setProcessor(i)),w})))}catch(d){if(!t)throw d;return ms(Object.assign(Object.assign({},A),{audio:s,video:o}),e)}})}function Qb(A){return m(this,void 0,void 0,function*(){return(yield ms({audio:!1,video:A??!0}))[0]})}function Ib(A){return m(this,void 0,void 0,function*(){return(yield ms({audio:A??!0,video:!1}))[0]})}var CA;(function(A){A.Excellent="excellent",A.Good="good",A.Poor="poor",A.Lost="lost",A.Unknown="unknown"})(CA||(CA={}));function _b(A){switch(A){case xi.EXCELLENT:return CA.Excellent;case xi.GOOD:return CA.Good;case xi.POOR:return CA.Poor;case xi.LOST:return CA.Lost;default:return CA.Unknown}}class Uf extends Ot.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===Xr.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Dn.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,i,r,s){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Xr.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=CA.Unknown,this.log=j,this.log=qt((a=s?.loggerName)!==null&&a!==void 0?a:Et.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=i,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 sc,this.once(R.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(T.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(T.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(T.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===Dn.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Dn.ACTIVE&&this.emit(R.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(R.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(R.ParticipantNameChanged,e)}_setAttributes(e){const t=MC(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(R.AttributesChanged,t)}setPermissions(e){var t,n,i,r,s,o;const a=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((i=this.permissions)===null||i===void 0?void 0:i.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((s=this.permissions)===null||s===void 0?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,d)=>{var u;return l!==((u=this.permissions)===null||u===void 0?void 0:u.canPublishSources[d])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(R.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(R.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=_b(e),t!==this._connectionQuality&&this.emit(R.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=>Yt(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(I.Muted,()=>{this.emit(R.TrackMuted,e)}),e.on(I.Unmuted,()=>{this.emit(R.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case T.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case T.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function xb(A){var e,t,n;if(!A.participantSid&&!A.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new $u({participantIdentity:(e=A.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=A.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=A.allowAll)!==null&&n!==void 0?n:!1,trackSids:A.allowedTrackSids||[]})}const Tf=15e3;class Rb extends Uf{constructor(e,t,n,i,r){super(e,t,void 0,void 0,void 0,{loggerName:i.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=st.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new sc)},this.handleReconnected=()=>{var s,o;(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.resolve)===null||o===void 0||o.call(s),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var s,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(a=>this.log.warn(a.message,this.logContext)),(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.reject)===null||o===void 0||o.call(s,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=s=>{const{requestId:o,reason:a,message:c}=s,l=this.pendingSignalRequests.get(o);l&&(a!==Ra.OK&&l.reject(new Oh(c,a)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=s=>{switch(s.value.case){case"rpcResponse":let o=s.value.value,a=null,c=null;o.value.case==="payload"?a=o.value.value:o.value.case==="error"&&(c=me.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,a,c);break;case"rpcAck":let l=s.value.value;this.handleIncomingRpcAck(l.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(s=>xb(s)))},this.onTrackUnmuted=s=>{this.onTrackMuted(s,s.isUpstreamPaused)},this.onTrackMuted=(s,o)=>{if(o===void 0&&(o=!0),!s.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),te(s)));return}this.engine.updateMuteStatus(s.sid,o)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),te(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),te(s))),this.onTrackMuted(s,s.isMuted)},this.onTrackFeatureUpdate=s=>{const o=this.audioTrackPublications.get(s.sid);if(!o){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(s.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.handleSubscribedQualityUpdate=s=>m(this,void 0,void 0,function*(){var o,a,c,l,d,u;if(!(!((d=this.roomOptions)===null||d===void 0)&&d.dynacast))return;const h=this.videoTrackPublications.get(s.trackSid);if(!h){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}if(s.subscribedCodecs.length>0){if(!h.videoTrack)return;const v=yield h.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var f=!0,p=uA(v),g;g=yield p.next(),o=g.done,!o;f=!0){l=g.value,f=!1;const w=l;vC(w)&&(this.log.debug("publish ".concat(w," for ").concat(h.videoTrack.sid),Object.assign(Object.assign({},this.logContext),te(h))),yield this.publishAdditionalCodecForTrack(h.videoTrack,w,h.options))}}catch(w){a={error:w}}finally{try{!f&&!o&&(c=p.return)&&(yield c.call(p))}finally{if(a)throw a.error}}}else s.subscribedQualities.length>0&&(yield(u=h.videoTrack)===null||u===void 0?void 0:u.setPublishingLayers(s.subscribedQualities))}),this.handleLocalTrackUnpublished=s=>{const o=this.trackPublications.get(s.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=s=>m(this,void 0,void 0,function*(){if(s.source===T.Source.ScreenShare||s.source===T.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),te(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(rn(s)||vA(s))try{if(tt())try{const o=yield navigator?.permissions.query({name:s.source===T.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(s.source),Object.assign(Object.assign({},this.logContext),te(s))),o.onchange=()=>{o.state!=="denied"&&(s.isMuted||s.restartTrack(),o.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}s.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),te(s))),rn(s)?yield s.restartTrack({deviceId:"default"}):yield s.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),te(s))),yield s.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=i,this.setupEngine(n),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==st.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){this.engine=e,this.engine.on(_.RemoteMute,(t,n)=>{const i=this.trackPublications.get(t);!i||!i.track||(n?i.mute():i.unmute())}),this.engine.on(_.Connected,this.handleReconnected).on(_.SignalRestarted,this.handleReconnected).on(_.SignalResumed,this.handleReconnected).on(_.Restarting,this.handleReconnecting).on(_.Resuming,this.handleReconnecting).on(_.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(_.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(_.Disconnected,this.handleDisconnected).on(_.SignalRequestResponse,this.handleSignalRequestResponse).on(_.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return m(this,arguments,void 0,function(t){var n=this;let{metadata:i,name:r,attributes:s}=t;return function*(){return new Promise((o,a)=>m(n,void 0,void 0,function*(){var c,l;try{let d=!1;const u=yield this.engine.client.sendUpdateLocalMetadata((c=i??this.metadata)!==null&&c!==void 0?c:"",(l=r??this.name)!==null&&l!==void 0?l:"",s),h=performance.now();for(this.pendingSignalRequests.set(u,{resolve:o,reject:f=>{a(f),d=!0},values:{name:r,metadata:i,attributes:s}});performance.now()-h<5e3&&!d;){if((!r||this.name===r)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every(f=>{let[p,g]=f;return this.attributes[p]===g||g===""&&!this.attributes[p]}))){this.pendingSignalRequests.delete(u),o();return}yield et(50)}a(new Oh("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error&&a(d)}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(T.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(T.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(T.Source.ScreenShare,e,t,n)}setPermissions(e){const t=this.permissions,n=super.setPermissions(e);return n&&t&&this.emit(R.ParticipantPermissionsChanged,t),n}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){this.encryptionType=e?st.GCM:st.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,i){return m(this,void 0,void 0,function*(){var r,s;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 a;if(this.pendingPublishing.has(e)){const c=yield this.waitForPendingPublicationOfSource(e);return c||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield c?.unmute(),c}this.pendingPublishing.add(e);try{switch(e){case T.Source.Camera:a=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case T.Source.Microphone:a=yield this.createTracks({audio:(s=n)!==null&&s!==void 0?s:!0});break;case T.Source.ScreenShare:a=yield this.createScreenTracks(Object.assign({},n));break;default:throw new zt(e)}}catch(c){throw a?.forEach(l=>{l.stop()}),c instanceof Error&&this.emit(R.MediaDevicesError,c),this.pendingPublishing.delete(e),c}try{const c=[];for(const d of a)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),te(d))),c.push(this.publishTrack(d,i));[o]=yield Promise.all(c)}catch(c){throw a?.forEach(l=>{l.stop()}),c}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===T.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const a=this.getTrackPublication(T.Source.ScreenShareAudio);a&&a.track&&this.unpublishTrack(a.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return m(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(T.Source.Camera)||this.pendingPublishing.has(T.Source.Microphone))){this.pendingPublishing.add(T.Source.Camera),this.pendingPublishing.add(T.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(T.Source.Camera),this.pendingPublishing.delete(T.Source.Microphone)}}})}createTracks(e){return m(this,void 0,void 0,function*(){var t,n;e??(e={});const i=qh(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults);try{return(yield ms(i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Yt(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=T.Source.Microphone,this.emit(R.AudioStreamAcquired)),Gn(o)&&(this.cameraError=void 0,o.source=T.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return m(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Ga("getDisplayMedia not supported");e.resolution===void 0&&!EC()&&(e.resolution=Ya.h1080fps30.resolution);const t=DC(e),n=yield navigator.mediaDevices.getDisplayMedia(t),i=n.getVideoTracks();if(i.length===0)throw new zt("no video track found");const r=new gs(i[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=T.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const s=[r];if(n.getAudioTracks().length>0){this.emit(R.AudioStreamAcquired);const o=new fs(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=T.Source.ScreenShareAudio,s.push(o)}return s})}publishTrack(e,t){return m(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return m(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,a,c,l;rn(n)&&n.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!s&&(yield r.republishPromise),Vn(n)&&r.pendingPublishPromises.has(n)&&(yield r.pendingPublishPromises.get(n));let d;if(n instanceof MediaStreamTrack)d=n.getConstraints();else{d=n.constraints;let v;switch(n.source){case T.Source.Microphone:v="audioinput";break;case T.Source.Camera:v="videoinput"}v&&r.activeDeviceMap.has(v)&&(d=Object.assign(Object.assign({},d),{deviceId:r.activeDeviceMap.get(v)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new fs(n,d,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":n=new gs(n,d,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new zt("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let u;if(r.trackPublications.forEach(v=>{v.track&&v.track===n&&(u=v)}),u)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),te(u))),u;const h="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.mediaStreamTrack.getConstraints().channelCount===2,f=(a=i?.forceStereo)!==null&&a!==void 0?a:h;f&&(i||(i={}),i.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),te(n))),i.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(c=i.dtx)!==null&&c!==void 0||(i.dtx=!1),(l=i.red)!==null&&l!==void 0||(i.red=!1));const p=Object.assign(Object.assign({},r.roomOptions.publishDefaults),i);!SC()&&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)),p.simulcast=!1),p.source&&(n.source=p.source);const g=new Promise((v,w)=>m(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ce.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:te(n)}));const y=()=>m(this,void 0,void 0,function*(){try{const B=yield this.publish(n,p,f);v(B)}catch(B){w(B)}});setTimeout(()=>{this.engine.off(_.SignalConnected,y),w(new Wa("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(_.SignalConnected,y),this.engine.on(_.Closing,()=>{this.engine.off(_.SignalConnected,y),w(new Wa("publishing rejected as engine closed",499))})}else try{const y=yield this.publish(n,p,f);v(y)}catch(y){w(y)}}catch(y){w(y)}}));r.pendingPublishPromises.set(n,g);try{return yield g}catch(v){throw v}finally{r.pendingPublishPromises.delete(n)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),te(e))),!1;const{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(i=>NC(i)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),te(e))),!1)}publish(e,t,n){return m(this,void 0,void 0,function*(){var i,r,s,o,a,c,l,d,u,h;if(!this.hasPermissionsToPublish(e))throw new Wa("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(C=>Vn(e)&&C.source===e.source)&&e.source!==T.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),te(e))),t.stopMicTrackOnMute&&Yt(e)&&(e.stopOnMute=!0),e.source===T.Source.ScreenShare&&$n()&&(t.simulcast=!1),t.videoCodec==="av1"&&!bC()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!wC()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Bc),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(C=>t.videoCodec===ds(C.mime))||(t.videoCodec=ds(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(I.Muted,this.onTrackMuted),e.on(I.Unmuted,this.onTrackUnmuted),e.on(I.Ended,this.handleTrackEnded),e.on(I.UpstreamPaused,this.onTrackUpstreamPaused),e.on(I.UpstreamResumed,this.onTrackUpstreamResumed),e.on(I.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const g=new Fa({cid:e.mediaStreamTrack.id,name:t.name,type:T.kindToProto(e.kind),muted:e.isMuted,source:T.sourceToProto(e.source),disableDtx:!(!((i=t.dtx)!==null&&i!==void 0)||i),encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy});let v;if(e.kind===T.Kind.Video){let C={width:0,height:0};try{C=yield e.waitForDimensions()}catch{const U=(o=(s=this.roomOptions.videoCaptureDefaults)===null||s===void 0?void 0:s.resolution)!==null&&o!==void 0?o:Di.h720.resolution;C={width:U.width,height:U.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),te(e)),{dims:C}))}g.width=C.width,g.height=C.height,vA(e)&&(Oi(p)&&(e.source===T.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),te(e))))),t.scalabilityMode=(a=t.scalabilityMode)!==null&&a!==void 0?a:"L3T3_KEY"),g.simulcastCodecs=[new ka({codec:p,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Bc}),t.backupCodec&&p!==t.backupCodec.codec&&g.encryption===st.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),g.simulcastCodecs.push(new ka({codec:t.backupCodec.codec,cid:""})))),v=Ec(e.source===T.Source.ScreenShare,g.width,g.height,t),g.layers=Cf(g.width,g.height,v,Oi(t.videoCodec))}else e.kind===T.Kind.Audio&&(v=[{maxBitrate:(c=t.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(d=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&d!==void 0?d:"high",networkPriority:(h=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&h!==void 0?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new Te("cannot publish track when not connected");const w=()=>m(this,void 0,void 0,function*(){var C,b,U;if(!this.engine.pcManager)throw new Te("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,v),vA(e)&&((C=t.degradationPreference)!==null&&C!==void 0||(t.degradationPreference=gb(e)),e.setDegradationPreference(t.degradationPreference)),v)if($n()&&e.kind===T.Kind.Audio){let Q;for(const x of this.engine.pcManager.publisher.getTransceivers())if(x.sender===e.sender){Q=x;break}Q&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:Q,codec:"opus",maxbr:!((b=v[0])===null||b===void 0)&&b.maxBitrate?v[0].maxBitrate/1e3:0})}else e.codec&&Oi(e.codec)&&(!((U=v[0])===null||U===void 0)&&U.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:g.cid,codec:e.codec,maxbr:v[0].maxBitrate/1e3});yield this.engine.negotiate()});let y;if(this.enabledPublishVideoCodecs.length>0)y=(yield Promise.all([this.engine.addTrack(g),w()]))[0];else{y=yield this.engine.addTrack(g);let C;if(y.codecs.forEach(b=>{C===void 0&&(C=b.mimeType)}),C&&e.kind===T.Kind.Video){const b=ds(C);b!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),te(e)),{codec:b})),t.videoCodec=b,v=Ec(e.source===T.Source.ScreenShare,g.width,g.height,t))}yield w()}const B=new Qc(e.kind,y,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return B.options=t,e.sid=y.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:v,trackInfo:y})),vA(e)?e.startMonitor(this.engine.client):rn(e)&&e.startMonitor(),this.addTrackPublication(B),this.emit(R.LocalTrackPublished,B),B})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return m(this,void 0,void 0,function*(){var i;if(this.encryptionType!==st.NONE)return;let r;if(this.trackPublications.forEach(h=>{h.track&&h.track===e&&(r=h)}),!r)throw new zt("track is not published");if(!vA(e))throw new zt("track is not a video track");const s=Object.assign(Object.assign({},(i=this.roomOptions)===null||i===void 0?void 0:i.publishDefaults),n),o=hb(e,t,s);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),te(e)));return}const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new Fa({cid:a.mediaStreamTrack.id,type:T.kindToProto(e.kind),muted:e.isMuted,source:T.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=Cf(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new Te("cannot publish track when not connected");const l=()=>m(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,s,o),yield this.engine.negotiate()}),u=(yield Promise.all([this.engine.addTrack(c),l()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:u}))})}unpublishTrack(e,t){return m(this,void 0,void 0,function*(){var n,i;if(Vn(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),te(e))),yield c)}const r=this.getPublicationForTrack(e),s=r?te(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),s)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),s));return}e=r.track,e.off(I.Muted,this.onTrackMuted),e.off(I.Unmuted,this.onTrackUnmuted),e.off(I.Ended,this.handleTrackEnded),e.off(I.UpstreamPaused,this.onTrackUpstreamPaused),e.off(I.UpstreamResumed,this.onTrackUpstreamResumed),e.off(I.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(i=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&i!==void 0?i:!0),t?e.stop():e.stopMonitor();let o=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ge.FAILED&&a)try{for(const c of this.engine.pcManager.publisher.getTransceivers())c.sender===a&&(c.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),vA(e)){for(const[,c]of e.simulcastCodecs)c.sender&&(this.engine.removeTrack(c.sender)&&(o=!0),c.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),s),{error:c}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case T.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case T.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(R.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return m(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new Promise((r,s)=>m(n,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(a=>{a.track&&(t&&(a.options=Object.assign(Object.assign({},a.options),t)),o.push(a))}),yield Promise.all(o.map(a=>m(this,void 0,void 0,function*(){const c=a.track;yield this.unpublishTrack(c,!1),i&&!c.isMuted&&c.source!==T.Source.ScreenShare&&c.source!==T.Source.ScreenShareAudio&&(rn(c)||vA(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:a.trackSid})),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,a.options,!0)}))),r()}catch(o){s(o)}finally{this.republishPromise=void 0}})),yield n.republishPromise}()})}publishData(e){return m(this,arguments,void 0,function(t){var n=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const r=i.reliable?Y.RELIABLE:Y.LOSSY,s=i.destinationIdentities,o=i.topic,a=new Ze({kind:r,value:{case:"user",value:new yu({participantIdentity:n.identity,payload:t,destinationIdentities:s,topic:o})}});yield n.engine.sendDataPacket(a,r)}()})}publishDtmf(e,t){return m(this,void 0,void 0,function*(){const n=new Ze({kind:Y.RELIABLE,value:{case:"sipDtmf",value:new Eu({code:e,digit:t})}});yield this.engine.sendDataPacket(n,Y.RELIABLE)})}sendChatMessage(e,t){return m(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},i=new Ze({value:{case:"chatMessage",value:new wa(Object.assign(Object.assign({},n),{timestamp:he.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(i,Y.RELIABLE),this.emit(R.ChatMessage,n),n})}editChatMessage(e,t){return m(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),i=new Ze({value:{case:"chatMessage",value:new wa(Object.assign(Object.assign({},n),{timestamp:he.parse(n.timestamp),editTimestamp:he.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(i,Y.RELIABLE),this.emit(R.ChatMessage,n),n})}sendText(e,t){return m(this,void 0,void 0,function*(){var n;const i=crypto.randomUUID(),s=new TextEncoder().encode(e).byteLength,o=(n=t?.attachments)===null||n===void 0?void 0:n.map(()=>crypto.randomUUID()),a=new Array(o?o.length+1:1).fill(0),c=(d,u)=>{var h;a[u]=d;const f=a.reduce((p,g)=>p+g,0);(h=t?.onProgress)===null||h===void 0||h.call(t,f)},l=yield this.streamText({streamId:i,totalSize:s,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:o,attributes:t?.attributes});return yield l.write(e),c(1,0),yield l.close(),t?.attachments&&o&&(yield Promise.all(t.attachments.map((d,u)=>m(this,void 0,void 0,function*(){return this._sendFile(o[u],d,{topic:t.topic,mimeType:d.type,onProgress:h=>{c(h,u+1)}})})))),l.info})}streamText(e){return m(this,void 0,void 0,function*(){var t,n;const i=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),r={id:i,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e?.topic)!==null&&n!==void 0?n:"",size:e?.totalSize,attributes:e?.attributes},s=new Ea({streamId:i,mimeType:r.mimeType,topic:r.topic,timestamp:nn(r.timestamp),totalLength:nn(e?.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new Pu({version:e?.version,attachedStreamIds:e?.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?ya.UPDATE:ya.CREATE})}}),o=e?.destinationIdentities,a=new Ze({destinationIdentities:o,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(a,Y.RELIABLE);let c=0;const l=this,d=new WritableStream({write(f){return m(this,void 0,void 0,function*(){for(const p of PC(f,Tf)){yield l.engine.waitForBufferStatusLow(Y.RELIABLE);const g=new Sa({content:p,streamId:i,chunkIndex:nn(c)}),v=new Ze({destinationIdentities:o,value:{case:"streamChunk",value:g}});yield l.engine.sendDataPacket(v,Y.RELIABLE),c+=1}})},close(){return m(this,void 0,void 0,function*(){const f=new Ua({streamId:i}),p=new Ze({destinationIdentities:o,value:{case:"streamTrailer",value:f}});yield l.engine.sendDataPacket(p,Y.RELIABLE)})},abort(f){console.log("Sink error:",f)}});let u=()=>m(this,void 0,void 0,function*(){yield h.close()});l.engine.once(_.Closing,u);const h=new Sb(d,r,()=>this.engine.off(_.Closing,u));return h})}sendFile(e,t){return m(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return m(this,void 0,void 0,function*(){var i;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(i=n?.mimeType)!==null&&i!==void 0?i:t.type,topic:n?.topic,destinationIdentities:n?.destinationIdentities}),s=t.stream().getReader();for(;;){const{done:o,value:a}=yield s.read();if(o)break;yield r.write(a)}return yield r.close(),r.info})}streamBytes(e){return m(this,void 0,void 0,function*(){var t,n,i,r,s;const o=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a=e?.destinationIdentities,c={id:o,mimeType:(n=e?.mimeType)!==null&&n!==void 0?n:"application/octet-stream",topic:(i=e?.topic)!==null&&i!==void 0?i:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(r=e?.name)!==null&&r!==void 0?r:"unknown"},l=new Ea({totalLength:nn((s=c.size)!==null&&s!==void 0?s:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:nn(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Lu({name:c.name})}}),d=new Ze({destinationIdentities:a,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(d,Y.RELIABLE);let u=0;const h=new ze,f=this.engine,p=this.log,g=new WritableStream({write(w){return m(this,void 0,void 0,function*(){const y=yield h.lock();let B=0;try{for(;B<w.byteLength;){const C=w.slice(B,B+Tf);yield f.waitForBufferStatusLow(Y.RELIABLE);const b=new Ze({destinationIdentities:a,value:{case:"streamChunk",value:new Sa({content:C,streamId:o,chunkIndex:nn(u)})}});yield f.sendDataPacket(b,Y.RELIABLE),u+=1,B+=C.byteLength}}finally{y()}})},close(){return m(this,void 0,void 0,function*(){const w=new Ua({streamId:o}),y=new Ze({destinationIdentities:a,value:{case:"streamTrailer",value:w}});yield f.sendDataPacket(y,Y.RELIABLE)})},abort(w){p.error("Sink error:",w)}});return new Ub(g,c)})}performRpc(e){return m(this,arguments,void 0,function(t){var n=this;let{destinationIdentity:i,method:r,payload:s,responseTimeout:o=1e4}=t;return function*(){return new Promise((c,l)=>m(n,void 0,void 0,function*(){var d,u,h,f;if(bc(s)>hf){l(me.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((u=(d=this.engine.latestJoinResponse)===null||d===void 0?void 0:d.serverInfo)===null||u===void 0)&&u.version&&An((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){l(me.builtIn("UNSUPPORTED_SERVER"));return}const p=crypto.randomUUID();yield this.publishRpcRequest(i,p,r,s,o-2e3);const g=setTimeout(()=>{this.pendingAcks.delete(p),l(me.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(p),clearTimeout(v)},2e3);this.pendingAcks.set(p,{resolve:()=>{clearTimeout(g)},participantIdentity:i});const v=setTimeout(()=>{this.pendingResponses.delete(p),l(me.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(p,{resolve:(w,y)=>{clearTimeout(v),this.pendingAcks.has(p)&&(console.warn("RPC response received before ack",p),this.pendingAcks.delete(p),clearTimeout(g)),y?l(y):c(w??"")},participantIdentity:i})}))}()})}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,n){const i=this.pendingResponses.get(e);i?(i.resolve(t,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,n,i,r){return m(this,void 0,void 0,function*(){const s=new Ze({destinationIdentities:[e],kind:Y.RELIABLE,value:{case:"rpcRequest",value:new Su({id:t,method:n,payload:i,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(s,Y.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:n,resolve:i}]of this.pendingResponses)n===e&&(i(null,me.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 n,i;const r=this.trackPublications.get(t.sid);if(r){const s=r.isMuted||((i=(n=r.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&i!==void 0?i:!1);s!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),te(r)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(t.sid,s))}}),!0):!1}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const i=n.track;i&&(e instanceof MediaStreamTrack?(rn(i)||vA(i))&&i.mediaStreamTrack===e&&(t=n):e===i&&(t=n))}),t}waitForPendingPublicationOfSource(e){return m(this,void 0,void 0,function*(){const n=Date.now();for(;Date.now()<n+1e4;){const i=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[s]=r;return s.source===e});if(i)return i[1];yield et(20)}})}}class Pb extends Zt{constructor(e,t,n,i){super(e,t.sid,t.name,i),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=ut.HIGH,this.handleEnded=r=>{this.setTrack(void 0),this.emit(I.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.disabled=!r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensions=r,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const i=new qr({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Fu({participantSid:"",trackSids:[this.trackSid]})]});this.emit(I.UpdateSubscription,i),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?Zt.SubscriptionStatus.Unsubscribed:super.isSubscribed?Zt.SubscriptionStatus.Subscribed:Zt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Zt.PermissionStatus.Allowed:Zt.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,n;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((n=this.videoDimensions)===null||n===void 0?void 0:n.height)===e.height||(cc(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&cc(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,i=this.track;i!==e&&(i&&(i.off(I.VideoDimensionsChanged,this.handleVideoDimensionsChange),i.off(I.VisibilityChanged,this.handleVisibilityChange),i.off(I.Ended,this.handleEnded),i.detach(),i.stopMonitor(),this.emit(I.Unsubscribed,i)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(I.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(I.VisibilityChanged,this.handleVisibilityChange),e.on(I.Ended,this.handleEnded),this.emit(I.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(I.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?I.Muted:I.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(I.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(I.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===T.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return cc(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Ou({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=ut.HIGH,this.emit(I.UpdateSettings,e)}}class vs extends Uf{static fromParticipantInfo(e,t,n){return new vs(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,i,r,s,o){let a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Xr.STANDARD;super(t,n||"",i,r,s,o,a),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(I.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),te(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(I.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(I.SubscriptionPermissionChanged,t=>{this.emit(R.TrackSubscriptionPermissionChanged,e,t)}),e.on(I.SubscriptionStatusChanged,t=>{this.emit(R.TrackSubscriptionStatusChanged,e,t)}),e.on(I.Subscribed,t=>{this.emit(R.TrackSubscribed,t,e)}),e.on(I.Unsubscribed,t=>{this.emit(R.TrackUnsubscribed,t,e)}),e.on(I.SubscriptionFailed,t=>{this.emit(R.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]:T.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:T.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,i,r,s){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(s===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(R.TrackSubscriptionFailed,t);return}s===void 0&&(s=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,i,r,s-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),te(o))),this.emit(R.TrackSubscriptionFailed,t);return}const a=e.kind==="video";let c;return a?c=new kb(e,t,i,r):c=new Tb(e,t,i,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(n),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&ac(c)&&Yt(c)&&c.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,n=new Map;return e.tracks.forEach(i=>{var r,s;let o=this.getTrackPublicationBySid(i.sid);if(o)o.updateInfo(i);else{const a=T.kindFromProto(i.type);if(!a)return;o=new Pb(a,i,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(s=this.loggerOptions)===null||s===void 0?void 0:s.loggerName}),o.updateInfo(i),n.set(i.sid,o);const c=Array.from(this.trackPublications.values()).find(l=>l.source===o?.source);c&&o.source!==T.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:te(c),newTrack:te(o)})),this.addTrackPublication(o)}t.set(i.sid,o)}),this.trackPublications.forEach(i=>{t.has(i.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),te(i))),this.unpublishTrack(i.trackSid,!0))}),n.forEach(i=>{this.emit(R.TrackPublished,i)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const{track:i}=n;switch(i&&(i.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case T.Kind.Audio:this.audioTrackPublications.delete(e);break;case T.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(R.TrackUnpublished,n)}setAudioOutput(e){return m(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var i;Yt(n.track)&&ac(n.track)&&t.push(n.track.setSinkId((i=e.deviceId)!==null&&i!==void 0?i:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var Z;(function(A){A.Disconnected="disconnected",A.Connecting="connecting",A.Connected="connected",A.Reconnecting="reconnecting",A.SignalReconnecting="signalReconnecting"})(Z||(Z={}));const Lb=4*1e3;class sn extends Ot.EventEmitter{constructor(e){var t,n,i,r;if(super(),t=this,this.state=Z.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=j,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(s,o,a)=>m(this,void 0,void 0,function*(){var c;if(!yC())throw Ht()?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 l=yield this.disconnectLock.lock();if(this.state===Z.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),l(),Promise.resolve();if(this.connectFuture)return l(),this.connectFuture.promise;this.setAndEmitConnectionState(Z.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==s&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Ac(new URL(s))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Tc(s,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(h=>{var f;(f=this.regionUrlProvider)===null||f===void 0||f.setServerReportedRegions(h)}).catch(h=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:h}))}));const d=(h,f,p)=>m(this,void 0,void 0,function*(){var g,v;this.abortController&&this.abortController.abort();const w=new AbortController;this.abortController=w,l?.();try{yield this.attemptConnection(p??s,o,a,w),this.abortController=void 0,h()}catch(y){if(this.regionUrlProvider&&y instanceof oe&&y.reason!==J.Cancelled&&y.reason!==J.NotAllowed){let B=null;try{B=yield this.regionUrlProvider.getNextBestRegionUrl((g=this.abortController)===null||g===void 0?void 0:g.signal)}catch(C){if(C instanceof oe&&(C.status===401||C.reason===J.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),f(C);return}}B&&!(!((v=this.abortController)===null||v===void 0)&&v.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(y.message,". Retrying with another region: ").concat(B),this.logContext),this.recreateEngine(),yield d(h,f,B)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Xh(y)),f(y))}else{let B=bt.UNKNOWN_REASON;y instanceof oe&&(B=Xh(y)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,B),f(y)}}}),u=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new sc((h,f)=>{d(h,f,u)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(s,o,a,c,l,d)=>m(this,void 0,void 0,function*(){var u,h,f;const p=yield a.join(s,o,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof l.adaptiveStream=="object"?!0:l.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},d.signal);let g=p.serverInfo;if(g||(g={version:p.serverVersion,region:p.serverRegion}),this.serverInfo=g,this.log.debug("connected to Livekit Server ".concat(Object.entries(g).map(v=>{let[w,y]=v;return"".concat(w,": ").concat(y)}).join(", ")),{room:(u=p.room)===null||u===void 0?void 0:u.name,roomSid:(h=p.room)===null||h===void 0?void 0:h.sid,identity:(f=p.participant)===null||f===void 0?void 0:f.identity}),!g.version)throw new aC("unknown server version");return g.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),l.dynacast=!1),p}),this.applyJoinResponse=s=>{const o=s.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(s.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(s.sifTrailer)}catch(a){this.log.error(a instanceof Error?a.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:a}))}this.handleParticipantUpdates([o,...s.otherParticipants]),s.room&&this.handleRoomUpdate(s.room)},this.attemptConnection=(s,o,a,c)=>m(this,void 0,void 0,function*(){var l,d;this.state===Z.Reconnecting||this.isResuming||!((l=this.engine)===null||l===void 0)&&l.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((d=this.regionUrlProvider)===null||d===void 0)&&d.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Cc),a),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const u=yield this.connectSignal(s,o,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(u),this.setupLocalParticipantEvents(),this.emit(F.SignalConnected)}catch(u){yield this.engine.close(),this.recreateEngine();const h=new oe("could not establish signal connection",J.ServerUnreachable);throw u instanceof Error&&(h.message="".concat(h.message,": ").concat(u.message)),u instanceof oe&&(h.reason=u.reason,h.status=u.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:u})),h}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new oe("Connection attempt aborted",J.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(u){throw yield this.engine.close(),this.recreateEngine(),u}tt()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),tt()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Z.Connected),this.emit(F.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];return m(t,[...o],void 0,function(){var c=this;let l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var d,u,h,f;const p=yield c.disconnectLock.lock();try{if(c.state===Z.Disconnected){c.log.debug("already disconnected",c.logContext);return}c.log.info("disconnect from room",Object.assign({},c.logContext)),(c.state===Z.Connecting||c.state===Z.Reconnecting||c.isResuming)&&(c.log.warn("abort connection attempt",c.logContext),(d=c.abortController)===null||d===void 0||d.abort(),(h=(u=c.connectFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,new oe("Client initiated disconnect",J.Cancelled)),c.connectFuture=void 0),!((f=c.engine)===null||f===void 0)&&f.client.isDisconnected||(yield c.engine.client.sendLeave()),c.engine&&(yield c.engine.close()),c.handleDisconnect(l,bt.CLIENT_INITIATED),c.engine=void 0}finally{p()}}()})},this.onPageLeave=()=>m(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>m(this,void 0,void 0,function*(){const s=[],o=St();if(o&&o.os==="iOS"){const a="livekit-dummy-audio-el";let c=document.getElementById(a);if(!c){c=document.createElement("audio"),c.id=a,c.autoplay=!0,c.hidden=!0;const l=rc();l.enabled=!0;const d=new MediaStream([l]);c.srcObject=d,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:d,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(c),this.once(F.Disconnected,()=>{c?.remove(),c=null})}s.push(c)}this.remoteParticipants.forEach(a=>{a.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(l=>{s.push(l)})})});try{yield Promise.all([this.acquireAudioContext(),...s.map(a=>(a.muted=!1,a.play()))]),this.handleAudioPlaybackStarted()}catch(a){throw this.handleAudioPlaybackFailed(a),a}}),this.startVideo=()=>m(this,void 0,void 0,function*(){const s=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(a=>{var c;(c=a.track)===null||c===void 0||c.attachedElements.forEach(l=>{s.includes(l)||s.push(l)})});yield Promise.all(s.map(o=>o.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(o=>{o.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 s of this.remoteParticipants.values())this.handleParticipantDisconnected(s.identity,s);this.setAndEmitConnectionState(Z.Reconnecting)&&this.emit(F.Reconnecting)},this.handleSignalRestarted=s=>m(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(s.serverRegion),Object.assign(Object.assign({},this.logContext),{region:s.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(s);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(o){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:o}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:s.serverRegion}))}catch{return}this.setAndEmitConnectionState(Z.Connected),this.emit(F.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=s=>{s.forEach(o=>{var a;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(a=this.sidToIdentity.get(o.sid))!==null&&a!==void 0?a:"");let c=this.remoteParticipants.get(o.identity);o.state===Dn.DISCONNECTED?this.handleParticipantDisconnected(o.identity,c):c=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=s=>{const o=[],a={};s.forEach(c=>{if(a[c.sid]=!0,c.sid===this.localParticipant.sid)this.localParticipant.audioLevel=c.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const l=this.getRemoteParticipantBySid(c.sid);l&&(l.audioLevel=c.level,l.setIsSpeaking(!0),o.push(l))}}),a[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{a[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(F.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=s=>{const o=new Map;this.activeSpeakers.forEach(c=>{const l=this.remoteParticipants.get(c.identity);l&&l.sid!==c.sid||o.set(c.sid,c)}),s.forEach(c=>{let l=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(l=this.localParticipant),l&&(l.audioLevel=c.level,l.setIsSpeaking(c.active),c.active?o.set(c.sid,l):o.delete(c.sid))});const a=Array.from(o.values());a.sort((c,l)=>l.audioLevel-c.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(F.ActiveSpeakersChanged,a)},this.handleStreamStateUpdate=s=>{s.streamStates.forEach(o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);if(!c||!c.track)return;const l=T.streamStateFromProto(o.state);l!==c.track.streamState&&(c.track.streamState=l,a.emit(R.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(F.TrackStreamStateChanged,c,c.track.streamState,a))})},this.handleSubscriptionPermissionUpdate=s=>{const o=this.getRemoteParticipantBySid(s.participantSid);if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setAllowed(s.allowed)},this.handleSubscriptionError=s=>{const o=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(s.trackSid));if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setSubscriptionError(s.err)},this.handleDataPacket=s=>{const o=this.remoteParticipants.get(s.participantIdentity);if(s.value.case==="user")this.handleUserPacket(o,s.value.value,s.kind);else if(s.value.case==="transcription")this.handleTranscription(o,s.value.value);else if(s.value.case==="sipDtmf")this.handleSipDtmf(o,s.value.value);else if(s.value.case==="chatMessage")this.handleChatMessage(o,s.value.value);else if(s.value.case==="metrics")this.handleMetrics(s.value.value,o);else if(s.value.case==="streamHeader")this.handleStreamHeader(s.value.value,s.participantIdentity);else if(s.value.case==="streamChunk")this.handleStreamChunk(s.value.value);else if(s.value.case==="streamTrailer")this.handleStreamTrailer(s.value.value);else if(s.value.case==="rpcRequest"){const a=s.value.value;this.handleIncomingRpcRequest(s.participantIdentity,a.id,a.method,a.payload,a.responseTimeoutMs,a.version)}},this.handleUserPacket=(s,o,a)=>{this.emit(F.DataReceived,o.payload,s,a,o.topic),s?.emit(R.DataReceived,o.payload,a)},this.handleSipDtmf=(s,o)=>{this.emit(F.SipDTMFReceived,o,s),s?.emit(R.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(s,o)=>{const a=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),c=a?.trackPublications.get(o.trackId),l=IC(o,this.transcriptionReceivedTimes);c?.emit(I.TranscriptionReceived,l),a?.emit(R.TranscriptionReceived,l,c),this.emit(F.TranscriptionReceived,l,a,c)},this.handleChatMessage=(s,o)=>{const a=_C(o);this.emit(F.ChatMessage,a,s)},this.handleMetrics=(s,o)=>{this.emit(F.MetricsReceived,s,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(F.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=s=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:s})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(F.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(F.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(F.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>m(this,void 0,void 0,function*(){var s,o,a;const c=Fe.getInstance().previousDevices,l=yield Fe.getInstance().getDevices(void 0,!1),d=St();if(d?.name==="Chrome"&&d.os!=="iOS")for(let h of l){const f=c.find(p=>p.deviceId===h.deviceId);f&&f.label!==""&&f.kind===h.kind&&f.label!==h.label&&this.getActiveDevice(h.kind)==="default"&&this.emit(F.ActiveDeviceChanged,h.kind,h.deviceId)}const u=["audiooutput","audioinput","videoinput"];for(let h of u){const f=LC(h),p=this.localParticipant.getTrackPublication(f);if(p&&(!((s=p.track)===null||s===void 0)&&s.isUserProvided))continue;const g=l.filter(w=>w.kind===h),v=this.getActiveDevice(h);if(v===((o=c.filter(w=>w.kind===h)[0])===null||o===void 0?void 0:o.deviceId)&&g.length>0&&((a=g[0])===null||a===void 0?void 0:a.deviceId)!==v){yield this.switchActiveDevice(h,g[0].deviceId);continue}h==="audioinput"&&!gA()||h==="videoinput"||g.length>0&&!g.find(w=>w.deviceId===this.getActiveDevice(h))&&(yield this.switchActiveDevice(h,g[0].deviceId))}this.emit(F.MediaDevicesChanged)}),this.handleRoomUpdate=s=>{const o=this.roomInfo;this.roomInfo=s,o&&o.metadata!==s.metadata&&this.emitWhenConnected(F.RoomMetadataChanged,s.metadata),o?.activeRecording!==s.activeRecording&&this.emitWhenConnected(F.RecordingStatusChanged,s.activeRecording)},this.handleConnectionQualityUpdate=s=>{s.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const a=this.getRemoteParticipantBySid(o.participantSid);a&&a.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=s=>{this.emit(F.ParticipantMetadataChanged,s,this.localParticipant)},this.onLocalParticipantNameChanged=s=>{this.emit(F.ParticipantNameChanged,s,this.localParticipant)},this.onLocalAttributesChanged=s=>{this.emit(F.ParticipantAttributesChanged,s,this.localParticipant)},this.onLocalTrackMuted=s=>{this.emit(F.TrackMuted,s,this.localParticipant)},this.onLocalTrackUnmuted=s=>{this.emit(F.TrackUnmuted,s,this.localParticipant)},this.onTrackProcessorUpdate=s=>{var o;(o=s?.onPublish)===null||o===void 0||o.call(s,this)},this.onLocalTrackPublished=s=>m(this,void 0,void 0,function*(){var o,a,c,l,d,u;(o=s.track)===null||o===void 0||o.on(I.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.on(I.Restarted,this.onLocalTrackRestarted),(d=(l=(c=s.track)===null||c===void 0?void 0:c.getProcessor())===null||l===void 0?void 0:l.onPublish)===null||d===void 0||d.call(l,this),this.emit(F.LocalTrackPublished,s,this.localParticipant),rn(s.track)&&(yield s.track.checkForSilence())&&this.emit(F.LocalAudioSilenceDetected,s);const h=yield(u=s.track)===null||u===void 0?void 0:u.getDeviceId(!1),f=Zh(s.source);f&&h&&h!==this.localParticipant.activeDeviceMap.get(f)&&(this.localParticipant.activeDeviceMap.set(f,h),this.emit(F.ActiveDeviceChanged,f,h))}),this.onLocalTrackUnpublished=s=>{var o,a;(o=s.track)===null||o===void 0||o.off(I.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.off(I.Restarted,this.onLocalTrackRestarted),this.emit(F.LocalTrackUnpublished,s,this.localParticipant)},this.onLocalTrackRestarted=s=>m(this,void 0,void 0,function*(){const o=yield s.getDeviceId(!1),a=Zh(s.source);a&&o&&o!==this.localParticipant.activeDeviceMap.get(a)&&(this.log.debug("local track restarted, setting ".concat(a," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(a,o),this.emit(F.ActiveDeviceChanged,a,o))}),this.onLocalConnectionQualityChanged=s=>{this.emit(F.ConnectionQualityChanged,s,this.localParticipant)},this.onMediaDevicesError=s=>{this.emit(F.MediaDevicesError,s)},this.onLocalParticipantPermissionsChanged=s=>{this.emit(F.ParticipantPermissionsChanged,s,this.localParticipant)},this.onLocalChatMessageSent=s=>{this.emit(F.ChatMessage,s,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},nb),e),this.log=qt((n=this.options.loggerName)!==null&&n!==void 0?n:Et.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},df),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},uf),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Ab),e?.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new ze,this.localParticipant=new Rb("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",mA(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",mA(this.options.audioCaptureDefaults.deviceId)),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&this.switchActiveDevice("audiooutput",mA(this.options.audioOutput.deviceId)).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),tt()){const s=new AbortController;(r=navigator.mediaDevices)===null||r===void 0||r.addEventListener("devicechange",this.handleDeviceChange,{signal:s.signal}),sn.cleanupRegistry&&sn.cleanupRegistry.register(this,()=>{s.abort()})}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(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)}handleIncomingRpcRequest(e,t,n,i,r,s){return m(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),s!==1){yield this.engine.publishRpcResponse(e,t,null,me.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(n);if(!o){yield this.engine.publishRpcResponse(e,t,null,me.builtIn("UNSUPPORTED_METHOD"));return}let a=null,c=null;try{const l=yield o({requestId:t,callerIdentity:e,payload:i,responseTimeout:r});bc(l)>hf?(a=me.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(n))):c=l}catch(l){l instanceof me?a=l:(console.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),l),a=me.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)})}setE2EEEnabled(e){return m(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;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new KC(this.options.e2ee),this.e2eeManager.on(fA.ParticipantEncryptionStatusChanged,(t,n)=>{RC(n)&&(this.isE2EEEnabled=t),this.emit(F.ParticipantEncryptionStatusChanged,t,n)}),this.e2eeManager.on(fA.EncryptionError,t=>this.emit(F.EncryptionError,t)),(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 m(this,void 0,void 0,function*(){return this.state===Z.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const n=i=>{i.sid!==""&&(this.engine.off(_.RoomUpdate,n),e(i.sid))};this.engine.on(_.RoomUpdate,n),this.once(F.Disconnected,()=>{this.engine.off(_.RoomUpdate,n),t("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 Bb(this.options),this.engine.on(_.ParticipantUpdate,this.handleParticipantUpdates).on(_.RoomUpdate,this.handleRoomUpdate).on(_.SpeakersChanged,this.handleSpeakersChanged).on(_.StreamStateChanged,this.handleStreamStateUpdate).on(_.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(_.SubscriptionError,this.handleSubscriptionError).on(_.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(_.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(_.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(_.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(_.DataPacketReceived,this.handleDataPacket).on(_.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Z.SignalReconnecting)&&this.emit(F.SignalReconnecting)}).on(_.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Z.Connected)&&this.emit(F.Reconnected)}).on(_.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Z.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(_.Restarting,this.handleRestarting).on(_.SignalRestarted,this.handleSignalRestarted).on(_.Offline,()=>{this.setAndEmitConnectionState(Z.Reconnecting)&&this.emit(F.Reconnecting)}).on(_.DCBufferStatusChanged,(e,t)=>{this.emit(F.DCBufferStatusChanged,e,t)}).on(_.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(n=>{let{trackSid:i}=n;return i===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(R.LocalTrackSubscribed,t),this.emitWhenConnected(F.LocalTrackSubscribed,t,this.localParticipant)}).on(_.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,n)=>{this.handleParticipantDisconnected(n,t)}),this.emit(F.Moved,e.room.name,e.token),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))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return Fe.getInstance().getDevices(e,t)}prepareConnection(e,t){return m(this,void 0,void 0,function*(){if(this.state===Z.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Ac(new URL(e))&&t){this.regionUrlProvider=new Tc(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===Z.Disconnected&&(this.regionUrl=n,yield fetch(oc(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(oc(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:n}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return m(this,void 0,void 0,function*(){let n=()=>{},i;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new Dt({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new Dt({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new Dt({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new Dt({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":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new Dt({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new Dt({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":i=new Dt({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>m(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new zr({reason:bt.CLIENT_INITIATED,action:Hn.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");i=new Dt({scenario:{case:"subscriberBandwidth",value:nn(t)}});break;case"leave-full-reconnect":i=new Dt({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return m(this,arguments,void 0,function(n,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,a,c,l,d,u,h,f;let p=!0,g=!1;const v=s?{exact:i}:i;if(n==="audioinput"){g=r.localParticipant.audioTrackPublications.size===0;const w=(o=r.getActiveDevice(n))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=v;const y=Array.from(r.localParticipant.audioTrackPublications.values()).filter(B=>B.source===T.Source.Microphone);try{p=(yield Promise.all(y.map(B=>{var C;return(C=B.audioTrack)===null||C===void 0?void 0:C.setDeviceId(v)}))).every(B=>B===!0)}catch(B){throw r.options.audioCaptureDefaults.deviceId=w,B}}else if(n==="videoinput"){g=r.localParticipant.videoTrackPublications.size===0;const w=(a=r.getActiveDevice(n))!==null&&a!==void 0?a:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=v;const y=Array.from(r.localParticipant.videoTrackPublications.values()).filter(B=>B.source===T.Source.Camera);try{p=(yield Promise.all(y.map(B=>{var C;return(C=B.videoTrack)===null||C===void 0?void 0:C.setDeviceId(v)}))).every(B=>B===!0)}catch(B){throw r.options.videoCaptureDefaults.deviceId=w,B}}else if(n==="audiooutput"){if(!tc()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");r.options.webAudioMix&&(i=(c=yield Fe.getInstance().normalizeDeviceId("audiooutput",i))!==null&&c!==void 0?c:""),(l=(f=r.options).audioOutput)!==null&&l!==void 0||(f.audioOutput={});const w=(d=r.getActiveDevice(n))!==null&&d!==void 0?d:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=i;try{r.options.webAudioMix&&((u=r.audioContext)===null||u===void 0||u.setSinkId(i)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(y=>y.setAudioOutput({deviceId:i})))}catch(y){throw r.options.audioOutput.deviceId=w,y}}return(g||n==="audiooutput")&&(r.localParticipant.activeDeviceMap.set(n,n==="audiooutput"&&((h=r.options.audioOutput)===null||h===void 0?void 0:h.deviceId)||i),r.emit(F.ActiveDeviceChanged,n,i)),p}()})}setupLocalParticipantEvents(){this.localParticipant.on(R.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(R.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(R.AttributesChanged,this.onLocalAttributesChanged).on(R.TrackMuted,this.onLocalTrackMuted).on(R.TrackUnmuted,this.onLocalTrackUnmuted).on(R.LocalTrackPublished,this.onLocalTrackPublished).on(R.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(R.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(R.MediaDevicesError,this.onMediaDevicesError).on(R.AudioStreamAcquired,this.startAudio).on(R.ChatMessage,this.onLocalChatMessageSent).on(R.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,n){if(this.state===Z.Connecting||this.state===Z.Reconnecting){const l=()=>{this.onTrackAdded(e,t,n),d()},d=()=>{this.off(F.Reconnected,l),this.off(F.Connected,l),this.off(F.Disconnected,d)};this.once(F.Reconnected,l),this.once(F.Connected,l),this.once(F.Disconnected,d);return}if(this.state===Z.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 i=CC(t.id),r=i[0];let s=i[1],o=e.id;if(s&&s.startsWith("TR")&&(o=s),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const a=Array.from(this.remoteParticipants.values()).find(l=>l.sid===r);if(!a){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={}),a.addSubscribedMediaTrack(e,o,t,n,c)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==Z.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(i=>{i.trackPublications.forEach(r=>{i.unpublishTrack(r.trackSid)})}),this.localParticipant.trackPublications.forEach(i=>{var r,s,o;i.track&&this.localParticipant.unpublishTrack(i.track,e),e?((r=i.track)===null||r===void 0||r.detach(),(s=i.track)===null||s===void 0||s.stop()):(o=i.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(R.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(R.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(R.AttributesChanged,this.onLocalAttributesChanged).off(R.TrackMuted,this.onLocalTrackMuted).off(R.TrackUnmuted,this.onLocalTrackUnmuted).off(R.LocalTrackPublished,this.onLocalTrackPublished).off(R.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(R.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(R.MediaDevicesError,this.onMediaDevicesError).off(R.AudioStreamAcquired,this.startAudio).off(R.ChatMessage,this.onLocalChatMessageSent).off(R.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),tt()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(n=navigator.mediaDevices)===null||n===void 0||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Z.Disconnected),this.emit(F.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(i=>{t.unpublishTrack(i.trackSid,!0)}),this.emit(F.ParticipantDisconnected,t),t.setDisconnected(),(n=this.localParticipant)===null||n===void 0||n.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return m(this,void 0,void 0,function*(){var n;if(e.contentHeader.case==="byteHeader"){const i=this.byteStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let r;const s={id:e.streamId,name:(n=e.contentHeader.value.name)!==null&&n!==void 0?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:ls(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{r=a,this.byteStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now()})}});i(new yb(s,o,ls(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const i=this.textStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let r;const s={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{r=a,this.textStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now()})}});i(new Eb(s,o,ls(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const n=this.textStreamControllers.get(e.streamId);n&&e.content.length>0&&n.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return m(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=Yh())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(i=>i.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),et(200)])}catch(i){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:i}))}const n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(F.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let i;return t?i=vs.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):i=new vs(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&i.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),i}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}const n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(F.ParticipantConnected,n),n.on(R.TrackPublished,i=>{this.emitWhenConnected(F.TrackPublished,i,n)}).on(R.TrackSubscribed,(i,r)=>{i.kind===T.Kind.Audio?(i.on(I.AudioPlaybackStarted,this.handleAudioPlaybackStarted),i.on(I.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):i.kind===T.Kind.Video&&(i.on(I.VideoPlaybackFailed,this.handleVideoPlaybackFailed),i.on(I.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(F.TrackSubscribed,i,r,n)}).on(R.TrackUnpublished,i=>{this.emit(F.TrackUnpublished,i,n)}).on(R.TrackUnsubscribed,(i,r)=>{this.emit(F.TrackUnsubscribed,i,r,n)}).on(R.TrackMuted,i=>{this.emitWhenConnected(F.TrackMuted,i,n)}).on(R.TrackUnmuted,i=>{this.emitWhenConnected(F.TrackUnmuted,i,n)}).on(R.ParticipantMetadataChanged,i=>{this.emitWhenConnected(F.ParticipantMetadataChanged,i,n)}).on(R.ParticipantNameChanged,i=>{this.emitWhenConnected(F.ParticipantNameChanged,i,n)}).on(R.AttributesChanged,i=>{this.emitWhenConnected(F.ParticipantAttributesChanged,i,n)}).on(R.ConnectionQualityChanged,i=>{this.emitWhenConnected(F.ConnectionQualityChanged,i,n)}).on(R.ParticipantPermissionsChanged,i=>{this.emitWhenConnected(F.ParticipantPermissionsChanged,i,n)}).on(R.TrackSubscriptionStatusChanged,(i,r)=>{this.emitWhenConnected(F.TrackSubscriptionStatusChanged,i,r,n)}).on(R.TrackSubscriptionFailed,(i,r)=>{this.emit(F.TrackSubscriptionFailed,i,n,r)}).on(R.TrackSubscriptionPermissionChanged,(i,r)=>{this.emitWhenConnected(F.TrackSubscriptionPermissionChanged,i,r,n)}).on(R.Active,()=>{this.emitWhenConnected(F.ParticipantActive,n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((n,i)=>(n.push(...i.getTrackPublications()),n),[]),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&&xC(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=_e.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,bt.STATE_MISMATCH))):e=0},Lb)}clearConnectionReconcile(){this.connectionReconcileInterval&&_e.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(F.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];if(this.state===Z.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===Z.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return m(this,void 0,void 0,function*(){var t,n;const i=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Wr({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:he.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new YA({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(F.SignalConnected),this.emit(F.Connected),this.setAndEmitConnectionState(Z.Connected),i.video){const s=new Qc(T.Kind.Video,new On({source:Ee.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ct.AUDIO,name:"video-dummy"}),new gs(i.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Jh(160*((t=r.aspectRatios[0])!==null&&t!==void 0?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(R.LocalTrackPublished,s)}if(i.audio){const s=new Qc(T.Kind.Audio,new On({source:Ee.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ct.AUDIO}),new fs(i.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:rc(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(R.LocalTrackPublished,s)}for(let s=0;s<r.count-1;s+=1){let o=new YA({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(s),state:Dn.ACTIVE,tracks:[],joinedAt:he.parse(Date.now())});const a=this.getOrCreateParticipant(o.identity,o);if(r.video){const c=Jh(160*((n=r.aspectRatios[s%r.aspectRatios.length])!==null&&n!==void 0?n:1),160,!1,!0),l=new On({source:Ee.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ct.AUDIO});a.addSubscribedMediaTrack(c,l.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,l]}if(r.audio){const c=rc(),l=new On({source:Ee.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ct.AUDIO});a.addSubscribedMediaTrack(c,l.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,l]}a.updateInfo(o)}})}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];if(e!==F.ActiveSpeakersChanged&&e!==F.TranscriptionReceived){const r=kf(n).filter(s=>s!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...n)}}sn.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(A=>{A()});function kf(A){return A.map(e=>{if(e)return Array.isArray(e)?kf(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var kt;(function(A){A[A.IDLE=0]="IDLE",A[A.RUNNING=1]="RUNNING",A[A.SKIPPED=2]="SKIPPED",A[A.SUCCESS=3]="SUCCESS",A[A.FAILED=4]="FAILED"})(kt||(kt={}));class bA extends Ot.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=kt.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new sn(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return m(this,void 0,void 0,function*(){if(this.status!==kt.IDLE)throw Error("check is running already");this.setStatus(kt.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!==kt.SKIPPED&&this.setStatus(this.isSuccess()?kt.SUCCESS:kt.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return m(this,void 0,void 0,function*(){return this.room.state===Z.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return m(this,void 0,void 0,function*(){this.room&&this.room.state!==Z.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(kt.SKIPPED)}switchProtocol(e){return m(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(F.Reconnecting,()=>{t=!0}),this.room.once(F.Reconnected,()=>{n=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const i=Date.now()+1e4;for(;Date.now()<i;){if(n)return;yield et(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 Db extends bA{get description(){return"Cloud regions"}perform(){return m(this,void 0,void 0,function*(){const e=new Tc(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],n=new Set;for(let r=0;r<3;r++){const s=yield e.getNextBestRegionUrl();if(!s)break;if(n.has(s))continue;n.add(s);const o=yield this.checkCloudRegion(s);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((r,s)=>(r.duration-s.duration)*.5+(r.rtt-s.rtt)*.5);const i=t[0];this.bestStats=i,this.appendMessage("best Cloud region: ".concat(i.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return m(this,void 0,void 0,function*(){var t,n;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const i=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!i)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),s=1e3,a=1e6/s,c="A".repeat(s),l=Date.now();for(let f=0;f<a;f++)yield r.write(c);yield r.close();const d=Date.now(),u=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),h={region:i,rtt:1e4,duration:d-l};return u?.forEach(f=>{f.type==="candidate-pair"&&f.nominated&&(h.rtt=f.currentRoundTripTime*1e3)}),yield this.disconnect(),h})}}const Ic=1e4;class Ob extends bA{get description(){return"Connection via UDP vs TCP"}perform(){return m(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 n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/(Ic/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(Ic/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return m(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 n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let i=0;const r=()=>{i=(i+1)%360,n.fillStyle="hsl(".concat(i,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const o=t.captureStream(30).getVideoTracks()[0],c=(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},d=setInterval(()=>m(this,void 0,void 0,function*(){const u=yield c.getRTCStatsReport();u?.forEach(h=>{h.type==="outbound-rtp"?(l.packetsSent=h.packetsSent,l.qualityLimitationDurations=h.qualityLimitationDurations,l.bitrateTotal+=h.targetBitrate,l.count++):h.type==="remote-inbound-rtp"&&(l.packetsLost=h.packetsLost,l.rttTotal+=h.roundTripTime,l.jitterTotal+=h.jitter)})}),1e3);return yield new Promise(u=>setTimeout(u,Ic)),clearInterval(d),o.stop(),t.remove(),yield this.disconnect(),l})}}class Hb extends bA{get description(){return"Can publish audio"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Ib();if(yield zh(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise(o=>setTimeout(o,3e3));const r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(s=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," audio packets"))})}}class Mb extends bA{get description(){return"Can publish video"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Qb();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise(s=>setTimeout(s,5e3));const i=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let r=0;if(i.forEach(s=>{s.type==="outbound-rtp"&&(s.kind==="video"||!s.kind&&s.mediaType==="video")&&(r+=s.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return m(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const n=document.createElement("video");n.srcObject=t,n.muted=!0,yield new Promise(i=>{n.onplay=()=>{setTimeout(()=>{var r,s,o,a;const c=document.createElement("canvas"),l=e.getSettings(),d=(s=(r=l.width)!==null&&r!==void 0?r:n.videoWidth)!==null&&s!==void 0?s:1280,u=(a=(o=l.height)!==null&&o!==void 0?o:n.videoHeight)!==null&&a!==void 0?a:720;c.width=d,c.height=u;const h=c.getContext("2d");h.drawImage(n,0,0);const p=h.getImageData(0,0,c.width,c.height).data;let g=!0;for(let v=0;v<p.length;v+=4)if(p[v]!==0||p[v+1]!==0||p[v+2]!==0){g=!1;break}g?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),i()},1e3)},n.play()}),n.remove()})}}class Nb extends bA{get description(){return"Resuming connection after interruption"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect();let n=!1,i=!1,r;const s=new Promise(c=>{setTimeout(c,5e3),r=c}),o=()=>{n=!0};t.on(F.SignalReconnecting,o).on(F.Reconnecting,o).on(F.Reconnected,()=>{i=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const a=t.engine.client.onClose;if(a&&a(""),yield s,n){if(!i||t.state!==Z.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 Kb extends bA{get description(){return"Can connect via TURN"}perform(){return m(this,void 0,void 0,function*(){var e,t;const n=new hc,i=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,s=!1,o=!1;for(let a of i.iceServers)for(let c of a.urls)c.startsWith("turn:")?(s=!0,o=!0):c.startsWith("turns:")&&(s=!0,o=!0,r=!0),c.startsWith("stun:")&&(o=!0);o?s&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield n.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(a=>setTimeout(a,0)))})}}class $b extends bA{get description(){return"Establishing WebRTC connection"}perform(){return m(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(F.SignalConnected,()=>{const n=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,r)=>{if(i.candidate){const s=new RTCIceCandidate(i);let o="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(Vb(s.address)?o+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,o+=" (passive)"):s.protocol==="udp"&&(t=!0)),this.appendMessage(o)}n&&n(i,r)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=i=>{i instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(i.errorCode," ").concat(i.errorText," ").concat(i.url))})});try{yield this.connect(),j.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}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 Vb(A){const e=A.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 Gb extends bA{get description(){return"Connecting to signal connection via WebSocket"}perform(){return m(this,void 0,void 0,function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new hc;const r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===Qu.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=r.serverInfo)===null||n===void 0?void 0:n.region)),yield i.close()})}}class w2 extends Ot.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:kt.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!==kt.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return m(this,void 0,void 0,function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),i=s=>{this.updateCheck(t,s)};n.on("update",i);const r=yield n.run();return n.off("update",i),r})}checkWebsocket(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Gb)})}checkWebRTC(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck($b)})}checkTURN(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Kb)})}checkReconnect(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Nb)})}checkPublishAudio(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Hb)})}checkPublishVideo(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Mb)})}checkConnectionProtocol(){return m(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Ob);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Db)})}}const At=Symbol.for("@ts-pattern/matcher"),Ff=Symbol.for("@ts-pattern/isVariadic"),Bs="@ts-pattern/anonymous-select-key",_c=A=>!!(A&&typeof A=="object"),Cs=A=>A&&!!A[At],xe=(A,e,t)=>{if(Cs(A)){const n=A[At](),{matched:i,selections:r}=n.match(e);return i&&r&&Object.keys(r).forEach(s=>t(s,r[s])),i}if(_c(A)){if(!_c(e))return!1;if(Array.isArray(A)){if(!Array.isArray(e))return!1;let n=[],i=[],r=[];for(const s of A.keys()){const o=A[s];Cs(o)&&o[Ff]?r.push(o):r.length?i.push(o):n.push(o)}if(r.length){if(r.length>1)throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(e.length<n.length+i.length)return!1;const s=e.slice(0,n.length),o=i.length===0?[]:e.slice(-i.length),a=e.slice(n.length,i.length===0?1/0:-i.length);return n.every((c,l)=>xe(c,s[l],t))&&i.every((c,l)=>xe(c,o[l],t))&&(r.length===0||xe(r[0],a,t))}return A.length===e.length&&A.every((s,o)=>xe(s,e[o],t))}return Reflect.ownKeys(A).every(n=>{const i=A[n];return(n in e||Cs(r=i)&&r[At]().matcherType==="optional")&&xe(i,e[n],t);var r})}return Object.is(e,A)},ot=A=>{var e,t,n;return _c(A)?Cs(A)?(e=(t=(n=A[At]()).getSelectionKeys)==null?void 0:t.call(n))!=null?e:[]:Array.isArray(A)?Ki(A,ot):Ki(Object.values(A),ot):[]},Ki=(A,e)=>A.reduce((t,n)=>t.concat(e(n)),[]);function jb(...A){if(A.length===1){const[e]=A;return t=>xe(e,t,()=>{})}if(A.length===2){const[e,t]=A;return xe(e,t,()=>{})}throw new Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${A.length}.`)}function Re(A){return Object.assign(A,{optional:()=>Rc(A),and:e=>le(A,e),or:e=>Qf(A,e),select:e=>e===void 0?$i(A):$i(e,A)})}function xc(A){return Object.assign((e=>Object.assign(e,{[Symbol.iterator](){let t=0;const n=[{value:Object.assign(e,{[Ff]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var i;return(i=n[t++])!=null?i:n.at(-1)}}}}))(A),{optional:()=>xc(Rc(A)),select:e=>xc(e===void 0?$i(A):$i(e,A))})}function Rc(A){return Re({[At]:()=>({match:e=>{let t={};const n=(i,r)=>{t[i]=r};return e===void 0?(ot(A).forEach(i=>n(i,void 0)),{matched:!0,selections:t}):{matched:xe(A,e,n),selections:t}},getSelectionKeys:()=>ot(A),matcherType:"optional"})})}const Wb=(A,e)=>{for(const t of A)if(!e(t))return!1;return!0},Jb=(A,e)=>{for(const[t,n]of A.entries())if(!e(n,t))return!1;return!0};function le(...A){return Re({[At]:()=>({match:e=>{let t={};const n=(i,r)=>{t[i]=r};return{matched:A.every(i=>xe(i,e,n)),selections:t}},getSelectionKeys:()=>Ki(A,ot),matcherType:"and"})})}function Qf(...A){return Re({[At]:()=>({match:e=>{let t={};const n=(i,r)=>{t[i]=r};return Ki(A,ot).forEach(i=>n(i,void 0)),{matched:A.some(i=>xe(i,e,n)),selections:t}},getSelectionKeys:()=>Ki(A,ot),matcherType:"or"})})}function X(A){return{[At]:()=>({match:e=>({matched:!!A(e)})})}}function $i(...A){const e=typeof A[0]=="string"?A[0]:void 0,t=A.length===2?A[1]:typeof A[0]=="string"?void 0:A[0];return Re({[At]:()=>({match:n=>{let i={[e??Bs]:n};return{matched:t===void 0||xe(t,n,(r,s)=>{i[r]=s}),selections:i}},getSelectionKeys:()=>[e??Bs].concat(t===void 0?[]:ot(t))})})}function Mt(A){return typeof A=="number"}function wA(A){return typeof A=="string"}function yA(A){return typeof A=="bigint"}const If=Re(X(function(A){return!0})),Xb=If,EA=A=>Object.assign(Re(A),{startsWith:e=>{return EA(le(A,(t=e,X(n=>wA(n)&&n.startsWith(t)))));var t},endsWith:e=>{return EA(le(A,(t=e,X(n=>wA(n)&&n.endsWith(t)))));var t},minLength:e=>EA(le(A,(t=>X(n=>wA(n)&&n.length>=t))(e))),length:e=>EA(le(A,(t=>X(n=>wA(n)&&n.length===t))(e))),maxLength:e=>EA(le(A,(t=>X(n=>wA(n)&&n.length<=t))(e))),includes:e=>{return EA(le(A,(t=e,X(n=>wA(n)&&n.includes(t)))));var t},regex:e=>{return EA(le(A,(t=e,X(n=>wA(n)&&!!n.match(t)))));var t}}),qb=EA(X(wA)),Nt=A=>Object.assign(Re(A),{between:(e,t)=>Nt(le(A,((n,i)=>X(r=>Mt(r)&&n<=r&&i>=r))(e,t))),lt:e=>Nt(le(A,(t=>X(n=>Mt(n)&&n<t))(e))),gt:e=>Nt(le(A,(t=>X(n=>Mt(n)&&n>t))(e))),lte:e=>Nt(le(A,(t=>X(n=>Mt(n)&&n<=t))(e))),gte:e=>Nt(le(A,(t=>X(n=>Mt(n)&&n>=t))(e))),int:()=>Nt(le(A,X(e=>Mt(e)&&Number.isInteger(e)))),finite:()=>Nt(le(A,X(e=>Mt(e)&&Number.isFinite(e)))),positive:()=>Nt(le(A,X(e=>Mt(e)&&e>0))),negative:()=>Nt(le(A,X(e=>Mt(e)&&e<0)))}),zb=Nt(X(Mt)),SA=A=>Object.assign(Re(A),{between:(e,t)=>SA(le(A,((n,i)=>X(r=>yA(r)&&n<=r&&i>=r))(e,t))),lt:e=>SA(le(A,(t=>X(n=>yA(n)&&n<t))(e))),gt:e=>SA(le(A,(t=>X(n=>yA(n)&&n>t))(e))),lte:e=>SA(le(A,(t=>X(n=>yA(n)&&n<=t))(e))),gte:e=>SA(le(A,(t=>X(n=>yA(n)&&n>=t))(e))),positive:()=>SA(le(A,X(e=>yA(e)&&e>0))),negative:()=>SA(le(A,X(e=>yA(e)&&e<0)))}),Yb=SA(X(yA)),Zb=Re(X(function(A){return typeof A=="boolean"})),ew=Re(X(function(A){return typeof A=="symbol"})),tw=Re(X(function(A){return A==null})),Aw=Re(X(function(A){return A!=null}));var nw={__proto__:null,matcher:At,optional:Rc,array:function(...A){return xc({[At]:()=>({match:e=>{if(!Array.isArray(e))return{matched:!1};if(A.length===0)return{matched:!0};const t=A[0];let n={};if(e.length===0)return ot(t).forEach(r=>{n[r]=[]}),{matched:!0,selections:n};const i=(r,s)=>{n[r]=(n[r]||[]).concat([s])};return{matched:e.every(r=>xe(t,r,i)),selections:n}},getSelectionKeys:()=>A.length===0?[]:ot(A[0])})})},set:function(...A){return Re({[At]:()=>({match:e=>{if(!(e instanceof Set))return{matched:!1};let t={};if(e.size===0)return{matched:!0,selections:t};if(A.length===0)return{matched:!0};const n=(r,s)=>{t[r]=(t[r]||[]).concat([s])},i=A[0];return{matched:Wb(e,r=>xe(i,r,n)),selections:t}},getSelectionKeys:()=>A.length===0?[]:ot(A[0])})})},map:function(...A){return Re({[At]:()=>({match:e=>{if(!(e instanceof Map))return{matched:!1};let t={};if(e.size===0)return{matched:!0,selections:t};const n=(o,a)=>{t[o]=(t[o]||[]).concat([a])};if(A.length===0)return{matched:!0};var i;if(A.length===1)throw new Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(i=A[0])==null?void 0:i.toString()}`);const[r,s]=A;return{matched:Jb(e,(o,a)=>{const c=xe(r,a,n),l=xe(s,o,n);return c&&l}),selections:t}},getSelectionKeys:()=>A.length===0?[]:[...ot(A[0]),...ot(A[1])]})})},intersection:le,union:Qf,not:function(A){return Re({[At]:()=>({match:e=>({matched:!xe(A,e,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:X,select:$i,any:If,_:Xb,string:qb,number:zb,bigint:Yb,boolean:Zb,symbol:ew,nullish:tw,nonNullable:Aw,instanceOf:function(A){return Re(X(function(e){return t=>t instanceof e}(A)))},shape:function(A){return Re(X(jb(A)))}};let iw=class extends Error{constructor(e){let t;try{t=JSON.stringify(e)}catch{t=e}super(`Pattern matching error: no pattern matches value ${t}`),this.input=void 0,this.input=e}};const Pc={matched:!1,value:void 0};function Vi(A){return new rw(A,Pc)}let rw=class Hd{constructor(e,t){this.input=void 0,this.state=void 0,this.input=e,this.state=t}with(...e){if(this.state.matched)return this;const t=e[e.length-1],n=[e[0]];let i;e.length===3&&typeof e[1]=="function"?i=e[1]:e.length>2&&n.push(...e.slice(1,e.length-1));let r=!1,s={};const o=(c,l)=>{r=!0,s[c]=l},a=!n.some(c=>xe(c,this.input,o))||i&&!i(this.input)?Pc:{matched:!0,value:t(r?Bs in s?s[Bs]:s:this.input,this.input)};return new Hd(this.input,a)}when(e,t){if(this.state.matched)return this;const n=!!e(this.input);return new Hd(this.input,n?{matched:!0,value:t(this.input,this.input)}:Pc)}otherwise(e){return this.state.matched?this.state.value:e(this.input)}exhaustive(e=sw){return this.state.matched?this.state.value:e(this.input)}run(){return this.exhaustive()}returnType(){return this}};function sw(A){throw new iw(A)}const ow=/\{[^{}]+\}/g;function aw(){return Math.random().toString(36).slice(2,11)}function cw(A){let{baseUrl:e="",Request:t=globalThis.Request,fetch:n=globalThis.fetch,querySerializer:i,bodySerializer:r,headers:s,...o}={...A};e=Pf(e);const a=[];async function c(l,d){const{baseUrl:u,fetch:h=n,Request:f=t,headers:p,params:g={},parseAs:v="json",querySerializer:w,bodySerializer:y=r??dw,body:B,...C}=d||{};u&&(e=Pf(u));let b=typeof i=="function"?i:Rf(i);w&&(b=typeof w=="function"?w:Rf({...typeof i=="object"?i:{},...w}));const U=B===void 0?void 0:y(B),Q=U===void 0||U instanceof FormData?{}:{"Content-Type":"application/json"},x={redirect:"follow",...o,...C,body:U,headers:hw(Q,s,p,g.header)};let O,M,N=new t(uw(l,{baseUrl:e,params:g,querySerializer:b}),x);for(const V in C)V in N||(N[V]=C[V]);if(a.length){O=aw(),M=Object.freeze({baseUrl:e,fetch:h,parseAs:v,querySerializer:b,bodySerializer:y});for(const V of a)if(V&&typeof V=="object"&&typeof V.onRequest=="function"){const z=await V.onRequest({request:N,schemaPath:l,params:g,options:M,id:O});if(z){if(!(z instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");N=z}}}let $=await h(N);if(a.length)for(let V=a.length-1;V>=0;V--){const z=a[V];if(z&&typeof z=="object"&&typeof z.onResponse=="function"){const rt=await z.onResponse({request:N,response:$,schemaPath:l,params:g,options:M,id:O});if(rt){if(!(rt instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");$=rt}}}if($.status===204||$.headers.get("Content-Length")==="0")return $.ok?{data:{},response:$}:{error:{},response:$};if($.ok)return v==="stream"?{data:$.body,response:$}:{data:await $[v](),response:$};let He=await $.text();try{He=JSON.parse(He)}catch{}return{error:He,response:$}}return{GET(l,d){return c(l,{...d,method:"GET"})},PUT(l,d){return c(l,{...d,method:"PUT"})},POST(l,d){return c(l,{...d,method:"POST"})},DELETE(l,d){return c(l,{...d,method:"DELETE"})},OPTIONS(l,d){return c(l,{...d,method:"OPTIONS"})},HEAD(l,d){return c(l,{...d,method:"HEAD"})},PATCH(l,d){return c(l,{...d,method:"PATCH"})},TRACE(l,d){return c(l,{...d,method:"TRACE"})},use(...l){for(const d of l)if(d){if(typeof d!="object"||!("onRequest"in d||"onResponse"in d))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");a.push(d)}},eject(...l){for(const d of l){const u=a.indexOf(d);u!==-1&&a.splice(u,1)}}}}function bs(A,e,t){if(e==null)return"";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${A}=${t?.allowReserved===!0?e:encodeURIComponent(e)}`}function _f(A,e,t){if(!e||typeof e!="object")return"";const n=[],i={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(const o in e)n.push(o,t.allowReserved===!0?e[o]:encodeURIComponent(e[o]));const s=n.join(",");switch(t.style){case"form":return`${A}=${s}`;case"label":return`.${s}`;case"matrix":return`;${A}=${s}`;default:return s}}for(const s in e){const o=t.style==="deepObject"?`${A}[${s}]`:s;n.push(bs(o,e[s],t))}const r=n.join(i);return t.style==="label"||t.style==="matrix"?`${i}${r}`:r}function xf(A,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){const r={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",s=(t.allowReserved===!0?e:e.map(o=>encodeURIComponent(o))).join(r);switch(t.style){case"simple":return s;case"label":return`.${s}`;case"matrix":return`;${A}=${s}`;default:return`${A}=${s}`}}const n={simple:",",label:".",matrix:";"}[t.style]||"&",i=[];for(const r of e)t.style==="simple"||t.style==="label"?i.push(t.allowReserved===!0?r:encodeURIComponent(r)):i.push(bs(A,r,t));return t.style==="label"||t.style==="matrix"?`${n}${i.join(n)}`:i.join(n)}function Rf(A){return function(t){const n=[];if(t&&typeof t=="object")for(const i in t){const r=t[i];if(r!=null){if(Array.isArray(r)){if(r.length===0)continue;n.push(xf(i,r,{style:"form",explode:!0,...A?.array,allowReserved:A?.allowReserved||!1}));continue}if(typeof r=="object"){n.push(_f(i,r,{style:"deepObject",explode:!0,...A?.object,allowReserved:A?.allowReserved||!1}));continue}n.push(bs(i,r,A))}}return n.join("&")}}function lw(A,e){let t=A;for(const n of A.match(ow)??[]){let i=n.substring(1,n.length-1),r=!1,s="simple";if(i.endsWith("*")&&(r=!0,i=i.substring(0,i.length-1)),i.startsWith(".")?(s="label",i=i.substring(1)):i.startsWith(";")&&(s="matrix",i=i.substring(1)),!e||e[i]===void 0||e[i]===null)continue;const o=e[i];if(Array.isArray(o)){t=t.replace(n,xf(i,o,{style:s,explode:r}));continue}if(typeof o=="object"){t=t.replace(n,_f(i,o,{style:s,explode:r}));continue}if(s==="matrix"){t=t.replace(n,`;${bs(i,o)}`);continue}t=t.replace(n,s==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function dw(A){return A instanceof FormData?A:JSON.stringify(A)}function uw(A,e){let t=`${e.baseUrl}${A}`;e.params?.path&&(t=lw(t,e.params.path));let n=e.querySerializer(e.params.query??{});return n.startsWith("?")&&(n=n.substring(1)),n&&(t+=`?${n}`),t}function hw(...A){const e=new Headers;for(const t of A){if(!t||typeof t!="object")continue;const n=t instanceof Headers?t.entries():Object.entries(t);for(const[i,r]of n)if(r===null)e.delete(i);else if(Array.isArray(r))for(const s of r)e.append(i,s);else r!==void 0&&e.set(i,r)}return e}function Pf(A){return A.endsWith("/")?A.substring(0,A.length-1):A}class Lf{constructor(e){this.client=cw({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch})}setAuthToken(e){this.client.use({onRequest({request:t}){return t.headers.set("Authorization",`Bearer ${e}`),t}})}setApiToken(e){this.client.use({onRequest({request:t}){return t.headers.set("Authorization",`Token ${e}`),t}})}async getAuthUrl(e){return await this.client.GET("/api/auth/{type}",{params:{path:{type:e}}})}async getConnectUrl(e){return await this.client.GET("/api/connect/{type}",{params:{path:{type:e}}})}async logout(){return await this.client.POST("/api/logout")}async getCurrentUser(){return await this.client.GET("/api/me")}async createPresignedUploadUrl(e){return await this.client.POST("/api/files",{body:e})}async createKnowledgeBlock(e){return await this.client.POST("/api/knowledge",{body:e})}async listOnboardees(){return await this.client.GET("/api/onboardees")}async getOnboardee(e){return await this.client.GET("/api/onboardees/{id}",{params:{path:{id:e}}})}async getOnboardeeWidgetConfig(e,t){return await this.client.GET("/api/onboardees/{id}/config",{params:{path:{id:e}},signal:t})}async listPlans(){return await this.client.GET("/api/plans")}async listProducts(){return await this.client.GET("/api/products")}async getProduct(e){return await this.client.GET("/api/products/{id}",{params:{path:{id:e}}})}async createProduct(e){return await this.client.POST("/api/products",{body:e})}async updateProduct(e,t){return await this.client.PATCH("/api/products/{id}",{params:{path:{id:e}},body:t})}async createPlan(e){return await this.client.POST("/api/plans",{body:e})}async getPlan(e){return await this.client.GET("/api/plans/{id}",{params:{path:{id:e}}})}async replacePlan(e,t){return await this.client.PUT("/api/plans/{id}",{params:{path:{id:e}},body:t})}async updatePlan(e,t){return await this.client.PATCH("/api/plans/{id}",{params:{path:{id:e}},body:t})}async getPlanVideoUrl(e){return await this.client.GET("/api/plans/{id}/video-url",{params:{path:{id:e}}})}async deletePlan(e){return await this.client.DELETE("/api/admin/plans/{id}",{params:{path:{id:e}}})}async publishPlanRevision(e,t){return await this.client.POST("/api/plans/{id}/publish",{params:{path:{id:e}},body:t})}async listPlanRevisions(e){return await this.client.GET("/api/plans/{id}/revisions",{params:{path:{id:e}}})}async getRevisionNavigationIndex(e){return await this.client.GET("/api/revisions/{id}/navigation-index",{params:{path:{id:e}}})}async replaceRevisionNavigationIndex(e,t){return await this.client.PUT("/api/revisions/{id}/navigation-index",{params:{path:{id:e}},body:t})}async getRevisionFAQ(e){return await this.client.GET("/api/revisions/{id}/faq",{params:{path:{id:e}}})}async replaceRevisionFAQ(e,t){return await this.client.PUT("/api/revisions/{id}/faq",{params:{path:{id:e}},body:t})}async listRevisionKnowledgeBlocks(e){return await this.client.GET("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}}})}async getRevisionSteps(e){return await this.client.GET("/api/revisions/{id}/steps",{params:{path:{id:e}}})}async replaceRevisionKnowledgeBlocks(e,t){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async createRevisionKnowledgeBlock(e,t){return await this.client.POST("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async updateRevisionKnowledgeBlock(e,t,n){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:n})}async deleteRevisionKnowledgeBlock(e,t){return await this.client.DELETE("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async listSessions(e){return await this.client.GET("/api/sessions",{params:{query:{token:e}}})}async createSession(e){return await this.client.POST("/api/sessions",{body:e})}async getSession(e){return await this.client.GET("/api/sessions/{id}",{params:{path:{id:e}}})}async startSession(e,t){return await this.client.GET("/api/sessions/{id}/start-session",{params:{path:{id:e},query:{token:t}}})}async getSessionRecording(e){return await this.client.GET("/api/sessions/{id}/recording",{params:{path:{id:e}}})}async getSessionProductUrl(e){return await this.client.GET("/api/sessions/{id}/product-url",{params:{path:{id:e}}})}async updateSession(e,t){return await this.client.PATCH("/api/sessions/{id}",{params:{path:{id:e}},body:t})}async getJoinToken(e,{skipIntro:t,user:n}={}){return await this.client.GET("/api/join-token",{params:{query:{token:e,...t&&{skip_intro:"true"},...n&&{user:encodeURIComponent(n)}}}})}async trackEvent(e){return await this.client.POST("/api/track",{body:e})}getClient(){return this.client}}const fw="https://app.coragents.ai";var H;(function(A){A.READY="ready",A.ERROR="error",A.PAUSED="paused",A.LOADING="loading",A.THINKING="thinking",A.RESEARCHING="researching",A.AGENT_SPEAKING="agent_speaking",A.USER_SPEAKING="user_speaking",A.AWAITING_USER_INPUT="awaiting_user_input"})(H||(H={}));class pw{constructor({sessionId:e,apiBaseUrl:t,embedded:n,user:i}){this.currentState=H.READY,this.livekitState="speaking",this.embedded=!1,this.agentHasSpoken=!1,this.assistantAudioContext=null,this.userAudioContext=null,this._assistantAudioTimer=null,this._userAudioTimer=null,this.user=void 0,this.sessionId=e,this.apiBaseUrl=t||fw,this.embedded=n??!0,this.client=new Lf({baseUrl:this.apiBaseUrl}),this.emitter=new uv,this.user=i}emit(e,t){this.emitter.emit(e,t)}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}setupRoomEventListeners(){this.room&&(this.room.on(F.LocalTrackUnpublished,e=>{e.source===T.Source.ScreenShare&&(this.screenStream=void 0)}),this.room.on(F.Disconnected,()=>{this.disconnect()}),this.room.on(F.ParticipantDisconnected,()=>{this.disconnect()}),this.room.on(F.TrackSubscribed,(e,t,n)=>{if(e.kind==="audio"&&e.attach(),e.source===T.Source.Microphone&&n.identity.includes("agent-")){const i=e.mediaStream;if(!i){console.error("No media stream available for assistant track");return}const r=new AudioContext,s=r.createAnalyser();r.createMediaStreamSource(i).connect(s),s.fftSize=2048;const a=new Uint8Array(s.frequencyBinCount);this.analyzeAudio(s,a,"ASSISTANT"),this.assistantAudioContext=r}}),this.room.on(F.ParticipantAttributesChanged,e=>{if(!e["lk.agent.state"]||this.currentState===H.RESEARCHING||this.currentState===H.PAUSED)return;const t=e["lk.agent.state"];if(t==="speaking"&&(this.agentHasSpoken=!0),!this.agentHasSpoken)return;const n=Vi(t).with("listening",()=>H.USER_SPEAKING).with("speaking",()=>H.AGENT_SPEAKING).with("thinking",()=>H.THINKING).otherwise(()=>{});n&&(this.setState(n),this.livekitState=t)}),this.room.on(F.DataReceived,async e=>{console.debug("[obi] data received",e);try{const t=JSON.parse(new TextDecoder().decode(e)),n=t.status||t.request;Vi(n).with("using_tool",()=>{this.currentState=H.RESEARCHING,this.emitter.emit("stateChanged",H.RESEARCHING)}).with("using_tool_ended",()=>{this.currentState=H.AGENT_SPEAKING,this.emitter.emit("stateChanged",H.AGENT_SPEAKING)}).with("share_mic",()=>{this.emitter.emit("micShareRequested")}).with("share_screen",()=>{this.emitter.emit("screenShareRequested")}).with("prompt_user",()=>{console.log("[obi] prompt user received"),this.emitter.emit("promptUser")}).with("capture_page_html",()=>{this.emitter.emit("capturePageHTML")}).with("fill",()=>{this.emitter.emit("fill",t.value)}).otherwise(()=>{console.warn("Unknown data received:",t)})}catch(t){console.error("Error parsing data:",t)}}),this.room.localParticipant.registerRpcMethod("screen_capture",async e=>(this.emitter.emit("screenCaptureRequested"),new Promise(t=>{this.emitter.once("screenCaptureComplete",async n=>{if(n==="error"){t("error");return}try{await this.room.localParticipant.sendFile(new File([n],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),t("ok")}catch{t("error")}})}))),this.room.localParticipant.registerRpcMethod("mic_check",async e=>await this.checkMic()?"ok":"error"))}async connect(){if(!this.sessionId){console.error("[obi] no session ID found"),this.emitter.emit("error",new Error("No session ID provided"));return}try{this.room=new sn({adaptiveStream:!0,dynacast:!0}),this.setupRoomEventListeners();const e=await this.client.getJoinToken(this.sessionId,{skipIntro:this.embedded,...this.user&&{user:JSON.stringify(this.user)}});return await this.room.connect(e.data.url,e.data.token),this.emitter.emit("connected"),{url:e.data.url,token:e.data.token}}catch(e){throw console.error("Failed to connect to LiveKit:",e),this.disconnect(),this.emitter.emit("error",e instanceof Error?e:new Error(String(e))),e}}async disconnect(){this.room&&(this.room.disconnect(!0),this.room.removeAllListeners(),this.room=void 0),this.screenStream?.track&&this.screenStream.track.stop(),this.microphoneStream&&this.microphoneStream.getTracks().forEach(e=>e.stop()),this._userAudioTimer&&(window.clearTimeout(this._userAudioTimer),this._userAudioTimer=null),this._assistantAudioTimer&&(window.clearTimeout(this._assistantAudioTimer),this._assistantAudioTimer=null),await this.userAudioContext?.close().catch(()=>{}),this.userAudioContext=null,await this.assistantAudioContext?.close().catch(()=>{}),this.assistantAudioContext=null,this.setState(H.READY),this.emitter.emit("disconnected")}setState(e){e!==this.currentState&&(this.currentState=e,this.emitter.emit("stateChanged",e))}getCurrentState(){return this.currentState}async checkMic(){let e=!1;try{e=(await navigator.permissions.query({name:"microphone"})).state==="granted"}catch(t){console.error("[obi] error checking microphone permission:",t)}return e&&await this.shareMic(),this.emitter.emit("micCheck",e),e}async requestMicrophone(){try{const e=await navigator.mediaDevices.getUserMedia({audio:!0});this.microphoneStream=e;const t=new AudioContext;this.userAudioContext=t;const n=t.createAnalyser(),i=t.createMediaStreamSource(e),r=t.createGain();r.gain.value=1.5,i.connect(r),r.connect(n),n.fftSize=2048;const s=new Uint8Array(n.frequencyBinCount);this.analyzeAudio(n,s,"USER")}catch(e){throw console.error("Microphone permission denied:",e),new Error("Microphone permission denied")}}async shareMic(){if(!this.room){console.warn("[obi] shareMic called while not connected");return}this.emitter.emit("preMicShare");try{if(await this.requestMicrophone(),!this.microphoneStream){console.warn("[obi] failed to share microphone");return}const e=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(e,{name:"microphone",source:T.Source.Microphone}),await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"share_mic",success:!0})),{reliable:!0}),this.emitter.emit("micShared")}catch(e){console.error("[obi] error sharing microphone:",e),this.emitter.emit("error",e instanceof Error?e:new Error(String(e)))}}async shareScreen(){if(!this.room){console.warn("[obi] shareScreen called while not connected");return}this.emitter.emit("preScreenShare");try{if(this.screenStream=await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),!this.screenStream){console.warn("Failed to share screen");return}await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"share_screen",success:!0})),{reliable:!0}),this.emitter.emit("screenShared")}catch(e){console.error("Error sharing screen:",e),this.emitter.emit("error",e instanceof Error?e:new Error(String(e)))}}pauseRecording(){this.room&&(this.setState(H.PAUSED),this.room.localParticipant.getTrackPublications().forEach(e=>{e.handleMuted(),e.track?.mediaStream?.getTracks().forEach(t=>t.enabled=!1)}),this.microphoneStream?.getTracks().forEach(e=>e.enabled=!1),this.screenStream?.track?.mute())}resumeRecording(){if(!this.room)return;const e=Vi(this.livekitState).with("listening",()=>H.USER_SPEAKING).with("speaking",()=>H.AGENT_SPEAKING).otherwise(()=>H.THINKING);this.setState(e),this.room.localParticipant.getTrackPublications().forEach(t=>{t.handleUnmuted(),t.track?.mediaStream?.getTracks().forEach(n=>n.enabled=!0)}),this.microphoneStream?.getTracks().forEach(t=>t.enabled=!0),this.screenStream?.track?.unmute()}async promptContinue(){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"prompt_user",success:!0})),{reliable:!0})}async analyzeAudio(e,t,n){if(n==="USER"&&this.currentState===H.USER_SPEAKING||n==="ASSISTANT"&&this.currentState===H.AGENT_SPEAKING){e.getByteFrequencyData(t);const i=t.reduce((o,a)=>o+a,0)/t.length,r=Math.max(.01,Math.min(1,i/128));let s;n==="USER"&&this.currentState===H.USER_SPEAKING?s="USER":n==="ASSISTANT"&&this.currentState===H.AGENT_SPEAKING&&(s="ASSISTANT"),s&&this.emitter.emit("volume",{speaker:s,spectrum:Array.from(t),volume:r})}n==="USER"?this._userAudioTimer=window.setTimeout(()=>this.analyzeAudio(e,t,n),200):this._assistantAudioTimer=window.setTimeout(()=>this.analyzeAudio(e,t,n),200)}async sendHTML(e){if(!this.room){console.log("Cannot send HTML: Not connected to room");return}try{const t={type:"page_content",html:e,timestamp:new Date().toISOString()},n=JSON.stringify(t),r=new TextEncoder().encode(n);await this.room.localParticipant.publishData(r,{reliable:!0})}catch(t){console.error("Error sending HTML to LiveKit:",t),this.emitter.emit("error",t instanceof Error?t:new Error(String(t)))}}async reconnect(e,t,n){try{if(!e||!t)return console.error("Missing room URL or token for reconnection"),this.emitter.emit("error",new Error("Missing room URL or token for reconnection")),!1;if(this.agentHasSpoken=!0,await this.requestMicrophone(),this.room=new sn({adaptiveStream:!0,dynacast:!0}),this.setupRoomEventListeners(),await this.room.connect(e,t),this.microphoneStream){const i=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(i,{name:"microphone",source:T.Source.Microphone})}return this.setState(n),n===H.PAUSED&&this.pauseRecording(),!0}catch(i){return console.error("Failed to reconnect to room:",i),this.disconnect(),this.emitter.emit("error",i instanceof Error?i:new Error(String(i))),!1}}async updateUser(e){if(!this.room)throw new Error("Cannot update user: No active session");const t=this.user;this.user=e;try{if(await this.client.updateSession(this.sessionId,{user:e?JSON.stringify(e):void 0}),this.room&&this.room.localParticipant){const n={type:"user_updated",user:e,timestamp:new Date().toISOString()},i=JSON.stringify(n),s=new TextEncoder().encode(i);await this.room.localParticipant.publishData(s,{reliable:!0})}this.emitter.emit("userUpdated",e)}catch(n){throw this.user=t,console.error("Failed to update user:",n),this.emitter.emit("error",n instanceof Error?n:new Error(String(n))),n}}}/**
43
43
  * @license
44
44
  * Copyright 2019 Google LLC
45
45
  * SPDX-License-Identifier: BSD-3-Clause
@@ -2541,7 +2541,7 @@ Url: ${$o(A)}`),!0}return!1}function yQ(A,e){return e?.length?zm(A).some(t=>Ro(t
2541
2541
  .disabled=${this.disabled}
2542
2542
  ></obi-voice-guidance-content>
2543
2543
  </obi-base-onboarding-modal>
2544
- `}}qA.styles=[Be],Ui([L({type:Object})],qA.prototype,"session",2),Ui([L({type:Boolean,reflect:!0})],qA.prototype,"open",2),Ui([L()],qA.prototype,"color",2),Ui([L({type:Boolean,reflect:!0})],qA.prototype,"disabled",2),Ui([L({type:Boolean,reflect:!0})],qA.prototype,"loading",2),Ui([L({type:Boolean,attribute:"close-disabled"})],qA.prototype,"closeDisabled",2),customElements.get("obi-voice-guidance-modal")||customElements.define("obi-voice-guidance-modal",qA);var h2=Object.defineProperty,f2=Object.getOwnPropertyDescriptor,Ce=(A,e,t,n)=>{for(var i=n>1?void 0:n?f2(e,t):e,r=A.length-1,s;r>=0;r--)(s=A[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&h2(e,t,i),i};let ue=class extends S.LitElement{constructor(){super(),this.apiKey="",this.isActive=!0,this.linkOnlyAccess=!1,this.urlBlacklist=[],this.position="bottom-right",this.user=null,this.state=H.READY,this.storedActiveState=void 0,this.showCourseModal=!1,this.showSessionStartModal=!1,this.showShareMicModal=!1,this.micShareEnabled=!1,this.showVoiceGuidanceModal=!1,this.voiceGuidanceEnabled=!1,this.selectedCourse=null,this.isHovering=!1,this.navVisible=!1,this.activeSession=null,this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.databaseConfig=null,this.configLoaded=!1,this.primaryColor="#9500FF",this.sessionToken=null,this.roomToken=null,this.roomUrl=null,this.boundSaveSessionData=null,this.obiClient=null,this.closeNavTimeoutRef=null,this.researchingTimeoutRef=null,this.urlCheckInterval=null,this.currentUrl="",this.connectObi=br(async e=>{if(this.activeSession){ee("connection_already_exists",{sessionToken:e},"ObiWidget"),console.log("Connection already exists");return}ee("session_connection_started",{sessionToken:e},"ObiWidget"),Cr({sessionId:e});try{const t=this.createSession(e);if(!t){this.handleSessionCreationFailure(()=>this.removeSessionUrlParams());return}this.setupSessionEventListeners(t,()=>this.removeSessionUrlParams()),t.on("screenCaptureRequested",br(async()=>{ee("screen_capture_requested",{},"ObiWidget");try{const r=(await q1(document.documentElement,{useCORS:!0,allowTaint:!0,foreignObjectRendering:!0})).toDataURL("image/png");this.activeSession.emit("screenCaptureComplete",r),ee("screen_capture_completed",{},"ObiWidget")}catch(i){$e(i,{componentName:"ObiWidget",handlerName:"screenCaptureRequested",sessionToken:e}),console.error("[obi] error capturing screen:",i),this.activeSession.emit("screenCaptureComplete","error"),ee("screen_capture_failed",{error:i instanceof Error?i.message:String(i)},"ObiWidget")}},"screenCaptureRequested","ObiWidget"));const n=await t.connect();n&&(this.sessionToken=e,this.roomToken=n.token,this.roomUrl=n.url,Cr({sessionId:e,widgetState:this.state.toString()}),this.removeSessionUrlParams(),ee("session_connection_established",{sessionToken:e,hasRoomToken:!!n.token},"ObiWidget")),this.activeSession=t}catch(t){console.error("Failed to start session:",t),$e(t,{componentName:"ObiWidget",handlerName:"connectObi",sessionToken:e}),this.handleSessionCreationFailure(()=>this.removeSessionUrlParams())}},"connectObi","ObiWidget"),this.handleCloseModals=()=>{this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null),this.state=H.READY,this.terminateSession(),this.showCourseModal=!1,this.showSessionStartModal=!1,this.showShareMicModal=!1},this.handleCourseSelectEvent=e=>{const t=e;this.selectedCourse=t.detail,this.showCourseModal=!1,this.showSessionStartModal=!0,this.showShareMicModal=!1,this.micShareEnabled=!1,this.showVoiceGuidanceModal=!1,this.voiceGuidanceEnabled=!1},this.handleUrlSessionEvent=br(async e=>{ee("url_session_event",{sessionToken:e},"ObiWidget");try{if(!this.obiClient){const n=new Error("ObiClient not initialized");$e(n,{componentName:"ObiWidget",handlerName:"handleUrlSessionEvent",sessionToken:e}),console.error("ObiClient not initialized");return}const t=await this.obiClient.startSession(e,this.apiKey);if(t.data){const{session:n}=t.data;if(console.log("[obi-sdk] session:",n),ee("session_started",{sessionId:n?.id,sessionToken:e},"ObiWidget"),n){const i=n;this.selectedCourse={id:e,name:i.onboarding_plan?.name||"",description:i.onboarding_plan?.description||""},this.state=H.LOADING,this.showSessionStartModal=!0,this.showShareMicModal=!1,this.micShareEnabled=!1,this.showVoiceGuidanceModal=!1,this.voiceGuidanceEnabled=!1,ee("matching_session_found",{sessionToken:e,hasOnboardingPlan:!!i.onboarding_plan},"ObiWidget")}else console.log("[obi-sdk] no session found with token:",e),ee("no_matching_session",{sessionToken:e},"ObiWidget")}}catch(t){console.error("Failed to fetch session details:",t),$e(t,{componentName:"ObiWidget",handlerName:"handleUrlSessionEvent",sessionToken:e})}},"handleUrlSessionEvent","ObiWidget"),this.handleSessionStart=br(async e=>{ee("session_start_requested",{sessionToken:e},"ObiWidget"),this.activeSession&&(ee("session_start_blocked",{sessionToken:e},"ObiWidget"),$e(new Error("Session start blocked"),{componentName:"ObiWidget",handlerName:"handleSessionStart",sessionToken:e}),this.activeSession.disconnect(),this.activeSession=null),this.showSessionStartModal=!1,this.showShareMicModal=!0,this.state=H.LOADING,Cr({widgetState:this.state.toString()}),await this.connectObi(e)},"handleSessionStart","ObiWidget"),this.handleSessionModalStart=e=>{const{sessionId:t,attempt:n}=e.detail;if(console.log("[SessionStartModal] Start button clicked",{sessionId:t,hasSession:!!this.selectedCourse,startAttempts:n,timestamp:new Date().toISOString()}),ee("session_start_modal_continue_clicked",{sessionId:t,sessionName:this.selectedCourse?.name},"SessionStartModal"),!this.selectedCourse){const i="Session data is missing.";console.error("[SessionStartModal] Validation failed:",i),$e(i,{componentName:"SessionStartModal",handlerName:"handleSessionModalStart",sessionData:this.selectedCourse});return}if(!this.selectedCourse.id){const i="Session ID is missing.";console.error("[SessionStartModal] Validation failed:",i,{session:this.selectedCourse}),$e(i,{componentName:"SessionStartModal",handlerName:"handleSessionModalStart",sessionData:this.selectedCourse});return}console.log("[SessionStartModal] Starting session attempt",{attempt:n,sessionId:this.selectedCourse.id}),ee("session_start_modal_calling_onStart",{sessionId:this.selectedCourse.id},"SessionStartModal"),this.handleSessionStart(this.selectedCourse.id),console.log("[SessionStartModal] Session start completed successfully",{sessionId:this.selectedCourse.id,attempt:n}),ee("session_start_modal_onStart_called",{sessionId:this.selectedCourse.id},"SessionStartModal")},this.handleSessionModalClose=()=>{console.log("[SessionStartModal] Close button clicked",{sessionId:this.selectedCourse?.id}),this.handleCloseModals(),this.selectedCourse=null,this.removeSessionUrlParams()},this.handleSessionModalError=e=>{const{error:t,sessionId:n}=e.detail;console.error("[SessionStartModal] Error occurred",{error:t instanceof Error?t.message:String(t),sessionId:n}),$e(t,{componentName:"SessionStartModal",handlerName:"handleSessionModalError",sessionId:n})},this.handleShareMicModalContinue=async e=>{const{session:t,micPermissionGranted:n}=e.detail;if(console.log("[ShareMicModal] Continue button clicked",{sessionId:t?.id,micPermissionGranted:n,timestamp:new Date().toISOString()}),ee("share_mic_modal_continue_clicked",{sessionId:t?.id,micPermissionGranted:n},"ShareMicModal"),!this.activeSession){console.error("[obi] no active session during microphone sharing");return}await this.activeSession.shareMic(),this.showShareMicModal=!1,this.showVoiceGuidanceModal=!0},this.handleShareMicModalClose=()=>{console.log("[ShareMicModal] Close button clicked",{sessionId:this.selectedCourse?.id}),this.handleCloseModals()},this.handleVoiceGuidanceModalContinue=async()=>{console.log("[obi] voice guidance modal continue",{sessionId:this.selectedCourse?.id,timestamp:new Date().toISOString()}),ee("voice_guidance_modal_continue_clicked",{sessionId:this.selectedCourse?.id},"ShareMicModal"),await this.activeSession?.promptContinue(),this.showVoiceGuidanceModal=!1},this.handleVoiceGuidanceModalClose=()=>{console.log("[obi] voice guidance modal close",{sessionId:this.selectedCourse?.id}),this.handleCloseModals()},this.checkExistingSession=br(async()=>{ee("checking_existing_session",{},"ObiWidget");try{const e=JSON.parse(Ed.getItem(yd.SESSION_DATA)||"{}"),{sessionToken:t,roomToken:n,roomUrl:i,sessionExpiry:r,obiState:s}=e;if(!t||!n||!i){ee("no_existing_session_data",{},"ObiWidget");return}if(console.log("[obi-sdk] using existing session"),ee("existing_session_data_found",{sessionToken:t,hasExpiry:!!r,obiState:s},"ObiWidget"),r&&new Date(r)<new Date){this.clearSessionStorage(),ee("session_expired",{sessionToken:t},"ObiWidget");return}this.state=H.LOADING,Cr({sessionId:t,widgetState:this.state.toString()});const o=this.createSession(t);if(!o){this.handleSessionCreationFailure(()=>this.clearSessionStorage());return}this.setupSessionEventListeners(o,()=>this.clearSessionStorage()),await o.reconnect(i,n,s)?(this.activeSession=o,this.sessionToken=t,this.roomToken=n,this.roomUrl=i,this.state=s,this.storedActiveState=s,ee("session_reconnected",{sessionToken:t,obiState:s},"ObiWidget")):(this.clearSessionStorage(),ee("session_reconnection_failed",{sessionToken:t},"ObiWidget"))}catch(e){console.error("Error reconnecting to session:",e),$e(e,{componentName:"ObiWidget",handlerName:"checkExistingSession"}),this.handleSessionCreationFailure(()=>this.clearSessionStorage())}},"checkExistingSession","ObiWidget");try{U0("ObiWidget").setContext(),this.obiClient=new Lf({baseUrl:Hc}),this.currentUrl=window.location.href;const t=()=>{try{this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl&&this.saveSessionData()}catch(n){$e(n,{componentName:"ObiWidget",handlerName:"handleUnload"})}};window.addEventListener("beforeunload",t),window.addEventListener("pagehide",t),ee("ObiWidget_constructor_completed",{},"ObiWidget")}catch(e){throw $e(e,{componentName:"ObiWidget",lifecycle:"constructor"}),e}}updateFromConfig(){window.obiWidgetConfig?(this.apiKey=window.obiWidgetConfig.apiKey||this.apiKey,window.obiWidgetConfig.position!==void 0&&(this.position=window.obiWidgetConfig.position,this.setAttribute("position",this.position)),window.obiWidgetConfig.primaryColor!==void 0&&(this.style.setProperty("--obi-primary",window.obiWidgetConfig.primaryColor),this.generateColorVariables(window.obiWidgetConfig.primaryColor)),window.obiWidgetConfig.user!==void 0&&(this.user=window.obiWidgetConfig.user),window.obiWidgetConfig.isActive!==void 0&&(this.isActive=window.obiWidgetConfig.isActive),window.obiWidgetConfig.linkOnlyAccess!==void 0&&(this.linkOnlyAccess=window.obiWidgetConfig.linkOnlyAccess),window.obiWidgetConfig.urlBlacklist!==void 0&&(this.urlBlacklist=window.obiWidgetConfig.urlBlacklist),this.fetchDatabaseConfig(),window.obiWidgetConfig.showMenu===!0&&(this.state=H.LOADING,this.showCourseModal=!0,window.obiWidgetConfig.showMenu=!1)):this.configLoaded||this.fetchDatabaseConfig()}generateColorVariables(e){try{this.primaryColor=e;const t=Mc(e,"#c4b5fd"),n=Mc(e,"#c76cff"),i=_w(e),r=Mc(e,"#A06DF9");this.style.setProperty("--obi-secondary",t),this.style.setProperty("--obi-course-selected",n),this.style.setProperty("--obi-course-selected-bg",i),this.style.setProperty("--obi-paused-pulse",r)}catch(t){console.warn("Failed to generate color variables:",t),this.style.setProperty("--obi-secondary","#c4b5fd"),this.style.setProperty("--obi-course-selected","#c76cff"),this.style.setProperty("--obi-course-selected-bg","#fbf3ff"),this.style.setProperty("--obi-paused-pulse","#A06DF9")}}removeSessionUrlParams(){const e=new URL(window.location.href);e.searchParams.delete($f),window.history.replaceState({},"",e.toString()),localStorage.removeItem("obi-url-params")}createSession(e){try{const t=new pw({sessionId:e,apiBaseUrl:Hc,...this.user&&{user:this.user}});return t||(console.error("Failed to create session"),null)}catch(t){return console.error("Error creating session:",t),null}}setupSessionEventListeners(e,t){e.on("stateChanged",n=>{if(n===H.RESEARCHING){this.researchingTimeoutRef&&window.clearTimeout(this.researchingTimeoutRef),this.state=n,this.researchingTimeoutRef=window.setTimeout(()=>{this.researchingTimeoutRef=null;const i=e.getCurrentState();this.state=i,i!==H.READY&&(this.storedActiveState=i)},1500),this.storedActiveState=n;return}this.researchingTimeoutRef===null&&(this.state=n,n!==H.READY&&(this.storedActiveState=n))}),e.on("volume",({speaker:n,spectrum:i,volume:r})=>{this.volume={speaker:n,spectrum:i,volume:r}}),e.on("error",n=>{console.error("Session error:",n),this.state=H.ERROR,this.activeSession=null,t&&t()}),e.on("micShareRequested",()=>{this.micShareEnabled=!0}),e.on("promptUser",()=>{this.voiceGuidanceEnabled=!0})}handleSessionCreationFailure(e){this.state=H.ERROR,this.activeSession=null,e&&e()}clearSessionStorage(){Ed.removeItem(yd.SESSION_DATA)}handleUrlChange(){this.requestUpdate(),Jo(this.urlBlacklist)&&this.activeSession&&this.terminateSession()}saveSessionData(){if(this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl){const e=new Date;e.setMinutes(e.getMinutes()+5);const t={sessionToken:this.sessionToken,roomToken:this.roomToken,roomUrl:this.roomUrl,obiState:this.storedActiveState??this.state,sessionExpiry:e.toISOString()};Ed.setItem(yd.SESSION_DATA,JSON.stringify(t))}}async sessionConnectionCheck(){const e=function(){let t={};return t=JSON.parse(localStorage.getItem("obi-url-params")||"{}"),Object.keys(t).length===0&&new URLSearchParams(window.location.search).forEach((i,r)=>{t[r]=i}),t[$f]}();if(!e){await this.checkExistingSession();return}console.log("[obi-sdk] using magic link"),this.apiKey?await this.handleUrlSessionEvent(e):(console.log("[obi-sdk] API key not ready, retrying..."),setTimeout(()=>{this.apiKey&&this.handleUrlSessionEvent(e)},100))}connectedCallback(){super.connectedCallback(),this.updateFromConfig(),this.addEventListener("obi-config-updated",this.handleConfigUpdate.bind(this)),this.setAttribute("position",this.position),this.boundSaveSessionData=this.saveSessionData.bind(this),window.addEventListener("beforeunload",this.boundSaveSessionData),window.addEventListener("pagehide",this.boundSaveSessionData),this.isActive&&(this.urlCheckInterval=window.setInterval(()=>{this.currentUrl!==window.location.href&&(this.currentUrl=window.location.href,this.handleUrlChange())},1e3)),this.addEventListener("course-select",this.handleCourseSelectEvent)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("obi-config-updated",this.handleConfigUpdate.bind(this)),this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.researchingTimeoutRef!==null&&(window.clearTimeout(this.researchingTimeoutRef),this.researchingTimeoutRef=null),this.boundSaveSessionData&&(window.removeEventListener("beforeunload",this.boundSaveSessionData),window.removeEventListener("pagehide",this.boundSaveSessionData)),this.urlCheckInterval!==null&&(clearInterval(this.urlCheckInterval),this.urlCheckInterval=null),this.removeSessionUrlParams()}async handleConfigUpdate(e){const n=e.detail,i=n.isActive&&!this.isActive,r=this.user;if(this.updateFromConfig(),this.activeSession&&n.user!==void 0){const s=n.user;if(JSON.stringify(r)!==JSON.stringify(s))try{await this.activeSession.updateUser(s)}catch(o){console.error("Failed to update session user data:",o)}}i&&!Jo(this.urlBlacklist)&&!this.activeSession&&this.sessionConnectionCheck(),this.requestUpdate()}handleMouseEnter(){this.isHovering=!0,this.navVisible=!0}handleMouseLeave(){this.isHovering=!1,this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.closeNavTimeoutRef=window.setTimeout(()=>{this.isHovering||(this.navVisible=!1),this.closeNavTimeoutRef=null},300)}terminateSession(){this.clearSessionStorage(),this.sessionToken=null,this.roomToken=null,this.roomUrl=null,this.researchingTimeoutRef!==null&&(window.clearTimeout(this.researchingTimeoutRef),this.researchingTimeoutRef=null),this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null),this.state=H.READY}handleItemSelect(e,t){if(e==="experiences"){this.showCourseModal=!0;return}Vi([e,t]).with(["pause",!0],()=>{this.activeSession?.pauseRecording()}).with(["pause",!1],()=>{this.activeSession?.resumeRecording()}).with(["activate",!1],()=>{this.terminateSession()}).otherwise(()=>{})}async fetchDatabaseConfig(){if(!this.apiKey){this.configLoaded=!0,this.applyFinalConfiguration();return}try{const e=`obi-widget-config-${this.apiKey}`,t=localStorage.getItem(e),n=localStorage.getItem(`${e}-timestamp`);if(t&&n){const a=Date.now()-parseInt(n,10),c=10*60*1e3;if(a<c){const l=JSON.parse(t);this.databaseConfig=l,this.configLoaded=!0,this.applyFinalConfiguration();return}}const i=new AbortController,r=setTimeout(()=>i.abort(),3e3),s=await this.obiClient.getOnboardeeWidgetConfig(this.apiKey,i.signal);if(clearTimeout(r),s.error){if(s.response?.status===404){localStorage.removeItem(e),localStorage.removeItem(`${e}-timestamp`),this.databaseConfig=null,this.configLoaded=!0,this.applyFinalConfiguration();return}throw new Error(`HTTP ${s.response?.status||"Unknown error"}`)}const o=s.data;localStorage.setItem(e,JSON.stringify(o)),localStorage.setItem(`${e}-timestamp`,Date.now().toString()),this.databaseConfig=o,this.configLoaded=!0,this.applyFinalConfiguration()}catch(e){e instanceof Error&&e.name==="AbortError"?console.warn("Widget config fetch timed out, using defaults"):console.warn("Failed to fetch widget config from database:",e),this.databaseConfig=null,this.configLoaded=!0,this.applyFinalConfiguration()}}applyFinalConfiguration(){const e=window.obiWidgetConfig,t=this.databaseConfig;this.user=e?.user||this.user,this.position=e?.position||t?.position||this.position,this.setAttribute("position",this.position),e?.isActive!==void 0&&(this.isActive=e.isActive),e?.linkOnlyAccess!==void 0?this.linkOnlyAccess=e.linkOnlyAccess:t?.linkOnlyAccess!==void 0&&(this.linkOnlyAccess=t.linkOnlyAccess);const n=e?.urlBlacklist||[],i=t?.urlBlacklist||[];if(n.length>0||i.length>0){const s=[...n,...i];this.urlBlacklist=[...new Set(s)]}const r=e?.primaryColor||t?.primaryColor||Es;this.primaryColor=r,this.style.setProperty("--obi-primary",r),this.generateColorVariables(r),this.isActive&&!Jo(this.urlBlacklist)&&!this.activeSession&&this.sessionConnectionCheck()}render(){if(!this.configLoaded||!this.isActive||this.linkOnlyAccess&&this.state===H.READY||Jo(this.urlBlacklist))return S.nothing;const e=Vi(this.state).with(H.LOADING,()=>S.html`<obi-dot-loader></obi-dot-loader>`).with(H.RESEARCHING,()=>S.html`<obi-searching-loader></obi-searching-loader>`).with(nw.union(H.USER_SPEAKING,H.AGENT_SPEAKING),()=>S.html`<obi-audio-equalizer .volume=${this.volume}></obi-audio-equalizer>`).with(H.THINKING,()=>S.html`<obi-dot-loader></obi-dot-loader>`).with(H.PAUSED,()=>Sd).otherwise(()=>Sd),t=this.state===H.USER_SPEAKING||this.state===H.AGENT_SPEAKING,n=this.state===H.PAUSED,i=this.state===H.RESEARCHING,r=this.state===H.USER_SPEAKING,s=this.state!==H.READY||this.navVisible,o=this.state!==H.READY||this.navVisible,a=this.position.includes("top")?"down":"up",c=["widget-container",s?"rotated":"",t?"pulse":"",n?"paused-pulse":"",i?"researching":"",r?"user-speaking":""].filter(Boolean).join(" ");return S.html`
2544
+ `}}qA.styles=[Be],Ui([L({type:Object})],qA.prototype,"session",2),Ui([L({type:Boolean,reflect:!0})],qA.prototype,"open",2),Ui([L()],qA.prototype,"color",2),Ui([L({type:Boolean,reflect:!0})],qA.prototype,"disabled",2),Ui([L({type:Boolean,reflect:!0})],qA.prototype,"loading",2),Ui([L({type:Boolean,attribute:"close-disabled"})],qA.prototype,"closeDisabled",2),customElements.get("obi-voice-guidance-modal")||customElements.define("obi-voice-guidance-modal",qA);var h2=Object.defineProperty,f2=Object.getOwnPropertyDescriptor,Ce=(A,e,t,n)=>{for(var i=n>1?void 0:n?f2(e,t):e,r=A.length-1,s;r>=0;r--)(s=A[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&h2(e,t,i),i};let ue=class extends S.LitElement{constructor(){super(),this.apiKey="",this.isActive=!0,this.linkOnlyAccess=!1,this.urlBlacklist=[],this.position="bottom-right",this.user=null,this.state=H.READY,this.storedActiveState=void 0,this.showCourseModal=!1,this.showSessionStartModal=!1,this.showShareMicModal=!1,this.micShareEnabled=!1,this.showVoiceGuidanceModal=!1,this.voiceGuidanceEnabled=!1,this.selectedCourse=null,this.isHovering=!1,this.navVisible=!1,this.activeSession=null,this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.databaseConfig=null,this.configLoaded=!1,this.primaryColor="#9500FF",this.sessionToken=null,this.roomToken=null,this.roomUrl=null,this.boundSaveSessionData=null,this.obiClient=null,this.closeNavTimeoutRef=null,this.researchingTimeoutRef=null,this.urlCheckInterval=null,this.currentUrl="",this.connectObi=br(async e=>{if(this.activeSession){ee("connection_already_exists",{sessionToken:e},"ObiWidget"),console.log("Connection already exists");return}ee("session_connection_started",{sessionToken:e},"ObiWidget"),Cr({sessionId:e});try{const t=this.createSession(e);if(!t){this.handleSessionCreationFailure(()=>this.removeSessionUrlParams());return}this.setupSessionEventListeners(t,()=>this.removeSessionUrlParams()),t.on("screenCaptureRequested",br(async()=>{ee("screen_capture_requested",{},"ObiWidget");try{const r=(await q1(document.documentElement,{useCORS:!0,allowTaint:!0,foreignObjectRendering:!0})).toDataURL("image/png");this.activeSession.emit("screenCaptureComplete",r),ee("screen_capture_completed",{},"ObiWidget")}catch(i){$e(i,{componentName:"ObiWidget",handlerName:"screenCaptureRequested",sessionToken:e}),console.error("[obi] error capturing screen:",i),this.activeSession.emit("screenCaptureComplete","error"),ee("screen_capture_failed",{error:i instanceof Error?i.message:String(i)},"ObiWidget")}},"screenCaptureRequested","ObiWidget"));const n=await t.connect();n&&(this.sessionToken=e,this.roomToken=n.token,this.roomUrl=n.url,Cr({sessionId:e,widgetState:this.state.toString()}),this.removeSessionUrlParams(),ee("session_connection_established",{sessionToken:e,hasRoomToken:!!n.token},"ObiWidget")),this.activeSession=t}catch(t){console.error("Failed to start session:",t),$e(t,{componentName:"ObiWidget",handlerName:"connectObi",sessionToken:e}),this.handleSessionCreationFailure(()=>this.removeSessionUrlParams())}},"connectObi","ObiWidget"),this.handleCloseModals=()=>{this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null),this.state=H.READY,this.terminateSession(),this.showCourseModal=!1,this.showSessionStartModal=!1,this.showShareMicModal=!1},this.handleCourseSelectEvent=e=>{const t=e;this.selectedCourse=t.detail,this.showCourseModal=!1,this.showSessionStartModal=!0,this.showShareMicModal=!1,this.micShareEnabled=!1,this.showVoiceGuidanceModal=!1,this.voiceGuidanceEnabled=!1},this.handleUrlSessionEvent=br(async e=>{ee("url_session_event",{sessionToken:e},"ObiWidget");try{if(!this.obiClient){const n=new Error("ObiClient not initialized");$e(n,{componentName:"ObiWidget",handlerName:"handleUrlSessionEvent",sessionToken:e}),console.error("ObiClient not initialized");return}const t=await this.obiClient.startSession(e,this.apiKey);if(t.data){const{session:n}=t.data;if(console.log("[obi-sdk] session:",n),ee("session_started",{sessionId:n?.id,sessionToken:e},"ObiWidget"),n){const i=n;this.selectedCourse={id:e,name:i.onboarding_plan?.name||"",description:i.onboarding_plan?.description||""},this.state=H.LOADING,this.showSessionStartModal=!0,this.showShareMicModal=!1,this.micShareEnabled=!1,this.showVoiceGuidanceModal=!1,this.voiceGuidanceEnabled=!1,ee("matching_session_found",{sessionToken:e,hasOnboardingPlan:!!i.onboarding_plan},"ObiWidget")}else console.log("[obi-sdk] no session found with token:",e),ee("no_matching_session",{sessionToken:e},"ObiWidget")}}catch(t){console.error("Failed to fetch session details:",t),$e(t,{componentName:"ObiWidget",handlerName:"handleUrlSessionEvent",sessionToken:e})}},"handleUrlSessionEvent","ObiWidget"),this.handleSessionStart=br(async e=>{ee("session_start_requested",{sessionToken:e},"ObiWidget"),this.activeSession&&(ee("session_start_blocked",{sessionToken:e},"ObiWidget"),$e(new Error("Session start blocked"),{componentName:"ObiWidget",handlerName:"handleSessionStart",sessionToken:e}),this.activeSession.disconnect(),this.activeSession=null),this.showSessionStartModal=!1,this.showVoiceGuidanceModal=!0,this.state=H.LOADING,Cr({widgetState:this.state.toString()}),await this.connectObi(e)},"handleSessionStart","ObiWidget"),this.handleSessionModalStart=e=>{const{sessionId:t,attempt:n}=e.detail;if(console.log("[SessionStartModal] Start button clicked",{sessionId:t,hasSession:!!this.selectedCourse,startAttempts:n,timestamp:new Date().toISOString()}),ee("session_start_modal_continue_clicked",{sessionId:t,sessionName:this.selectedCourse?.name},"SessionStartModal"),!this.selectedCourse){const i="Session data is missing.";console.error("[SessionStartModal] Validation failed:",i),$e(i,{componentName:"SessionStartModal",handlerName:"handleSessionModalStart",sessionData:this.selectedCourse});return}if(!this.selectedCourse.id){const i="Session ID is missing.";console.error("[SessionStartModal] Validation failed:",i,{session:this.selectedCourse}),$e(i,{componentName:"SessionStartModal",handlerName:"handleSessionModalStart",sessionData:this.selectedCourse});return}console.log("[SessionStartModal] Starting session attempt",{attempt:n,sessionId:this.selectedCourse.id}),ee("session_start_modal_calling_onStart",{sessionId:this.selectedCourse.id},"SessionStartModal"),this.handleSessionStart(this.selectedCourse.id),console.log("[SessionStartModal] Session start completed successfully",{sessionId:this.selectedCourse.id,attempt:n}),ee("session_start_modal_onStart_called",{sessionId:this.selectedCourse.id},"SessionStartModal")},this.handleSessionModalClose=()=>{console.log("[SessionStartModal] Close button clicked",{sessionId:this.selectedCourse?.id}),this.handleCloseModals(),this.selectedCourse=null,this.removeSessionUrlParams()},this.handleSessionModalError=e=>{const{error:t,sessionId:n}=e.detail;console.error("[SessionStartModal] Error occurred",{error:t instanceof Error?t.message:String(t),sessionId:n}),$e(t,{componentName:"SessionStartModal",handlerName:"handleSessionModalError",sessionId:n})},this.handleShareMicModalContinue=async e=>{const{session:t,micPermissionGranted:n}=e.detail;if(console.log("[ShareMicModal] Continue button clicked",{sessionId:t?.id,micPermissionGranted:n,timestamp:new Date().toISOString()}),ee("share_mic_modal_continue_clicked",{sessionId:t?.id,micPermissionGranted:n},"ShareMicModal"),!this.activeSession){console.error("[obi] no active session during microphone sharing");return}await this.activeSession.shareMic(),this.showShareMicModal=!1,this.showVoiceGuidanceModal=!0},this.handleShareMicModalClose=()=>{console.log("[ShareMicModal] Close button clicked",{sessionId:this.selectedCourse?.id}),this.handleCloseModals()},this.handleVoiceGuidanceModalContinue=async()=>{console.log("[obi] voice guidance modal continue",{sessionId:this.selectedCourse?.id,timestamp:new Date().toISOString()}),ee("voice_guidance_modal_continue_clicked",{sessionId:this.selectedCourse?.id},"ShareMicModal"),await this.activeSession?.promptContinue(),this.showVoiceGuidanceModal=!1},this.handleVoiceGuidanceModalClose=()=>{console.log("[obi] voice guidance modal close",{sessionId:this.selectedCourse?.id}),this.handleCloseModals()},this.checkExistingSession=br(async()=>{ee("checking_existing_session",{},"ObiWidget");try{const e=JSON.parse(Ed.getItem(yd.SESSION_DATA)||"{}"),{sessionToken:t,roomToken:n,roomUrl:i,sessionExpiry:r,obiState:s}=e;if(!t||!n||!i){ee("no_existing_session_data",{},"ObiWidget");return}if(console.log("[obi-sdk] using existing session"),ee("existing_session_data_found",{sessionToken:t,hasExpiry:!!r,obiState:s},"ObiWidget"),r&&new Date(r)<new Date){this.clearSessionStorage(),ee("session_expired",{sessionToken:t},"ObiWidget");return}this.state=H.LOADING,Cr({sessionId:t,widgetState:this.state.toString()});const o=this.createSession(t);if(!o){this.handleSessionCreationFailure(()=>this.clearSessionStorage());return}this.setupSessionEventListeners(o,()=>this.clearSessionStorage()),await o.reconnect(i,n,s)?(this.activeSession=o,this.sessionToken=t,this.roomToken=n,this.roomUrl=i,this.state=s,this.storedActiveState=s,ee("session_reconnected",{sessionToken:t,obiState:s},"ObiWidget")):(this.clearSessionStorage(),ee("session_reconnection_failed",{sessionToken:t},"ObiWidget"))}catch(e){console.error("Error reconnecting to session:",e),$e(e,{componentName:"ObiWidget",handlerName:"checkExistingSession"}),this.handleSessionCreationFailure(()=>this.clearSessionStorage())}},"checkExistingSession","ObiWidget");try{U0("ObiWidget").setContext(),this.obiClient=new Lf({baseUrl:Hc}),this.currentUrl=window.location.href;const t=()=>{try{this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl&&this.saveSessionData()}catch(n){$e(n,{componentName:"ObiWidget",handlerName:"handleUnload"})}};window.addEventListener("beforeunload",t),window.addEventListener("pagehide",t),ee("ObiWidget_constructor_completed",{},"ObiWidget")}catch(e){throw $e(e,{componentName:"ObiWidget",lifecycle:"constructor"}),e}}updateFromConfig(){window.obiWidgetConfig?(this.apiKey=window.obiWidgetConfig.apiKey||this.apiKey,window.obiWidgetConfig.position!==void 0&&(this.position=window.obiWidgetConfig.position,this.setAttribute("position",this.position)),window.obiWidgetConfig.primaryColor!==void 0&&(this.style.setProperty("--obi-primary",window.obiWidgetConfig.primaryColor),this.generateColorVariables(window.obiWidgetConfig.primaryColor)),window.obiWidgetConfig.user!==void 0&&(this.user=window.obiWidgetConfig.user),window.obiWidgetConfig.isActive!==void 0&&(this.isActive=window.obiWidgetConfig.isActive),window.obiWidgetConfig.linkOnlyAccess!==void 0&&(this.linkOnlyAccess=window.obiWidgetConfig.linkOnlyAccess),window.obiWidgetConfig.urlBlacklist!==void 0&&(this.urlBlacklist=window.obiWidgetConfig.urlBlacklist),this.fetchDatabaseConfig(),window.obiWidgetConfig.showMenu===!0&&(this.state=H.LOADING,this.showCourseModal=!0,window.obiWidgetConfig.showMenu=!1)):this.configLoaded||this.fetchDatabaseConfig()}generateColorVariables(e){try{this.primaryColor=e;const t=Mc(e,"#c4b5fd"),n=Mc(e,"#c76cff"),i=_w(e),r=Mc(e,"#A06DF9");this.style.setProperty("--obi-secondary",t),this.style.setProperty("--obi-course-selected",n),this.style.setProperty("--obi-course-selected-bg",i),this.style.setProperty("--obi-paused-pulse",r)}catch(t){console.warn("Failed to generate color variables:",t),this.style.setProperty("--obi-secondary","#c4b5fd"),this.style.setProperty("--obi-course-selected","#c76cff"),this.style.setProperty("--obi-course-selected-bg","#fbf3ff"),this.style.setProperty("--obi-paused-pulse","#A06DF9")}}removeSessionUrlParams(){const e=new URL(window.location.href);e.searchParams.delete($f),window.history.replaceState({},"",e.toString()),localStorage.removeItem("obi-url-params")}createSession(e){try{const t=new pw({sessionId:e,apiBaseUrl:Hc,...this.user&&{user:this.user}});return t||(console.error("Failed to create session"),null)}catch(t){return console.error("Error creating session:",t),null}}setupSessionEventListeners(e,t){e.on("stateChanged",n=>{if(n===H.RESEARCHING){this.researchingTimeoutRef&&window.clearTimeout(this.researchingTimeoutRef),this.state=n,this.researchingTimeoutRef=window.setTimeout(()=>{this.researchingTimeoutRef=null;const i=e.getCurrentState();this.state=i,i!==H.READY&&(this.storedActiveState=i)},1500),this.storedActiveState=n;return}this.researchingTimeoutRef===null&&(this.state=n,n!==H.READY&&(this.storedActiveState=n))}),e.on("volume",({speaker:n,spectrum:i,volume:r})=>{this.volume={speaker:n,spectrum:i,volume:r}}),e.on("error",n=>{console.error("Session error:",n),this.state=H.ERROR,this.activeSession=null,t&&t()}),e.on("micShareRequested",()=>{this.micShareEnabled=!0}),e.on("micCheck",n=>{n?(this.showVoiceGuidanceModal=!1,this.showShareMicModal=!0):(this.showShareMicModal=!0,this.showVoiceGuidanceModal=!1)}),e.on("promptUser",()=>{this.voiceGuidanceEnabled=!0}),e.on("micCheck",n=>{n&&(this.showVoiceGuidanceModal=!0,this.showShareMicModal=!1)})}handleSessionCreationFailure(e){this.state=H.ERROR,this.activeSession=null,e&&e()}clearSessionStorage(){Ed.removeItem(yd.SESSION_DATA)}handleUrlChange(){this.requestUpdate(),Jo(this.urlBlacklist)&&this.activeSession&&this.terminateSession()}saveSessionData(){if(this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl){const e=new Date;e.setMinutes(e.getMinutes()+5);const t={sessionToken:this.sessionToken,roomToken:this.roomToken,roomUrl:this.roomUrl,obiState:this.storedActiveState??this.state,sessionExpiry:e.toISOString()};Ed.setItem(yd.SESSION_DATA,JSON.stringify(t))}}async sessionConnectionCheck(){const e=function(){let t={};return t=JSON.parse(localStorage.getItem("obi-url-params")||"{}"),Object.keys(t).length===0&&new URLSearchParams(window.location.search).forEach((i,r)=>{t[r]=i}),t[$f]}();if(!e){await this.checkExistingSession();return}console.log("[obi-sdk] using magic link"),this.apiKey?await this.handleUrlSessionEvent(e):(console.log("[obi-sdk] API key not ready, retrying..."),setTimeout(()=>{this.apiKey&&this.handleUrlSessionEvent(e)},100))}connectedCallback(){super.connectedCallback(),this.updateFromConfig(),this.addEventListener("obi-config-updated",this.handleConfigUpdate.bind(this)),this.setAttribute("position",this.position),this.boundSaveSessionData=this.saveSessionData.bind(this),window.addEventListener("beforeunload",this.boundSaveSessionData),window.addEventListener("pagehide",this.boundSaveSessionData),this.isActive&&(this.urlCheckInterval=window.setInterval(()=>{this.currentUrl!==window.location.href&&(this.currentUrl=window.location.href,this.handleUrlChange())},1e3)),this.addEventListener("course-select",this.handleCourseSelectEvent)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("obi-config-updated",this.handleConfigUpdate.bind(this)),this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.researchingTimeoutRef!==null&&(window.clearTimeout(this.researchingTimeoutRef),this.researchingTimeoutRef=null),this.boundSaveSessionData&&(window.removeEventListener("beforeunload",this.boundSaveSessionData),window.removeEventListener("pagehide",this.boundSaveSessionData)),this.urlCheckInterval!==null&&(clearInterval(this.urlCheckInterval),this.urlCheckInterval=null),this.removeSessionUrlParams()}async handleConfigUpdate(e){const n=e.detail,i=n.isActive&&!this.isActive,r=this.user;if(this.updateFromConfig(),this.activeSession&&n.user!==void 0){const s=n.user;if(JSON.stringify(r)!==JSON.stringify(s))try{await this.activeSession.updateUser(s)}catch(o){console.error("Failed to update session user data:",o)}}i&&!Jo(this.urlBlacklist)&&!this.activeSession&&this.sessionConnectionCheck(),this.requestUpdate()}handleMouseEnter(){this.isHovering=!0,this.navVisible=!0}handleMouseLeave(){this.isHovering=!1,this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.closeNavTimeoutRef=window.setTimeout(()=>{this.isHovering||(this.navVisible=!1),this.closeNavTimeoutRef=null},300)}terminateSession(){this.clearSessionStorage(),this.sessionToken=null,this.roomToken=null,this.roomUrl=null,this.researchingTimeoutRef!==null&&(window.clearTimeout(this.researchingTimeoutRef),this.researchingTimeoutRef=null),this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null),this.state=H.READY}handleItemSelect(e,t){if(e==="experiences"){this.showCourseModal=!0;return}Vi([e,t]).with(["pause",!0],()=>{this.activeSession?.pauseRecording()}).with(["pause",!1],()=>{this.activeSession?.resumeRecording()}).with(["activate",!1],()=>{this.terminateSession()}).otherwise(()=>{})}async fetchDatabaseConfig(){if(!this.apiKey){this.configLoaded=!0,this.applyFinalConfiguration();return}try{const e=`obi-widget-config-${this.apiKey}`,t=localStorage.getItem(e),n=localStorage.getItem(`${e}-timestamp`);if(t&&n){const a=Date.now()-parseInt(n,10),c=10*60*1e3;if(a<c){const l=JSON.parse(t);this.databaseConfig=l,this.configLoaded=!0,this.applyFinalConfiguration();return}}const i=new AbortController,r=setTimeout(()=>i.abort(),3e3),s=await this.obiClient.getOnboardeeWidgetConfig(this.apiKey,i.signal);if(clearTimeout(r),s.error){if(s.response?.status===404){localStorage.removeItem(e),localStorage.removeItem(`${e}-timestamp`),this.databaseConfig=null,this.configLoaded=!0,this.applyFinalConfiguration();return}throw new Error(`HTTP ${s.response?.status||"Unknown error"}`)}const o=s.data;localStorage.setItem(e,JSON.stringify(o)),localStorage.setItem(`${e}-timestamp`,Date.now().toString()),this.databaseConfig=o,this.configLoaded=!0,this.applyFinalConfiguration()}catch(e){e instanceof Error&&e.name==="AbortError"?console.warn("Widget config fetch timed out, using defaults"):console.warn("Failed to fetch widget config from database:",e),this.databaseConfig=null,this.configLoaded=!0,this.applyFinalConfiguration()}}applyFinalConfiguration(){const e=window.obiWidgetConfig,t=this.databaseConfig;this.user=e?.user||this.user,this.position=e?.position||t?.position||this.position,this.setAttribute("position",this.position),e?.isActive!==void 0&&(this.isActive=e.isActive),e?.linkOnlyAccess!==void 0?this.linkOnlyAccess=e.linkOnlyAccess:t?.linkOnlyAccess!==void 0&&(this.linkOnlyAccess=t.linkOnlyAccess);const n=e?.urlBlacklist||[],i=t?.urlBlacklist||[];if(n.length>0||i.length>0){const s=[...n,...i];this.urlBlacklist=[...new Set(s)]}const r=e?.primaryColor||t?.primaryColor||Es;this.primaryColor=r,this.style.setProperty("--obi-primary",r),this.generateColorVariables(r),this.isActive&&!Jo(this.urlBlacklist)&&!this.activeSession&&this.sessionConnectionCheck()}render(){if(!this.configLoaded||!this.isActive||this.linkOnlyAccess&&this.state===H.READY||Jo(this.urlBlacklist))return S.nothing;const e=Vi(this.state).with(H.LOADING,()=>S.html`<obi-dot-loader></obi-dot-loader>`).with(H.RESEARCHING,()=>S.html`<obi-searching-loader></obi-searching-loader>`).with(nw.union(H.USER_SPEAKING,H.AGENT_SPEAKING),()=>S.html`<obi-audio-equalizer .volume=${this.volume}></obi-audio-equalizer>`).with(H.THINKING,()=>S.html`<obi-dot-loader></obi-dot-loader>`).with(H.PAUSED,()=>Sd).otherwise(()=>Sd),t=this.state===H.USER_SPEAKING||this.state===H.AGENT_SPEAKING,n=this.state===H.PAUSED,i=this.state===H.RESEARCHING,r=this.state===H.USER_SPEAKING,s=this.state!==H.READY||this.navVisible,o=this.state!==H.READY||this.navVisible,a=this.position.includes("top")?"down":"up",c=["widget-container",s?"rotated":"",t?"pulse":"",n?"paused-pulse":"",i?"researching":"",r?"user-speaking":""].filter(Boolean).join(" ");return S.html`
2545
2545
  <div
2546
2546
  class="${c}"
2547
2547
  @mouseenter=${this.handleMouseEnter}