obi-sdk 0.18.34-beta.3 → 0.19.1-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/obi-sdk.standalone.iife.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -39,7 +39,7 @@ a=extmap-allow-mixed`)!==-1){const A=i.sdp.split(`
|
|
|
39
39
|
`).filter(s=>s.trim()!=="a=extmap-allow-mixed").join(`
|
|
40
40
|
`);n.RTCSessionDescription&&i instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:i.type,sdp:A}):i.sdp=A}return t.apply(this,arguments)}}function $o(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(n.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ea(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let 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 fF=Object.freeze({__proto__:null,removeExtmapAllowMixed:bl,shimAddIceCandidateNullOrEmpty:$o,shimConnectionState:wl,shimMaxMessageSize:Yo,shimParameterlessSetLocalDescription:ea,shimRTCIceCandidate:Xo,shimRTCIceCandidateRelayProtocol:yl,shimSendThrowTypeError:Zo});function gF(){let{window:n}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=ov,r=lF(n),i={browserDetails:r,commonShim:fF,extractVersion:zo,disableLog:cF,disableWarnings:uF,sdp:pF};switch(r.browser){case"chrome":if(!wv||!gl||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),i;if(r.version===null)return t("Chrome shim can not determine version, not shimming."),i;t("adapter.js shimming chrome."),i.browserShim=wv,$o(n,r),ea(n),dv(n,r),hv(n),gl(n,r),pv(n),vv(n,r),fv(n),gv(n),yv(n,r),Xo(n),yl(n),wl(n),Yo(n,r),Zo(n),bl(n,r);break;case"firefox":if(!Fv||!ml||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),i;t("adapter.js shimming firefox."),i.browserShim=Fv,$o(n,r),ea(n),bv(n,r),ml(n,r),Bv(n),Sv(n),Cv(n),_v(n),kv(n),Ev(n),Uv(n),Tv(n),Iv(n),Xo(n),wl(n),Yo(n,r),Zo(n);break;case"safari":if(!Hv||!e.shimSafari)return t("Safari shim is not included in this adapter release."),i;t("adapter.js shimming safari."),i.browserShim=Hv,$o(n,r),ea(n),Mv(n),Dv(n),Rv(n),xv(n),Qv(n),Lv(n),Pv(n),Nv(n),Xo(n),yl(n),Yo(n,r),Zo(n),bl(n,r);break;default:t("Unsupported browser!");break}return i}gF({window:typeof window>"u"?void 0:window});const mF=10,ta="lk_e2ee",vF={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:mF,keyringSize:16};var lr;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(lr||(lr={}));var Gv;(function(n){n.KeyRatcheted="keyRatcheted"})(Gv||(Gv={}));var dr;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(dr||(dr={}));var jv;(function(n){n.Error="cryptorError"})(jv||(jv={}));function yF(){return wF()||Bl()}function Bl(){return typeof window.RTCRtpScriptTransform<"u"}function wF(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class x4 extends Sn.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,r,i)=>{ue.debug("key ratcheted event received",{ratchetResult:t,participantId:r,keyIndex:i})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},vF),e),this.on(lr.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,r){const i={key:e,participantIdentity:t,keyIndex:r};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(r??0),i),this.emit(lr.SetKey,i)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(lr.RatchetRequest,e,t)}}class hr extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var de;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.ServerUnreachable=1]="ServerUnreachable",n[n.InternalError=2]="InternalError",n[n.Cancelled=3]="Cancelled",n[n.LeaveRequest=4]="LeaveRequest"})(de||(de={}));class Fe extends hr{constructor(e,t,r,i){super(1,e),this.name="ConnectionError",this.status=r,this.reason=t,this.context=i,this.reasonName=de[t]}}class Cl extends hr{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class Dn extends hr{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class bF extends hr{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class lt extends hr{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class _l extends hr{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Sl extends hr{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Wv extends hr{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:dl[t]}}var na;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(na||(na={})),function(n){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?n.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?n.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?n.DeviceInUse:n.Other}n.getFailure=e}(na||(na={}));var qv;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(qv||(qv={}));var O;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",n.Moved="moved",n.MediaDevicesChanged="mediaDevicesChanged",n.ParticipantConnected="participantConnected",n.ParticipantDisconnected="participantDisconnected",n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalAudioSilenceDetected="localAudioSilenceDetected",n.ActiveSpeakersChanged="activeSpeakersChanged",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.ParticipantAttributesChanged="participantAttributesChanged",n.ParticipantActive="participantActive",n.RoomMetadataChanged="roomMetadataChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.AudioPlaybackStatusChanged="audioPlaybackChanged",n.VideoPlaybackStatusChanged="videoPlaybackChanged",n.MediaDevicesError="mediaDevicesError",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.SignalConnected="signalConnected",n.RecordingStatusChanged="recordingStatusChanged",n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ActiveDeviceChanged="activeDeviceChanged",n.ChatMessage="chatMessage",n.LocalTrackSubscribed="localTrackSubscribed",n.MetricsReceived="metricsReceived"})(O||(O={}));var K;(function(n){n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.IsSpeakingChanged="isSpeakingChanged",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded",n.AttributesChanged="attributesChanged",n.LocalTrackSubscribed="localTrackSubscribed",n.ChatMessage="chatMessage",n.Active="active"})(K||(K={}));var D;(function(n){n.TransportsCreated="transportsCreated",n.Connected="connected",n.Disconnected="disconnected",n.Resuming="resuming",n.Resumed="resumed",n.Restarting="restarting",n.Restarted="restarted",n.SignalResumed="signalResumed",n.SignalRestarted="signalRestarted",n.Closing="closing",n.MediaTrackAdded="mediaTrackAdded",n.ActiveSpeakersUpdate="activeSpeakersUpdate",n.DataPacketReceived="dataPacketReceived",n.RTPVideoMapUpdate="rtpVideoMapUpdate",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ParticipantUpdate="participantUpdate",n.RoomUpdate="roomUpdate",n.SpeakersChanged="speakersChanged",n.StreamStateChanged="streamStateChanged",n.ConnectionQualityUpdate="connectionQualityUpdate",n.SubscriptionError="subscriptionError",n.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",n.RemoteMute="remoteMute",n.SubscribedQualityUpdate="subscribedQualityUpdate",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackSubscribed="localTrackSubscribed",n.Offline="offline",n.SignalRequestResponse="signalRequestResponse",n.SignalConnected="signalConnected",n.RoomMoved="roomMoved"})(D||(D={}));var L;(function(n){n.Message="message",n.Muted="muted",n.Unmuted="unmuted",n.Restarted="restarted",n.Ended="ended",n.Subscribed="subscribed",n.Unsubscribed="unsubscribed",n.UpdateSettings="updateSettings",n.UpdateSubscription="updateSubscription",n.AudioPlaybackStarted="audioPlaybackStarted",n.AudioPlaybackFailed="audioPlaybackFailed",n.AudioSilenceDetected="audioSilenceDetected",n.VisibilityChanged="visibilityChanged",n.VideoDimensionsChanged="videoDimensionsChanged",n.VideoPlaybackStarted="videoPlaybackStarted",n.VideoPlaybackFailed="videoPlaybackFailed",n.ElementAttached="elementAttached",n.ElementDetached="elementDetached",n.UpstreamPaused="upstreamPaused",n.UpstreamResumed="upstreamResumed",n.SubscriptionPermissionChanged="subscriptionPermissionChanged",n.SubscriptionStatusChanged="subscriptionStatusChanged",n.SubscriptionFailed="subscriptionFailed",n.TrackProcessorUpdate="trackProcessorUpdate",n.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",n.TranscriptionReceived="transcriptionReceived",n.TimeSyncUpdate="timeSyncUpdate"})(L||(L={}));function BF(n){return typeof n>"u"?n:typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}const CF=/version\/(\d+(\.?_?\d+)+)/i;let kl;function un(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof n>"u"&&typeof navigator>"u")return;const t=(n??navigator.userAgent).toLowerCase();if(kl===void 0||e){const r=_F.find(i=>{let{test:A}=i;return A.test(t)});kl=r==null?void 0:r.describe(t)}return kl}const _F=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:ra(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:El(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:ra(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:El(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:ra(CF,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:El(n)}}}];function ra(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const r=e.match(n);return r&&r.length>=t&&r[t]||""}function El(n){return n.includes("mac os")?ra(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var SF="2.13.0";const kF=SF,EF=16;class wt{}wt.setTimeout=function(){return setTimeout(...arguments)},wt.setInterval=function(){return setInterval(...arguments)},wt.clearTimeout=function(){return clearTimeout(...arguments)},wt.clearInterval=function(){return clearInterval(...arguments)};const UF=5e3,NA=[];var Yt;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Yt||(Yt={}));class R extends Sn.EventEmitter{constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var i;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=R.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=ue,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),UF):this.handleAppVisibilityChanged()},this.log=Ln((i=r.loggerName)!==null&&i!==void 0?i:cn.Track),this.loggerContextCb=r.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=R.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),_e(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===R.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===R.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(NA.forEach(A=>{A.parentElement===null&&!e&&(e=A)}),e&&NA.splice(NA.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Fi(this.mediaStreamTrack,e);const r=e.srcObject.getTracks(),i=r.some(A=>A.kind==="audio");return e.play().then(()=>{this.emit(i?L.AudioPlaybackStarted:L.VideoPlaybackStarted)}).catch(A=>{A.name==="NotAllowedError"?this.emit(i?L.AudioPlaybackFailed:L.VideoPlaybackFailed,A):A.name==="AbortError"?ue.debug("".concat(i?"audio":"video"," playback aborted, likely due to new play request")):ue.warn("could not playback ".concat(i?"audio":"video"),A),i&&e&&r.some(s=>s.kind==="video")&&A.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(L.ElementAttached,e),e}detach(e){try{if(e){xi(this.mediaStreamTrack,e);const r=this.attachedElements.indexOf(e);return r>=0&&(this.attachedElements.splice(r,1),this.recycleElement(e),this.emit(L.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(r=>{xi(this.mediaStreamTrack,r),t.push(r),this.recycleElement(r),this.emit(L.ElementDetached,r)}),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=Ln(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),NA.forEach(r=>{r.parentElement||(t=!1)}),t&&NA.push(e)}}handleAppVisibilityChanged(){return S(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===R.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Ht()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Ht()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Fi(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let r;n.kind==="audio"?r=t.getAudioTracks():r=t.getVideoTracks(),r.includes(n)||(r.forEach(i=>{t.removeTrack(i)}),t.addTrack(n)),(!pr()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(pr()||Qi())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function xi(n,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(n),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(n){let e;(function(c){c.Audio="audio",c.Video="video",c.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(c){c.Camera="camera",c.Microphone="microphone",c.ScreenShare="screen_share",c.ScreenShareAudio="screen_share_audio",c.Unknown="unknown"})(t=n.Source||(n.Source={}));let r;(function(c){c.Active="active",c.Paused="paused",c.Unknown="unknown"})(r=n.StreamState||(n.StreamState={}));function i(c){switch(c){case e.Audio:return An.AUDIO;case e.Video:return An.VIDEO;default:return An.DATA}}n.kindToProto=i;function A(c){switch(c){case An.AUDIO:return e.Audio;case An.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=A;function s(c){switch(c){case t.Camera:return at.CAMERA;case t.Microphone:return at.MICROPHONE;case t.ScreenShare:return at.SCREEN_SHARE;case t.ScreenShareAudio:return at.SCREEN_SHARE_AUDIO;default:return at.UNKNOWN}}n.sourceToProto=s;function o(c){switch(c){case at.CAMERA:return t.Camera;case at.MICROPHONE:return t.Microphone;case at.SCREEN_SHARE:return t.ScreenShare;case at.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function a(c){switch(c){case Al.ACTIVE:return r.Active;case Al.PAUSED:return r.Paused;default:return r.Unknown}}n.streamStateFromProto=a})(R||(R={}));class Te{constructor(e,t,r,i,A){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&&r!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:r,maxFramerate:i,priority:A};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 TF=["vp8","h264"],IF=["vp8","h264","vp9","av1"];function FF(n){return!!TF.find(e=>e===n)}var Jv;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(Jv||(Jv={}));var Ul;(function(n){n.telephone={maxBitrate:12e3},n.speech={maxBitrate:24e3},n.music={maxBitrate:48e3},n.musicStereo={maxBitrate:64e3},n.musicHighQuality={maxBitrate:96e3},n.musicHighQualityStereo={maxBitrate:128e3}})(Ul||(Ul={}));const HA={h90:new Te(160,90,9e4,20),h180:new Te(320,180,16e4,20),h216:new Te(384,216,18e4,20),h360:new Te(640,360,45e4,20),h540:new Te(960,540,8e5,25),h720:new Te(1280,720,17e5,30),h1080:new Te(1920,1080,3e6,30),h1440:new Te(2560,1440,5e6,30),h2160:new Te(3840,2160,8e6,30)},Tl={h120:new Te(160,120,7e4,20),h180:new Te(240,180,125e3,20),h240:new Te(320,240,14e4,20),h360:new Te(480,360,33e4,20),h480:new Te(640,480,5e5,20),h540:new Te(720,540,6e5,25),h720:new Te(960,720,13e5,30),h1080:new Te(1440,1080,23e5,30),h1440:new Te(1920,1440,38e5,30)},Il={h360fps3:new Te(640,360,2e5,3,"medium"),h360fps15:new Te(640,360,4e5,15,"medium"),h720fps5:new Te(1280,720,8e5,5,"medium"),h720fps15:new Te(1280,720,15e5,15,"medium"),h720fps30:new Te(1280,720,2e6,30,"medium"),h1080fps15:new Te(1920,1080,25e5,15,"medium"),h1080fps30:new Te(1920,1080,5e6,30,"medium"),original:new Te(0,0,7e6,30,"medium")},xF="|",zv="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function QF(n){const e=n.split(xF);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function Nt(n){return S(this,void 0,void 0,function*(){return new Promise(e=>wt.setTimeout(e,n))})}function Fl(){return"addTransceiver"in RTCPeerConnection.prototype}function xl(){return"addTrack"in RTCPeerConnection.prototype}function RF(){if(!("getCapabilities"in RTCRtpSender)||pr())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType==="video/AV1"){e=!0;break}}return e}function PF(){if(!("getCapabilities"in RTCRtpSender)||Qi())return!1;if(pr()){const t=un();if(t!=null&&t.version&&Wr(t.version,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType==="video/VP9"){e=!0;break}}return e}function KA(n){return n==="av1"||n==="vp9"}function Ql(n){return document?(n||(n=document.createElement("audio")),"setSinkId"in n):!1}function OF(){return typeof RTCPeerConnection>"u"?!1:Fl()||xl()}function Qi(){var n;return((n=un())===null||n===void 0?void 0:n.name)==="Firefox"}function pr(){var n;return((n=un())===null||n===void 0?void 0:n.name)==="Safari"}function MF(){const n=un();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")}function Xv(){var n,e;return Ht()?(e=(n=navigator.userAgentData)===null||n===void 0?void 0:n.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function LF(){const n=un(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&Wr(e,n.osVersion)>=0?!0:n.name==="Safari"&&Wr(e,n.version)>=0}function Ht(){return typeof document<"u"}function kn(){return navigator.product=="ReactNative"}function Rl(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function Yv(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Zv(){if(!kn())return;let n=Yv();if(n)return n.platform}function $v(){if(Ht())return window.devicePixelRatio;if(kn()){let n=Yv();if(n)return n.devicePixelRatio}return 1}function Wr(n,e){const t=n.split("."),r=e.split("."),i=Math.min(t.length,r.length);for(let A=0;A<i;++A){const s=parseInt(t[A],10),o=parseInt(r[A],10);if(s>o)return 1;if(s<o)return-1;if(A===i-1&&s===o)return 0}return n===""&&e!==""?-1:e===""?1:t.length==r.length?0:t.length<r.length?-1:1}function DF(n){for(const e of n)e.target.handleResize(e)}function NF(n){for(const e of n)e.target.handleVisibilityChanged(e)}let Pl=null;const e0=()=>(Pl||(Pl=new ResizeObserver(DF)),Pl);let Ol=null;const t0=()=>(Ol||(Ol=new IntersectionObserver(NF,{root:null,rootMargin:"0px"})),Ol);function HF(){var n;const e=new II({sdk:Dm.JS,protocol:EF,version:kF});return kn()&&(e.os=(n=Zv())!==null&&n!==void 0?n:""),e}function n0(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const i=document.createElement("canvas");i.width=n,i.height=e;const A=i.getContext("2d");A==null||A.fillRect(0,0,i.width,i.height),r&&A&&(A.beginPath(),A.arc(n/2,e/2,50,0,Math.PI*2,!0),A.closePath(),A.fillStyle="grey",A.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 VA;function Ml(){if(!VA){const n=new AudioContext,e=n.createOscillator(),t=n.createGain();t.gain.setValueAtTime(0,0);const r=n.createMediaStreamDestination();if(e.connect(t),t.connect(r),e.start(),[VA]=r.stream.getAudioTracks(),!VA)throw Error("Could not get empty media stream audio track");VA.enabled=!1}return VA.clone()}class Ll{constructor(e,t){this.onFinally=t,this.promise=new Promise((r,i)=>S(this,void 0,void 0,function*(){this.resolve=r,this.reject=i,e&&(yield e(r,i))})).finally(()=>{var r;return(r=this.onFinally)===null||r===void 0?void 0:r.call(this)})}}function KF(n){return IF.includes(n)}function fr(n){if(typeof n=="string"||typeof n=="number")return n;if(Array.isArray(n))return n[0];if(n.exact)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function VF(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function Dl(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function GF(n,e){return n.segments.map(t=>{let{id:r,text:i,language:A,startTime:s,endTime:o,final:a}=t;var c;const u=(c=e.get(r))!==null&&c!==void 0?c:Date.now(),l=Date.now();return a?e.delete(r):e.set(r,u),{id:r,text:i,startTime:Number.parseInt(s.toString()),endTime:Number.parseInt(o.toString()),final:a,language:A,firstReceivedTime:u,lastReceivedTime:l}})}function jF(n){const{id:e,timestamp:t,message:r,editTimestamp:i}=n;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:r}}function r0(n){switch(n.reason){case de.LeaveRequest:return n.context;case de.Cancelled:return sn.CLIENT_INITIATED;case de.NotAllowed:return sn.USER_REJECTED;case de.ServerUnreachable:return sn.JOIN_FAILURE;default:return sn.UNKNOWN_REASON}}function ia(n){return n!==void 0?Number(n):void 0}function qr(n){return n!==void 0?BigInt(n):void 0}function Ri(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function Nn(n){return!!n&&n.kind==R.Kind.Audio}function Pi(n){return!!n&&n.kind==R.Kind.Video}function gr(n){return Ri(n)&&Pi(n)}function Jr(n){return Ri(n)&&Nn(n)}function Nl(n){return!!n&&!n.isLocal}function WF(n){return!!n&&!n.isLocal}function Hl(n){return Nl(n)&&Pi(n)}function qF(n){return n.isLocal}function JF(n,e){const t=[];let r=new TextEncoder().encode(n);for(;r.length>e;){let i=e;for(;i>0;){const A=r[i];if(A!==void 0&&(A&192)!==128)break;i--}t.push(r.slice(0,i)),r=r.slice(i)}return r.length>0&&t.push(r),t}function i0(n,e,t){var r,i,A,s;const{optionsWithoutProcessor:o,audioProcessor:a,videoProcessor:c}=a0(n??{}),u=e==null?void 0:e.processor,l=t==null?void 0:t.processor,d=o??{};return d.audio===!0&&(d.audio={}),d.video===!0&&(d.video={}),d.audio&&(Kl(d.audio,e),(r=(A=d.audio).deviceId)!==null&&r!==void 0||(A.deviceId={ideal:"default"}),(a||u)&&(d.audio.processor=a??u)),d.video&&(Kl(d.video,t),(i=(s=d.video).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||l)&&(d.video.processor=c??l)),d}function Kl(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function Vl(n){var e,t,r,i;const A={};if(n.video)if(typeof n.video=="object"){const s={},o=s,a=n.video;Object.keys(a).forEach(c=>{switch(c){case"resolution":Kl(o,a.resolution);break;default:o[c]=a[c]}}),A.video=s,(e=(r=A.video).deviceId)!==null&&e!==void 0||(r.deviceId={ideal:"default"})}else A.video=n.video?{deviceId:{ideal:"default"}}:!1;else A.video=!1;return n.audio?typeof n.audio=="object"?(A.audio=n.audio,(t=(i=A.audio).deviceId)!==null&&t!==void 0||(i.deviceId={ideal:"default"})):A.audio={deviceId:{ideal:"default"}}:A.audio=!1,A}function A0(n){return S(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const r=s0();if(r){const i=r.createAnalyser();i.fftSize=2048;const A=i.frequencyBinCount,s=new Uint8Array(A);r.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(i),yield Nt(t),i.getByteTimeDomainData(s);const a=s.some(c=>c!==128&&c!==0);return r.close(),!a}return!1}()})}function s0(){var n;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((n=window.document)===null||n===void 0)&&n.body)){const r=()=>S(this,void 0,void 0,function*(){var i;try{t.state==="suspended"&&(yield t.resume())}catch(A){console.warn("Error trying to auto-resume audio context",A)}(i=window.document.body)===null||i===void 0||i.removeEventListener("click",r)});window.document.body.addEventListener("click",r)}return t}}function zF(n){return n==="audioinput"?R.Source.Microphone:n==="videoinput"?R.Source.Camera:R.Source.Unknown}function o0(n){return n===R.Source.Microphone?"audioinput":n===R.Source.Camera?"videoinput":void 0}function XF(n){var e,t;let r=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(r=typeof r=="boolean"?{}:r,pr()?r=Object.assign(Object.assign({},r),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):r=Object.assign(Object.assign({},r),{width:{ideal:n.resolution.width},height:{ideal:n.resolution.height},frameRate:n.resolution.frameRate})),{audio:(t=n.audio)!==null&&t!==void 0?t:!1,video:r,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function Aa(n){return n.split("/")[1].toLowerCase()}function YF(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new ul({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function _e(n){return"mediaStreamTrack"in n?{trackID:n.sid,source:n.source,muted:n.isMuted,enabled:n.mediaStreamTrack.enabled,kind:n.kind,streamID:n.mediaStreamID,streamTrackID:n.mediaStreamTrack.id}:{trackID:n.trackSid,enabled:n.isEnabled,muted:n.isMuted,trackInfo:Object.assign({mimeType:n.mimeType,name:n.trackName,encrypted:n.isEncrypted,kind:n.kind,source:n.source},n.track?_e(n.track):{})}}function ZF(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function $F(n,e){var t;n===void 0&&(n={}),e===void 0&&(e={});const r=[...Object.keys(e),...Object.keys(n)],i={};for(const A of r)n[A]!==e[A]&&(i[A]=(t=e[A])!==null&&t!==void 0?t:"");return i}function a0(n){const e=Object.assign({},n);let t,r;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&&(r=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:r,optionsWithoutProcessor:BF(e)}}function ex(n){switch(n){case at.CAMERA:return R.Source.Camera;case at.MICROPHONE:return R.Source.Microphone;case at.SCREEN_SHARE:return R.Source.ScreenShare;case at.SCREEN_SHARE_AUDIO:return R.Source.ScreenShareAudio;default:return R.Source.Unknown}}class tx extends Sn.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var r,i;const{kind:A,data:s}=t.data;switch(A){case"error":ue.error(s.error.message),this.emit(dr.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===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity))this.emit(dr.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(dr.ParticipantEncryptionStatusChanged,s.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(lr.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break}},this.onWorkerError=t=>{ue.error("e2ee worker encountered an error:",{error:t.error}),this.emit(dr.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!yF())throw new Cl("tried to setup end-to-end encryption on an unsupported browser");if(ue.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:iF.getLevel()}};this.worker&&(ue.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){ue.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?ue.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(D.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(O.TrackPublished,(r,i)=>this.setParticipantCryptorEnabled(r.trackInfo.encryption!==Wt.NONE,i.identity)),e.on(O.ConnectionStateChanged,r=>{r===fe.Connected&&e.remoteParticipants.forEach(i=>{i.trackPublications.forEach(A=>{this.setParticipantCryptorEnabled(A.trackInfo.encryption!==Wt.NONE,i.identity)})})}).on(O.TrackUnsubscribed,(r,i,A)=>{var s;const o={kind:"removeTransform",data:{participantIdentity:A.identity,trackId:r.mediaStreamID}};(s=this.worker)===null||s===void 0||s.postMessage(o)}).on(O.TrackSubscribed,(r,i,A)=>{this.setupE2EEReceiver(r,A.identity,i.trackInfo)}).on(O.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(r=>{this.postKey(r)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(K.LocalTrackPublished,r=>S(this,void 0,void 0,function*(){this.setupE2EESender(r.track,r.track.sender)})),t.on(lr.SetKey,r=>this.postKey(r)).on(lr.RatchetRequest,(r,i)=>this.postRatchetRequest(r,i))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const r={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(r)}postKey(e){let{key:t,participantIdentity:r,keyIndex:i}=e;var A;if(!this.worker)throw Error("could not set key, worker is missing");const s={kind:"setKey",data:{participantIdentity:r,isPublisher:r===((A=this.room)===null||A===void 0?void 0:A.localParticipant.identity),key:t,keyIndex:i}};this.worker.postMessage(s)}postEnable(e,t){if(this.worker){const r={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(r)}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 r={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(r)}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,r){if(e.receiver){if(!(r!=null&&r.mimeType)||r.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?Aa(r.mimeType):void 0)}}setupE2EESender(e,t){if(!Ri(e)||!t){t||ue.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,r,i){return S(this,void 0,void 0,function*(){if(this.worker){if(Bl()){const A={kind:"decode",participantIdentity:r,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,A)}else{if(ta in e&&i){const a={kind:"updateCodec",data:{trackId:t,codec:i,participantIdentity:r}};this.worker.postMessage(a);return}let A=e.writableStream,s=e.readableStream;if(!A||!s){const a=e.createEncodedStreams();e.writableStream=a.writable,A=a.writable,e.readableStream=a.readable,s=a.readable}const o={kind:"decode",data:{readableStream:s,writableStream:A,trackId:t,codec:i,participantIdentity:r}};this.worker.postMessage(o,[s,A])}e[ta]=!0}})}handleSender(e,t,r){var i;if(!(ta 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(Bl()){ue.info("initialize script transform");const A={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,A)}else{ue.info("initialize encoded streams");const A=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:A.readable,writableStream:A.writable,codec:r,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s,[A.readable,A.writable])}e[ta]=!0}}}const Gl="default";class ft{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new ft),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var A;if(((A=ft.userMediaPromiseMap)===null||A===void 0?void 0:A.size)>0){ue.debug("awaiting getUserMedia promise");try{t?yield ft.userMediaPromiseMap.get(t):yield Promise.all(ft.userMediaPromiseMap.values())}catch{ue.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&!(pr()&&r.hasDeviceInUse(t))&&(s.filter(a=>a.kind===t).length===0||s.some(a=>{const c=a.label==="",u=t?a.kind===t:!0;return c&&u}))){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(u=>{u.stop()})}return r._previousDevices=s,t&&(s=s.filter(o=>o.kind===t)),s}()})}normalizeDeviceId(e,t,r){return S(this,void 0,void 0,function*(){if(t!==Gl)return t;const i=yield this.getDevices(e),A=i.find(o=>o.deviceId===Gl);if(!A){ue.warn("could not reliably determine default device");return}const s=i.find(o=>o.deviceId!==Gl&&o.groupId===(r??A.groupId));if(!s){ue.warn("could not reliably determine default device");return}return s==null?void 0:s.deviceId})}hasDeviceInUse(e){return e?ft.userMediaPromiseMap.has(e):ft.userMediaPromiseMap.size>0}}ft.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],ft.userMediaPromiseMap=new Map;var GA;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(GA||(GA={}));class nx{constructor(){this.pendingTasks=new Map,this.taskMutex=new Mt,this.nextTaskIndex=0}run(e){return S(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:GA.WAITING};this.pendingTasks.set(t.id,t);const r=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=GA.RUNNING,yield e()}finally{t.status=GA.COMPLETED,this.pendingTasks.delete(t.id),r()}})}flush(){return S(this,void 0,void 0,function*(){return this.run(()=>S(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function rx(n,e){const t=new URL(VF(n));return e.forEach((r,i)=>{t.searchParams.set(i,r)}),c0(t,"rtc")}function ix(n){const e=new URL(Dl(n));return c0(e,"validate")}function Ax(n){return n.endsWith("/")?n:"".concat(n,"/")}function c0(n,e){return n.pathname="".concat(Ax(n.pathname)).concat(e),n.toString()}const sx=["syncState","trickle","offer","answer","simulate","leave"];function ox(n){const e=sx.indexOf(n.case)>=0;return ue.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var Oe;(function(n){n[n.CONNECTING=0]="CONNECTING",n[n.CONNECTED=1]="CONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.DISCONNECTING=3]="DISCONNECTING",n[n.DISCONNECTED=4]="DISCONNECTED"})(Oe||(Oe={}));class jl{get currentState(){return this.state}get isDisconnected(){return this.state===Oe.DISCONNECTING||this.state===Oe.DISCONNECTED}get isEstablishingConnection(){return this.state===Oe.CONNECTING||this.state===Oe.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 r;this.rtt=0,this.state=Oe.DISCONNECTED,this.log=ue,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=Ln((r=t.loggerName)!==null&&r!==void 0?r:cn.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new nx,this.queuedRequests=[],this.closingLock=new Mt,this.connectionLock=new Mt,this.state=Oe.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,r,i){return S(this,void 0,void 0,function*(){return this.state=Oe.CONNECTING,this.options=r,yield this.connect(e,t,r,i)})}reconnect(e,t,r,i){return S(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=Oe.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:r,reconnectReason:i}))})}connect(e,t,r,i){this.connectOptions=r;const A=HF(),s=ax(t,A,r),o=rx(e,s),a=ix(o);return new Promise((c,u)=>S(this,void 0,void 0,function*(){const l=yield this.connectionLock.lock();try{const d=()=>S(this,void 0,void 0,function*(){this.close(),clearTimeout(h),u(new Fe("room connection has been cancelled (signal)",de.Cancelled))}),h=setTimeout(()=>{this.close(),u(new Fe("room connection has timed out (signal)",de.ServerUnreachable))},r.websocketTimeout);i!=null&&i.aborted&&d(),i==null||i.addEventListener("abort",d);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:r.reconnect,reconnectReason:r.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=>S(this,void 0,void 0,function*(){if(this.state!==Oe.CONNECTED){this.state=Oe.DISCONNECTED,clearTimeout(h);try{const g=yield fetch(a);if(g.status.toFixed(0).startsWith("4")){const v=yield g.text();u(new Fe(v,de.NotAllowed,g.status))}else u(new Fe("Encountered unknown websocket error during connection: ".concat(p.toString()),de.InternalError,g.status))}catch(g){u(new Fe(g instanceof Error?g.message:"server was not reachable",de.ServerUnreachable))}return}this.handleWSError(p)}),this.ws.onmessage=p=>S(this,void 0,void 0,function*(){var g,v,y;let B;if(typeof p.data=="string"){const b=JSON.parse(p.data);B=jm.fromJson(b,{ignoreUnknownFields:!0})}else if(p.data instanceof ArrayBuffer)B=jm.fromBinary(new Uint8Array(p.data));else{this.log.error("could not decode websocket message: ".concat(typeof p.data),this.logContext);return}if(this.state!==Oe.CONNECTED){let b=!1;if(((g=B.message)===null||g===void 0?void 0:g.case)==="join"?(this.state=Oe.CONNECTED,i==null||i.removeEventListener("abort",d),this.pingTimeoutDuration=B.message.value.pingTimeout,this.pingIntervalDuration=B.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(B.message.value)):this.state===Oe.RECONNECTING&&B.message.case!=="leave"?(this.state=Oe.CONNECTED,i==null||i.removeEventListener("abort",d),this.startPingInterval(),((v=B.message)===null||v===void 0?void 0:v.case)==="reconnect"?c(B.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),c(void 0),b=!0)):this.isEstablishingConnection&&B.message.case==="leave"?u(new Fe("Received leave request while trying to (re)connect",de.LeaveRequest,void 0,B.message.value.reason)):r.reconnect||u(new Fe("did not receive join response, got ".concat((y=B.message)===null||y===void 0?void 0:y.case," instead"),de.InternalError)),!b)return}this.signalLatency&&(yield Nt(this.signalLatency)),this.handleSignalResponse(B)}),this.ws.onclose=p=>{this.isEstablishingConnection&&u(new Fe("Websocket got closed during a (re)connection attempt",de.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{l()}}))}close(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const r=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Oe.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const i=new Promise(A=>{e.ws?e.ws.onclose=()=>{A()}:A()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([i,Nt(250)])),e.ws=void 0}}finally{t&&(e.state=Oe.DISCONNECTED),r()}}()})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:sa(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:sa(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 al({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new cl({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const o=A.getNextRequestId();return yield A.sendRequest({case:"updateMetadata",value:new zm({requestId:o,metadata:r,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 Jm({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Zm({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Ke.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new tv({timestamp:Ke.parse(Date.now()),rtt:Ke.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new qm({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new jo({reason:sn.CLIENT_INITIATED,action:Ti.DISCONNECT})})}sendRequest(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!i&&!ox(t)&&r.state===Oe.RECONNECTING){r.queuedRequests.push(()=>S(r,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(i||(yield r.requestQueue.flush()),r.signalLatency&&(yield Nt(r.signalLatency)),!r.ws||r.ws.readyState!==r.ws.OPEN){r.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),r.logContext);return}const s=new QI({message:t});try{r.useJSON?r.ws.send(s.toJsonString()):r.ws.send(s.toBinary())}catch(o){r.log.error("error sending signal message",Object.assign(Object.assign({},r.logContext),{error:o}))}}()})}handleSignalResponse(e){var t,r;const i=e.message;if(i==null){this.log.debug("received unsupported message",this.logContext);return}let A=!1;if(i.case==="answer"){const s=u0(i.value);this.onAnswer&&this.onAnswer(s)}else if(i.case==="offer"){const s=u0(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((r=i.value.speakers)!==null&&r!==void 0?r:[]):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(),A=!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})));A||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return S(this,void 0,void 0,function*(){if(this.state===Oe.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=wt.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&&wt.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=wt.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&wt.clearInterval(this.pingInterval)}}function u0(n){const e={type:"offer",sdp:n.sdp};switch(n.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=n.type;break}return e}function sa(n){return new Gr({sdp:n.sdp,type:n.type})}function ax(n,e,t){var r;const i=new URLSearchParams;return i.set("access_token",n),t.reconnect&&(i.set("reconnect","1"),t.sid&&i.set("sid",t.sid)),i.set("auto_subscribe",t.autoSubscribe?"1":"0"),i.set("sdk",kn()?"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()),!((r=navigator.connection)===null||r===void 0)&&r.type&&i.set("network",navigator.connection.type),i}var ln={},Wl={},ql={exports:{}},l0;function Jl(){if(l0)return ql.exports;l0=1;var n=ql.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(n).forEach(function(e){var t=n[e];t.forEach(function(r){r.reg||(r.reg=/(.*)/),r.format||(r.format="%s")})}),ql.exports}var d0;function cx(){return d0||(d0=1,function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,a,c,u){if(u&&!c)a[u]=e(o[1]);else for(var l=0;l<c.length;l+=1)o[l+1]!=null&&(a[c[l]]=e(o[l+1]))},r=function(o,a,c){var u=o.name&&o.names;o.push&&!a[o.push]?a[o.push]=[]:u&&!a[o.name]&&(a[o.name]={});var l=o.push?{}:u?a[o.name]:a;t(c.match(o.reg),l,o.names,o.name),o.push&&a[o.push].push(l)},i=Jl(),A=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var a={},c=[],u=a;return o.split(/(\r\n|\r|\n)/).filter(A).forEach(function(l){var d=l[0],h=l.slice(2);d==="m"&&(c.push({rtp:[],fmtp:[]}),u=c[c.length-1]);for(var f=0;f<(i[d]||[]).length;f+=1){var p=i[d][f];if(p.reg.test(h))return r(p,u,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};n.parseParams=function(o){return o.split(/;\s?/).reduce(s,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(o){return o.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(o){for(var a=[],c=o.split(" ").map(e),u=0;u<c.length;u+=3)a.push({component:c[u],ip:c[u+1],port:c[u+2]});return a},n.parseImageAttributes=function(o){return o.split(" ").map(function(a){return a.substring(1,a.length-1).split(",").reduce(s,{})})},n.parseSimulcastStreamList=function(o){return o.split(";").map(function(a){return a.split(",").map(function(c){var u,l=!1;return c[0]!=="~"?u=e(c):(u=e(c.substring(1,c.length)),l=!0),{scid:u,paused:l}})})}}(Wl)),Wl}var zl,h0;function ux(){if(h0)return zl;h0=1;var n=Jl(),e=/%[sdv%]/g,t=function(s){var o=1,a=arguments,c=a.length;return s.replace(e,function(u){if(o>=c)return u;var l=a[o];switch(o+=1,u){case"%%":return"%";case"%s":return String(l);case"%d":return Number(l);case"%v":return""}})},r=function(s,o,a){var c=o.format instanceof Function?o.format(o.push?a:a[o.name]):o.format,u=[s+"="+c];if(o.names)for(var l=0;l<o.names.length;l+=1){var d=o.names[l];o.name?u.push(a[o.name][d]):u.push(a[o.names[l]])}else u.push(a[o.name]);return t.apply(null,u)},i=["v","o","s","i","u","e","p","c","b","t","r","z","a"],A=["i","c","b","a"];return zl=function(s,o){o=o||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(l){l.payloads==null&&(l.payloads="")});var a=o.outerOrder||i,c=o.innerOrder||A,u=[];return a.forEach(function(l){n[l].forEach(function(d){d.name in s&&s[d.name]!=null?u.push(r(l,d,s)):d.push in s&&s[d.push]!=null&&s[d.push].forEach(function(h){u.push(r(l,d,h))})})}),s.media.forEach(function(l){u.push(r("m",n.m[0],l)),c.forEach(function(d){n[d].forEach(function(h){h.name in l&&l[h.name]!=null?u.push(r(d,h,l)):h.push in l&&l[h.push]!=null&&l[h.push].forEach(function(f){u.push(r(d,h,f))})})})}),u.join(`\r
|
|
41
41
|
`)+`\r
|
|
42
|
-
`},zl}var p0;function lx(){if(p0)return ln;p0=1;var n=cx(),e=ux(),t=Jl();return ln.grammar=t,ln.write=e,ln.parse=n.parse,ln.parseParams=n.parseParams,ln.parseFmtpConfig=n.parseFmtpConfig,ln.parsePayloads=n.parsePayloads,ln.parseRemoteCandidates=n.parseRemoteCandidates,ln.parseImageAttributes=n.parseImageAttributes,ln.parseSimulcastStreamList=n.parseSimulcastStreamList,ln}var mr=lx();function Xl(n,e,t){var r,i,A;e===void 0&&(e=50),t===void 0&&(t={});var s=(r=t.isImmediate)!=null&&r,o=(i=t.callback)!=null&&i,a=t.maxWait,c=Date.now(),u=[];function l(){if(a!==void 0){var h=Date.now()-c;if(h+e>=a)return a-h}return e}var d=function(){var h=[].slice.call(arguments),f=this;return new Promise(function(p,g){var v=s&&A===void 0;if(A!==void 0&&clearTimeout(A),A=setTimeout(function(){if(A=void 0,c=Date.now(),!s){var B=n.apply(f,h);o&&o(B),u.forEach(function(b){return(0,b.resolve)(B)}),u=[]}},l()),v){var y=n.apply(f,h);return o&&o(y),p(y)}u.push({resolve:p,reject:g})})};return d.cancel=function(h){A!==void 0&&clearTimeout(A),u.forEach(function(f){return(0,f.reject)(h)}),u=[]},d}const dx=.7,hx=20,Oi={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class f0 extends Sn.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 r;super(),this.log=ue,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Xl(i=>S(this,void 0,void 0,function*(){this.emit(Oi.NegotiationStarted);try{yield this.createAndSendOffer()}catch(A){if(i)i(A);else throw A}}),hx),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=Ln((r=t.loggerName)!==null&&r!==void 0?r:cn.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var r;t.candidate&&((r=this.onIceCandidate)===null||r===void 0||r.call(this,t.candidate))},e.onicecandidateerror=t=>{var r;(r=this.onIceCandidateError)===null||r===void 0||r.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 r;(r=this.onDataChannel)===null||r===void 0||r.call(this,t)},e.ontrack=t=>{var r;(r=this.onTrack)===null||r===void 0||r.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 S(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return S(this,void 0,void 0,function*(){var t;let r;if(e.type==="offer"){let{stereoMids:i,nackMids:A}=px(e);this.remoteStereoMids=i,this.remoteNackMids=A}else if(e.type==="answer"){const i=mr.parse((t=e.sdp)!==null&&t!==void 0?t:"");i.media.forEach(A=>{A.type==="audio"&&this.trackBitrates.some(s=>{if(!s.transceiver||A.mid!=s.transceiver.mid)return!1;let o=0;if(A.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 A.fmtp)if(c.payload===o){c.config=c.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),s.maxbr>0&&(c.config+=";maxaveragebitrate=".concat(s.maxbr*1e3)),a=!0;break}return a||s.maxbr>0&&A.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(s.maxbr*1e3)}),!0})}),r=mr.write(i)}yield this.setMungedSDP(e,r,!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(Oi.NegotiationComplete),e.sdp&&mr.parse(e.sdp).media.forEach(A=>{A.type==="video"&&this.emit(Oi.RTPVideoPayloadTypes,A.rtp)}))})}createAndSendOffer(e){return S(this,void 0,void 0,function*(){var t;if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const A=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&A)yield this._pc.setRemoteDescription(A);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 r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const i=mr.parse((t=r.sdp)!==null&&t!==void 0?t:"");i.media.forEach(A=>{m0(A),A.type==="audio"?g0(A,[],[]):A.type==="video"&&this.trackBitrates.some(s=>{if(!A.msid||!s.cid||!A.msid.includes(s.cid))return!1;let o=0;if(A.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0||(KA(s.codec)&&this.ensureVideoDDExtensionForSVC(A,i),s.codec!=="av1"))return!0;const a=Math.round(s.maxbr*dx);for(const c of A.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(r,mr.write(i)),this.onOffer(r)})}createAndSetAnswer(){return S(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),r=mr.parse((e=t.sdp)!==null&&e!==void 0?e:"");return r.media.forEach(i=>{m0(i),i.type==="audio"&&g0(i,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,mr.write(r)),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 lt("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 lt("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 S(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const r=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),r.set(o.id,o);break;case"remote-candidate":i.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const s=(e=r.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(s!==void 0)return i.get(s)})}setMungedSDP(e,t,r){return S(this,void 0,void 0,function*(){if(t){const i=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(r?"remote":"local"," description"),this.logContext),r?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(A){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:A,sdp:t})),e.sdp=i}}try{r?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(i){let A="unknown error";i instanceof Error?A=i.message:typeof i=="string"&&(A=i);const s={error:A,sdp:e.sdp};throw!r&&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 _l(A)}})}ensureVideoDDExtensionForSVC(e,t){var r,i;if(!((r=e.ext)===null||r===void 0?void 0:r.some(s=>s.uri===zv))){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:zv})}}}function g0(n,e,t){let r=0;n.rtp.some(i=>i.codec==="opus"?(r=i.payload,!0):!1),r>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(n.mid)&&!n.rtcpFb.some(i=>i.payload===r&&i.type==="nack")&&n.rtcpFb.push({payload:r,type:"nack"}),e.includes(n.mid)&&n.fmtp.some(i=>i.payload===r?(i.config.includes("stereo=1")||(i.config+=";stereo=1"),!0):!1))}function px(n){var e;const t=[],r=[],i=mr.parse((e=n.sdp)!==null&&e!==void 0?e:"");let A=0;return i.media.forEach(s=>{var o;s.type==="audio"&&(s.rtp.some(a=>a.codec==="opus"?(A=a.payload,!0):!1),!((o=s.rtcpFb)===null||o===void 0)&&o.some(a=>a.payload===A&&a.type==="nack")&&r.push(s.mid),s.fmtp.some(a=>a.payload===A?(a.config.includes("sprop-stereo=1")&&t.push(s.mid),!0):!1))}),{stereoMids:t,nackMids:r}}function m0(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}const Yl="vp8",fx={audioPreset:Ul.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Il.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Yl,backupCodec:!0},v0={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},y0={deviceId:{ideal:"default"},resolution:HA.h720.resolution},gx={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new sF,disconnectOnPageLeave:!0,webAudioMix:!1},Zl={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Ye;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(Ye||(Ye={}));class mx{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,r){var i;this.peerConnectionTimeout=Zl.peerConnectionTimeout,this.log=ue,this.updateState=()=>{var A;const s=this.state,o=this.requiredTransports.map(a=>a.getConnectionState());o.every(a=>a==="connected")?this.state=Ye.CONNECTED:o.some(a=>a==="failed")?this.state=Ye.FAILED:o.some(a=>a==="connecting")?this.state=Ye.CONNECTING:o.every(a=>a==="closed")?this.state=Ye.CLOSED:o.some(a=>a==="closed")?this.state=Ye.CLOSING:o.every(a=>a==="new")&&(this.state=Ye.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(Ye[s]," to ").concat(Ye[this.state]),this.logContext),(A=this.onStateChange)===null||A===void 0||A.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Ln((i=r.loggerName)!==null&&i!==void 0?i:cn.PCManager),this.loggerOptions=r,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new f0(e,r),this.subscriber=new f0(e,r),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=A=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,A,an.PUBLISHER)},this.subscriber.onIceCandidate=A=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,A,an.SUBSCRIBER)},this.subscriber.onDataChannel=A=>{var s;(s=this.onDataChannel)===null||s===void 0||s.call(this,A)},this.subscriber.onTrack=A=>{var s;(s=this.onTrack)===null||s===void 0||s.call(this,A)},this.publisher.onOffer=A=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,A)},this.state=Ye.NEW,this.connectionLock=new Mt,this.remoteOfferLock=new Mt}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 S(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(r){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:r}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return S(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return S(this,void 0,void 0,function*(){t===an.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return S(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 S(this,void 0,void 0,function*(){var r;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((r=this.requiredTransports)===null||r===void 0?void 0:r.map(A=>this.ensureTransportConnected(A,e,t)))}finally{i()}})}negotiate(e){return S(this,void 0,void 0,function*(){return new Promise((t,r)=>S(this,void 0,void 0,function*(){const i=setTimeout(()=>{r("negotiation timed out")},this.peerConnectionTimeout),A=()=>{clearTimeout(i),r("negotiation aborted")};e.signal.addEventListener("abort",A),this.publisher.once(Oi.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Oi.NegotiationComplete,()=>{clearTimeout(i),t()})}),yield this.publisher.negotiate(s=>{clearTimeout(i),r(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===an.PUBLISHER?this.publisher.getConnectedAddress():e===an.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 S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(r.getConnectionState()!=="connected")return new Promise((a,c)=>S(A,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),wt.clearTimeout(l),c(new Fe("room connection has been cancelled",de.Cancelled))};i!=null&&i.signal.aborted&&u(),i==null||i.signal.addEventListener("abort",u);const l=wt.setTimeout(()=>{i==null||i.signal.removeEventListener("abort",u),c(new Fe("could not establish pc connection",de.InternalError))},s);for(;this.state!==Ye.CONNECTED;)if(yield Nt(50),i!=null&&i.signal.aborted){c(new Fe("room connection has been cancelled",de.Cancelled));return}wt.clearTimeout(l),i==null||i.signal.removeEventListener("abort",u),a()}))}()})}}class Ze extends Error{constructor(e,t,r){super(t),this.code=e,this.message=b0(t,Ze.MAX_MESSAGE_BYTES),this.data=r?b0(r,Ze.MAX_DATA_BYTES):void 0}static fromProto(e){return new Ze(e.code,e.message,e.data)}toProto(){return new Om({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new Ze(Ze.ErrorCode[e],Ze.ErrorMessage[e],t)}}Ze.MAX_MESSAGE_BYTES=256,Ze.MAX_DATA_BYTES=15360,Ze.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},Ze.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 w0=15360;function $l(n){return new TextEncoder().encode(n).length}function b0(n,e){if($l(n)<=e)return n;let t=0,r=n.length;const i=new TextEncoder;for(;t<r;){const A=Math.floor((t+r+1)/2);i.encode(n.slice(0,A)).length<=e?t=A:r=A-1}return n.slice(0,t)}const ed=2e3;function oa(n,e){if(!e)return 0;let t,r;return"bytesReceived"in n?(t=n.bytesReceived,r=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,r=e.bytesSent),t===void 0||r===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-r)*8*1e3/(n.timestamp-e.timestamp)}const vx=1e3;class B0 extends R{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,r){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,A=arguments.length>4?arguments[4]:void 0;super(e,t,A),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=Xl(()=>S(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>S(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(L.Ended,this)},this.reacquireTrack=!1,this.providedByUser=i,this.muteLock=new Mt,this.pauseUpstreamLock=new Mt,this.processorLock=new Mt,this.restartLock=new Mt,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),r&&(this._constraints=r)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==R.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 S(this,void 0,void 0,function*(){var r;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(A=>{xi(this._mediaStreamTrack,A)}),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 A=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&&(Fi(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}finally{A()}}this.sender&&((r=this.sender.transport)===null||r===void 0?void 0:r.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(A=>{Fi(i??e,A)}))})}waitForDimensions(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:vx;return function*(){var r;if(e.kind===R.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((r=un())===null||r===void 0?void 0:r.os)==="iOS"&&(yield Nt(10));const i=Date.now();for(;Date.now()-i<t;){const A=e.dimensions;if(A)return A;yield Nt(50)}throw new Dn("unable to get track dimensions after timeout")}()})}setDeviceId(e){return S(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===fr(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),fr(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return S(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===R.Source.ScreenShare)return;const{deviceId:r,groupId:i}=e._mediaStreamTrack.getSettings(),A=e.kind===R.Kind.Audio?"audioinput":"videoinput";return t?ft.getInstance().normalizeDeviceId(A,r,i):r}()})}mute(){return S(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return S(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return S(this,void 0,void 0,function*(){if(!this.sender)throw new Dn("unable to replace an unpublished track");let r,i;return typeof t=="boolean"?r=t:t!==void 0&&(r=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return S(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:r,facingMode:i}=e,A=oF(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===R.Kind.Video?s.video=r||i?{deviceId:r,facingMode:i}:!0:s.audio=r?{deviceId:r}:!0,this.attachedElements.forEach(c=>{xi(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(A),a.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(a),this._constraints=e,this.emit(L.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?L.Muted:L.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 S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Xv()&&(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 S(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(L.UpstreamPaused,this);const r=un();if((r==null?void 0:r.name)==="Safari"&&Wr(r.version,"12.0")<0)throw new Cl("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 S(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(L.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 S(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 S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var A;const s=yield r.processorLock.lock();try{r.log.debug("setting up processor",r.logContext);const o=document.createElement(r.kind),a={kind:r.kind,track:r._mediaStreamTrack,element:o,audioContext:r.audioContext};if(yield t.init(a),r.log.debug("processor initialized",r.logContext),r.processor&&(yield r.stopProcessor()),r.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Fi(r._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>r.log.error("failed to play processor element",Object.assign(Object.assign({},r.logContext),{error:c}))),r.processor=t,r.processorElement=o,r.processor.processedTrack){for(const c of r.attachedElements)c!==r.processorElement&&i&&(xi(r._mediaStreamTrack,c),Fi(r.processor.processedTrack,c));yield(A=r.sender)===null||A===void 0?void 0:A.replaceTrack(r.processor.processedTrack)}r.emit(L.TrackProcessorUpdate,r.processor)}finally{s()}}()})}getProcessor(){return this.processor}stopProcessor(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var r,i;e.processor&&(e.log.debug("stopping processor",e.logContext),(r=e.processor.processedTrack)===null||r===void 0||r.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(L.TrackProcessorUpdate))}()})}}class aa extends B0{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0,A=arguments.length>4?arguments[4]:void 0;super(e,R.Kind.Audio,t,r,A),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>S(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=oa(s,this.prevStats)),this.prevStats=s}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(L.AudioTrackFeatureUpdate,this,on.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(L.AudioTrackFeatureUpdate,this,on.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return S(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===R.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 S(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 r=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==fr(this._constraints.deviceId);return this.source===R.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||r)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return S(this,void 0,void 0,function*(){let t;if(e){const r=Vl({audio:e});typeof r.audio!="boolean"&&(t=r.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return S(this,void 0,void 0,function*(){const r=yield t.restart.call(this,e);return this.checkForSilence(),r})}startMonitor(){Ht()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},ed)))}setProcessor(e){return S(this,void 0,void 0,function*(){var t;const r=yield this.processorLock.lock();try{if(!kn()&&!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(L.TrackProcessorUpdate,this.processor)}finally{r()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return S(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 r;return t.forEach(i=>{i.type==="outbound-rtp"&&(r={type:"audio",streamId:i.id,packetsSent:i.packetsSent,packetsLost:i.packetsLost,bytesSent:i.bytesSent,timestamp:i.timestamp,roundTripTime:i.roundTripTime,jitter:i.jitter})}),r})}checkForSilence(){return S(this,void 0,void 0,function*(){const e=yield A0(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(L.AudioSilenceDetected)),e})}}function yx(n,e,t){switch(n.kind){case"audio":return new aa(n,e,!1,void 0,t);case"video":return new ua(n,e,!1,t);default:throw new Dn("unsupported track type: ".concat(n.kind))}}const wx=Object.values(HA),bx=Object.values(Tl),Bx=Object.values(Il),Cx=[HA.h180,HA.h360],_x=[Tl.h180,Tl.h360],Sx=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var r,i;return new Te(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((r=n.encoding.maxFramerate)!==null&&r!==void 0?r:30)/((i=t.fps)!==null&&i!==void 0?i:30))))),t.fps,n.encoding.priority)}),td=["q","h","f"];function nd(n,e,t,r){var i,A;let s=r==null?void 0:r.videoEncoding;n&&(s=r==null?void 0:r.screenShareEncoding);const o=r==null?void 0:r.simulcast,a=r==null?void 0:r.scalabilityMode,c=r==null?void 0:r.videoCodec;if(!s&&!o&&!a||!e||!t)return[{}];s||(s=Ex(n,e,t,c),ue.debug("using video encoding",s));const u=s.maxFramerate,l=new Te(e,t,s.maxBitrate,s.maxFramerate,s.priority);if(a&&KA(c)){const f=new ca(a),p=[];if(f.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(a));const g=un();if(pr()||kn()||(g==null?void 0:g.name)==="Chrome"&&Wr(g==null?void 0:g.version,"113")<0){const v=f.suffix=="h"?2:3;for(let y=0;y<f.spatial;y+=1)p.push({rid:td[2-y],maxBitrate:s.maxBitrate/Math.pow(v,y),maxFramerate:l.encoding.maxFramerate});p[0].scalabilityMode=a}else p.push({maxBitrate:s.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:a});return l.encoding.priority&&(p[0].priority=l.encoding.priority,p[0].networkPriority=l.encoding.priority),ue.debug("using svc encoding",{encodings:p}),p}if(!o)return[s];let d=[];n?d=(i=_0(r==null?void 0:r.screenShareSimulcastLayers))!==null&&i!==void 0?i:C0(n,l):d=(A=_0(r==null?void 0:r.videoSimulcastLayers))!==null&&A!==void 0?A:C0(n,l);let h;if(d.length>0){const f=d[0];d.length>1&&([,h]=d);const p=Math.max(e,t);if(p>=960&&h)return rd(e,t,[f,h,l],u);if(p>=480)return rd(e,t,[f,l],u)}return rd(e,t,[l])}function kx(n,e,t){var r,i,A,s;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&ue.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),a=(r=o.width)!==null&&r!==void 0?r:(i=n.dimensions)===null||i===void 0?void 0:i.width,c=(A=o.height)!==null&&A!==void 0?A:(s=n.dimensions)===null||s===void 0?void 0:s.height;return n.source===R.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),nd(n.source===R.Source.ScreenShare,a,c,t)}function Ex(n,e,t,r){const i=Ux(n,e,t);let{encoding:A}=i[0];const s=Math.max(e,t);for(let o=0;o<i.length;o+=1){const a=i[o];if(A=a.encoding,a.width>=s)break}if(r)switch(r){case"av1":A=Object.assign({},A),A.maxBitrate=A.maxBitrate*.7;break;case"vp9":A=Object.assign({},A),A.maxBitrate=A.maxBitrate*.85;break}return A}function Ux(n,e,t){if(n)return Bx;const r=e>t?e/t:t/e;return Math.abs(r-16/9)<Math.abs(r-4/3)?wx:bx}function C0(n,e){if(n)return Sx(e);const{width:t,height:r}=e,i=t>r?t/r:r/t;return Math.abs(i-16/9)<Math.abs(i-4/3)?Cx:_x}function rd(n,e,t,r){const i=[];if(t.forEach((A,s)=>{if(s>=td.length)return;const o=Math.min(n,e),c={rid:td[s],scaleResolutionDownBy:Math.max(1,o/Math.min(A.width,A.height)),maxBitrate:A.encoding.maxBitrate},u=r&&A.encoding.maxFramerate?Math.min(r,A.encoding.maxFramerate):A.encoding.maxFramerate;u&&(c.maxFramerate=u);const l=Qi()||s===0;A.encoding.priority&&l&&(c.priority=A.encoding.priority,c.networkPriority=A.encoding.priority),i.push(c)}),kn()&&Zv()==="ios"){let A;i.forEach(o=>{A?o.maxFramerate&&o.maxFramerate>A&&(A=o.maxFramerate):A=o.maxFramerate});let s=!0;i.forEach(o=>{var a;o.maxFramerate!=A&&(s&&(s=!1,ue.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ue.info('Setting framerate of encoding "'.concat((a=o.rid)!==null&&a!==void 0?a:"",'" to ').concat(A)),o.maxFramerate=A)})}return i}function _0(n){if(n)return n.sort((e,t)=>{const{encoding:r}=e,{encoding:i}=t;return r.maxBitrate>i.maxBitrate?1:r.maxBitrate<i.maxBitrate?-1:r.maxBitrate===i.maxBitrate&&r.maxFramerate&&i.maxFramerate?r.maxFramerate>i.maxFramerate?1:-1:0})}class ca{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 Tx(n){return n.source===R.Source.ScreenShare||n.constraints.height&&fr(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const Ix=5e3;class ua extends B0{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0;super(e,R.Kind.Video,t,r,i),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>S(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let A;try{A=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}const s=new Map(A.map(o=>[o.rid,o]));if(this.prevStats){let o=0;s.forEach((a,c)=>{var u;const l=(u=this.prevStats)===null||u===void 0?void 0:u.get(c);o+=oa(a,l)}),this._currentBitrate=o}this.prevStats=s}),this.senderLock=new Mt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Ht())return;const r=(t=this.sender)===null||t===void 0?void 0:t.getParameters();r&&(this.encodings=r.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},ed))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return S(this,void 0,void 0,function*(){var t,r,i,A,s;yield e.pauseUpstream.call(this);try{for(var o=!0,a=ur(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0)A=c.value,o=!1,yield(s=A.sender)===null||s===void 0?void 0:s.replaceTrack(null)}catch(u){r={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(r)throw r.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return S(this,void 0,void 0,function*(){var t,r,i,A,s;yield e.resumeUpstream.call(this);try{for(var o=!0,a=ur(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0){A=c.value,o=!1;const u=A;yield(s=u.sender)===null||s===void 0?void 0:s.replaceTrack(u.mediaStreamTrack)}}catch(u){r={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(r)throw r.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return S(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===R.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 S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===R.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 S(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],r=yield this.sender.getStats();return r.forEach(i=>{var A;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:(A=i.rid)!==null&&A!==void 0?A:i.id,retransmittedPacketsSent:i.retransmittedPacketsSent,targetBitrate:i.targetBitrate,timestamp:i.timestamp},o=r.get(i.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}}),t.sort((i,A)=>{var s,o;return((s=A.frameWidth)!==null&&s!==void 0?s:0)-((o=i.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let r=Yt.LOW;r<=Yt.HIGH;r+=1)t.push(new ll({quality:r,enabled:r<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return S(this,void 0,void 0,function*(){var t,r,i,A,s;let o;if(e){const l=Vl({video:e});typeof l.video!="boolean"&&(o=l.video)}yield this.restart(o);try{for(var a=!0,c=ur(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;a=!0){A=u.value,a=!1;const l=A;l.sender&&((s=l.sender.transport)===null||s===void 0?void 0:s.state)!=="closed"&&(l.mediaStreamTrack=this.mediaStreamTrack.clone(),yield l.sender.replaceTrack(l.mediaStreamTrack))}}catch(l){r={error:l}}finally{try{!a&&!t&&(i=c.return)&&(yield i.call(c))}finally{if(r)throw r.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return S(this,arguments,void 0,function(r){var i=this;let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s,o,a,c,u,l;if(yield t.setProcessor.call(i,r,A),!((u=i.processor)===null||u===void 0)&&u.processedTrack)try{for(var d=!0,h=ur(i.simulcastCodecs.values()),f;f=yield h.next(),s=f.done,!s;d=!0)c=f.value,d=!1,yield(l=c.sender)===null||l===void 0?void 0:l.replaceTrack(i.processor.processedTrack)}catch(p){o={error:p}}finally{try{!d&&!s&&(a=h.return)&&(yield a.call(h))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return S(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 r={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,r),r}setSimulcastTrackSender(e,t){const r=this.simulcastCodecs.get(e);r&&(r.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Ix))}setPublishingCodecs(e){return S(this,void 0,void 0,function*(){var t,r,i,A,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,r=ur(e);i=yield r.next(),A=i.done,!A;t=!0){a=i.value,t=!1;const u=a;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(u.qualities);else{const l=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:l})),!l||!l.sender){for(const d of u.qualities)if(d.enabled){c.push(u.codec);break}}else l.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield S0(l.sender,l.encodings,u.qualities,this.senderLock,this.log,this.logContext))}}}catch(u){s={error:u}}finally{try{!t&&!A&&(o=r.return)&&(yield o.call(r))}finally{if(s)throw s.error}}return c})}setPublishingLayers(e){return S(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 S0(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Xv()&&this.isInBackground&&this.source===R.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function S0(n,e,t,r,i,A){return S(this,void 0,void 0,function*(){const s=yield r.lock();i.debug("setPublishingLayersForSender",Object.assign(Object.assign({},A),{sender:n,qualities:t,senderEncodings:e}));try{const o=n.getParameters(),{encodings:a}=o;if(!a)return;if(a.length!==e.length){i.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},A),{encodings:a,senderEncodings:e}));return}let c=!1;const u=un();if((u==null?void 0:u.name)==="Chrome"&&Wr(u==null?void 0:u.version,"133")>0&&a[0].scalabilityMode){const d=a[0],h=new ca(d.scalabilityMode);let f=Si.OFF;if(t.forEach(p=>{p.enabled&&(f===Si.OFF||p.quality>f)&&(f=p.quality)}),f===Si.OFF)d.active&&(d.active=!1,c=!0);else if(!d.active||h.spatial!==f+1){c=!0,d.active=!0;const p=new ca(e[0].scalabilityMode);h.spatial=f+1,h.suffix=p.suffix,h.spatial===1&&(h.suffix=void 0),d.scalabilityMode=h.toString(),d.scaleResolutionDownBy=Math.pow(2,2-f),e[0].maxBitrate&&(d.maxBitrate=e[0].maxBitrate/(d.scaleResolutionDownBy*d.scaleResolutionDownBy))}}else a.forEach((d,h)=>{var f;let p=(f=d.rid)!==null&&f!==void 0?f:"";p===""&&(p="q");const g=k0(p),v=t.find(y=>y.quality===g);v&&d.active!==v.enabled&&(c=!0,d.active=v.enabled,i.debug("setting layer ".concat(v.quality," to ").concat(d.active?"enabled":"disabled"),A),Qi()&&(v.enabled?(d.scaleResolutionDownBy=e[h].scaleResolutionDownBy,d.maxBitrate=e[h].maxBitrate,d.maxFrameRate=e[h].maxFrameRate):(d.scaleResolutionDownBy=4,d.maxBitrate=10,d.maxFrameRate=2)))});c&&(o.encodings=a,i.debug("setting encodings",Object.assign(Object.assign({},A),{encodings:o.encodings})),yield n.setParameters(o))}finally{s()}})}function k0(n){switch(n){case"f":return Yt.HIGH;case"h":return Yt.MEDIUM;case"q":return Yt.LOW;default:return Yt.HIGH}}function E0(n,e,t,r){if(!t)return[new Vr({quality:Yt.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(r){const i=t[0].scalabilityMode,A=new ca(i),s=[],o=A.suffix=="h"?1.5:2,a=A.suffix=="h"?2:3;for(let c=0;c<A.spatial;c+=1)s.push(new Vr({quality:Math.min(Yt.HIGH,A.spatial-1)-c,width:Math.ceil(n/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 A,s,o;const a=(A=i.scaleResolutionDownBy)!==null&&A!==void 0?A:1;let c=k0((s=i.rid)!==null&&s!==void 0?s:"");return new Vr({quality:c,width:Math.ceil(n/a),height:Math.ceil(e/a),bitrate:(o=i.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const U0="_lossy",T0="_reliable",Fx=2*1e3,id="leave-reconnect";var dn;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(dn||(dn={}));class xx extends Sn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Zl.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=dn.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=ue,this.handleDataChannel=r=>S(this,[r],void 0,function(i){var A=this;let{channel:s}=i;return function*(){if(s){if(s.label===T0)A.reliableDCSub=s;else if(s.label===U0)A.lossyDCSub=s;else return;A.log.debug("on data channel ".concat(s.id,", ").concat(s.label),A.logContext),s.onmessage=A.handleDataMessage}}()}),this.handleDataMessage=r=>S(this,void 0,void 0,function*(){var i,A;const s=yield this.dataProcessLock.lock();try{let o;if(r.data instanceof ArrayBuffer)o=r.data;else if(r.data instanceof Blob)o=yield r.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:r.data}));return}const a=Dt.fromBinary(new Uint8Array(o));((i=a.value)===null||i===void 0?void 0:i.case)==="speaker"?this.emit(D.ActiveSpeakersUpdate,a.value.value.speakers):(((A=a.value)===null||A===void 0?void 0:A.case)==="user"&&Rx(a,a.value.value),this.emit(D.DataPacketReceived,a))}finally{s()}}),this.handleDataError=r=>{const A=r.currentTarget.maxRetransmits===0?"lossy":"reliable";if(r instanceof ErrorEvent&&r.error){const{error:s}=r.error;this.log.error("DataChannel error on ".concat(A,": ").concat(r.message),Object.assign(Object.assign({},this.logContext),{error:s}))}else this.log.error("Unknown DataChannel error on ".concat(A),Object.assign(Object.assign({},this.logContext),{event:r}))},this.handleBufferedAmountLow=r=>{const A=r.currentTarget.maxRetransmits===0?pe.LOSSY:pe.RELIABLE;this.updateAndEmitDCBufferStatus(A)},this.handleDisconnect=(r,i)=>{if(this._isClosed)return;this.log.warn("".concat(r," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const A=a=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(a,"ms. giving up"),this.logContext),this.emit(D.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});if(o===null){A(s);return}r===id&&(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=wt.setTimeout(()=>this.attemptReconnect(i).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((r,i)=>{this.pcState===dn.Connected&&r();const A=()=>{this.off(D.Disconnected,s),r()},s=()=>{this.off(D.Restarted,A),i()};this.once(D.Restarted,A),this.once(D.Disconnected,s)}),this.updateAndEmitDCBufferStatus=r=>{const i=this.isBufferStatusLow(r);typeof i<"u"&&i!==this.dcBufferStatus.get(r)&&(this.dcBufferStatus.set(r,i),this.emit(D.DCBufferStatusChanged,i,r))},this.isBufferStatusLow=r=>{const i=this.dataChannelForKind(r);if(i)return i.bufferedAmount<=i.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Oe.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ki.RR_SIGNAL_DISCONNECTED))},this.log=Ln((t=e.loggerName)!==null&&t!==void 0?t:cn.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new jl(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Mt,this.dataProcessLock=new Mt,this.dcBufferStatus=new Map([[pe.LOSSY,!0],[pe.RELIABLE,!0]]),this.client.onParticipantUpdate=r=>this.emit(D.ParticipantUpdate,r),this.client.onConnectionQuality=r=>this.emit(D.ConnectionQualityUpdate,r),this.client.onRoomUpdate=r=>this.emit(D.RoomUpdate,r),this.client.onSubscriptionError=r=>this.emit(D.SubscriptionError,r),this.client.onSubscriptionPermissionUpdate=r=>this.emit(D.SubscriptionPermissionUpdate,r),this.client.onSpeakersChanged=r=>this.emit(D.SpeakersChanged,r),this.client.onStreamStateUpdate=r=>this.emit(D.StreamStateChanged,r),this.client.onRequestResponse=r=>this.emit(D.SignalRequestResponse,r)}get logContext(){var e,t,r,i,A,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=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.room)===null||i===void 0?void 0:i.sid,participant:(s=(A=this.latestJoinResponse)===null||A===void 0?void 0:A.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,r,i){return S(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=r,this.maxJoinAttempts=r.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const A=yield this.client.join(e,t,r,i);return this._isClosed=!1,this.latestJoinResponse=A,this.subscriberPrimary=A.subscriberPrimary,this.pcManager||(yield this.configure(A)),(!this.subscriberPrimary||A.fastPublish)&&this.negotiate(),this.clientConfiguration=A.clientConfiguration,setTimeout(()=>{this.emit(D.SignalConnected)},10),A}catch(A){if(A instanceof Fe&&A.reason===de.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,r,i);throw A}})}close(){return S(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(D.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return S(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=r=>{r&&(r.close(),r.onbufferedamountlow=null,r.onclose=null,r.onclosing=null,r.onerror=null,r.onmessage=null,r.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 S(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Dn("a track with the same ID has already been published");return new Promise((t,r)=>{const i=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],r(new Fe("publication of local track timed out, no response from server",de.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:A=>{clearTimeout(i),t(A)},reject:()=>{clearTimeout(i),r(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 S(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 S(this,void 0,void 0,function*(){var t,r;if(this.pcManager&&this.pcManager.currentState!==Ye.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const i=this.makeRTCConfiguration(e);this.pcManager=new mx(i,e.subscriberPrimary,this.loggerOptions),this.emit(D.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(A,s)=>{this.client.sendIceCandidate(A,s)},this.pcManager.onPublisherOffer=A=>{this.client.sendOffer(A)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(A,s,o)=>S(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(A),this.logContext),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),A===Ye.CONNECTED){const u=this.pcState===dn.New;this.pcState=dn.Connected,u&&this.emit(D.Connected,e)}else A===Ye.FAILED&&this.pcState===dn.Connected&&(this.pcState=dn.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?ki.RR_SUBSCRIBER_FAILED:ki.RR_PUBLISHER_FAILED));const a=this.client.isDisconnected||this.client.currentState===Oe.RECONNECTING,c=[Ye.FAILED,Ye.CLOSING,Ye.CLOSED].includes(A);a&&c&&!this._isClosed&&this.emit(D.Offline)}),this.pcManager.onTrack=A=>{this.emit(D.MediaTrackAdded,A.track,A.streams[0],A.receiver)},Qx((r=e.serverInfo)===null||r===void 0?void 0:r.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>S(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=>S(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:r}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],r(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(D.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(D.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(D.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(D.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.emit(D.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",ki.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Ti.DISCONNECT:this.emit(D.Disconnected,e==null?void 0:e.reason),this.close();break;case Ti.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(id);break;case Ti.RESUME:this.handleDisconnect(id)}}}makeRTCConfiguration(e){var t;const r=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),r.encodedInsertableStreams=!0),e.iceServers&&!r.iceServers){const i=[];e.iceServers.forEach(A=>{const s={urls:A.urls};A.username&&(s.username=A.username),A.credential&&(s.credential=A.credential),i.push(s)}),r.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===LA.ENABLED&&(r.iceTransportPolicy="relay"),r.sdpSemantics="unified-plan",r.continualGatheringPolicy="gather_continually",r}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(U0,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(T0,{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,r){return S(this,void 0,void 0,function*(){if(Fl())return yield this.createTransceiverRTCRtpSender(e,t,r);if(xl())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new lt("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,r,i){return S(this,void 0,void 0,function*(){if(Fl())return this.createSimulcastTransceiverSender(e,t,r,i);if(xl())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new lt("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,r){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new lt("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),Pi(e)&&(e.codec=t.videoCodec);const A={direction:"sendonly",streams:i};return r&&(A.sendEncodings=r),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,A)).sender})}createSimulcastTransceiverSender(e,t,r,i){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new lt("publisher is closed");const A={direction:"sendonly"};i&&(A.sendEncodings=i);const s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,A);if(r.videoCodec)return e.setSimulcastTrackSender(r.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new lt("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return S(this,void 0,void 0,function*(){var t,r,i;if(!this._isClosed){if(this.attemptingReconnect){ue.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===LA.DISABLED||((i=(r=this.pcManager)===null||r===void 0?void 0:r.currentState)!==null&&i!==void 0?i:Ye.NEW)===Ye.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(A){this.reconnectAttempts+=1;let s=!0;A instanceof lt?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:A})),s=!1):A instanceof Mi||(this.fullReconnectOnNext=!0),s?this.handleDisconnect("reconnect",ki.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(D.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 S(this,void 0,void 0,function*(){var t,r,i;try{if(!this.url||!this.token)throw new lt("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(D.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let A;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Mi;A=yield this.join(e??this.url,this.token,this.signalOpts)}catch(s){throw s instanceof Fe&&s.reason===de.NotAllowed?new lt("could not reconnect, token might be expired"):new Mi}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(D.SignalRestarted,A),yield this.waitForPCReconnected(),this.client.currentState!==Oe.CONNECTED)throw new Mi("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(D.Restarted)}catch(A){const s=yield(r=this.regionUrlProvider)===null||r===void 0?void 0:r.getNextBestRegionUrl();if(s){yield this.restartConnection(s);return}else throw(i=this.regionUrlProvider)===null||i===void 0||i.resetAttempts(),A}})}resumeConnection(e){return S(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new lt("could not reconnect, url or token not saved");if(!this.pcManager)throw new lt("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(D.Resuming);let r;try{this.setupSignalClientCallbacks(),r=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(i){let A="";throw i instanceof Error&&(A=i.message,this.log.error(i.message,Object.assign(Object.assign({},this.logContext),{error:i}))),i instanceof Fe&&i.reason===de.NotAllowed?new lt("could not reconnect, token might be expired"):i instanceof Fe&&i.reason===de.LeaveRequest?i:new Mi(A)}if(this.emit(D.SignalResumed),r){const i=this.makeRTCConfiguration(r);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!==Oe.CONNECTED)throw new Mi("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(D.Resumed)})}waitForPCInitialConnection(e,t){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new lt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return S(this,void 0,void 0,function*(){this.pcState=dn.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Nt(Fx),!this.pcManager)throw new lt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=dn.Connected}catch(e){throw this.pcState=dn.Disconnected,new Fe("could not establish PC connection, ".concat(e.message),de.InternalError)}})}publishRpcResponse(e,t,r,i){return S(this,void 0,void 0,function*(){const A=new Dt({destinationIdentities:[e],kind:pe.RELIABLE,value:{case:"rpcResponse",value:new Pm({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:r??""}})}});yield this.sendDataPacket(A,pe.RELIABLE)})}publishRpcAck(e,t){return S(this,void 0,void 0,function*(){const r=new Dt({destinationIdentities:[e],kind:pe.RELIABLE,value:{case:"rpcAck",value:new Rm({requestId:t})}});yield this.sendDataPacket(r,pe.RELIABLE)})}sendDataPacket(e,t){return S(this,void 0,void 0,function*(){const r=e.toBinary();yield this.ensurePublisherConnected(t);const i=this.dataChannelForKind(t);i&&i.send(r),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,r)=>S(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const i=()=>r("Engine closed");for(this.once(D.Closing,i);!this.dcBufferStatus.get(e);)yield Nt(10);this.off(D.Closing,i),t()}}))}ensureDataTransportConnected(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var A;if(!r.pcManager)throw new lt("PC manager is closed");const s=i?r.pcManager.subscriber:r.pcManager.publisher,o=i?"Subscriber":"Publisher";if(!s)throw new Fe("".concat(o," connection not set"),de.InternalError);let a=!1;!i&&!r.dataChannelForKind(t,i)&&(r.createDataChannels(),a=!0),!a&&!i&&!r.pcManager.publisher.isICEConnected&&r.pcManager.publisher.getICEConnectionState()!=="checking"&&(a=!0),a&&r.negotiate();const c=r.dataChannelForKind(t,i);if((c==null?void 0:c.readyState)==="open")return;const u=new Date().getTime()+r.peerConnectionTimeout;for(;new Date().getTime()<u;){if(s.isICEConnected&&((A=r.dataChannelForKind(t,i))===null||A===void 0?void 0:A.readyState)==="open")return;yield Nt(50)}throw new Fe("could not establish ".concat(o," connection, state: ").concat(s.getICEConnectionState()),de.InternalError)}()})}ensurePublisherConnected(e){return S(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Ye.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return S(this,void 0,void 0,function*(){return new Promise((e,t)=>S(this,void 0,void 0,function*(){if(!this.pcManager){t(new _l("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const r=new AbortController,i=()=>{r.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(D.Closing,i),this.pcManager.publisher.once(Oi.RTPVideoPayloadTypes,A=>{const s=new Map;A.forEach(o=>{const a=o.codec.toLowerCase();KF(a)&&s.set(o.payload,a)}),this.emit(D.RTPVideoMapUpdate,s)});try{yield this.pcManager.negotiate(r),e()}catch(A){A instanceof _l&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ki.RR_UNKNOWN),t(A)}finally{this.off(D.Closing,i)}}))})}dataChannelForKind(e,t){if(t){if(e===pe.LOSSY)return this.lossyDCSub;if(e===pe.RELIABLE)return this.reliableDCSub}else{if(e===pe.LOSSY)return this.lossyDC;if(e===pe.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var r,i;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const A=this.pcManager.subscriber.getLocalDescription(),s=this.pcManager.subscriber.getRemoteDescription(),o=(i=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&i!==void 0?i:!0,a=new Array,c=new Array;e.forEach(u=>{u.isDesired!==o&&a.push(u.trackSid),u.isEnabled||c.push(u.trackSid)}),this.client.sendSyncState(new $m({answer:A?sa({sdp:A.sdp,type:A.type}):void 0,offer:s?sa({sdp:s.sdp,type:s.type}):void 0,subscription:new Go({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:YF(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(r,i)=>{(r==null?void 0:r.id)!==void 0&&r.id!==null&&e.push(new ev({label:r.label,id:r.id,target:i}))};return t(this.dataChannelForKind(pe.LOSSY),an.PUBLISHER),t(this.dataChannelForKind(pe.RELIABLE),an.PUBLISHER),t(this.dataChannelForKind(pe.LOSSY,!0),an.SUBSCRIBER),t(this.dataChannelForKind(pe.RELIABLE,!0),an.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&wt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ht()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Ht()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Mi extends Error{}function Qx(n){return n!==void 0&&n>13}function Rx(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const r=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=r,e.destinationIdentities=r}class Ad{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 Rl(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return S(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(r=>!this.attemptedRegions.find(i=>i.url===r.url));if(t.length>0){const r=t[0];return this.attemptedRegions.push(r),ue.debug("next region: ".concat(r.region)),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return S(this,void 0,void 0,function*(){const t=yield fetch("".concat(Px(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const r=yield t.json();return this.lastUpdateAt=Date.now(),r}else throw new Fe("Could not fetch region settings: ".concat(t.statusText),t.status===401?de.NotAllowed:de.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function Px(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class I0{get info(){return this._info}constructor(e,t,r){this.reader=t,this.totalByteSize=r,this._info=e,this.bytesReceived=0}}class Ox extends I0{handleChunkReceived(e){var t;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();return{next:()=>S(this,void 0,void 0,function*(){try{const{done:t,value:r}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(r),{done:!1,value:r.content})}catch{return{done:!0,value:void 0}}}),return(){return S(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return S(this,void 0,void 0,function*(){var e,t,r,i;let A=new Set;try{for(var s=!0,o=ur(this),a;a=yield o.next(),e=a.done,!e;s=!0){i=a.value,s=!1;const c=i;A.add(c)}}catch(c){t={error:c}}finally{try{!s&&!e&&(r=o.return)&&(yield r.call(o))}finally{if(t)throw t.error}}return Array.from(A)})}}class Mx extends I0{constructor(e,t,r){super(e,t,r),this.receivedChunks=new Map}handleChunkReceived(e){var t;const r=ia(e.chunkIndex),i=this.receivedChunks.get(r);if(i&&i.version>e.version)return;this.receivedChunks.set(r,e),this.bytesReceived+=e.content.byteLength;const A=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,A)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>S(this,void 0,void 0,function*(){try{const{done:r,value:i}=yield e.read();return r?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:t.decode(i.content)})}catch{return{done:!0,value:void 0}}}),return(){return S(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return S(this,void 0,void 0,function*(){var e,t,r,i;let A="";try{for(var s=!0,o=ur(this),a;a=yield o.next(),e=a.done,!e;s=!0)i=a.value,s=!1,A+=i}catch(c){t={error:c}}finally{try{!s&&!e&&(r=o.return)&&(yield r.call(o))}finally{if(t)throw t.error}}return A})}}class F0{constructor(e,t,r){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=r,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return S(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 Lx extends F0{}class Dx extends F0{}class x0 extends R{constructor(e,t,r,i,A){super(e,r,A),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?L.Muted:L.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=r=>{r.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(L.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return S(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(),ed)),ZF()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const r=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(r){const{timestamp:i,rtpTimestamp:A}=r;A&&this.rtpTimestamp!==A&&(this.emit(L.TimeSyncUpdate,{timestamp:i,rtpTimestamp:A}),this.rtpTimestamp=A)}};e()}}class Nx extends x0{constructor(e,t,r,i,A,s){super(e,t,R.Kind.Audio,r,s),this.monitorReceiver=()=>S(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=oa(o,this.prevStats)),this.prevStats=o}),this.audioContext=i,this.webAudioPluginNodes=[],A&&(this.sinkId=A.deviceId)}setVolume(e){var t;for(const r of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):r.volume=e;kn()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(kn())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return S(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Ql(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Ql(e)&&e.setSinkId(this.sinkId).catch(r=>{this.log.error("Failed to set sink id on remote audio track",r,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 r=this.sourceNode;this.webAudioPluginNodes.forEach(i=>{r.connect(i),r=i}),this.gainNode=e.createGain(),r.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(L.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(i=>{this.emit(L.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 S(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(r=>{r.type==="inbound-rtp"&&(t={type:"audio",streamId:r.id,timestamp:r.timestamp,jitter:r.jitter,bytesReceived:r.bytesReceived,concealedSamples:r.concealedSamples,concealmentEvents:r.concealmentEvents,silentConcealedSamples:r.silentConcealedSamples,silentConcealmentEvents:r.silentConcealmentEvents,totalAudioEnergy:r.totalAudioEnergy,totalSamplesDuration:r.totalSamplesDuration})}),t})}}const sd=100;class Hx extends x0{constructor(e,t,r,i,A){super(e,t,R.Kind.Video,r,A),this.elementInfos=[],this.monitorReceiver=()=>S(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=oa(s,this.prevStats)),this.prevStats=s}),this.debouncedHandleResize=Xl(()=>{this.updateDimensions()},sd),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?xi(this._mediaStreamTrack,t):Fi(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 Kx(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(r=>r===e);for(const r of t)r.stopObserving();this.elementInfos=this.elementInfos.filter(r=>r!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const r of t)this.stopObservingElement(r);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return S(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,r="",i=new Map;return e.forEach(A=>{A.type==="inbound-rtp"?(r=A.codecId,t={type:"video",streamId:A.id,framesDecoded:A.framesDecoded,framesDropped:A.framesDropped,framesReceived:A.framesReceived,packetsReceived:A.packetsReceived,packetsLost:A.packetsLost,frameWidth:A.frameWidth,frameHeight:A.frameHeight,pliCount:A.pliCount,firCount:A.firCount,nackCount:A.nackCount,jitter:A.jitter,timestamp:A.timestamp,bytesReceived:A.bytesReceived,decoderImplementation:A.decoderImplementation}):A.type==="codec"&&i.set(A.id,A)}),t&&r!==""&&i.get(r)&&(t.mimeType=i.get(r).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(r=>r.element===e);for(const r of t)this.stopObservingElementInfo(r)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const r=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,A=this.elementInfos.some(o=>o.pictureInPicture),s=this.elementInfos.some(o=>o.visible)&&!i||A;if(this.lastVisible!==s){if(!s&&Date.now()-r<sd){wt.setTimeout(()=>{this.updateVisibility()},sd);return}this.lastVisible=s,this.emit(L.VisibilityChanged,s,this)}}updateDimensions(){var e,t;let r=0,i=0;const A=this.getPixelDensity();for(const s of this.elementInfos){const o=s.width()*A,a=s.height()*A;o+a>r+i&&(r=o,i=a)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===r&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===i||(this.lastDimensions={width:r,height:i},this.emit(L.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?$v():t||($v()>2?2:1)}}class Kx{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=r=>{var i;const{target:A,isIntersecting:s}=r;A===this.element&&(this.isIntersecting=s,this.isPiP=jA(this.element),this.visibilityChangedAt=Date.now(),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this))},this.onEnterPiP=()=>{var r,i,A;(i=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP),this.isPiP=jA(this.element),(A=this.handleVisibilityChanged)===null||A===void 0||A.call(this)},this.onLeavePiP=()=>{var r;this.isPiP=jA(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.element=e,this.isIntersecting=t??od(e),this.isPiP=Ht()&&jA(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,r;this.isIntersecting=od(this.element),this.isPiP=jA(this.element),this.element.handleResize=()=>{var i;(i=this.handleResize)===null||i===void 0||i.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,t0().observe(this.element),e0().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),(r=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,r,i,A;(e=t0())===null||e===void 0||e.unobserve(this.element),(t=e0())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(r=window.documentPictureInPicture)===null||r===void 0||r.removeEventListener("enter",this.onEnterPiP),(A=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||A===void 0||A.removeEventListener("pagehide",this.onLeavePiP)}}function jA(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?od(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function od(n,e){const t=e||window;let r=n.offsetTop,i=n.offsetLeft;const A=n.offsetWidth,s=n.offsetHeight,{hidden:o}=n,{display:a}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,r+=n.offsetTop,i+=n.offsetLeft;return r<t.pageYOffset+t.innerHeight&&i<t.pageXOffset+t.innerWidth&&r+s>t.pageYOffset&&i+A>t.pageXOffset&&!o&&a!=="none"}class Hn extends Sn.EventEmitter{constructor(e,t,r,i){var A;super(),this.metadataMuted=!1,this.encryption=Wt.NONE,this.log=ue,this.handleMuted=()=>{this.emit(L.Muted)},this.handleUnmuted=()=>{this.emit(L.Unmuted)},this.log=Ln((A=i==null?void 0:i.loggerName)!==null&&A!==void 0?A:cn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=r,this.source=R.Source.Unknown}setTrack(e){this.track&&(this.track.off(L.Muted,this.handleMuted),this.track.off(L.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(L.Muted,this.handleMuted),e.on(L.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),_e(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Wt.NONE}get audioTrack(){if(Nn(this.track))return this.track}get videoTrack(){if(Pi(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=R.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===R.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(n.PermissionStatus||(n.PermissionStatus={}))})(Hn||(Hn={}));class ad extends Hn{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,r,i){super(e,t.sid,t.name,i),this.track=void 0,this.handleTrackEnded=()=>{this.emit(L.Ended)},this.updateInfo(t),this.setTrack(r)}setTrack(e){this.track&&this.track.off(L.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(L.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 S(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return S(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return S(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return S(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Nn(this.track)){const t=this.track.getSourceTrackSettings(),r=new Set;return t.autoGainControl&&r.add(on.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&r.add(on.TF_ECHO_CANCELLATION),t.noiseSuppression&&r.add(on.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&r.add(on.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||r.add(on.TF_NO_DTX),this.track.enhancedNoiseCancellation&&r.add(on.TF_ENHANCED_NOISE_CANCELLATION),Array.from(r.values())}else return[]}}function la(n,e){return S(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:r,videoProcessor:i,optionsWithoutProcessor:A}=a0(n);let s=A.audio,o=A.video;if(r&&typeof A.audio=="object"&&(A.audio.processor=r),i&&typeof A.video=="object"&&(A.video.processor=i),n.audio&&typeof A.audio=="object"&&typeof A.audio.deviceId=="string"){const l=A.audio.deviceId;A.audio.deviceId={exact:l},t=!0,s=Object.assign(Object.assign({},A.audio),{deviceId:{ideal:l}})}if(A.video&&typeof A.video=="object"&&typeof A.video.deviceId=="string"){const l=A.video.deviceId;A.video.deviceId={exact:l},t=!0,o=Object.assign(Object.assign({},A.video),{deviceId:{ideal:l}})}(A.audio===!0||typeof A.audio=="object"&&!A.audio.deviceId)&&(A.audio={deviceId:"default"}),A.video===!0?A.video={deviceId:"default"}:typeof A.video=="object"&&!A.video.deviceId&&(A.video.deviceId="default");const a=i0(A,v0,y0),c=Vl(a),u=navigator.mediaDevices.getUserMedia(c);A.audio&&(ft.userMediaPromiseMap.set("audioinput",u),u.catch(()=>ft.userMediaPromiseMap.delete("audioinput"))),A.video&&(ft.userMediaPromiseMap.set("videoinput",u),u.catch(()=>ft.userMediaPromiseMap.delete("videoinput")));try{const l=yield u;return yield Promise.all(l.getTracks().map(d=>S(this,void 0,void 0,function*(){const h=d.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=d.getSettings().deviceId;p!=null&&p.deviceId&&fr(p.deviceId)!==v?p.deviceId=v:p||(p={deviceId:v});const y=yx(d,p,e);return y.kind===R.Kind.Video?y.source=R.Source.Camera:y.kind===R.Kind.Audio&&(y.source=R.Source.Microphone),y.mediaStream=l,Nn(y)&&r?yield y.setProcessor(r):Pi(y)&&i&&(yield y.setProcessor(i)),y})))}catch(l){if(!t)throw l;return la(Object.assign(Object.assign({},n),{audio:s,video:o}),e)}})}function Vx(n){return S(this,void 0,void 0,function*(){return(yield la({audio:!1,video:n??!0}))[0]})}function Gx(n){return S(this,void 0,void 0,function*(){return(yield la({audio:n??!0,video:!1}))[0]})}var vr;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(vr||(vr={}));function jx(n){switch(n){case MA.EXCELLENT:return vr.Excellent;case MA.GOOD:return vr.Good;case MA.POOR:return vr.Poor;case MA.LOST:return vr.Lost;default:return vr.Unknown}}class Q0 extends Sn.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===Vo.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Ei.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,r,i,A,s){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Vo.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=vr.Unknown,this.log=ue,this.log=Ln((a=s==null?void 0:s.loggerName)!==null&&a!==void 0?a:cn.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=r,this.metadata=i,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=A??{}}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 Ll,this.once(K.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(R.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(R.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(R.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===Ei.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Ei.ACTIVE&&this.emit(K.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,r=this.metadata;this.metadata=e,t&&this.emit(K.ParticipantMetadataChanged,r)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(K.ParticipantNameChanged,e)}_setAttributes(e){const t=$F(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(K.AttributesChanged,t)}setPermissions(e){var t,r,i,A,s,o;const a=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((r=this.permissions)===null||r===void 0?void 0:r.canSubscribe)||e.canPublishData!==((i=this.permissions)===null||i===void 0?void 0:i.canPublishData)||e.hidden!==((A=this.permissions)===null||A===void 0?void 0:A.hidden)||e.recorder!==((s=this.permissions)===null||s===void 0?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,l)=>{var d;return u!==((d=this.permissions)===null||d===void 0?void 0:d.canPublishSources[l])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(K.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(K.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=jx(e),t!==this._connectionQuality&&this.emit(K.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=>Nn(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(L.Muted,()=>{this.emit(K.TrackMuted,e)}),e.on(L.Unmuted,()=>{this.emit(K.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case R.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case R.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Wx(n){var e,t,r;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Ym({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(r=n.allowAll)!==null&&r!==void 0?r:!1,trackSids:n.allowedTrackSids||[]})}const R0=15e3;class qx extends Q0{constructor(e,t,r,i,A){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=Wt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Ll)},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,u=this.pendingSignalRequests.get(o);u&&(a!==dl.OK&&u.reject(new Wv(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=Ze.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,a,c);break;case"rpcAck":let u=s.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(s=>Wx(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),_e(s)));return}this.engine.updateMuteStatus(s.sid,o)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),_e(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),_e(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=>S(this,void 0,void 0,function*(){var o,a,c,u,l,d;if(!(!((l=this.roomOptions)===null||l===void 0)&&l.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=ur(v),g;g=yield p.next(),o=g.done,!o;f=!0){u=g.value,f=!1;const y=u;FF(y)&&(this.log.debug("publish ".concat(y," for ").concat(h.videoTrack.sid),Object.assign(Object.assign({},this.logContext),_e(h))),yield this.publishAdditionalCodecForTrack(h.videoTrack,y,h.options))}}catch(y){a={error:y}}finally{try{!f&&!o&&(c=p.return)&&(yield c.call(p))}finally{if(a)throw a.error}}}else s.subscribedQualities.length>0&&(yield(d=h.videoTrack)===null||d===void 0?void 0:d.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=>S(this,void 0,void 0,function*(){if(s.source===R.Source.ScreenShare||s.source===R.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),_e(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(Jr(s)||gr(s))try{if(Ht())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:s.source===R.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),_e(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),_e(s))),Jr(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),_e(s))),yield s.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=r,this.roomOptions=i,this.setupEngine(r),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=A}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Wt.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(D.RemoteMute,(t,r)=>{const i=this.trackPublications.get(t);!i||!i.track||(r?i.mute():i.unmute())}),this.engine.on(D.Connected,this.handleReconnected).on(D.SignalRestarted,this.handleReconnected).on(D.SignalResumed,this.handleReconnected).on(D.Restarting,this.handleReconnecting).on(D.Resuming,this.handleReconnecting).on(D.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(D.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(D.Disconnected,this.handleDisconnected).on(D.SignalRequestResponse,this.handleSignalRequestResponse).on(D.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return S(this,arguments,void 0,function(t){var r=this;let{metadata:i,name:A,attributes:s}=t;return function*(){return new Promise((o,a)=>S(r,void 0,void 0,function*(){var c,u;try{let l=!1;const d=yield this.engine.client.sendUpdateLocalMetadata((c=i??this.metadata)!==null&&c!==void 0?c:"",(u=A??this.name)!==null&&u!==void 0?u:"",s),h=performance.now();for(this.pendingSignalRequests.set(d,{resolve:o,reject:f=>{a(f),l=!0},values:{name:A,metadata:i,attributes:s}});performance.now()-h<5e3&&!l;){if((!A||this.name===A)&&(!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(d),o();return}yield Nt(50)}a(new Wv("Request to update local metadata timed out","TimeoutError"))}catch(l){l instanceof Error&&a(l)}}))}()})}setCameraEnabled(e,t,r){return this.setTrackEnabled(R.Source.Camera,e,t,r)}setMicrophoneEnabled(e,t,r){return this.setTrackEnabled(R.Source.Microphone,e,t,r)}setScreenShareEnabled(e,t,r){return this.setTrackEnabled(R.Source.ScreenShare,e,t,r)}setPermissions(e){const t=this.permissions,r=super.setPermissions(e);return r&&t&&this.emit(K.ParticipantPermissionsChanged,t),r}setE2EEEnabled(e){return S(this,void 0,void 0,function*(){this.encryptionType=e?Wt.GCM:Wt.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,r,i){return S(this,void 0,void 0,function*(){var A,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==null?void 0:c.unmute(),c}this.pendingPublishing.add(e);try{switch(e){case R.Source.Camera:a=yield this.createTracks({video:(A=r)!==null&&A!==void 0?A:!0});break;case R.Source.Microphone:a=yield this.createTracks({audio:(s=r)!==null&&s!==void 0?s:!0});break;case R.Source.ScreenShare:a=yield this.createScreenTracks(Object.assign({},r));break;default:throw new Dn(e)}}catch(c){throw a==null||a.forEach(u=>{u.stop()}),c instanceof Error&&this.emit(K.MediaDevicesError,c),this.pendingPublishing.delete(e),c}try{const c=[];for(const l of a)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),_e(l))),c.push(this.publishTrack(l,i));[o]=yield Promise.all(c)}catch(c){throw a==null||a.forEach(u=>{u.stop()}),c}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&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===R.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const a=this.getTrackPublication(R.Source.ScreenShareAudio);a&&a.track&&this.unpublishTrack(a.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return S(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(R.Source.Camera)||this.pendingPublishing.has(R.Source.Microphone))){this.pendingPublishing.add(R.Source.Camera),this.pendingPublishing.add(R.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(R.Source.Camera),this.pendingPublishing.delete(R.Source.Microphone)}}})}createTracks(e){return S(this,void 0,void 0,function*(){var t,r;e??(e={});const i=i0(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(r=this.roomOptions)===null||r===void 0?void 0:r.videoCaptureDefaults);try{return(yield la(i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Nn(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=R.Source.Microphone,this.emit(K.AudioStreamAcquired)),Pi(o)&&(this.cameraError=void 0,o.source=R.Source.Camera),o))}catch(A){throw A instanceof Error&&(e.audio&&(this.microphoneError=A),e.video&&(this.cameraError=A)),A}})}createScreenTracks(e){return S(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Cl("getDisplayMedia not supported");e.resolution===void 0&&!MF()&&(e.resolution=Il.h1080fps30.resolution);const t=XF(e),r=yield navigator.mediaDevices.getDisplayMedia(t),i=r.getVideoTracks();if(i.length===0)throw new Dn("no video track found");const A=new ua(i[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});A.source=R.Source.ScreenShare,e.contentHint&&(A.mediaStreamTrack.contentHint=e.contentHint);const s=[A];if(r.getAudioTracks().length>0){this.emit(K.AudioStreamAcquired);const o=new aa(r.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=R.Source.ScreenShareAudio,s.push(o)}return s})}publishTrack(e,t){return S(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,a,c,u;Jr(r)&&r.setAudioContext(A.audioContext),yield(o=A.reconnectFuture)===null||o===void 0?void 0:o.promise,A.republishPromise&&!s&&(yield A.republishPromise),Ri(r)&&A.pendingPublishPromises.has(r)&&(yield A.pendingPublishPromises.get(r));let l;if(r instanceof MediaStreamTrack)l=r.getConstraints();else{l=r.constraints;let v;switch(r.source){case R.Source.Microphone:v="audioinput";break;case R.Source.Camera:v="videoinput"}v&&A.activeDeviceMap.has(v)&&(l=Object.assign(Object.assign({},l),{deviceId:A.activeDeviceMap.get(v)}))}if(r instanceof MediaStreamTrack)switch(r.kind){case"audio":r=new aa(r,l,!0,A.audioContext,{loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});break;case"video":r=new ua(r,l,!0,{loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});break;default:throw new Dn("unsupported MediaStreamTrack kind ".concat(r.kind))}else r.updateLoggerOptions({loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});let d;if(A.trackPublications.forEach(v=>{v.track&&v.track===r&&(d=v)}),d)return A.log.warn("track has already been published, skipping",Object.assign(Object.assign({},A.logContext),_e(d))),d;const h="channelCount"in r.mediaStreamTrack.getSettings()&&r.mediaStreamTrack.getSettings().channelCount===2||r.mediaStreamTrack.getConstraints().channelCount===2,f=(a=i==null?void 0:i.forceStereo)!==null&&a!==void 0?a:h;f&&(i||(i={}),i.dtx===void 0&&A.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},A.logContext),_e(r))),i.red===void 0&&A.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),(u=i.red)!==null&&u!==void 0||(i.red=!1));const p=Object.assign(Object.assign({},A.roomOptions.publishDefaults),i);!LF()&&A.roomOptions.e2ee&&(A.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({},A.logContext)),p.simulcast=!1),p.source&&(r.source=p.source);const g=new Promise((v,y)=>S(A,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Oe.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:_e(r)}));const B=()=>S(this,void 0,void 0,function*(){try{const b=yield this.publish(r,p,f);v(b)}catch(b){y(b)}});setTimeout(()=>{this.engine.off(D.SignalConnected,B),y(new Sl("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(D.SignalConnected,B),this.engine.on(D.Closing,()=>{this.engine.off(D.SignalConnected,B),y(new Sl("publishing rejected as engine closed",499))})}else try{const B=yield this.publish(r,p,f);v(B)}catch(B){y(B)}}catch(B){y(B)}}));A.pendingPublishPromises.set(r,g);try{return yield g}catch(v){throw v}finally{A.pendingPublishPromises.delete(r)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),_e(e))),!1;const{canPublish:t,canPublishSources:r}=this.permissions;return t&&(r.length===0||r.map(i=>ex(i)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),_e(e))),!1)}publish(e,t,r){return S(this,void 0,void 0,function*(){var i,A,s,o,a,c,u,l,d,h;if(!this.hasPermissionsToPublish(e))throw new Sl("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(w=>Ri(e)&&w.source===e.source)&&e.source!==R.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),_e(e))),t.stopMicTrackOnMute&&Nn(e)&&(e.stopOnMute=!0),e.source===R.Source.ScreenShare&&Qi()&&(t.simulcast=!1),t.videoCodec==="av1"&&!RF()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!PF()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Yl),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(w=>t.videoCodec===Aa(w.mime))||(t.videoCodec=Aa(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(L.Muted,this.onTrackMuted),e.on(L.Unmuted,this.onTrackUnmuted),e.on(L.Ended,this.handleTrackEnded),e.on(L.UpstreamPaused,this.onTrackUpstreamPaused),e.on(L.UpstreamResumed,this.onTrackUpstreamResumed),e.on(L.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const g=new ol({cid:e.mediaStreamTrack.id,name:t.name,type:R.kindToProto(e.kind),muted:e.isMuted,source:R.sourceToProto(e.source),disableDtx:!(!((i=t.dtx)!==null&&i!==void 0)||i),encryption:this.encryptionType,stereo:r,disableRed:this.isE2EEEnabled||!(!((A=t.red)!==null&&A!==void 0)||A),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy});let v;if(e.kind===R.Kind.Video){let w={width:0,height:0};try{w=yield e.waitForDimensions()}catch{const k=(o=(s=this.roomOptions.videoCaptureDefaults)===null||s===void 0?void 0:s.resolution)!==null&&o!==void 0?o:HA.h720.resolution;w={width:k.width,height:k.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),_e(e)),{dims:w}))}g.width=w.width,g.height=w.height,gr(e)&&(KA(p)&&(e.source===R.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),_e(e))))),t.scalabilityMode=(a=t.scalabilityMode)!==null&&a!==void 0?a:"L3T3_KEY"),g.simulcastCodecs=[new sl({codec:p,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Yl}),t.backupCodec&&p!==t.backupCodec.codec&&g.encryption===Wt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),g.simulcastCodecs.push(new sl({codec:t.backupCodec.codec,cid:""})))),v=nd(e.source===R.Source.ScreenShare,g.width,g.height,t),g.layers=E0(g.width,g.height,v,KA(t.videoCodec))}else e.kind===R.Kind.Audio&&(v=[{maxBitrate:(c=t.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(l=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&l!==void 0?l:"high",networkPriority:(h=(d=t.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&h!==void 0?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new lt("cannot publish track when not connected");const y=()=>S(this,void 0,void 0,function*(){var w,_,k;if(!this.engine.pcManager)throw new lt("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,v),gr(e)&&((w=t.degradationPreference)!==null&&w!==void 0||(t.degradationPreference=Tx(e)),e.setDegradationPreference(t.degradationPreference)),v)if(Qi()&&e.kind===R.Kind.Audio){let T;for(const x of this.engine.pcManager.publisher.getTransceivers())if(x.sender===e.sender){T=x;break}T&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:T,codec:"opus",maxbr:!((_=v[0])===null||_===void 0)&&_.maxBitrate?v[0].maxBitrate/1e3:0})}else e.codec&&KA(e.codec)&&(!((k=v[0])===null||k===void 0)&&k.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:g.cid,codec:e.codec,maxbr:v[0].maxBitrate/1e3});yield this.engine.negotiate()});let B;if(this.enabledPublishVideoCodecs.length>0)B=(yield Promise.all([this.engine.addTrack(g),y()]))[0];else{B=yield this.engine.addTrack(g);let w;if(B.codecs.forEach(_=>{w===void 0&&(w=_.mimeType)}),w&&e.kind===R.Kind.Video){const _=Aa(w);_!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),_e(e)),{codec:_})),t.videoCodec=_,v=nd(e.source===R.Source.ScreenShare,g.width,g.height,t))}yield y()}const b=new ad(e.kind,B,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return b.options=t,e.sid=B.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:v,trackInfo:B})),gr(e)?e.startMonitor(this.engine.client):Jr(e)&&e.startMonitor(),this.addTrackPublication(b),this.emit(K.LocalTrackPublished,b),b})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,r){return S(this,void 0,void 0,function*(){var i;if(this.encryptionType!==Wt.NONE)return;let A;if(this.trackPublications.forEach(h=>{h.track&&h.track===e&&(A=h)}),!A)throw new Dn("track is not published");if(!gr(e))throw new Dn("track is not a video track");const s=Object.assign(Object.assign({},(i=this.roomOptions)===null||i===void 0?void 0:i.publishDefaults),r),o=kx(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),_e(e)));return}const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new ol({cid:a.mediaStreamTrack.id,type:R.kindToProto(e.kind),muted:e.isMuted,source:R.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=E0(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new lt("cannot publish track when not connected");const u=()=>S(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,s,o),yield this.engine.negotiate()}),d=(yield Promise.all([this.engine.addTrack(c),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))})}unpublishTrack(e,t){return S(this,void 0,void 0,function*(){var r,i;if(Ri(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),_e(e))),yield c)}const A=this.getPublicationForTrack(e),s=A?_e(A):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),s)),!A||!A.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),s));return}e=A.track,e.off(L.Muted,this.onTrackMuted),e.off(L.Unmuted,this.onTrackUnmuted),e.off(L.Ended,this.handleTrackEnded),e.off(L.UpstreamPaused,this.onTrackUpstreamPaused),e.off(L.UpstreamResumed,this.onTrackUpstreamResumed),e.off(L.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(i=(r=this.roomOptions)===null||r===void 0?void 0:r.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<Ye.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),gr(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(A.trackSid),A.kind){case R.Kind.Audio:this.audioTrackPublications.delete(A.trackSid);break;case R.Kind.Video:this.videoTrackPublications.delete(A.trackSid);break}return this.emit(K.LocalTrackUnpublished,A),A.setTrack(void 0),o&&(yield this.engine.negotiate()),A})}unpublishTracks(e){return S(this,void 0,void 0,function*(){return(yield Promise.all(e.map(r=>this.unpublishTrack(r)))).filter(r=>!!r)})}republishAllTracks(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){r.republishPromise&&(yield r.republishPromise),r.republishPromise=new Promise((A,s)=>S(r,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=>S(this,void 0,void 0,function*(){const c=a.track;yield this.unpublishTrack(c,!1),i&&!c.isMuted&&c.source!==R.Source.ScreenShare&&c.source!==R.Source.ScreenShareAudio&&(Jr(c)||gr(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)}))),A()}catch(o){s(o)}finally{this.republishPromise=void 0}})),yield r.republishPromise}()})}publishData(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const A=i.reliable?pe.RELIABLE:pe.LOSSY,s=i.destinationIdentities,o=i.topic,a=new Dt({kind:A,value:{case:"user",value:new Fm({participantIdentity:r.identity,payload:t,destinationIdentities:s,topic:o})}});yield r.engine.sendDataPacket(a,A)}()})}publishDtmf(e,t){return S(this,void 0,void 0,function*(){const r=new Dt({kind:pe.RELIABLE,value:{case:"sipDtmf",value:new xm({code:e,digit:t})}});yield this.engine.sendDataPacket(r,pe.RELIABLE)})}sendChatMessage(e,t){return S(this,void 0,void 0,function*(){const r={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},i=new Dt({value:{case:"chatMessage",value:new el(Object.assign(Object.assign({},r),{timestamp:Ke.parse(r.timestamp)}))}});return yield this.engine.sendDataPacket(i,pe.RELIABLE),this.emit(K.ChatMessage,r),r})}editChatMessage(e,t){return S(this,void 0,void 0,function*(){const r=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),i=new Dt({value:{case:"chatMessage",value:new el(Object.assign(Object.assign({},r),{timestamp:Ke.parse(r.timestamp),editTimestamp:Ke.parse(r.editTimestamp)}))}});return yield this.engine.sendDataPacket(i,pe.RELIABLE),this.emit(K.ChatMessage,r),r})}sendText(e,t){return S(this,void 0,void 0,function*(){var r;const i=crypto.randomUUID(),s=new TextEncoder().encode(e).byteLength,o=(r=t==null?void 0:t.attachments)===null||r===void 0?void 0:r.map(()=>crypto.randomUUID()),a=new Array(o?o.length+1:1).fill(0),c=(l,d)=>{var h;a[d]=l;const f=a.reduce((p,g)=>p+g,0);(h=t==null?void 0:t.onProgress)===null||h===void 0||h.call(t,f)},u=yield this.streamText({streamId:i,totalSize:s,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:o,attributes:t==null?void 0:t.attributes});return yield u.write(e),c(1,0),yield u.close(),t!=null&&t.attachments&&o&&(yield Promise.all(t.attachments.map((l,d)=>S(this,void 0,void 0,function*(){return this._sendFile(o[d],l,{topic:t.topic,mimeType:l.type,onProgress:h=>{c(h,d+1)}})})))),u.info})}streamText(e){return S(this,void 0,void 0,function*(){var t,r;const i=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),A={id:i,mimeType:"text/plain",timestamp:Date.now(),topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},s=new nl({streamId:i,mimeType:A.mimeType,topic:A.topic,timestamp:qr(A.timestamp),totalLength:qr(e==null?void 0:e.totalSize),attributes:A.attributes,contentHeader:{case:"textHeader",value:new Vm({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?tl.UPDATE:tl.CREATE})}}),o=e==null?void 0:e.destinationIdentities,a=new Dt({destinationIdentities:o,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(a,pe.RELIABLE);let c=0;const u=this,l=new WritableStream({write(f){return S(this,void 0,void 0,function*(){for(const p of JF(f,R0)){yield u.engine.waitForBufferStatusLow(pe.RELIABLE);const g=new rl({content:p,streamId:i,chunkIndex:qr(c)}),v=new Dt({destinationIdentities:o,value:{case:"streamChunk",value:g}});yield u.engine.sendDataPacket(v,pe.RELIABLE),c+=1}})},close(){return S(this,void 0,void 0,function*(){const f=new il({streamId:i}),p=new Dt({destinationIdentities:o,value:{case:"streamTrailer",value:f}});yield u.engine.sendDataPacket(p,pe.RELIABLE)})},abort(f){console.log("Sink error:",f)}});let d=()=>S(this,void 0,void 0,function*(){yield h.close()});u.engine.once(D.Closing,d);const h=new Lx(l,A,()=>this.engine.off(D.Closing,d));return h})}sendFile(e,t){return S(this,void 0,void 0,function*(){const r=crypto.randomUUID();return yield this._sendFile(r,e,t),{id:r}})}_sendFile(e,t,r){return S(this,void 0,void 0,function*(){var i;const A=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(i=r==null?void 0:r.mimeType)!==null&&i!==void 0?i:t.type,topic:r==null?void 0:r.topic,destinationIdentities:r==null?void 0:r.destinationIdentities}),s=t.stream().getReader();for(;;){const{done:o,value:a}=yield s.read();if(o)break;yield A.write(a)}return yield A.close(),A.info})}streamBytes(e){return S(this,void 0,void 0,function*(){var t,r,i,A,s;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a=e==null?void 0:e.destinationIdentities,c={id:o,mimeType:(r=e==null?void 0:e.mimeType)!==null&&r!==void 0?r:"application/octet-stream",topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(A=e==null?void 0:e.name)!==null&&A!==void 0?A:"unknown"},u=new nl({totalLength:qr((s=c.size)!==null&&s!==void 0?s:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:qr(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Gm({name:c.name})}}),l=new Dt({destinationIdentities:a,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(l,pe.RELIABLE);let d=0;const h=new Mt,f=this.engine,p=this.log,g=new WritableStream({write(y){return S(this,void 0,void 0,function*(){const B=yield h.lock();let b=0;try{for(;b<y.byteLength;){const w=y.slice(b,b+R0);yield f.waitForBufferStatusLow(pe.RELIABLE);const _=new Dt({destinationIdentities:a,value:{case:"streamChunk",value:new rl({content:w,streamId:o,chunkIndex:qr(d)})}});yield f.sendDataPacket(_,pe.RELIABLE),d+=1,b+=w.byteLength}}finally{B()}})},close(){return S(this,void 0,void 0,function*(){const y=new il({streamId:o}),B=new Dt({destinationIdentities:a,value:{case:"streamTrailer",value:y}});yield f.sendDataPacket(B,pe.RELIABLE)})},abort(y){p.error("Sink error:",y)}});return new Dx(g,c)})}performRpc(e){return S(this,arguments,void 0,function(t){var r=this;let{destinationIdentity:i,method:A,payload:s,responseTimeout:o=1e4}=t;return function*(){return new Promise((c,u)=>S(r,void 0,void 0,function*(){var l,d,h,f;if($l(s)>w0){u(Ze.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((d=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||d===void 0)&&d.version&&Wr((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){u(Ze.builtIn("UNSUPPORTED_SERVER"));return}const p=crypto.randomUUID();yield this.publishRpcRequest(i,p,A,s,o-2e3);const g=setTimeout(()=>{this.pendingAcks.delete(p),u(Ze.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),u(Ze.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(p,{resolve:(y,B)=>{clearTimeout(v),this.pendingAcks.has(p)&&(console.warn("RPC response received before ack",p),this.pendingAcks.delete(p),clearTimeout(g)),B?u(B):c(y??"")},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,r){const i=this.pendingResponses.get(e);i?(i.resolve(t,r),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,r,i,A){return S(this,void 0,void 0,function*(){const s=new Dt({destinationIdentities:[e],kind:pe.RELIABLE,value:{case:"rpcRequest",value:new Qm({id:t,method:r,payload:i,responseTimeoutMs:A,version:1})}});yield this.engine.sendDataPacket(s,pe.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:r}]of this.pendingAcks)r===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:r,resolve:i}]of this.pendingResponses)r===e&&(i(null,Ze.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 r,i;const A=this.trackPublications.get(t.sid);if(A){const s=A.isMuted||((i=(r=A.track)===null||r===void 0?void 0:r.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),_e(A)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(t.sid,s))}}),!0):!1}getPublicationForTrack(e){let t;return this.trackPublications.forEach(r=>{const i=r.track;i&&(e instanceof MediaStreamTrack?(Jr(i)||gr(i))&&i.mediaStreamTrack===e&&(t=r):e===i&&(t=r))}),t}waitForPendingPublicationOfSource(e){return S(this,void 0,void 0,function*(){const r=Date.now();for(;Date.now()<r+1e4;){const i=Array.from(this.pendingPublishPromises.entries()).find(A=>{let[s]=A;return s.source===e});if(i)return i[1];yield Nt(20)}})}}class Jx extends Hn{constructor(e,t,r,i){super(e,t.sid,t.name,i),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Yt.HIGH,this.handleEnded=A=>{this.setTrack(void 0),this.emit(L.Ended,A)},this.handleVisibilityChange=A=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(A),this.logContext),this.disabled=!A,this.emitTrackUpdate()},this.handleVideoDimensionsChange=A=>{this.log.debug("adaptivestream video dimensions ".concat(A.width,"x").concat(A.height),this.logContext),this.videoDimensions=A,this.emitTrackUpdate()},this.subscribed=r,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,r=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const i=new Go({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Mm({participantSid:"",trackSids:[this.trackSid]})]});this.emit(L.UpdateSubscription,i),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(r)}get subscriptionStatus(){return this.subscribed===!1?Hn.SubscriptionStatus.Unsubscribed:super.isSubscribed?Hn.SubscriptionStatus.Subscribed:Hn.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Hn.PermissionStatus.Allowed:Hn.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,r;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((r=this.videoDimensions)===null||r===void 0?void 0:r.height)===e.height||(Hl(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Hl(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,r=this.permissionStatus,i=this.track;i!==e&&(i&&(i.off(L.VideoDimensionsChanged,this.handleVideoDimensionsChange),i.off(L.VisibilityChanged,this.handleVisibilityChange),i.off(L.Ended,this.handleEnded),i.detach(),i.stopMonitor(),this.emit(L.Unsubscribed,i)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(L.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(L.VisibilityChanged,this.handleVisibilityChange),e.on(L.Ended,this.handleEnded),this.emit(L.Subscribed,e)),this.emitPermissionUpdateIfChanged(r),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,r=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(r),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(L.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?L.Muted:L.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(L.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(L.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===R.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 Hl(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Wm({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=Yt.HIGH,this.emit(L.UpdateSettings,e)}}class da extends Q0{static fromParticipantInfo(e,t,r){return new da(e,t.sid,t.identity,t.name,t.metadata,t.attributes,r,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,r,i,A,s,o){let a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Vo.STANDARD;super(t,r||"",i,A,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(L.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),_e(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(L.UpdateSubscription,t=>{t.participantTracks.forEach(r=>{r.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(L.SubscriptionPermissionChanged,t=>{this.emit(K.TrackSubscriptionPermissionChanged,e,t)}),e.on(L.SubscriptionStatusChanged,t=>{this.emit(K.TrackSubscriptionStatusChanged,e,t)}),e.on(L.Subscribed,t=>{this.emit(K.TrackSubscribed,t,e)}),e.on(L.Unsubscribed,t=>{this.emit(K.TrackUnsubscribed,t,e)}),e.on(L.SubscriptionFailed,t=>{this.emit(K.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]:R.Source.Microphone;this.volumeMap.set(t,e);const r=this.getTrackPublication(t);r&&r.track&&r.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:R.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,r,i,A,s){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(u=>{!o&&e.kind===u.kind.toString()&&(o=u)}),!o){if(s===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(K.TrackSubscriptionFailed,t);return}s===void 0&&(s=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,r,i,A,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),_e(o))),this.emit(K.TrackSubscriptionFailed,t);return}const a=e.kind==="video";let c;return a?c=new Hx(e,t,i,A):c=new Nx(e,t,i,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(r),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&Nl(c)&&Nn(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,r=new Map;return e.tracks.forEach(i=>{var A,s;let o=this.getTrackPublicationBySid(i.sid);if(o)o.updateInfo(i);else{const a=R.kindFromProto(i.type);if(!a)return;o=new Jx(a,i,(A=this.signalClient.connectOptions)===null||A===void 0?void 0:A.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(s=this.loggerOptions)===null||s===void 0?void 0:s.loggerName}),o.updateInfo(i),r.set(i.sid,o);const c=Array.from(this.trackPublications.values()).find(u=>u.source===(o==null?void 0:o.source));c&&o.source!==R.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:_e(c),newTrack:_e(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),_e(i))),this.unpublishTrack(i.trackSid,!0))}),r.forEach(i=>{this.emit(K.TrackPublished,i)}),!0}unpublishTrack(e,t){const r=this.trackPublications.get(e);if(!r)return;const{track:i}=r;switch(i&&(i.stop(),r.setTrack(void 0)),this.trackPublications.delete(e),r.kind){case R.Kind.Audio:this.audioTrackPublications.delete(e);break;case R.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(K.TrackUnpublished,r)}setAudioOutput(e){return S(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(r=>{var i;Nn(r.track)&&Nl(r.track)&&t.push(r.track.setSinkId((i=e.deviceId)!==null&&i!==void 0?i:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:r})),super.emit(e,...r)}}var fe;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(fe||(fe={}));const zx=4*1e3;class Li extends Sn.EventEmitter{constructor(e){var t,r,i,A;if(super(),t=this,this.state=fe.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ue,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)=>S(this,void 0,void 0,function*(){var c;if(!OF())throw kn()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const u=yield this.disconnectLock.lock();if(this.state===fe.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(fe.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==s&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Rl(new URL(s))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Ad(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 l=(h,f,p)=>S(this,void 0,void 0,function*(){var g,v;this.abortController&&this.abortController.abort();const y=new AbortController;this.abortController=y,u==null||u();try{yield this.attemptConnection(p??s,o,a,y),this.abortController=void 0,h()}catch(B){if(this.regionUrlProvider&&B instanceof Fe&&B.reason!==de.Cancelled&&B.reason!==de.NotAllowed){let b=null;try{b=yield this.regionUrlProvider.getNextBestRegionUrl((g=this.abortController)===null||g===void 0?void 0:g.signal)}catch(w){if(w instanceof Fe&&(w.status===401||w.reason===de.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),f(w);return}}b&&!(!((v=this.abortController)===null||v===void 0)&&v.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(B.message,". Retrying with another region: ").concat(b),this.logContext),this.recreateEngine(),yield l(h,f,b)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,r0(B)),f(B))}else{let b=sn.UNKNOWN_REASON;B instanceof Fe&&(b=r0(B)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,b),f(B)}}}),d=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ll((h,f)=>{l(h,f,d)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(s,o,a,c,u,l)=>S(this,void 0,void 0,function*(){var d,h,f;const p=yield a.join(s,o,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},l.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[y,B]=v;return"".concat(y,": ").concat(B)}).join(", ")),{room:(d=p.room)===null||d===void 0?void 0:d.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 bF("unknown server version");return g.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.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)=>S(this,void 0,void 0,function*(){var u,l;this.state===fe.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((l=this.regionUrlProvider)===null||l===void 0)&&l.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Zl),a),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const d=yield this.connectSignal(s,o,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(d),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected)}catch(d){yield this.engine.close(),this.recreateEngine();const h=new Fe("could not establish signal connection",de.ServerUnreachable);throw d instanceof Error&&(h.message="".concat(h.message,": ").concat(d.message)),d instanceof Fe&&(h.reason=d.reason,h.status=d.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:d})),h}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new Fe("Connection attempt aborted",de.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(d){throw yield this.engine.close(),this.recreateEngine(),d}Ht()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ht()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(fe.Connected),this.emit(O.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 S(t,[...o],void 0,function(){var c=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var l,d,h,f;const p=yield c.disconnectLock.lock();try{if(c.state===fe.Disconnected){c.log.debug("already disconnected",c.logContext);return}c.log.info("disconnect from room",Object.assign({},c.logContext)),(c.state===fe.Connecting||c.state===fe.Reconnecting||c.isResuming)&&(c.log.warn("abort connection attempt",c.logContext),(l=c.abortController)===null||l===void 0||l.abort(),(h=(d=c.connectFuture)===null||d===void 0?void 0:d.reject)===null||h===void 0||h.call(d,new Fe("Client initiated disconnect",de.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(u,sn.CLIENT_INITIATED),c.engine=void 0}finally{p()}}()})},this.onPageLeave=()=>S(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>S(this,void 0,void 0,function*(){const s=[],o=un();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 u=Ml();u.enabled=!0;const l=new MediaStream([u]);c.srcObject=l,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:l,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(O.Disconnected,()=>{c==null||c.remove(),c=null})}s.push(c)}this.remoteParticipants.forEach(a=>{a.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(u=>{s.push(u)})})});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=()=>S(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(u=>{s.includes(u)||s.push(u)})});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(fe.Reconnecting)&&this.emit(O.Reconnecting)},this.handleSignalRestarted=s=>S(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(fe.Connected),this.emit(O.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===Ei.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 u=this.getRemoteParticipantBySid(c.sid);u&&(u.audioLevel=c.level,u.setIsSpeaking(!0),o.push(u))}}),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(O.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=s=>{const o=new Map;this.activeSpeakers.forEach(c=>{const u=this.remoteParticipants.get(c.identity);u&&u.sid!==c.sid||o.set(c.sid,c)}),s.forEach(c=>{let u=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=c.level,u.setIsSpeaking(c.active),c.active?o.set(c.sid,u):o.delete(c.sid))});const a=Array.from(o.values());a.sort((c,u)=>u.audioLevel-c.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(O.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 u=R.streamStateFromProto(o.state);u!==c.track.streamState&&(c.track.streamState=u,a.emit(K.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(O.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(O.DataReceived,o.payload,s,a,o.topic),s==null||s.emit(K.DataReceived,o.payload,a)},this.handleSipDtmf=(s,o)=>{this.emit(O.SipDTMFReceived,o,s),s==null||s.emit(K.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==null?void 0:a.trackPublications.get(o.trackId),u=GF(o,this.transcriptionReceivedTimes);c==null||c.emit(L.TranscriptionReceived,u),a==null||a.emit(K.TranscriptionReceived,u,c),this.emit(O.TranscriptionReceived,u,a,c)},this.handleChatMessage=(s,o)=>{const a=jF(o);this.emit(O.ChatMessage,a,s)},this.handleMetrics=(s,o)=>{this.emit(O.MetricsReceived,s,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(O.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(O.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(O.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(O.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>S(this,void 0,void 0,function*(){var s,o,a;const c=ft.getInstance().previousDevices,u=yield ft.getInstance().getDevices(void 0,!1),l=un();if((l==null?void 0:l.name)==="Chrome"&&l.os!=="iOS")for(let h of u){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(O.ActiveDeviceChanged,h.kind,h.deviceId)}const d=["audiooutput","audioinput","videoinput"];for(let h of d){const f=zF(h),p=this.localParticipant.getTrackPublication(f);if(p&&(!((s=p.track)===null||s===void 0)&&s.isUserProvided))continue;const g=u.filter(y=>y.kind===h),v=this.getActiveDevice(h);if(v===((o=c.filter(y=>y.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"&&!pr()||h==="videoinput"||g.length>0&&!g.find(y=>y.deviceId===this.getActiveDevice(h))&&(yield this.switchActiveDevice(h,g[0].deviceId))}this.emit(O.MediaDevicesChanged)}),this.handleRoomUpdate=s=>{const o=this.roomInfo;this.roomInfo=s,o&&o.metadata!==s.metadata&&this.emitWhenConnected(O.RoomMetadataChanged,s.metadata),(o==null?void 0:o.activeRecording)!==s.activeRecording&&this.emitWhenConnected(O.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(O.ParticipantMetadataChanged,s,this.localParticipant)},this.onLocalParticipantNameChanged=s=>{this.emit(O.ParticipantNameChanged,s,this.localParticipant)},this.onLocalAttributesChanged=s=>{this.emit(O.ParticipantAttributesChanged,s,this.localParticipant)},this.onLocalTrackMuted=s=>{this.emit(O.TrackMuted,s,this.localParticipant)},this.onLocalTrackUnmuted=s=>{this.emit(O.TrackUnmuted,s,this.localParticipant)},this.onTrackProcessorUpdate=s=>{var o;(o=s==null?void 0:s.onPublish)===null||o===void 0||o.call(s,this)},this.onLocalTrackPublished=s=>S(this,void 0,void 0,function*(){var o,a,c,u,l,d;(o=s.track)===null||o===void 0||o.on(L.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.on(L.Restarted,this.onLocalTrackRestarted),(l=(u=(c=s.track)===null||c===void 0?void 0:c.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||l===void 0||l.call(u,this),this.emit(O.LocalTrackPublished,s,this.localParticipant),Jr(s.track)&&(yield s.track.checkForSilence())&&this.emit(O.LocalAudioSilenceDetected,s);const h=yield(d=s.track)===null||d===void 0?void 0:d.getDeviceId(!1),f=o0(s.source);f&&h&&h!==this.localParticipant.activeDeviceMap.get(f)&&(this.localParticipant.activeDeviceMap.set(f,h),this.emit(O.ActiveDeviceChanged,f,h))}),this.onLocalTrackUnpublished=s=>{var o,a;(o=s.track)===null||o===void 0||o.off(L.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.off(L.Restarted,this.onLocalTrackRestarted),this.emit(O.LocalTrackUnpublished,s,this.localParticipant)},this.onLocalTrackRestarted=s=>S(this,void 0,void 0,function*(){const o=yield s.getDeviceId(!1),a=o0(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(O.ActiveDeviceChanged,a,o))}),this.onLocalConnectionQualityChanged=s=>{this.emit(O.ConnectionQualityChanged,s,this.localParticipant)},this.onMediaDevicesError=s=>{this.emit(O.MediaDevicesError,s)},this.onLocalParticipantPermissionsChanged=s=>{this.emit(O.ParticipantPermissionsChanged,s,this.localParticipant)},this.onLocalChatMessageSent=s=>{this.emit(O.ChatMessage,s,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},gx),e),this.log=Ln((r=this.options.loggerName)!==null&&r!==void 0?r:cn.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},v0),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},y0),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},fx),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Mt,this.localParticipant=new qx("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",fr(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",fr(this.options.audioCaptureDefaults.deviceId)),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&this.switchActiveDevice("audiooutput",fr(this.options.audioOutput.deviceId)).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),Ht()){const s=new AbortController;(A=navigator.mediaDevices)===null||A===void 0||A.addEventListener("devicechange",this.handleDeviceChange,{signal:s.signal}),Li.cleanupRegistry&&Li.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,r,i,A,s){return S(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),s!==1){yield this.engine.publishRpcResponse(e,t,null,Ze.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(r);if(!o){yield this.engine.publishRpcResponse(e,t,null,Ze.builtIn("UNSUPPORTED_METHOD"));return}let a=null,c=null;try{const u=yield o({requestId:t,callerIdentity:e,payload:i,responseTimeout:A});$l(u)>w0?(a=Ze.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(r))):c=u}catch(u){u instanceof Ze?a=u:(console.warn("Uncaught error returned by RPC handler for ".concat(r,". Returning APPLICATION_ERROR instead."),u),a=Ze.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)})}setE2EEEnabled(e){return S(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 tx(this.options.e2ee),this.e2eeManager.on(dr.ParticipantEncryptionStatusChanged,(t,r)=>{qF(r)&&(this.isE2EEEnabled=t),this.emit(O.ParticipantEncryptionStatusChanged,t,r)}),this.e2eeManager.on(dr.EncryptionError,t=>this.emit(O.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 S(this,void 0,void 0,function*(){return this.state===fe.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const r=i=>{i.sid!==""&&(this.engine.off(D.RoomUpdate,r),e(i.sid))};this.engine.on(D.RoomUpdate,r),this.once(O.Disconnected,()=>{this.engine.off(D.RoomUpdate,r),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 xx(this.options),this.engine.on(D.ParticipantUpdate,this.handleParticipantUpdates).on(D.RoomUpdate,this.handleRoomUpdate).on(D.SpeakersChanged,this.handleSpeakersChanged).on(D.StreamStateChanged,this.handleStreamStateUpdate).on(D.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(D.SubscriptionError,this.handleSubscriptionError).on(D.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(D.MediaTrackAdded,(e,t,r)=>{this.onTrackAdded(e,t,r)}).on(D.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(D.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(D.DataPacketReceived,this.handleDataPacket).on(D.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(fe.SignalReconnecting)&&this.emit(O.SignalReconnecting)}).on(D.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(fe.Connected)&&this.emit(O.Reconnected)}).on(D.SignalResumed,()=>{this.bufferedEvents=[],(this.state===fe.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(D.Restarting,this.handleRestarting).on(D.SignalRestarted,this.handleSignalRestarted).on(D.Offline,()=>{this.setAndEmitConnectionState(fe.Reconnecting)&&this.emit(O.Reconnecting)}).on(D.DCBufferStatusChanged,(e,t)=>{this.emit(O.DCBufferStatusChanged,e,t)}).on(D.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(r=>{let{trackSid:i}=r;return i===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(K.LocalTrackSubscribed,t),this.emitWhenConnected(O.LocalTrackSubscribed,t,this.localParticipant)}).on(D.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,r)=>{this.handleParticipantDisconnected(r,t)}),this.emit(O.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 ft.getInstance().getDevices(e,t)}prepareConnection(e,t){return S(this,void 0,void 0,function*(){if(this.state===fe.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Rl(new URL(e))&&t){this.regionUrlProvider=new Ad(e,t);const r=yield this.regionUrlProvider.getNextBestRegionUrl();r&&this.state===fe.Disconnected&&(this.regionUrl=r,yield fetch(Dl(r),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(r),this.logContext))}else yield fetch(Dl(e),{method:"HEAD"})}catch(r){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:r}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return S(this,void 0,void 0,function*(){let r=()=>{},i;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new _n({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new _n({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new _n({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new _n({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":r=()=>S(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new _n({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":r=()=>S(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new _n({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 _n({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),r=()=>S(this,void 0,void 0,function*(){const A=this.engine.client.onLeave;A&&A(new jo({reason:sn.CLIENT_INITIATED,action:Ti.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");i=new _n({scenario:{case:"subscriberBandwidth",value:qr(t)}});break;case"leave-full-reconnect":i=new _n({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield r())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,a,c,u,l,d,h,f;let p=!0,g=!1;const v=s?{exact:i}:i;if(r==="audioinput"){g=A.localParticipant.audioTrackPublications.size===0;const y=(o=A.getActiveDevice(r))!==null&&o!==void 0?o:A.options.audioCaptureDefaults.deviceId;A.options.audioCaptureDefaults.deviceId=v;const B=Array.from(A.localParticipant.audioTrackPublications.values()).filter(b=>b.source===R.Source.Microphone);try{p=(yield Promise.all(B.map(b=>{var w;return(w=b.audioTrack)===null||w===void 0?void 0:w.setDeviceId(v)}))).every(b=>b===!0)}catch(b){throw A.options.audioCaptureDefaults.deviceId=y,b}}else if(r==="videoinput"){g=A.localParticipant.videoTrackPublications.size===0;const y=(a=A.getActiveDevice(r))!==null&&a!==void 0?a:A.options.videoCaptureDefaults.deviceId;A.options.videoCaptureDefaults.deviceId=v;const B=Array.from(A.localParticipant.videoTrackPublications.values()).filter(b=>b.source===R.Source.Camera);try{p=(yield Promise.all(B.map(b=>{var w;return(w=b.videoTrack)===null||w===void 0?void 0:w.setDeviceId(v)}))).every(b=>b===!0)}catch(b){throw A.options.videoCaptureDefaults.deviceId=y,b}}else if(r==="audiooutput"){if(!Ql()&&!A.options.webAudioMix||A.options.webAudioMix&&A.audioContext&&!("setSinkId"in A.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");A.options.webAudioMix&&(i=(c=yield ft.getInstance().normalizeDeviceId("audiooutput",i))!==null&&c!==void 0?c:""),(u=(f=A.options).audioOutput)!==null&&u!==void 0||(f.audioOutput={});const y=(l=A.getActiveDevice(r))!==null&&l!==void 0?l:A.options.audioOutput.deviceId;A.options.audioOutput.deviceId=i;try{A.options.webAudioMix&&((d=A.audioContext)===null||d===void 0||d.setSinkId(i)),yield Promise.all(Array.from(A.remoteParticipants.values()).map(B=>B.setAudioOutput({deviceId:i})))}catch(B){throw A.options.audioOutput.deviceId=y,B}}return(g||r==="audiooutput")&&(A.localParticipant.activeDeviceMap.set(r,r==="audiooutput"&&((h=A.options.audioOutput)===null||h===void 0?void 0:h.deviceId)||i),A.emit(O.ActiveDeviceChanged,r,i)),p}()})}setupLocalParticipantEvents(){this.localParticipant.on(K.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(K.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(K.AttributesChanged,this.onLocalAttributesChanged).on(K.TrackMuted,this.onLocalTrackMuted).on(K.TrackUnmuted,this.onLocalTrackUnmuted).on(K.LocalTrackPublished,this.onLocalTrackPublished).on(K.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(K.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(K.MediaDevicesError,this.onMediaDevicesError).on(K.AudioStreamAcquired,this.startAudio).on(K.ChatMessage,this.onLocalChatMessageSent).on(K.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,r){if(this.state===fe.Connecting||this.state===fe.Reconnecting){const u=()=>{this.onTrackAdded(e,t,r),l()},l=()=>{this.off(O.Reconnected,u),this.off(O.Connected,u),this.off(O.Disconnected,l)};this.once(O.Reconnected,u),this.once(O.Connected,u),this.once(O.Disconnected,l);return}if(this.state===fe.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=QF(t.id),A=i[0];let s=i[1],o=e.id;if(s&&s.startsWith("TR")&&(o=s),A===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const a=Array.from(this.remoteParticipants.values()).find(u=>u.sid===A);if(!a){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(A),this.logContext);return}let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={}),a.addSubscribedMediaTrack(e,o,t,r,c)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==fe.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(i=>{i.trackPublications.forEach(A=>{i.unpublishTrack(A.trackSid)})}),this.localParticipant.trackPublications.forEach(i=>{var A,s,o;i.track&&this.localParticipant.unpublishTrack(i.track,e),e?((A=i.track)===null||A===void 0||A.detach(),(s=i.track)===null||s===void 0||s.stop()):(o=i.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(K.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(K.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(K.AttributesChanged,this.onLocalAttributesChanged).off(K.TrackMuted,this.onLocalTrackMuted).off(K.TrackUnmuted,this.onLocalTrackUnmuted).off(K.LocalTrackPublished,this.onLocalTrackPublished).off(K.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(K.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(K.MediaDevicesError,this.onMediaDevicesError).off(K.AudioStreamAcquired,this.startAudio).off(K.ChatMessage,this.onLocalChatMessageSent).off(K.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),Ht()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(r=navigator.mediaDevices)===null||r===void 0||r.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(fe.Disconnected),this.emit(O.Disconnected,t)}}}handleParticipantDisconnected(e,t){var r;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(i=>{t.unpublishTrack(i.trackSid,!0)}),this.emit(O.ParticipantDisconnected,t),t.setDisconnected(),(r=this.localParticipant)===null||r===void 0||r.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return S(this,void 0,void 0,function*(){var r;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 A;const s={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:ia(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{A=a,this.byteStreamControllers.set(e.streamId,{info:s,controller:A,startTime:Date.now()})}});i(new Ox(s,o,ia(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 A;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=>{A=a,this.textStreamControllers.set(e.streamId,{info:s,controller:A,startTime:Date.now()})}});i(new Mx(s,o,ia(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const r=this.textStreamControllers.get(e.streamId);r&&e.content.length>0&&r.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 r=this.byteStreamControllers.get(e.streamId);r&&(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return S(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=s0())!==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(),Nt(200)])}catch(i){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:i}))}const r=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";r!==this.canPlaybackAudio&&(this.audioEnabled=r,this.emit(O.AudioPlaybackStatusChanged,r))})}createParticipant(e,t){var r;let i;return t?i=da.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):i=new da(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&i.setAudioOutput(this.options.audioOutput).catch(A=>this.log.warn("Could not set audio output: ".concat(A.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 r=this.createParticipant(e,t);return this.remoteParticipants.set(e,r),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(O.ParticipantConnected,r),r.on(K.TrackPublished,i=>{this.emitWhenConnected(O.TrackPublished,i,r)}).on(K.TrackSubscribed,(i,A)=>{i.kind===R.Kind.Audio?(i.on(L.AudioPlaybackStarted,this.handleAudioPlaybackStarted),i.on(L.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):i.kind===R.Kind.Video&&(i.on(L.VideoPlaybackFailed,this.handleVideoPlaybackFailed),i.on(L.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(O.TrackSubscribed,i,A,r)}).on(K.TrackUnpublished,i=>{this.emit(O.TrackUnpublished,i,r)}).on(K.TrackUnsubscribed,(i,A)=>{this.emit(O.TrackUnsubscribed,i,A,r)}).on(K.TrackMuted,i=>{this.emitWhenConnected(O.TrackMuted,i,r)}).on(K.TrackUnmuted,i=>{this.emitWhenConnected(O.TrackUnmuted,i,r)}).on(K.ParticipantMetadataChanged,i=>{this.emitWhenConnected(O.ParticipantMetadataChanged,i,r)}).on(K.ParticipantNameChanged,i=>{this.emitWhenConnected(O.ParticipantNameChanged,i,r)}).on(K.AttributesChanged,i=>{this.emitWhenConnected(O.ParticipantAttributesChanged,i,r)}).on(K.ConnectionQualityChanged,i=>{this.emitWhenConnected(O.ConnectionQualityChanged,i,r)}).on(K.ParticipantPermissionsChanged,i=>{this.emitWhenConnected(O.ParticipantPermissionsChanged,i,r)}).on(K.TrackSubscriptionStatusChanged,(i,A)=>{this.emitWhenConnected(O.TrackSubscriptionStatusChanged,i,A,r)}).on(K.TrackSubscriptionFailed,(i,A)=>{this.emit(O.TrackSubscriptionFailed,i,r,A)}).on(K.TrackSubscriptionPermissionChanged,(i,A)=>{this.emitWhenConnected(O.TrackSubscriptionPermissionChanged,i,A,r)}).on(K.Active,()=>{this.emitWhenConnected(O.ParticipantActive,r)}),t&&r.updateInfo(t),r}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((r,i)=>(r.push(...i.getTrackPublications()),r),[]),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&&WF(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=wt.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,sn.STATE_MISMATCH))):e=0},zx)}clearConnectionReconcile(){this.connectionReconcileInterval&&wt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(O.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,r]=e;this.emit(t,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];if(this.state===fe.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,r]);else if(this.state===fe.Connected)return this.emit(e,...r);return!1}simulateParticipants(e){return S(this,void 0,void 0,function*(){var t,r;const i=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),A=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Ho({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Ke.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Kr({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected),this.emit(O.Connected),this.setAndEmitConnectionState(fe.Connected),i.video){const s=new ad(R.Kind.Video,new Ui({source:at.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:An.AUDIO,name:"video-dummy"}),new ua(i.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:n0(160*((t=A.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(K.LocalTrackPublished,s)}if(i.audio){const s=new ad(R.Kind.Audio,new Ui({source:at.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:An.AUDIO}),new aa(i.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ml(),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(K.LocalTrackPublished,s)}for(let s=0;s<A.count-1;s+=1){let o=new Kr({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(s),state:Ei.ACTIVE,tracks:[],joinedAt:Ke.parse(Date.now())});const a=this.getOrCreateParticipant(o.identity,o);if(A.video){const c=n0(160*((r=A.aspectRatios[s%A.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),u=new Ui({source:at.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:An.AUDIO});a.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}if(A.audio){const c=Ml(),u=new Ui({source:at.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:An.AUDIO});a.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}a.updateInfo(o)}})}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];if(e!==O.ActiveSpeakersChanged&&e!==O.TranscriptionReceived){const A=P0(r).filter(s=>s!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:A}))}return super.emit(e,...r)}}Li.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function P0(n){return n.map(e=>{if(e)return Array.isArray(e)?P0(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var hn;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(hn||(hn={}));class yr extends Sn.EventEmitter{constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=hn.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Li(r.roomOptions),this.connectOptions=r.connectOptions,this.options=r}run(e){return S(this,void 0,void 0,function*(){if(this.status!==hn.IDLE)throw Error("check is running already");this.setStatus(hn.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!==hn.SKIPPED&&this.setStatus(this.isSuccess()?hn.SUCCESS:hn.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return S(this,void 0,void 0,function*(){return this.room.state===fe.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return S(this,void 0,void 0,function*(){this.room&&this.room.state!==fe.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(hn.SKIPPED)}switchProtocol(e){return S(this,void 0,void 0,function*(){let t=!1,r=!1;if(this.room.on(O.Reconnecting,()=>{t=!0}),this.room.once(O.Reconnected,()=>{r=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(A=>setTimeout(A,1e3)),!t)return;const i=Date.now()+1e4;for(;Date.now()<i;){if(r)return;yield Nt(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 Xx extends yr{get description(){return"Cloud regions"}perform(){return S(this,void 0,void 0,function*(){const e=new Ad(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],r=new Set;for(let A=0;A<3;A++){const s=yield e.getNextBestRegionUrl();if(!s)break;if(r.has(s))continue;r.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((A,s)=>(A.duration-s.duration)*.5+(A.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 S(this,void 0,void 0,function*(){var t,r;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 A=yield this.room.localParticipant.streamText({topic:"test"}),s=1e3,a=1e6/s,c="A".repeat(s),u=Date.now();for(let f=0;f<a;f++)yield A.write(c);yield A.close();const l=Date.now(),d=yield(r=this.room.engine.pcManager)===null||r===void 0?void 0:r.publisher.getStats(),h={region:i,rtt:1e4,duration:l-u};return d==null||d.forEach(f=>{f.type==="candidate-pair"&&f.nominated&&(h.rtt=f.currentRoundTripTime*1e3)}),yield this.disconnect(),h})}}const cd=1e4;class Yx extends yr{get description(){return"Connection via UDP vs TCP"}perform(){return S(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 r=this.bestStats;this.appendMessage("upstream bitrate: ".concat((r.bitrateTotal/r.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((r.rttTotal/r.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((r.jitterTotal/r.count*1e3).toFixed(2)," ms")),r.packetsLost>0&&this.appendWarning("packets lost: ".concat((r.packetsLost/r.packetsSent*100).toFixed(2),"%")),r.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((r.qualityLimitationDurations.bandwidth/(cd/1e3)*100).toFixed(2),"%")),r.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((r.qualityLimitationDurations.cpu/(cd/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return S(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 r=t.getContext("2d");if(!r)throw new Error("Could not get canvas context");let i=0;const A=()=>{i=(i+1)%360,r.fillStyle="hsl(".concat(i,", 100%, 50%)"),r.fillRect(0,0,t.width,t.height),requestAnimationFrame(A)};A();const o=t.captureStream(30).getVideoTracks()[0],c=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,u={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},l=setInterval(()=>S(this,void 0,void 0,function*(){const d=yield c.getRTCStatsReport();d==null||d.forEach(h=>{h.type==="outbound-rtp"?(u.packetsSent=h.packetsSent,u.qualityLimitationDurations=h.qualityLimitationDurations,u.bitrateTotal+=h.targetBitrate,u.count++):h.type==="remote-inbound-rtp"&&(u.packetsLost=h.packetsLost,u.rttTotal+=h.roundTripTime,u.jitterTotal+=h.jitter)})}),1e3);return yield new Promise(d=>setTimeout(d,cd)),clearInterval(l),o.stop(),t.remove(),yield this.disconnect(),u})}}class Zx extends yr{get description(){return"Can publish audio"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect(),r=yield Gx();if(yield A0(r,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(r),yield new Promise(o=>setTimeout(o,3e3));const A=yield(e=r.sender)===null||e===void 0?void 0:e.getStats();if(!A)throw new Error("Could not get RTCStats");let s=0;if(A.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 $x extends yr{get description(){return"Can publish video"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect(),r=yield Vx();yield this.checkForVideo(r.mediaStreamTrack),t.localParticipant.publishTrack(r),yield new Promise(s=>setTimeout(s,5e3));const i=yield(e=r.sender)===null||e===void 0?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let A=0;if(i.forEach(s=>{s.type==="outbound-rtp"&&(s.kind==="video"||!s.kind&&s.mediaType==="video")&&(A+=s.packetsSent)}),A===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(A," video packets"))})}checkForVideo(e){return S(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const r=document.createElement("video");r.srcObject=t,r.muted=!0,yield new Promise(i=>{r.onplay=()=>{setTimeout(()=>{var A,s,o,a;const c=document.createElement("canvas"),u=e.getSettings(),l=(s=(A=u.width)!==null&&A!==void 0?A:r.videoWidth)!==null&&s!==void 0?s:1280,d=(a=(o=u.height)!==null&&o!==void 0?o:r.videoHeight)!==null&&a!==void 0?a:720;c.width=l,c.height=d;const h=c.getContext("2d");h.drawImage(r,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)},r.play()}),r.remove()})}}class eQ extends yr{get description(){return"Resuming connection after interruption"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect();let r=!1,i=!1,A;const s=new Promise(c=>{setTimeout(c,5e3),A=c}),o=()=>{r=!0};t.on(O.SignalReconnecting,o).on(O.Reconnecting,o).on(O.Reconnected,()=>{i=!0,A(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const a=t.engine.client.onClose;if(a&&a(""),yield s,r){if(!i||t.state!==fe.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 tQ extends yr{get description(){return"Can connect via TURN"}perform(){return S(this,void 0,void 0,function*(){var e,t;const r=new jl,i=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let A=!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,A=!0),c.startsWith("stun:")&&(o=!0);o?s&&!A&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.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 nQ extends yr{get description(){return"Establishing WebRTC connection"}perform(){return S(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(O.SignalConnected,()=>{const r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,A)=>{if(i.candidate){const s=new RTCIceCandidate(i);let o="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(rQ(s.address)?o+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,o+=" (passive)"):s.protocol==="udp"&&(t=!0)),this.appendMessage(o)}r&&r(i,A)},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(),ue.info("now the room is connected")}catch(r){throw this.appendWarning("ports need to be open on firewall in order to connect."),r}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 rQ(n){const e=n.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class iQ extends yr{get description(){return"Connecting to signal connection via WebSocket"}perform(){return S(this,void 0,void 0,function*(){var e,t,r;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new jl;const A=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(A.serverVersion,".")),((e=A.serverInfo)===null||e===void 0?void 0:e.edition)===Lm.Cloud&&(!((t=A.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((r=A.serverInfo)===null||r===void 0?void 0:r.region)),yield i.close()})}}class Q4 extends Sn.EventEmitter{constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=r}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:hn.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!==hn.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return S(this,void 0,void 0,function*(){const t=this.getNextCheckId(),r=new e(this.url,this.token,this.options),i=s=>{this.updateCheck(t,s)};r.on("update",i);const A=yield r.run();return r.off("update",i),A})}checkWebsocket(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(iQ)})}checkWebRTC(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(nQ)})}checkTURN(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(tQ)})}checkReconnect(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(eQ)})}checkPublishAudio(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Zx)})}checkPublishVideo(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck($x)})}checkConnectionProtocol(){return S(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Yx);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Xx)})}}const AQ=/\{[^{}]+\}/g;function sQ(){return Math.random().toString(36).slice(2,11)}function oQ(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:r=globalThis.fetch,querySerializer:i,bodySerializer:A,headers:s,...o}={...n};e=D0(e);const a=[];async function c(u,l){const{baseUrl:d,fetch:h=r,Request:f=t,headers:p,params:g={},parseAs:v="json",querySerializer:y,bodySerializer:B=A??cQ,body:b,...w}=l||{};d&&(e=D0(d));let _=typeof i=="function"?i:L0(i);y&&(_=typeof y=="function"?y:L0({...typeof i=="object"?i:{},...y}));const k=b===void 0?void 0:B(b),T=k===void 0||k instanceof FormData?{}:{"Content-Type":"application/json"},x={redirect:"follow",...o,...w,body:k,headers:lQ(T,s,p,g.header)};let P,E,F=new t(uQ(u,{baseUrl:e,params:g,querySerializer:_}),x);for(const N in w)N in F||(F[N]=w[N]);if(a.length){P=sQ(),E=Object.freeze({baseUrl:e,fetch:h,parseAs:v,querySerializer:_,bodySerializer:B});for(const N of a)if(N&&typeof N=="object"&&typeof N.onRequest=="function"){const q=await N.onRequest({request:F,schemaPath:u,params:g,options:E,id:P});if(q){if(!(q instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");F=q}}}let M=await h(F);if(a.length)for(let N=a.length-1;N>=0;N--){const q=a[N];if(q&&typeof q=="object"&&typeof q.onResponse=="function"){const ve=await q.onResponse({request:F,response:M,schemaPath:u,params:g,options:E,id:P});if(ve){if(!(ve instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");M=ve}}}if(M.status===204||M.headers.get("Content-Length")==="0")return M.ok?{data:{},response:M}:{error:{},response:M};if(M.ok)return v==="stream"?{data:M.body,response:M}:{data:await M[v](),response:M};let J=await M.text();try{J=JSON.parse(J)}catch{}return{error:J,response:M}}return{GET(u,l){return c(u,{...l,method:"GET"})},PUT(u,l){return c(u,{...l,method:"PUT"})},POST(u,l){return c(u,{...l,method:"POST"})},DELETE(u,l){return c(u,{...l,method:"DELETE"})},OPTIONS(u,l){return c(u,{...l,method:"OPTIONS"})},HEAD(u,l){return c(u,{...l,method:"HEAD"})},PATCH(u,l){return c(u,{...l,method:"PATCH"})},TRACE(u,l){return c(u,{...l,method:"TRACE"})},use(...u){for(const l of u)if(l){if(typeof l!="object"||!("onRequest"in l||"onResponse"in l))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");a.push(l)}},eject(...u){for(const l of u){const d=a.indexOf(l);d!==-1&&a.splice(d,1)}}}}function ha(n,e,t){if(e==null)return"";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${n}=${(t==null?void 0:t.allowReserved)===!0?e:encodeURIComponent(e)}`}function O0(n,e,t){if(!e||typeof e!="object")return"";const r=[],i={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(const o in e)r.push(o,t.allowReserved===!0?e[o]:encodeURIComponent(e[o]));const s=r.join(",");switch(t.style){case"form":return`${n}=${s}`;case"label":return`.${s}`;case"matrix":return`;${n}=${s}`;default:return s}}for(const s in e){const o=t.style==="deepObject"?`${n}[${s}]`:s;r.push(ha(o,e[s],t))}const A=r.join(i);return t.style==="label"||t.style==="matrix"?`${i}${A}`:A}function M0(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){const A={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",s=(t.allowReserved===!0?e:e.map(o=>encodeURIComponent(o))).join(A);switch(t.style){case"simple":return s;case"label":return`.${s}`;case"matrix":return`;${n}=${s}`;default:return`${n}=${s}`}}const r={simple:",",label:".",matrix:";"}[t.style]||"&",i=[];for(const A of e)t.style==="simple"||t.style==="label"?i.push(t.allowReserved===!0?A:encodeURIComponent(A)):i.push(ha(n,A,t));return t.style==="label"||t.style==="matrix"?`${r}${i.join(r)}`:i.join(r)}function L0(n){return function(t){const r=[];if(t&&typeof t=="object")for(const i in t){const A=t[i];if(A!=null){if(Array.isArray(A)){if(A.length===0)continue;r.push(M0(i,A,{style:"form",explode:!0,...n==null?void 0:n.array,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}if(typeof A=="object"){r.push(O0(i,A,{style:"deepObject",explode:!0,...n==null?void 0:n.object,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}r.push(ha(i,A,n))}}return r.join("&")}}function aQ(n,e){let t=n;for(const r of n.match(AQ)??[]){let i=r.substring(1,r.length-1),A=!1,s="simple";if(i.endsWith("*")&&(A=!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(r,M0(i,o,{style:s,explode:A}));continue}if(typeof o=="object"){t=t.replace(r,O0(i,o,{style:s,explode:A}));continue}if(s==="matrix"){t=t.replace(r,`;${ha(i,o)}`);continue}t=t.replace(r,s==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function cQ(n){return n instanceof FormData?n:JSON.stringify(n)}function uQ(n,e){var i;let t=`${e.baseUrl}${n}`;(i=e.params)!=null&&i.path&&(t=aQ(t,e.params.path));let r=e.querySerializer(e.params.query??{});return r.startsWith("?")&&(r=r.substring(1)),r&&(t+=`?${r}`),t}function lQ(...n){const e=new Headers;for(const t of n){if(!t||typeof t!="object")continue;const r=t instanceof Headers?t.entries():Object.entries(t);for(const[i,A]of r)if(A===null)e.delete(i);else if(Array.isArray(A))for(const s of A)e.append(i,s);else A!==void 0&&e.set(i,A)}return e}function D0(n){return n.endsWith("/")?n.substring(0,n.length-1):n}const N0="Onboardee-Session-Token",H0="OnboardeeSessionToken";class K0{constructor(e){this.client=oQ({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch}),this.client.use({onRequest({request:t}){if(window.localStorage){const r=window.localStorage.getItem(H0);r&&t.headers.set(N0,r)}return t},onResponse({response:t}){const r=t.headers.get(N0);return r&&window.localStorage&&window.localStorage.setItem(H0,r),t}})}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 clientInitialise(e,t={}){return await this.client.POST("/api/client/{appToken}/initialise",{params:{path:{appToken:e}},body:t})}async clientStartSession(e,t){return await this.client.POST("/api/client/{appToken}/start-session",{params:{path:{appToken:e}},body:t})}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(e){return await this.client.GET("/api/plans",{params:{query:{...e&&{client_type:e}}}})}async listPlansWithStatus(){return await this.client.GET("/api/plans-with-status")}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 getProductAnalytics(e,t,r,i){return await this.client.GET("/api/products/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...r&&{end_date:r},...i&&{course_id:i}}}})}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 getProductNavigationIndex(e){return await this.client.GET("/api/products/{id}/navigation-index",{params:{path:{id:e}}})}async replaceProductNavigationIndex(e,t){return await this.client.PUT("/api/products/{id}/navigation-index",{params:{path:{id:e}},body:t})}async listProductKnowledgeBlocks(e){return await this.client.GET("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createProductKnowledgeBlock(e,t){return await this.client.POST("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async searchProductKnowledgeBlocks(e,t,r){return await this.client.GET("/api/products/{id}/knowledge-blocks/search",{params:{path:{id:e},query:{q:t,...r&&{limit:r.toString()}}}})}async updateProductKnowledgeBlock(e,t,r){return await this.client.PATCH("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deleteProductKnowledgeBlock(e,t){return await this.client.DELETE("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId: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 getAdminPlan(e){return await this.client.GET("/api/admin/plans/{id}",{params:{path:{id:e}}})}async getPlanAnalytics(e,t,r){return await this.client.GET("/api/plans/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...r&&{end_date:r}}}})}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 getPlanVideoMetadata(e){return await this.client.GET("/api/plans/{id}/video-metadata",{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 listPlanKnowledgeBlocks(e){return await this.client.GET("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createPlanKnowledgeBlock(e,t){return await this.client.POST("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async updatePlanKnowledgeBlock(e,t,r){return await this.client.PUT("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deletePlanKnowledgeBlock(e,t){return await this.client.DELETE("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async getPlanNavigationIndex(e){return await this.client.GET("/api/plans/{id}/navigation-index",{params:{path:{id:e}}})}async replacePlanNavigationIndex(e,t){return await this.client.POST("/api/plans/{id}/navigation-index",{params:{path:{id:e}},body:t})}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 getPlanFAQ(e){return await this.client.GET("/api/plans/{id}/faq",{params:{path:{id:e}}})}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,r){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deleteRevisionKnowledgeBlock(e,t){return await this.client.DELETE("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async listSessions(e,t){const r={token:e};return t!=null&&t.productId&&(r.product_id=t.productId),t!=null&&t.startDate&&(r.start_date=t.startDate),t!=null&&t.endDate&&(r.end_date=t.endDate),await this.client.GET("/api/sessions",{params:{query:r}})}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 getSessionSummary(e){return await this.client.GET("/api/sessions/{id}/summary",{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 listUserSessions(e){const t={};return e!=null&&e.productId&&(t.product_id=e.productId),e!=null&&e.courseId&&(t.course_id=e.courseId),e!=null&&e.startDate&&(t.start_date=e.startDate),e!=null&&e.endDate&&(t.end_date=e.endDate),e!=null&&e.page&&(t.page=e.page),e!=null&&e.limit&&(t.limit=e.limit),e!=null&&e.courseName&&(t.course_name=e.courseName),e!=null&&e.userName&&(t.user_name=e.userName),e!=null&&e.company&&(t.company=e.company),e!=null&&e.email&&(t.email=e.email),e!=null&&e.sortBy&&(t.sort_by=e.sortBy),e!=null&&e.sortOrder&&(t.sort_order=e.sortOrder),await this.client.GET("/api/user-sessions",{params:Object.keys(t).length>0?{query:t}:void 0})}async listUserSessionsAggregate(e){const t={};return e!=null&&e.productId&&(t.product_id=e.productId),e!=null&&e.courseId&&(t.course_id=e.courseId),e!=null&&e.startDate&&(t.start_date=e.startDate),e!=null&&e.endDate&&(t.end_date=e.endDate),await this.client.GET("/api/user-sessions-aggregate",{params:Object.keys(t).length>0?{query:t}:void 0})}async getJoinToken(e,{clientType:t,user:r}={}){return await this.client.GET("/api/join-token",{params:{query:{token:e,...t&&{client_type:t},...r&&{user:encodeURIComponent(r)}}}})}async getSessionPlan(e){return await this.client.GET("/api/sessions/{id}/plan",{params:{path:{id:e}}})}async getPlanSDK(e){return await this.client.GET("/api/plans/{uuid}/sdk",{params:{path:{uuid:e}}})}getClient(){return this.client}}const V0="https://app.coragents.ai";class pa extends jc{constructor(e,t,r,i){super(),this.state=null,this.isPaused=!1,this.speakingState=null,this.captureScreen=null,this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.room=null,this.startedAt=null,this.agentAnalyser=null,this.userAnalyser=null,this.appToken=e,this.planId=t,this.clientType=r,this.api=i.api||new K0({baseUrl:V0}),this.identity=i.identity||null,this.roomFactory=i.roomFactory||(A=>new Li(A)),this.captureScreen=i.captureScreen||null}async start(){this.planId,this.setState("connecting"),this.speakingStateChanged("thinking");try{const t=(await this.api.clientStartSession(this.appToken,{client_type:this.clientType,onboarding_plan:this.planId})).data;if(!(t!=null&&t.url)||!(t!=null&&t.token)||!(t!=null&&t.room)||!(t!=null&&t.session_uuid))throw new Error("Invalid room info");this.sessionUuid=t==null?void 0:t.session_uuid,this.roomId=t==null?void 0:t.room,this.joinToken=t==null?void 0:t.token,this.roomUrl=t==null?void 0:t.url,this.startedAt=Date.now(),await this.joinRoom(),this.setState("connected"),this.planId,this.sessionUuid}catch(e){console.error("[obi] error starting session",{error:e}),this.setState("error")}}async joinRoom({withMicrophone:e=!1,withStateRecovery:t=!1}={}){this.room=this.roomFactory({adaptiveStream:!0,dynacast:!0}),this.room.on(O.Disconnected,r=>{if(!this.room)return;let i=null;switch(r){case 12:i="invalid-room";break}this.shutdown(i)}),this.room.on(O.TrackSubscribed,r=>{r.kind==="audio"&&(r.attach(),r.source===R.Source.Microphone&&(this.agentAnalyser&&this.agentAnalyser.disconnect(),this.agentAnalyser=this.createFFT(r.mediaStream)))}),this.room.on(O.LocalTrackPublished,r=>{r.kind==="audio"&&(this.userAnalyser&&this.userAnalyser.disconnect(),this.userAnalyser=this.createFFT(r.audioTrack.mediaStream))}),this.room.on(O.ParticipantAttributesChanged,r=>{if(!r["lk.agent.state"])return;const i=r["lk.agent.state"];switch(i){case"speaking":this.speakingStateChanged("speaking");break;case"listening":this.state!=="connected"&&this.speakingStateChanged("listening");break;case"thinking":this.speakingStateChanged("thinking");break;default:console.warn("[obi] unknown speaking state",i)}}),this.room.on(O.DataReceived,async r=>{try{const i=new TextDecoder().decode(r),A=JSON.parse(i);switch(A.status||A.request||A.type){case"course_progress":typeof A.current_step=="number"&&typeof A.total_steps=="number"&&Array.isArray(A.step_names)&&this.emit("courseProgress",{currentStep:Math.max(1,A.current_step),totalSteps:Math.max(1,A.total_steps),stepNames:A.step_names});break;case"using_tool":this.speakingStateChanged("busy");break;case"using_tool_ended":this.speakingStateChanged("speaking");break;case"prompt_user":this.setState("volume-check");break;case"mic_check":this.setState("mic-check");break;case"share_mic":this.setState("mic-share");break;case"share_screen":this.setState("screen-share");break;case"navigate":this.setState("navigate");break;default:console.warn("[obi] unknown data received",A)}}catch(i){console.error("[obi] error parsing data",i)}}),this.room.localParticipant.registerRpcMethod("mic_check",async r=>(this.sessionUuid,await this.checkMicrophone()?"ok":"error")),this.room.localParticipant.registerRpcMethod("screen_capture",async r=>{if(!this.captureScreen)return console.error("[obi] no captureScreen function provided"),"error";let i=null,A=null;try{i=await this.captureScreen()}catch(s){i=null,s=s}if(!i||A)return console.error("[obi] error capturing screen",{error:A}),"error";try{return await this.room.localParticipant.sendFile(new File([i],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),"ok"}catch(s){return console.error("[obi] error sending screen capture",{error:s}),"error"}}),await this.room.connect(this.roomUrl,this.joinToken);for(let r=0;r<9&&!(this.room.state===fe.Connected&&this.room.remoteParticipants.size>=1);r++)await new Promise(i=>setTimeout(i,1e3));if(!(this.room.state===fe.Connected&&this.room.remoteParticipants.size>=1)){console.error("[obi] room not connected",{state:this.room.state,numParticipants:this.room.remoteParticipants.size}),this.shutdown("invalid-room");return}if(e&&await this.room.localParticipant.setMicrophoneEnabled(!0),t){let r=!1;for(const i of this.room.remoteParticipants.values())i.isSpeaking&&(r=!0);r?this.speakingState="speaking":this.speakingState="listening"}}async continue(){this.sessionUuid,this.speakingStateChanged("thinking"),await this.sendData({request:"prompt_user",success:!0})}async checkMicrophone(){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?(this.sessionUuid,await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0):this.sessionUuid,e&&this.clientType==="sdk"&&this.setState("in-progress"),this.emit("micCheckComplete",e),e}async shareMicrophone(){this.sessionUuid,this.speakingStateChanged("thinking");let e=null,t=null;try{e=await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0}catch(r){r=r,this.isMicShared=!1}e?this.sessionUuid:console.error("[obi] failed to share microphone",{error:t}),await this.sendData({request:"share_mic",success:!!e}),this.clientType==="sdk"&&this.setState("in-progress")}async shareMicrophoneFailed(){this.isMicShared=!1,await this.sendData({request:"share_mic",success:!1}),this.clientType==="sdk"&&this.setState("in-progress")}async shareScreen(){this.sessionUuid,this.speakingStateChanged("thinking"),await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),await this.sendData({request:"share_screen",success:!0}),this.setState("navigate")}async pause(){this.muteMicrophone(),this.isPaused=!0,this.emit("paused"),await this.sendData({request:"pause"}),console.log("[obi] paused session",{sessionUuid:this.sessionUuid})}async unpause(){this.unmuteMicrophone(),this.isPaused=!1,this.emit("unpaused"),await this.sendData({request:"unpause"}),console.log("[obi] unpaused session",{sessionUuid:this.sessionUuid})}muteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var t,r;e.handleMuted(),(r=(t=e.track)==null?void 0:t.mediaStream)==null||r.getTracks().forEach(i=>i.enabled=!1)})}unmuteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var t,r;e.handleUnmuted(),(r=(t=e.track)==null?void 0:t.mediaStream)==null||r.getTracks().forEach(i=>i.enabled=!0)})}async stop(){this.emit("stopped"),await this.shutdown()}async shutdown(e=null){if(this.room){this.sessionUuid,await this.sendData({request:"shutdown"});const t=this.room;this.room=null,await t.disconnect(),this.sessionUuid}this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.emit("shutdown",e)}async say(e){this.speakingStateChanged("thinking"),this.isPaused&&await this.unpause(),await this.sendData({request:"say",message:e})}serialise(){return JSON.stringify({state:this.state,speakingState:this.speakingState,appToken:this.appToken,planId:this.planId,clientType:this.clientType,isPaused:this.isPaused,identity:this.identity,sessionUuid:this.sessionUuid,roomId:this.roomId,joinToken:this.joinToken,roomUrl:this.roomUrl,startedAt:this.startedAt})}audioSpectrum(){return this.speakingState==="speaking"&&this.agentAnalyser?this.normaliseSpectrum(this.agentAnalyser):this.speakingState==="listening"&&this.userAnalyser?this.normaliseSpectrum(this.userAnalyser):null}normaliseSpectrum(e){const r=e.context.sampleRate/2/e.frequencyBinCount,i=new Uint8Array(e.frequencyBinCount);e.getByteFrequencyData(i);const A=[],s=50,o=5e3,a=8,c=Math.pow(o/s,1/a);for(let u=0;u<a;u++){const l=s*Math.pow(c,u),d=s*Math.pow(c,u+1),h=Math.floor(l/r),f=Math.floor(d/r),p=Math.min(f,i.length),g=Math.min(h,p);if(g<p){const v=i.slice(g,p).reduce((y,B)=>y+B,0)/(p-g)/255;A.push(v)}else A.push(0)}return A}setState(e){this.state;const t=this.state;this.state=e,this.emit("stateChanged",e,t)}static deserialise(e,t,r,i={}){const A=JSON.parse(e),s=new pa(t,A.planId,r,i);return s.state=A.state,s.speakingState=A.speakingState,s.identity=A.identity||null,s.isPaused=A.isPaused||!1,s.sessionUuid=A.sessionUuid||null,s.roomId=A.roomId||null,s.joinToken=A.joinToken||null,s.roomUrl=A.roomUrl||null,s.startedAt=A.startedAt||null,s}speakingStateChanged(e){this.speakingState;const t=this.speakingState;this.speakingState=e,this.emit("speakingStateChanged",e,t)}async sendData(e){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0})}createFFT(e){const t=new AudioContext,r=t.createAnalyser();return t.createMediaStreamSource(e).connect(r),r.fftSize=2048,r.smoothingTimeConstant=.6,r}}class fa extends jc{constructor(e,t,r={}){super(),this.state="loading",this.error=null,this.identity=null,this.product=null,this.plans=[],this.planIsCompleted=[],this.selectedPlan=null,this.selectedPlanUuid=null,this.showWidget=!1,this.session=null,this.captureScreen=null,this.appToken=e,this.clientType=t,this.api=r.api||new K0({baseUrl:r.apiBaseUrl||V0}),this.sessionFactory=r.sessionFactory||((i,A,s,o)=>new pa(i,A,s,o)),this.captureScreen=r.captureScreen||null}async initialise(e={}){var t,r,i,A,s,o;if(!this.appToken)throw new Error("App token is required");this.setState("loading");try{const a=await this.api.clientInitialise(this.appToken,{identity:e.identity,client_type:this.clientType});if(this.identity=e.identity||null,this.product=((t=a.data)==null?void 0:t.product)||null,this.plans=((r=a.data)==null?void 0:r.onboarding_plans)||[],this.selectedPlan=((i=a.data)==null?void 0:i.selected_plan)||null,this.planIsCompleted=((A=a.data)==null?void 0:A.plan_is_completed)||[],this.showWidget=((s=a.data)==null?void 0:s.show_widget)||!1,e.planUuid){let c=null;try{const u=await this.api.getPlanSDK(e.planUuid);u.data&&(c=u.data)}catch(u){try{const l=await this.api.getSessionPlan(e.planUuid);(o=l.data)!=null&&o.plan_uuid&&(c={uuid:l.data.plan_uuid})}catch(l){console.error("[obi] error getting plan via both endpoints",{planErr:u,sessionErr:l})}}c?(this.selectedPlan=c,this.selectedPlanUuid=e.planUuid):console.warn("[obi] plan not found",{planUuid:e.planUuid})}this.identity,this.product,this.plans,this.selectedPlan,this.showWidget}catch(a){throw this.error=a instanceof Error?a:new Error(String(a)),this.setState("error"),a}finally{this.setState("ready")}}selectPlan(e){this.selectedPlan=e,this.selectedPlanUuid=(e==null?void 0:e.uuid)||null,this.emit("planSelected",e)}async startSession(e,t){return await this._stopSession(),this.session=this.sessionFactory(this.appToken,e,this.clientType,{api:this.api,identity:this.identity,captureScreen:this.captureScreen}),this.prepareSession(t),this.session.start().then(()=>{this.emit("sessionStarted",this.session)}).catch(r=>{this.session=null,console.error("[obi] error starting session",r)}),this.session}async resumeSession(e){var t,r;return this.state,(t=this.session)==null||t.state,(r=this.session)==null||r.speakingState,this.session.captureScreen=this.captureScreen,this.prepareSession(e),this.session.joinRoom({withMicrophone:!0,withStateRecovery:!0}).then(()=>{this.emit("sessionResumed",this.session)}).catch(i=>{console.error("[obi] error joining room",{error:i}),i instanceof Error&&i.message==="Room is not connected"&&this.session.stop()}),this.session}prepareSession(e){if(!this.session)throw new Error("No session to prepare");return e(this.session),this.session.on("stopped",()=>{this.emit("sessionStopped")}),this.session.on("shutdown",t=>{var r,i,A;if((r=this.session)!=null&&r.startedAt&&this.session.startedAt+5*60*1e3<Date.now()){const s=this.plans.findIndex(o=>{var a;return o.uuid===((a=this.selectedPlan)==null?void 0:a.uuid)});s!==-1&&(this.planIsCompleted[s]=!0)}(A=(i=this.session)==null?void 0:i.removeAllListeners)==null||A.call(i),this.session=null,this.selectedPlan=null,this.selectedPlanUuid=null,this.emit("sessionShutdown",t)}),this.session}async stopSession(){await this._stopSession(),this.selectedPlan&&this.selectPlan(null)}async _stopSession(){this.session&&(this.trackEvent("session-stopped",{sessionUuid:this.session.sessionUuid}),await this.session.stop(),this.session=null)}isLoading(){return this.state==="loading"}isReady(){return this.state==="ready"}serialise(){var e;return JSON.stringify({state:this.state,appToken:this.appToken,clientType:this.clientType,identity:this.identity,product:this.product,plans:this.plans,selectedPlan:this.selectedPlan,selectedPlanUuid:this.selectedPlanUuid,showWidget:this.showWidget,session:(e=this.session)==null?void 0:e.serialise(),serialisedAt:new Date().toISOString()})}static deserialise(e,t,r,i={}){const A=JSON.parse(e);if(A.serialisedAt){const o=new Date(A.serialisedAt);if(new Date().getTime()-o.getTime()>1e3*20)throw new Error("Client was serialised more than 20 seconds ago, assuming it's dead.")}else throw new Error("Client was not serialised, assuming it's dead.");const s=new fa(t,r,i);return s.state=A.state,s.identity=A.identity||null,s.product=A.product||null,s.plans=A.plans||[],s.selectedPlan=A.selectedPlan||null,s.selectedPlanUuid=A.selectedPlanUuid||null,s.showWidget=A.showWidget||!1,A.session&&(s.session=pa.deserialise(A.session,t,r,{api:s.api})),s}setState(e){const t=this.state;this.state=e,this.emit("stateChanged",e,t)}trackEvent(e,t={}){var r,i,A;this.emit("trackEvent",e,{...t,clientType:this.clientType,planId:(r=this.selectedPlan)==null?void 0:r.uuid,productId:(i=this.product)==null?void 0:i.uuid,sessionId:(A=this.session)==null?void 0:A.sessionUuid})}}var ga,ee,G0,zr,j0,W0,q0,J0,ud,ld,dd,z0,WA={},X0=[],dQ=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,qA=Array.isArray;function Kn(n,e){for(var t in e)n[t]=e[t];return n}function hd(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function pd(n,e,t){var r,i,A,s={};for(A in e)A=="key"?r=e[A]:A=="ref"?i=e[A]:s[A]=e[A];if(arguments.length>2&&(s.children=arguments.length>3?ga.call(arguments,2):t),typeof n=="function"&&n.defaultProps!=null)for(A in n.defaultProps)s[A]==null&&(s[A]=n.defaultProps[A]);return ma(n,s,r,i,null)}function ma(n,e,t,r,i){var A={type:n,props:e,key:t,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++G0,__i:-1,__u:0};return i==null&&ee.vnode!=null&&ee.vnode(A),A}function St(n){return n.children}function Vn(n,e){this.props=n,this.context=e}function Di(n,e){if(e==null)return n.__?Di(n.__,n.__i+1):null;for(var t;e<n.__k.length;e++)if((t=n.__k[e])!=null&&t.__e!=null)return t.__e;return typeof n.type=="function"?Di(n):null}function Y0(n){var e,t;if((n=n.__)!=null&&n.__c!=null){for(n.__e=n.__c.base=null,e=0;e<n.__k.length;e++)if((t=n.__k[e])!=null&&t.__e!=null){n.__e=n.__c.base=t.__e;break}return Y0(n)}}function fd(n){(!n.__d&&(n.__d=!0)&&zr.push(n)&&!va.__r++||j0!=ee.debounceRendering)&&((j0=ee.debounceRendering)||W0)(va)}function va(){for(var n,e,t,r,i,A,s,o=1;zr.length;)zr.length>o&&zr.sort(q0),n=zr.shift(),o=zr.length,n.__d&&(t=void 0,i=(r=(e=n).__v).__e,A=[],s=[],e.__P&&((t=Kn({},r)).__v=r.__v+1,ee.vnode&&ee.vnode(t),gd(e.__P,t,r,e.__n,e.__P.namespaceURI,32&r.__u?[i]:null,A,i??Di(r),!!(32&r.__u),s),t.__v=r.__v,t.__.__k[t.__i]=t,ny(A,t,s),t.__e!=i&&Y0(t)));va.__r=0}function Z0(n,e,t,r,i,A,s,o,a,c,u){var l,d,h,f,p,g,v=r&&r.__k||X0,y=e.length;for(a=hQ(t,e,v,a,y),l=0;l<y;l++)(h=t.__k[l])!=null&&(d=h.__i==-1?WA:v[h.__i]||WA,h.__i=l,g=gd(n,h,d,i,A,s,o,a,c,u),f=h.__e,h.ref&&d.ref!=h.ref&&(d.ref&&md(d.ref,null,h),u.push(h.ref,h.__c||f,h)),p==null&&f!=null&&(p=f),4&h.__u||d.__k===h.__k?a=$0(h,a,n):typeof h.type=="function"&&g!==void 0?a=g:f&&(a=f.nextSibling),h.__u&=-7);return t.__e=p,a}function hQ(n,e,t,r,i){var A,s,o,a,c,u=t.length,l=u,d=0;for(n.__k=new Array(i),A=0;A<i;A++)(s=e[A])!=null&&typeof s!="boolean"&&typeof s!="function"?(a=A+d,(s=n.__k[A]=typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?ma(null,s,null,null,null):qA(s)?ma(St,{children:s},null,null,null):s.constructor==null&&s.__b>0?ma(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):s).__=n,s.__b=n.__b+1,o=null,(c=s.__i=pQ(s,t,a,l))!=-1&&(l--,(o=t[c])&&(o.__u|=2)),o==null||o.__v==null?(c==-1&&(i>u?d--:i<u&&d++),typeof s.type!="function"&&(s.__u|=4)):c!=a&&(c==a-1?d--:c==a+1?d++:(c>a?d--:d++,s.__u|=4))):n.__k[A]=null;if(l)for(A=0;A<u;A++)(o=t[A])!=null&&!(2&o.__u)&&(o.__e==r&&(r=Di(o)),iy(o,o));return r}function $0(n,e,t){var r,i;if(typeof n.type=="function"){for(r=n.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=n,e=$0(r[i],e,t));return e}n.__e!=e&&(e&&n.type&&!t.contains(e)&&(e=Di(n)),t.insertBefore(n.__e,e||null),e=n.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ya(n,e){return e=e||[],n==null||typeof n=="boolean"||(qA(n)?n.some(function(t){ya(t,e)}):e.push(n)),e}function pQ(n,e,t,r){var i,A,s=n.key,o=n.type,a=e[t];if(a===null&&n.key==null||a&&s==a.key&&o==a.type&&!(2&a.__u))return t;if(r>(a!=null&&!(2&a.__u)?1:0))for(i=t-1,A=t+1;i>=0||A<e.length;){if(i>=0){if((a=e[i])&&!(2&a.__u)&&s==a.key&&o==a.type)return i;i--}if(A<e.length){if((a=e[A])&&!(2&a.__u)&&s==a.key&&o==a.type)return A;A++}}return-1}function ey(n,e,t){e[0]=="-"?n.setProperty(e,t??""):n[e]=t==null?"":typeof t!="number"||dQ.test(e)?t:t+"px"}function wa(n,e,t,r,i){var A;e:if(e=="style")if(typeof t=="string")n.style.cssText=t;else{if(typeof r=="string"&&(n.style.cssText=r=""),r)for(e in r)t&&e in t||ey(n.style,e,"");if(t)for(e in t)r&&t[e]==r[e]||ey(n.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")A=e!=(e=e.replace(J0,"$1")),e=e.toLowerCase()in n||e=="onFocusOut"||e=="onFocusIn"?e.toLowerCase().slice(2):e.slice(2),n.l||(n.l={}),n.l[e+A]=t,t?r?t.u=r.u:(t.u=ud,n.addEventListener(e,A?dd:ld,A)):n.removeEventListener(e,A?dd:ld,A);else{if(i=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in n)try{n[e]=t??"";break e}catch{}typeof t=="function"||(t==null||t===!1&&e[4]!="-"?n.removeAttribute(e):n.setAttribute(e,e=="popover"&&t==1?"":t))}}function ty(n){return function(e){if(this.l){var t=this.l[e.type+n];if(e.t==null)e.t=ud++;else if(e.t<t.u)return;return t(ee.event?ee.event(e):e)}}}function gd(n,e,t,r,i,A,s,o,a,c){var u,l,d,h,f,p,g,v,y,B,b,w,_,k,T,x,P,E=e.type;if(e.constructor!=null)return null;128&t.__u&&(a=!!(32&t.__u),A=[o=e.__e=t.__e]),(u=ee.__b)&&u(e);e:if(typeof E=="function")try{if(v=e.props,y="prototype"in E&&E.prototype.render,B=(u=E.contextType)&&r[u.__c],b=u?B?B.props.value:u.__:r,t.__c?g=(l=e.__c=t.__c).__=l.__E:(y?e.__c=l=new E(v,b):(e.__c=l=new Vn(v,b),l.constructor=E,l.render=gQ),B&&B.sub(l),l.props=v,l.state||(l.state={}),l.context=b,l.__n=r,d=l.__d=!0,l.__h=[],l._sb=[]),y&&l.__s==null&&(l.__s=l.state),y&&E.getDerivedStateFromProps!=null&&(l.__s==l.state&&(l.__s=Kn({},l.__s)),Kn(l.__s,E.getDerivedStateFromProps(v,l.__s))),h=l.props,f=l.state,l.__v=e,d)y&&E.getDerivedStateFromProps==null&&l.componentWillMount!=null&&l.componentWillMount(),y&&l.componentDidMount!=null&&l.__h.push(l.componentDidMount);else{if(y&&E.getDerivedStateFromProps==null&&v!==h&&l.componentWillReceiveProps!=null&&l.componentWillReceiveProps(v,b),!l.__e&&l.shouldComponentUpdate!=null&&l.shouldComponentUpdate(v,l.__s,b)===!1||e.__v==t.__v){for(e.__v!=t.__v&&(l.props=v,l.state=l.__s,l.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.some(function(F){F&&(F.__=e)}),w=0;w<l._sb.length;w++)l.__h.push(l._sb[w]);l._sb=[],l.__h.length&&s.push(l);break e}l.componentWillUpdate!=null&&l.componentWillUpdate(v,l.__s,b),y&&l.componentDidUpdate!=null&&l.__h.push(function(){l.componentDidUpdate(h,f,p)})}if(l.context=b,l.props=v,l.__P=n,l.__e=!1,_=ee.__r,k=0,y){for(l.state=l.__s,l.__d=!1,_&&_(e),u=l.render(l.props,l.state,l.context),T=0;T<l._sb.length;T++)l.__h.push(l._sb[T]);l._sb=[]}else do l.__d=!1,_&&_(e),u=l.render(l.props,l.state,l.context),l.state=l.__s;while(l.__d&&++k<25);l.state=l.__s,l.getChildContext!=null&&(r=Kn(Kn({},r),l.getChildContext())),y&&!d&&l.getSnapshotBeforeUpdate!=null&&(p=l.getSnapshotBeforeUpdate(h,f)),x=u,u!=null&&u.type===St&&u.key==null&&(x=ry(u.props.children)),o=Z0(n,qA(x)?x:[x],e,t,r,i,A,s,o,a,c),l.base=e.__e,e.__u&=-161,l.__h.length&&s.push(l),g&&(l.__E=l.__=null)}catch(F){if(e.__v=null,a||A!=null)if(F.then){for(e.__u|=a?160:128;o&&o.nodeType==8&&o.nextSibling;)o=o.nextSibling;A[A.indexOf(o)]=null,e.__e=o}else for(P=A.length;P--;)hd(A[P]);else e.__e=t.__e,e.__k=t.__k;ee.__e(F,e,t)}else A==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):o=e.__e=fQ(t.__e,e,t,r,i,A,s,a,c);return(u=ee.diffed)&&u(e),128&e.__u?void 0:o}function ny(n,e,t){for(var r=0;r<t.length;r++)md(t[r],t[++r],t[++r]);ee.__c&&ee.__c(e,n),n.some(function(i){try{n=i.__h,i.__h=[],n.some(function(A){A.call(i)})}catch(A){ee.__e(A,i.__v)}})}function ry(n){return typeof n!="object"||n==null||n.__b&&n.__b>0?n:qA(n)?n.map(ry):Kn({},n)}function fQ(n,e,t,r,i,A,s,o,a){var c,u,l,d,h,f,p,g=t.props,v=e.props,y=e.type;if(y=="svg"?i="http://www.w3.org/2000/svg":y=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),A!=null){for(c=0;c<A.length;c++)if((h=A[c])&&"setAttribute"in h==!!y&&(y?h.localName==y:h.nodeType==3)){n=h,A[c]=null;break}}if(n==null){if(y==null)return document.createTextNode(v);n=document.createElementNS(i,y,v.is&&v),o&&(ee.__m&&ee.__m(e,A),o=!1),A=null}if(y==null)g===v||o&&n.data==v||(n.data=v);else{if(A=A&&ga.call(n.childNodes),g=t.props||WA,!o&&A!=null)for(g={},c=0;c<n.attributes.length;c++)g[(h=n.attributes[c]).name]=h.value;for(c in g)if(h=g[c],c!="children"){if(c=="dangerouslySetInnerHTML")l=h;else if(!(c in v)){if(c=="value"&&"defaultValue"in v||c=="checked"&&"defaultChecked"in v)continue;wa(n,c,null,h,i)}}for(c in v)h=v[c],c=="children"?d=h:c=="dangerouslySetInnerHTML"?u=h:c=="value"?f=h:c=="checked"?p=h:o&&typeof h!="function"||g[c]===h||wa(n,c,h,g[c],i);if(u)o||l&&(u.__html==l.__html||u.__html==n.innerHTML)||(n.innerHTML=u.__html),e.__k=[];else if(l&&(n.innerHTML=""),Z0(e.type=="template"?n.content:n,qA(d)?d:[d],e,t,r,y=="foreignObject"?"http://www.w3.org/1999/xhtml":i,A,s,A?A[0]:t.__k&&Di(t,0),o,a),A!=null)for(c=A.length;c--;)hd(A[c]);o||(c="value",y=="progress"&&f==null?n.removeAttribute("value"):f!=null&&(f!==n[c]||y=="progress"&&!f||y=="option"&&f!=g[c])&&wa(n,c,f,g[c],i),c="checked",p!=null&&p!=n[c]&&wa(n,c,p,g[c],i))}return n}function md(n,e,t){try{if(typeof n=="function"){var r=typeof n.__u=="function";r&&n.__u(),r&&e==null||(n.__u=n(e))}else n.current=e}catch(i){ee.__e(i,t)}}function iy(n,e,t){var r,i;if(ee.unmount&&ee.unmount(n),(r=n.ref)&&(r.current&&r.current!=n.__e||md(r,null,e)),(r=n.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(A){ee.__e(A,e)}r.base=r.__P=null}if(r=n.__k)for(i=0;i<r.length;i++)r[i]&&iy(r[i],e,t||typeof n.type!="function");t||hd(n.__e),n.__c=n.__=n.__e=void 0}function gQ(n,e,t){return this.constructor(n,t)}function mQ(n,e,t){var r,i,A,s;e==document&&(e=document.documentElement),ee.__&&ee.__(n,e),i=(r=typeof t=="function")?null:t&&t.__k||e.__k,A=[],s=[],gd(e,n=(!r&&t||e).__k=pd(St,null,[n]),i||WA,WA,e.namespaceURI,!r&&t?[t]:i?null:e.firstChild?ga.call(e.childNodes):null,A,!r&&t?t:i?i.__e:e.firstChild,r,s),ny(A,n,s)}function Ay(n){function e(t){var r,i;return this.getChildContext||(r=new Set,(i={})[e.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(A){this.props.value!=A.value&&r.forEach(function(s){s.__e=!0,fd(s)})},this.sub=function(A){r.add(A);var s=A.componentWillUnmount;A.componentWillUnmount=function(){r&&r.delete(A),s&&s.call(A)}}),t.children}return e.__c="__cC"+z0++,e.__=n,e.Provider=e.__l=(e.Consumer=function(t,r){return t.children(r)}).contextType=e,e}ga=X0.slice,ee={__e:function(n,e,t,r){for(var i,A,s;e=e.__;)if((i=e.__c)&&!i.__)try{if((A=i.constructor)&&A.getDerivedStateFromError!=null&&(i.setState(A.getDerivedStateFromError(n)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(n,r||{}),s=i.__d),s)return i.__E=i}catch(o){n=o}throw n}},G0=0,Vn.prototype.setState=function(n,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Kn({},this.state),typeof n=="function"&&(n=n(Kn({},t),this.props)),n&&Kn(t,n),n!=null&&this.__v&&(e&&this._sb.push(e),fd(this))},Vn.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),fd(this))},Vn.prototype.render=St,zr=[],W0=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,q0=function(n,e){return n.__v.__b-e.__v.__b},va.__r=0,J0=/(PointerCapture)$|Capture$/i,ud=0,ld=ty(!1),dd=ty(!0),z0=0;var vQ=0;function C(n,e,t,r,i,A){e||(e={});var s,o,a=e;if("ref"in a)for(o in a={},e)o=="ref"?s=e[o]:a[o]=e[o];var c={type:n,props:a,key:t,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--vQ,__i:-1,__u:0,__source:i,__self:A};if(typeof n=="function"&&(s=n.defaultProps))for(o in s)a[o]===void 0&&(a[o]=s[o]);return ee.vnode&&ee.vnode(c),c}var Xr,Ve,vd,sy,JA=0,oy=[],it=ee,ay=it.__b,cy=it.__r,uy=it.diffed,ly=it.__c,dy=it.unmount,hy=it.__;function zA(n,e){it.__h&&it.__h(Ve,n,JA||e),JA=0;var t=Ve.__H||(Ve.__H={__:[],__h:[]});return n>=t.__.length&&t.__.push({}),t.__[n]}function ge(n){return JA=1,yQ(gy,n)}function yQ(n,e,t){var r=zA(Xr++,2);if(r.t=n,!r.__c&&(r.__=[t?t(e):gy(void 0,e),function(o){var a=r.__N?r.__N[0]:r.__[0],c=r.t(a,o);a!==c&&(r.__N=[c,r.__[1]],r.__c.setState({}))}],r.__c=Ve,!Ve.__f)){var i=function(o,a,c){if(!r.__c.__H)return!0;var u=r.__c.__H.__.filter(function(d){return!!d.__c});if(u.every(function(d){return!d.__N}))return!A||A.call(this,o,a,c);var l=r.__c.props!==o;return u.forEach(function(d){if(d.__N){var h=d.__[0];d.__=d.__N,d.__N=void 0,h!==d.__[0]&&(l=!0)}}),A&&A.call(this,o,a,c)||l};Ve.__f=!0;var A=Ve.shouldComponentUpdate,s=Ve.componentWillUpdate;Ve.componentWillUpdate=function(o,a,c){if(this.__e){var u=A;A=void 0,i(o,a,c),A=u}s&&s.call(this,o,a,c)},Ve.shouldComponentUpdate=i}return r.__N||r.__}function Kt(n,e){var t=zA(Xr++,3);!it.__s&&Bd(t.__H,e)&&(t.__=n,t.u=e,Ve.__H.__h.push(t))}function yd(n,e){var t=zA(Xr++,4);!it.__s&&Bd(t.__H,e)&&(t.__=n,t.u=e,Ve.__h.push(t))}function En(n){return JA=5,wd(function(){return{current:n}},[])}function wd(n,e){var t=zA(Xr++,7);return Bd(t.__H,e)&&(t.__=n(),t.__H=e,t.__h=n),t.__}function wQ(n,e){return JA=8,wd(function(){return n},e)}function py(n){var e=Ve.context[n.__c],t=zA(Xr++,9);return t.c=n,e?(t.__==null&&(t.__=!0,e.sub(Ve)),e.props.value):n.__}function bQ(){for(var n;n=oy.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(ba),n.__H.__h.forEach(bd),n.__H.__h=[]}catch(e){n.__H.__h=[],it.__e(e,n.__v)}}it.__b=function(n){Ve=null,ay&&ay(n)},it.__=function(n,e){n&&e.__k&&e.__k.__m&&(n.__m=e.__k.__m),hy&&hy(n,e)},it.__r=function(n){cy&&cy(n),Xr=0;var e=(Ve=n.__c).__H;e&&(vd===Ve?(e.__h=[],Ve.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.forEach(ba),e.__h.forEach(bd),e.__h=[],Xr=0)),vd=Ve},it.diffed=function(n){uy&&uy(n);var e=n.__c;e&&e.__H&&(e.__H.__h.length&&(oy.push(e)!==1&&sy===it.requestAnimationFrame||((sy=it.requestAnimationFrame)||BQ)(bQ)),e.__H.__.forEach(function(t){t.u&&(t.__H=t.u),t.u=void 0})),vd=Ve=null},it.__c=function(n,e){e.some(function(t){try{t.__h.forEach(ba),t.__h=t.__h.filter(function(r){return!r.__||bd(r)})}catch(r){e.some(function(i){i.__h&&(i.__h=[])}),e=[],it.__e(r,t.__v)}}),ly&&ly(n,e)},it.unmount=function(n){dy&&dy(n);var e,t=n.__c;t&&t.__H&&(t.__H.__.forEach(function(r){try{ba(r)}catch(i){e=i}}),t.__H=void 0,e&&it.__e(e,t.__v))};var fy=typeof requestAnimationFrame=="function";function BQ(n){var e,t=function(){clearTimeout(r),fy&&cancelAnimationFrame(e),setTimeout(n)},r=setTimeout(t,100);fy&&(e=requestAnimationFrame(t))}function ba(n){var e=Ve,t=n.__c;typeof t=="function"&&(n.__c=void 0,t()),Ve=e}function bd(n){var e=Ve;n.__c=n.__(),Ve=e}function Bd(n,e){return!n||n.length!==e.length||e.some(function(t,r){return t!==n[r]})}function gy(n,e){return typeof e=="function"?e(n):e}function CQ({size:n=24,color:e="#000"}){return C("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:e,"stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"lucide lucide-x-icon lucide-x",children:[C("path",{d:"M18 6 6 18"}),C("path",{d:"m6 6 12 12"})]})}function my({onClose:n}){return C("button",{class:"obi-button obi-close-button",onClick:n,"aria-label":"Close",type:"button",children:C(CQ,{})})}function vy({open:n=!1,children:e,onClose:t,size:r="medium"}){const i=En(null),A=En(null);Kt(()=>{const c=i.current;c&&(n&&!c.open?c.showModal():!n&&c.open&&(A.current="programmatic",c.close()))},[n]);const s=c=>{const u=i.current;c.target===u&&(A.current="user-initiated",u==null||u.close())},o=c=>{c.preventDefault(),A.current||(A.current="user-initiated");const u=A.current;A.current=null,t==null||t(u)},a=()=>{var c;A.current="user-initiated",(c=i.current)==null||c.close()};return Kt(()=>{const c=i.current;if(c)return c.addEventListener("click",s),c.addEventListener("close",o),()=>{c.removeEventListener("click",s),c.removeEventListener("close",o)}},[t]),C("dialog",{ref:i,className:`modal-${r}`,children:[C(my,{onClose:a}),C("div",{class:"modal-content",children:n?typeof e=="function"?e():e:null})]})}function Cd(n){const{children:e,className:t="",...r}=n;return C("div",{className:`${t} obi-panel`,...r,children:e})}function _d({className:n="",isActive:e=!1,speakingStatus:t,onClick:r,onMouseEnter:i,onMouseLeave:A,children:s}){let o=`obi-pill container ${e&&"active"}`;return t==="user-speaking"&&(o+=" user-speaking"),t==="busy"&&(o+=" busy"),C("div",{className:o,onMouseEnter:i,onMouseLeave:A,children:C("div",{className:`obi-pill pill ${n}`,onClick:r,children:s})})}function yy({className:n="",active:e,speakingStatus:t,onClick:r,onMouseEnter:i,onMouseLeave:A,children:s,...o}){const a=`obi-pill2 container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return C("div",{className:a,...o,children:C("div",{className:"pill",onClick:r,onMouseEnter:i,onMouseLeave:A,children:s})})}function Yr({type:n,size:e=24}){return C("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:_Q(n)})}function _Q(n){switch(n){case"pause":return C(St,{children:[C("rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}),C("rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"})]});case"play":return C(St,{children:C("path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"})});case"close":return C(St,{children:[C("path",{d:"M18 6 6 18"}),C("path",{d:"m6 6 12 12"})]});case"message":return C(St,{children:C("path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"})});case"minimize":return C(St,{children:[C("path",{d:"m14 10 7-7"}),C("path",{d:"M20 10h-6V4"}),C("path",{d:"m3 21 7-7"}),C("path",{d:"M4 14h6v6"})]});case"voice":return C(St,{children:[C("path",{d:"M2 10v3"}),C("path",{d:"M6 6v11"}),C("path",{d:"M10 3v18"}),C("path",{d:"M14 8v7"}),C("path",{d:"M18 5v13"}),C("path",{d:"M22 10v3"})]});case"open":return C(St,{children:[C("path",{d:"M12 7v14"}),C("path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"})]})}}const Sd=Ay(null);function SQ({children:n}){const e=py(Sd);if(!e)throw new Error("PopoutTarget must be used within a Popout component");const{controlledOpen:t,isOpen:r,setIsOpen:i,setAnimating:A,targetRef:s,trigger:o,onChange:a,delayMs:c}=e,u=En(null),l=wy(s,A),[d,h]=ge(!1);Kt(()=>{t!==void 0&&t!==d&&(t?p():g()),h(t)},[t]),Kt(()=>()=>{u.current&&clearTimeout(u.current)},[]);function f(){u.current&&(clearTimeout(u.current),u.current=null)}function p(){f(),c>0?u.current=setTimeout(()=>{a==null||a(!0),i(!0),u.current=null},c):(a==null||a(!0),i(!0))}function g(){f(),a==null||a(!1),i(!1)}const v=()=>{o==="click"&&(r?g():p())};function y(){o==="hover"&&p()}function B(){o==="hover"&&g()}return C("div",{ref:l,class:"target",onClick:v,onMouseEnter:y,onMouseLeave:B,children:n})}function kQ({children:n}){const e=py(Sd);if(!e)throw new Error("PopoutContent must be used within a Popout component");const{isOpen:t,animating:r,setAnimating:i,targetRef:A,contentRef:s}=e,o=wy(s,i);return yd(()=>{if(t&&!r&&A.current&&s.current){const a=s.current;if(!a)return;const c=A.current;if(!c)return;const u=a.getBoundingClientRect(),l=c.getBoundingClientRect(),d=l.right-l.left;a.style.top=`${u.top-u.bottom-(8+e.offset)}px`,a.style.left=`${-(u.right-u.left-d)/2}px`}},[t,r]),t?C("div",{ref:o,class:"content",style:{opacity:r?0:1},children:n}):null}function Vt({trigger:n="click",open:e,onChange:t,children:r,delayMs:i=0,offset:A=0,className:s=""}){const[o,a]=ge(!1),[c,u]=ge(!1),l=En(null),d=En(null),h={controlledOpen:e,isOpen:o,setIsOpen:a,animating:c,setAnimating:u,targetRef:l,contentRef:d,trigger:n,onChange:t,delayMs:i,offset:A};return C(Sd.Provider,{value:h,children:C("div",{class:`obi-popout ${s}`,children:r})})}Vt.Target=SQ,Vt.Content=kQ;function wy(n,e){const t=En(null),r=En(null),i=En(!0),A=wQ(s=>{if(n.current=s,!s){r.current&&(r.current.disconnect(),r.current=null),i.current=!0;return}function o(){if(i.current){i.current=!1;return}t.current?clearTimeout(t.current):e(!0),t.current=setTimeout(()=>{e(!1),t.current=null},200)}r.current=new ResizeObserver(o),r.current.observe(s,{box:"border-box"})},[]);return Kt(()=>()=>{r.current&&(r.current.disconnect(),r.current=null)},[]),A}function pn({className:n,onClick:e,type:t,disabled:r,title:i}){const A={cancel:C(Yr,{type:"close",size:16}),pause:C(Yr,{type:"pause",size:16}),play:C(Yr,{type:"play",size:16}),message:C(Yr,{type:"message",size:16}),minimize:C(Yr,{type:"minimize",size:16}),voice:C(Yr,{type:"voice",size:16}),open:C(Yr,{type:"open",size:16})}[t],s={cancel:"",pause:"",play:"",message:"",minimize:"",voice:"",open:""}[t],o=C("button",{class:`obi-button obi-round-button ${s} ${n}`,onClick:r?void 0:e,disabled:r,children:A});return i?C(Vt,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[C(Vt.Target,{children:o}),C(Vt.Content,{children:C("div",{className:"obi-round-button-title",children:i})})]}):o}const by=8,Ba=8,EQ=50,UQ=.7,Ni=3;function By({getBands:n,color:e="white"}){const t=En(null);return Kt(()=>{if(!n)return;const r=setInterval(()=>{try{const i=n();if(!t.current)return;const A=t.current.querySelectorAll(".bar"),s=i&&i.length>0?i.slice(0,Ba).map(o=>{const a=Math.abs(o);return Math.min(a/UQ*by,by)||Ni}):Array(Ba).fill(Ni);for(;s.length<Ba;)s.push(Ni);s.forEach((o,a)=>{if(o<Ni&&(o=Ni),A[a]){const c=o*2;A[a].style.height=`${c}px`,A[a].style.display=o>0?"block":"none"}})}catch(i){console.warn("Error updating equaliser:",i)}},EQ);return()=>{clearInterval(r)}},[n]),C("div",{className:"obi-equaliser",ref:t,children:Array.from({length:Ba},(r,i)=>C("div",{className:"column",children:C("div",{className:"bar",style:{height:`${Ni}px`,backgroundColor:e,display:"block"}})},i))})}function XA({className:n,children:e,onClick:t}){return t?C("button",{class:`obi-button obi-message ${n} clickable`,onClick:t,children:e}):C("div",{class:`obi-message ${n}`,children:e})}const TQ=8;function Cy({color:n="white"}){return C("div",{className:"obi-loading-dots",children:Array.from({length:TQ},(e,t)=>C("div",{className:"column",children:[C("div",{className:"bar",style:{backgroundColor:n,animationDelay:`${t*.15}s`}}),C("div",{className:"dot",style:{backgroundColor:n}})]},t))})}function IQ({onContinue:n,onWrapUp:e}){return C(Cd,{className:"obi-exit-survey",children:C(xQ,{onContinue:n,onWrapUp:()=>{e()}})})}function FQ({onOtherSelect:n,onReasonSelect:e,onClose:t}){const[r,i]=ge("reason"),A=s=>{s==="other"?(n(),i("other-reason")):e(s)};return C(Cd,{className:`obi-exit-survey ${r==="reason"?"obi-exit-survey-reason":""}`,children:r==="reason"?C(QQ,{onReasonSelect:A}):C(RQ,{onReasonSelect:A,onClose:t})})}function xQ({onContinue:n,onWrapUp:e}){return C("div",{className:"obi-exit-survey-container",children:[C("h2",{className:"obi-exit-survey-title",children:"Wrapping up early?"}),C("div",{className:"obi-exit-survey-options",children:[C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-continue",onClick:n,type:"button",children:"No, let's continue"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:e,type:"button",children:"Yes, let's wrap up"})]})]})}function QQ({onReasonSelect:n}){return C("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[C("div",{className:"obi-exit-survey-header",children:C("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Quick feedback?"})}),C("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("do-later"),type:"button",children:"Will do later"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("cant-talk"),type:"button",children:"Can't talk right now"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("prefer-written"),type:"button",children:"Prefer written instructions"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("technical-issues"),type:"button",children:"Experienced technical issues"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("other"),type:"button",children:"Other"})]})]})}function RQ({onReasonSelect:n,onClose:e}){const[t,r]=ge("");return C("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[C("div",{className:"obi-exit-survey-header",children:[C(my,{onClose:e}),C("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Tell us more"})]}),C("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[C("textarea",{className:"obi-exit-survey-button obi-exit-survey-reason-button",placeholder:"What's on your mind?",value:t,onChange:i=>r(i.target.value)}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:()=>n("other-feedback",t),type:"button",children:"Send feedback"})]})]})}function PQ(n,e){for(var t in e)n[t]=e[t];return n}function _y(n,e){for(var t in n)if(t!=="__source"&&!(t in e))return!0;for(var r in e)if(r!=="__source"&&n[r]!==e[r])return!0;return!1}function Sy(n,e){this.props=n,this.context=e}(Sy.prototype=new Vn).isPureReactComponent=!0,Sy.prototype.shouldComponentUpdate=function(n,e){return _y(this.props,n)||_y(this.state,e)};var ky=ee.__b;ee.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),ky&&ky(n)};var OQ=ee.__e;ee.__e=function(n,e,t,r){if(n.then){for(var i,A=e;A=A.__;)if((i=A.__c)&&i.__c)return e.__e==null&&(e.__e=t.__e,e.__k=t.__k),i.__c(n,e)}OQ(n,e,t,r)};var Ey=ee.unmount;function Uy(n,e,t){return n&&(n.__c&&n.__c.__H&&(n.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),n.__c.__H=null),(n=PQ({},n)).__c!=null&&(n.__c.__P===t&&(n.__c.__P=e),n.__c.__e=!0,n.__c=null),n.__k=n.__k&&n.__k.map(function(r){return Uy(r,e,t)})),n}function Ty(n,e,t){return n&&t&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(r){return Ty(r,e,t)}),n.__c&&n.__c.__P===e&&(n.__e&&t.appendChild(n.__e),n.__c.__e=!0,n.__c.__P=t)),n}function kd(){this.__u=0,this.o=null,this.__b=null}function Iy(n){var e=n.__.__c;return e&&e.__a&&e.__a(n)}function Ca(){this.i=null,this.l=null}ee.unmount=function(n){var e=n.__c;e&&e.__R&&e.__R(),e&&32&n.__u&&(n.type=null),Ey&&Ey(n)},(kd.prototype=new Vn).__c=function(n,e){var t=e.__c,r=this;r.o==null&&(r.o=[]),r.o.push(t);var i=Iy(r.__v),A=!1,s=function(){A||(A=!0,t.__R=null,i?i(o):o())};t.__R=s;var o=function(){if(!--r.__u){if(r.state.__a){var a=r.state.__a;r.__v.__k[0]=Ty(a,a.__c.__P,a.__c.__O)}var c;for(r.setState({__a:r.__b=null});c=r.o.pop();)c.forceUpdate()}};r.__u++||32&e.__u||r.setState({__a:r.__b=r.__v.__k[0]}),n.then(s,s)},kd.prototype.componentWillUnmount=function(){this.o=[]},kd.prototype.render=function(n,e){if(this.__b){if(this.__v.__k){var t=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=Uy(this.__b,t,r.__O=r.__P)}this.__b=null}var i=e.__a&&pd(St,null,n.fallback);return i&&(i.__u&=-33),[pd(St,null,e.__a?null:n.children),i]};var Fy=function(n,e,t){if(++t[1]===t[0]&&n.l.delete(e),n.props.revealOrder&&(n.props.revealOrder[0]!=="t"||!n.l.size))for(t=n.i;t;){for(;t.length>3;)t.pop()();if(t[1]<t[0])break;n.i=t=t[2]}};(Ca.prototype=new Vn).__a=function(n){var e=this,t=Iy(e.__v),r=e.l.get(n);return r[0]++,function(i){var A=function(){e.props.revealOrder?(r.push(i),Fy(e,n,r)):i()};t?t(A):A()}},Ca.prototype.render=function(n){this.i=null,this.l=new Map;var e=ya(n.children);n.revealOrder&&n.revealOrder[0]==="b"&&e.reverse();for(var t=e.length;t--;)this.l.set(e[t],this.i=[1,0,this.i]);return n.children},Ca.prototype.componentDidUpdate=Ca.prototype.componentDidMount=function(){var n=this;this.l.forEach(function(e,t){Fy(n,t,e)})};var MQ=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,LQ=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,DQ=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,NQ=/[A-Z0-9]/g,HQ=typeof document<"u",KQ=function(n){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(n)};Vn.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(n){Object.defineProperty(Vn.prototype,n,{configurable:!0,get:function(){return this["UNSAFE_"+n]},set:function(e){Object.defineProperty(this,n,{configurable:!0,writable:!0,value:e})}})});var xy=ee.event;function VQ(){}function GQ(){return this.cancelBubble}function jQ(){return this.defaultPrevented}ee.event=function(n){return xy&&(n=xy(n)),n.persist=VQ,n.isPropagationStopped=GQ,n.isDefaultPrevented=jQ,n.nativeEvent=n};var WQ={enumerable:!1,configurable:!0,get:function(){return this.class}},Qy=ee.vnode;ee.vnode=function(n){typeof n.type=="string"&&function(e){var t=e.props,r=e.type,i={},A=r.indexOf("-")===-1;for(var s in t){var o=t[s];if(!(s==="value"&&"defaultValue"in t&&o==null||HQ&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var a=s.toLowerCase();s==="defaultValue"&&"value"in t&&t.value==null?s="value":s==="download"&&o===!0?o="":a==="translate"&&o==="no"?o=!1:a[0]==="o"&&a[1]==="n"?a==="ondoubleclick"?s="ondblclick":a!=="onchange"||r!=="input"&&r!=="textarea"||KQ(t.type)?a==="onfocus"?s="onfocusin":a==="onblur"?s="onfocusout":DQ.test(s)&&(s=a):a=s="oninput":A&&LQ.test(s)?s=s.replace(NQ,"-$&").toLowerCase():o===null&&(o=void 0),a==="oninput"&&i[s=a]&&(s="oninputCapture"),i[s]=o}}r=="select"&&i.multiple&&Array.isArray(i.value)&&(i.value=ya(t.children).forEach(function(c){c.props.selected=i.value.indexOf(c.props.value)!=-1})),r=="select"&&i.defaultValue!=null&&(i.value=ya(t.children).forEach(function(c){c.props.selected=i.multiple?i.defaultValue.indexOf(c.props.value)!=-1:i.defaultValue==c.props.value})),t.class&&!t.className?(i.class=t.class,Object.defineProperty(i,"className",WQ)):(t.className&&!t.class||t.class&&t.className)&&(i.class=i.className=t.className),e.props=i}(n),n.$$typeof=MQ,Qy&&Qy(n)};var Ry=ee.__r;ee.__r=function(n){Ry&&Ry(n),n.__c};var Py=ee.diffed;ee.diffed=function(n){Py&&Py(n);var e=n.props,t=n.__e;t!=null&&n.type==="textarea"&&"value"in e&&e.value!==t.value&&(t.value=e.value==null?"":e.value)};function qQ(n){const{placeholder:e="Type your message...",value:t,defaultValue:r,onChange:i,onSend:A,onCancel:s,onExpand:o,isLoading:a=!1,disabled:c=!1,maxLength:u=500,children:l}=n,[d,h]=ge(t||r||""),[f,p]=ge((t||r||"").length>24),g=En(null);yd(()=>{f&&(o==null||o(!0))},[]);const v=t!==void 0?t:d,y=w=>{const _=w.currentTarget.value;t===void 0&&h(_),i==null||i(_)},B=w=>{w.key==="Escape"&&(h(t||r||""),p(!1),s==null||s()),w.key==="Enter"&&!w.shiftKey&&v.trim()&&(w.preventDefault(),h(t||r||""),p(!1),b()),(v||"").length>=24&&!f&&(p(!0),o==null||o(!0))};Kt(()=>{g.current&&g.current.focus()},[g.current]);const b=()=>{!v.trim()||a||c||(A==null||A(v.trim()),t===void 0&&h(""))};return C("div",{className:`obi-message-input ${f?"expanded":""}`,children:[C("div",{className:"container",children:C("textarea",{ref:g,className:"field",placeholder:e,value:v,onInput:y,onKeyDown:B,disabled:c||a,maxLength:u,rows:1})}),C("div",{className:"button-container",children:[f&&C("div",{children:l}),C("button",{className:"obi-button send",onClick:b,disabled:!v.trim()||a||c,type:"button",children:C("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:C("path",{d:"M6.00016 10.6673V1.33398M6.00016 1.33398L1.3335 6.00065M6.00016 1.33398L10.6668 6.00065",stroke:"#F3F3F3","stroke-width":"1.6","stroke-linecap":"round","stroke-linejoin":"round"})})})]})]})}function JQ(n){const{currentStep:e,totalSteps:t,stepNames:r,className:i}=n,A=Array.from({length:t},(a,c)=>({isCompleted:c<e,stepNumber:c+1})),s=r[e-1]||`Step ${e}`,o=`${e}/${t} \u2022 ${s}`;return C("div",{class:`obi-course-progress ${i||""}`,children:[C("div",{class:"obi-course-progress-steps",children:A.map((a,c)=>C("div",{class:"obi-course-progress-container",children:C("div",{class:`obi-course-progress-step ${a.isCompleted?"completed":""}`})},c))}),C("div",{class:"obi-course-progress-description",children:o})]})}function Ed({className:n="",size:e=64}){return C("svg",{width:e,height:e,viewBox:"0 0 256 256",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:n,children:C("path",{d:"M158.803 0L160.352 0.0399439C176.267 0.844061 188.922 13.9634 188.922 30.0311C188.922 46.6174 175.438 60.0653 158.803 60.0656H99.0263L98.9061 60.0722C78.8071 61.4795 62.6269 77.004 60.2644 96.7673L60.241 96.9704V158.93L60.2644 159.13C62.7406 179.86 80.4234 195.934 101.881 195.935H153.842C176.993 195.935 195.759 177.223 195.759 154.14V96.9138L195.799 95.3693C196.606 79.5009 209.766 66.8827 225.881 66.8827C242.515 66.8834 256 80.328 256 96.9138V159.086L255.963 160.564C255.225 175.748 243.176 187.971 228.038 189.038V189.214C207.121 190.591 190.4 207.263 189.019 228.119H188.842C187.738 243.7 174.712 256 158.803 256H96.4491C79.8147 256 66.3309 242.555 66.3302 225.969C66.3302 225.673 66.3349 225.375 66.3436 225.077H66.3503H66.3035C63.3344 206.008 47.4427 190.589 27.8321 189.231L27.8354 189.031C12.2702 187.868 0.000167669 174.905 0 159.086V96.9138L0.0367222 95.4192C0.791087 80.0787 13.0909 67.7634 28.453 66.9293C47.7697 65.3039 63.3522 50.3234 66.2969 31.4658L66.3469 31.1595L66.3369 30.85C66.3301 30.5933 66.3302 30.3238 66.3302 30.0311C66.3309 13.4454 79.8148 0.000165137 96.4491 0H158.803Z",fill:"currentColor"})})}function zQ({children:n}){const e={container:{position:"relative",width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},logo:{display:"flex",width:"120px",height:"120px",justifyContent:"center",alignItems:"center",aspectRatio:"1/1",borderRadius:"8px",color:"#FFFFFF",position:"relative",overflow:"hidden",background:"var(--obi-color-primary)",boxShadow:`
|
|
42
|
+
`},zl}var p0;function lx(){if(p0)return ln;p0=1;var n=cx(),e=ux(),t=Jl();return ln.grammar=t,ln.write=e,ln.parse=n.parse,ln.parseParams=n.parseParams,ln.parseFmtpConfig=n.parseFmtpConfig,ln.parsePayloads=n.parsePayloads,ln.parseRemoteCandidates=n.parseRemoteCandidates,ln.parseImageAttributes=n.parseImageAttributes,ln.parseSimulcastStreamList=n.parseSimulcastStreamList,ln}var mr=lx();function Xl(n,e,t){var r,i,A;e===void 0&&(e=50),t===void 0&&(t={});var s=(r=t.isImmediate)!=null&&r,o=(i=t.callback)!=null&&i,a=t.maxWait,c=Date.now(),u=[];function l(){if(a!==void 0){var h=Date.now()-c;if(h+e>=a)return a-h}return e}var d=function(){var h=[].slice.call(arguments),f=this;return new Promise(function(p,g){var v=s&&A===void 0;if(A!==void 0&&clearTimeout(A),A=setTimeout(function(){if(A=void 0,c=Date.now(),!s){var B=n.apply(f,h);o&&o(B),u.forEach(function(b){return(0,b.resolve)(B)}),u=[]}},l()),v){var y=n.apply(f,h);return o&&o(y),p(y)}u.push({resolve:p,reject:g})})};return d.cancel=function(h){A!==void 0&&clearTimeout(A),u.forEach(function(f){return(0,f.reject)(h)}),u=[]},d}const dx=.7,hx=20,Oi={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class f0 extends Sn.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 r;super(),this.log=ue,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Xl(i=>S(this,void 0,void 0,function*(){this.emit(Oi.NegotiationStarted);try{yield this.createAndSendOffer()}catch(A){if(i)i(A);else throw A}}),hx),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=Ln((r=t.loggerName)!==null&&r!==void 0?r:cn.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var r;t.candidate&&((r=this.onIceCandidate)===null||r===void 0||r.call(this,t.candidate))},e.onicecandidateerror=t=>{var r;(r=this.onIceCandidateError)===null||r===void 0||r.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 r;(r=this.onDataChannel)===null||r===void 0||r.call(this,t)},e.ontrack=t=>{var r;(r=this.onTrack)===null||r===void 0||r.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 S(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return S(this,void 0,void 0,function*(){var t;let r;if(e.type==="offer"){let{stereoMids:i,nackMids:A}=px(e);this.remoteStereoMids=i,this.remoteNackMids=A}else if(e.type==="answer"){const i=mr.parse((t=e.sdp)!==null&&t!==void 0?t:"");i.media.forEach(A=>{A.type==="audio"&&this.trackBitrates.some(s=>{if(!s.transceiver||A.mid!=s.transceiver.mid)return!1;let o=0;if(A.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 A.fmtp)if(c.payload===o){c.config=c.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),s.maxbr>0&&(c.config+=";maxaveragebitrate=".concat(s.maxbr*1e3)),a=!0;break}return a||s.maxbr>0&&A.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(s.maxbr*1e3)}),!0})}),r=mr.write(i)}yield this.setMungedSDP(e,r,!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(Oi.NegotiationComplete),e.sdp&&mr.parse(e.sdp).media.forEach(A=>{A.type==="video"&&this.emit(Oi.RTPVideoPayloadTypes,A.rtp)}))})}createAndSendOffer(e){return S(this,void 0,void 0,function*(){var t;if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const A=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&A)yield this._pc.setRemoteDescription(A);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 r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const i=mr.parse((t=r.sdp)!==null&&t!==void 0?t:"");i.media.forEach(A=>{m0(A),A.type==="audio"?g0(A,[],[]):A.type==="video"&&this.trackBitrates.some(s=>{if(!A.msid||!s.cid||!A.msid.includes(s.cid))return!1;let o=0;if(A.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0||(KA(s.codec)&&this.ensureVideoDDExtensionForSVC(A,i),s.codec!=="av1"))return!0;const a=Math.round(s.maxbr*dx);for(const c of A.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(r,mr.write(i)),this.onOffer(r)})}createAndSetAnswer(){return S(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),r=mr.parse((e=t.sdp)!==null&&e!==void 0?e:"");return r.media.forEach(i=>{m0(i),i.type==="audio"&&g0(i,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,mr.write(r)),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 lt("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 lt("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 S(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const r=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),r.set(o.id,o);break;case"remote-candidate":i.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const s=(e=r.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(s!==void 0)return i.get(s)})}setMungedSDP(e,t,r){return S(this,void 0,void 0,function*(){if(t){const i=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(r?"remote":"local"," description"),this.logContext),r?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(A){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:A,sdp:t})),e.sdp=i}}try{r?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(i){let A="unknown error";i instanceof Error?A=i.message:typeof i=="string"&&(A=i);const s={error:A,sdp:e.sdp};throw!r&&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 _l(A)}})}ensureVideoDDExtensionForSVC(e,t){var r,i;if(!((r=e.ext)===null||r===void 0?void 0:r.some(s=>s.uri===zv))){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:zv})}}}function g0(n,e,t){let r=0;n.rtp.some(i=>i.codec==="opus"?(r=i.payload,!0):!1),r>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(n.mid)&&!n.rtcpFb.some(i=>i.payload===r&&i.type==="nack")&&n.rtcpFb.push({payload:r,type:"nack"}),e.includes(n.mid)&&n.fmtp.some(i=>i.payload===r?(i.config.includes("stereo=1")||(i.config+=";stereo=1"),!0):!1))}function px(n){var e;const t=[],r=[],i=mr.parse((e=n.sdp)!==null&&e!==void 0?e:"");let A=0;return i.media.forEach(s=>{var o;s.type==="audio"&&(s.rtp.some(a=>a.codec==="opus"?(A=a.payload,!0):!1),!((o=s.rtcpFb)===null||o===void 0)&&o.some(a=>a.payload===A&&a.type==="nack")&&r.push(s.mid),s.fmtp.some(a=>a.payload===A?(a.config.includes("sprop-stereo=1")&&t.push(s.mid),!0):!1))}),{stereoMids:t,nackMids:r}}function m0(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}const Yl="vp8",fx={audioPreset:Ul.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Il.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Yl,backupCodec:!0},v0={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},y0={deviceId:{ideal:"default"},resolution:HA.h720.resolution},gx={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new sF,disconnectOnPageLeave:!0,webAudioMix:!1},Zl={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Ye;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(Ye||(Ye={}));class mx{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,r){var i;this.peerConnectionTimeout=Zl.peerConnectionTimeout,this.log=ue,this.updateState=()=>{var A;const s=this.state,o=this.requiredTransports.map(a=>a.getConnectionState());o.every(a=>a==="connected")?this.state=Ye.CONNECTED:o.some(a=>a==="failed")?this.state=Ye.FAILED:o.some(a=>a==="connecting")?this.state=Ye.CONNECTING:o.every(a=>a==="closed")?this.state=Ye.CLOSED:o.some(a=>a==="closed")?this.state=Ye.CLOSING:o.every(a=>a==="new")&&(this.state=Ye.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(Ye[s]," to ").concat(Ye[this.state]),this.logContext),(A=this.onStateChange)===null||A===void 0||A.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Ln((i=r.loggerName)!==null&&i!==void 0?i:cn.PCManager),this.loggerOptions=r,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new f0(e,r),this.subscriber=new f0(e,r),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=A=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,A,an.PUBLISHER)},this.subscriber.onIceCandidate=A=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,A,an.SUBSCRIBER)},this.subscriber.onDataChannel=A=>{var s;(s=this.onDataChannel)===null||s===void 0||s.call(this,A)},this.subscriber.onTrack=A=>{var s;(s=this.onTrack)===null||s===void 0||s.call(this,A)},this.publisher.onOffer=A=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,A)},this.state=Ye.NEW,this.connectionLock=new Mt,this.remoteOfferLock=new Mt}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 S(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(r){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:r}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return S(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return S(this,void 0,void 0,function*(){t===an.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return S(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 S(this,void 0,void 0,function*(){var r;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((r=this.requiredTransports)===null||r===void 0?void 0:r.map(A=>this.ensureTransportConnected(A,e,t)))}finally{i()}})}negotiate(e){return S(this,void 0,void 0,function*(){return new Promise((t,r)=>S(this,void 0,void 0,function*(){const i=setTimeout(()=>{r("negotiation timed out")},this.peerConnectionTimeout),A=()=>{clearTimeout(i),r("negotiation aborted")};e.signal.addEventListener("abort",A),this.publisher.once(Oi.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Oi.NegotiationComplete,()=>{clearTimeout(i),t()})}),yield this.publisher.negotiate(s=>{clearTimeout(i),r(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===an.PUBLISHER?this.publisher.getConnectedAddress():e===an.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 S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(r.getConnectionState()!=="connected")return new Promise((a,c)=>S(A,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),wt.clearTimeout(l),c(new Fe("room connection has been cancelled",de.Cancelled))};i!=null&&i.signal.aborted&&u(),i==null||i.signal.addEventListener("abort",u);const l=wt.setTimeout(()=>{i==null||i.signal.removeEventListener("abort",u),c(new Fe("could not establish pc connection",de.InternalError))},s);for(;this.state!==Ye.CONNECTED;)if(yield Nt(50),i!=null&&i.signal.aborted){c(new Fe("room connection has been cancelled",de.Cancelled));return}wt.clearTimeout(l),i==null||i.signal.removeEventListener("abort",u),a()}))}()})}}class Ze extends Error{constructor(e,t,r){super(t),this.code=e,this.message=b0(t,Ze.MAX_MESSAGE_BYTES),this.data=r?b0(r,Ze.MAX_DATA_BYTES):void 0}static fromProto(e){return new Ze(e.code,e.message,e.data)}toProto(){return new Om({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new Ze(Ze.ErrorCode[e],Ze.ErrorMessage[e],t)}}Ze.MAX_MESSAGE_BYTES=256,Ze.MAX_DATA_BYTES=15360,Ze.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},Ze.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 w0=15360;function $l(n){return new TextEncoder().encode(n).length}function b0(n,e){if($l(n)<=e)return n;let t=0,r=n.length;const i=new TextEncoder;for(;t<r;){const A=Math.floor((t+r+1)/2);i.encode(n.slice(0,A)).length<=e?t=A:r=A-1}return n.slice(0,t)}const ed=2e3;function oa(n,e){if(!e)return 0;let t,r;return"bytesReceived"in n?(t=n.bytesReceived,r=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,r=e.bytesSent),t===void 0||r===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-r)*8*1e3/(n.timestamp-e.timestamp)}const vx=1e3;class B0 extends R{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,r){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,A=arguments.length>4?arguments[4]:void 0;super(e,t,A),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=Xl(()=>S(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>S(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(L.Ended,this)},this.reacquireTrack=!1,this.providedByUser=i,this.muteLock=new Mt,this.pauseUpstreamLock=new Mt,this.processorLock=new Mt,this.restartLock=new Mt,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),r&&(this._constraints=r)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==R.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 S(this,void 0,void 0,function*(){var r;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(A=>{xi(this._mediaStreamTrack,A)}),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 A=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&&(Fi(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}finally{A()}}this.sender&&((r=this.sender.transport)===null||r===void 0?void 0:r.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(A=>{Fi(i??e,A)}))})}waitForDimensions(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:vx;return function*(){var r;if(e.kind===R.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((r=un())===null||r===void 0?void 0:r.os)==="iOS"&&(yield Nt(10));const i=Date.now();for(;Date.now()-i<t;){const A=e.dimensions;if(A)return A;yield Nt(50)}throw new Dn("unable to get track dimensions after timeout")}()})}setDeviceId(e){return S(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===fr(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),fr(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return S(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===R.Source.ScreenShare)return;const{deviceId:r,groupId:i}=e._mediaStreamTrack.getSettings(),A=e.kind===R.Kind.Audio?"audioinput":"videoinput";return t?ft.getInstance().normalizeDeviceId(A,r,i):r}()})}mute(){return S(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return S(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return S(this,void 0,void 0,function*(){if(!this.sender)throw new Dn("unable to replace an unpublished track");let r,i;return typeof t=="boolean"?r=t:t!==void 0&&(r=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return S(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:r,facingMode:i}=e,A=oF(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===R.Kind.Video?s.video=r||i?{deviceId:r,facingMode:i}:!0:s.audio=r?{deviceId:r}:!0,this.attachedElements.forEach(c=>{xi(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(A),a.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(a),this._constraints=e,this.emit(L.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?L.Muted:L.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 S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Xv()&&(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 S(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(L.UpstreamPaused,this);const r=un();if((r==null?void 0:r.name)==="Safari"&&Wr(r.version,"12.0")<0)throw new Cl("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 S(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(L.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 S(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 S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var A;const s=yield r.processorLock.lock();try{r.log.debug("setting up processor",r.logContext);const o=document.createElement(r.kind),a={kind:r.kind,track:r._mediaStreamTrack,element:o,audioContext:r.audioContext};if(yield t.init(a),r.log.debug("processor initialized",r.logContext),r.processor&&(yield r.stopProcessor()),r.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Fi(r._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>r.log.error("failed to play processor element",Object.assign(Object.assign({},r.logContext),{error:c}))),r.processor=t,r.processorElement=o,r.processor.processedTrack){for(const c of r.attachedElements)c!==r.processorElement&&i&&(xi(r._mediaStreamTrack,c),Fi(r.processor.processedTrack,c));yield(A=r.sender)===null||A===void 0?void 0:A.replaceTrack(r.processor.processedTrack)}r.emit(L.TrackProcessorUpdate,r.processor)}finally{s()}}()})}getProcessor(){return this.processor}stopProcessor(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var r,i;e.processor&&(e.log.debug("stopping processor",e.logContext),(r=e.processor.processedTrack)===null||r===void 0||r.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(L.TrackProcessorUpdate))}()})}}class aa extends B0{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0,A=arguments.length>4?arguments[4]:void 0;super(e,R.Kind.Audio,t,r,A),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>S(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=oa(s,this.prevStats)),this.prevStats=s}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(L.AudioTrackFeatureUpdate,this,on.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(L.AudioTrackFeatureUpdate,this,on.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return S(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===R.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 S(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 r=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==fr(this._constraints.deviceId);return this.source===R.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||r)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return S(this,void 0,void 0,function*(){let t;if(e){const r=Vl({audio:e});typeof r.audio!="boolean"&&(t=r.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return S(this,void 0,void 0,function*(){const r=yield t.restart.call(this,e);return this.checkForSilence(),r})}startMonitor(){Ht()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},ed)))}setProcessor(e){return S(this,void 0,void 0,function*(){var t;const r=yield this.processorLock.lock();try{if(!kn()&&!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(L.TrackProcessorUpdate,this.processor)}finally{r()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return S(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 r;return t.forEach(i=>{i.type==="outbound-rtp"&&(r={type:"audio",streamId:i.id,packetsSent:i.packetsSent,packetsLost:i.packetsLost,bytesSent:i.bytesSent,timestamp:i.timestamp,roundTripTime:i.roundTripTime,jitter:i.jitter})}),r})}checkForSilence(){return S(this,void 0,void 0,function*(){const e=yield A0(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(L.AudioSilenceDetected)),e})}}function yx(n,e,t){switch(n.kind){case"audio":return new aa(n,e,!1,void 0,t);case"video":return new ua(n,e,!1,t);default:throw new Dn("unsupported track type: ".concat(n.kind))}}const wx=Object.values(HA),bx=Object.values(Tl),Bx=Object.values(Il),Cx=[HA.h180,HA.h360],_x=[Tl.h180,Tl.h360],Sx=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var r,i;return new Te(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((r=n.encoding.maxFramerate)!==null&&r!==void 0?r:30)/((i=t.fps)!==null&&i!==void 0?i:30))))),t.fps,n.encoding.priority)}),td=["q","h","f"];function nd(n,e,t,r){var i,A;let s=r==null?void 0:r.videoEncoding;n&&(s=r==null?void 0:r.screenShareEncoding);const o=r==null?void 0:r.simulcast,a=r==null?void 0:r.scalabilityMode,c=r==null?void 0:r.videoCodec;if(!s&&!o&&!a||!e||!t)return[{}];s||(s=Ex(n,e,t,c),ue.debug("using video encoding",s));const u=s.maxFramerate,l=new Te(e,t,s.maxBitrate,s.maxFramerate,s.priority);if(a&&KA(c)){const f=new ca(a),p=[];if(f.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(a));const g=un();if(pr()||kn()||(g==null?void 0:g.name)==="Chrome"&&Wr(g==null?void 0:g.version,"113")<0){const v=f.suffix=="h"?2:3;for(let y=0;y<f.spatial;y+=1)p.push({rid:td[2-y],maxBitrate:s.maxBitrate/Math.pow(v,y),maxFramerate:l.encoding.maxFramerate});p[0].scalabilityMode=a}else p.push({maxBitrate:s.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:a});return l.encoding.priority&&(p[0].priority=l.encoding.priority,p[0].networkPriority=l.encoding.priority),ue.debug("using svc encoding",{encodings:p}),p}if(!o)return[s];let d=[];n?d=(i=_0(r==null?void 0:r.screenShareSimulcastLayers))!==null&&i!==void 0?i:C0(n,l):d=(A=_0(r==null?void 0:r.videoSimulcastLayers))!==null&&A!==void 0?A:C0(n,l);let h;if(d.length>0){const f=d[0];d.length>1&&([,h]=d);const p=Math.max(e,t);if(p>=960&&h)return rd(e,t,[f,h,l],u);if(p>=480)return rd(e,t,[f,l],u)}return rd(e,t,[l])}function kx(n,e,t){var r,i,A,s;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&ue.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),a=(r=o.width)!==null&&r!==void 0?r:(i=n.dimensions)===null||i===void 0?void 0:i.width,c=(A=o.height)!==null&&A!==void 0?A:(s=n.dimensions)===null||s===void 0?void 0:s.height;return n.source===R.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),nd(n.source===R.Source.ScreenShare,a,c,t)}function Ex(n,e,t,r){const i=Ux(n,e,t);let{encoding:A}=i[0];const s=Math.max(e,t);for(let o=0;o<i.length;o+=1){const a=i[o];if(A=a.encoding,a.width>=s)break}if(r)switch(r){case"av1":A=Object.assign({},A),A.maxBitrate=A.maxBitrate*.7;break;case"vp9":A=Object.assign({},A),A.maxBitrate=A.maxBitrate*.85;break}return A}function Ux(n,e,t){if(n)return Bx;const r=e>t?e/t:t/e;return Math.abs(r-16/9)<Math.abs(r-4/3)?wx:bx}function C0(n,e){if(n)return Sx(e);const{width:t,height:r}=e,i=t>r?t/r:r/t;return Math.abs(i-16/9)<Math.abs(i-4/3)?Cx:_x}function rd(n,e,t,r){const i=[];if(t.forEach((A,s)=>{if(s>=td.length)return;const o=Math.min(n,e),c={rid:td[s],scaleResolutionDownBy:Math.max(1,o/Math.min(A.width,A.height)),maxBitrate:A.encoding.maxBitrate},u=r&&A.encoding.maxFramerate?Math.min(r,A.encoding.maxFramerate):A.encoding.maxFramerate;u&&(c.maxFramerate=u);const l=Qi()||s===0;A.encoding.priority&&l&&(c.priority=A.encoding.priority,c.networkPriority=A.encoding.priority),i.push(c)}),kn()&&Zv()==="ios"){let A;i.forEach(o=>{A?o.maxFramerate&&o.maxFramerate>A&&(A=o.maxFramerate):A=o.maxFramerate});let s=!0;i.forEach(o=>{var a;o.maxFramerate!=A&&(s&&(s=!1,ue.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ue.info('Setting framerate of encoding "'.concat((a=o.rid)!==null&&a!==void 0?a:"",'" to ').concat(A)),o.maxFramerate=A)})}return i}function _0(n){if(n)return n.sort((e,t)=>{const{encoding:r}=e,{encoding:i}=t;return r.maxBitrate>i.maxBitrate?1:r.maxBitrate<i.maxBitrate?-1:r.maxBitrate===i.maxBitrate&&r.maxFramerate&&i.maxFramerate?r.maxFramerate>i.maxFramerate?1:-1:0})}class ca{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 Tx(n){return n.source===R.Source.ScreenShare||n.constraints.height&&fr(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const Ix=5e3;class ua extends B0{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0;super(e,R.Kind.Video,t,r,i),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>S(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let A;try{A=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}const s=new Map(A.map(o=>[o.rid,o]));if(this.prevStats){let o=0;s.forEach((a,c)=>{var u;const l=(u=this.prevStats)===null||u===void 0?void 0:u.get(c);o+=oa(a,l)}),this._currentBitrate=o}this.prevStats=s}),this.senderLock=new Mt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Ht())return;const r=(t=this.sender)===null||t===void 0?void 0:t.getParameters();r&&(this.encodings=r.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},ed))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return S(this,void 0,void 0,function*(){var t,r,i,A,s;yield e.pauseUpstream.call(this);try{for(var o=!0,a=ur(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0)A=c.value,o=!1,yield(s=A.sender)===null||s===void 0?void 0:s.replaceTrack(null)}catch(u){r={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(r)throw r.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return S(this,void 0,void 0,function*(){var t,r,i,A,s;yield e.resumeUpstream.call(this);try{for(var o=!0,a=ur(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0){A=c.value,o=!1;const u=A;yield(s=u.sender)===null||s===void 0?void 0:s.replaceTrack(u.mediaStreamTrack)}}catch(u){r={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(r)throw r.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return S(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===R.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 S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===R.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 S(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],r=yield this.sender.getStats();return r.forEach(i=>{var A;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:(A=i.rid)!==null&&A!==void 0?A:i.id,retransmittedPacketsSent:i.retransmittedPacketsSent,targetBitrate:i.targetBitrate,timestamp:i.timestamp},o=r.get(i.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}}),t.sort((i,A)=>{var s,o;return((s=A.frameWidth)!==null&&s!==void 0?s:0)-((o=i.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let r=Yt.LOW;r<=Yt.HIGH;r+=1)t.push(new ll({quality:r,enabled:r<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return S(this,void 0,void 0,function*(){var t,r,i,A,s;let o;if(e){const l=Vl({video:e});typeof l.video!="boolean"&&(o=l.video)}yield this.restart(o);try{for(var a=!0,c=ur(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;a=!0){A=u.value,a=!1;const l=A;l.sender&&((s=l.sender.transport)===null||s===void 0?void 0:s.state)!=="closed"&&(l.mediaStreamTrack=this.mediaStreamTrack.clone(),yield l.sender.replaceTrack(l.mediaStreamTrack))}}catch(l){r={error:l}}finally{try{!a&&!t&&(i=c.return)&&(yield i.call(c))}finally{if(r)throw r.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return S(this,arguments,void 0,function(r){var i=this;let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s,o,a,c,u,l;if(yield t.setProcessor.call(i,r,A),!((u=i.processor)===null||u===void 0)&&u.processedTrack)try{for(var d=!0,h=ur(i.simulcastCodecs.values()),f;f=yield h.next(),s=f.done,!s;d=!0)c=f.value,d=!1,yield(l=c.sender)===null||l===void 0?void 0:l.replaceTrack(i.processor.processedTrack)}catch(p){o={error:p}}finally{try{!d&&!s&&(a=h.return)&&(yield a.call(h))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return S(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 r={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,r),r}setSimulcastTrackSender(e,t){const r=this.simulcastCodecs.get(e);r&&(r.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Ix))}setPublishingCodecs(e){return S(this,void 0,void 0,function*(){var t,r,i,A,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,r=ur(e);i=yield r.next(),A=i.done,!A;t=!0){a=i.value,t=!1;const u=a;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(u.qualities);else{const l=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:l})),!l||!l.sender){for(const d of u.qualities)if(d.enabled){c.push(u.codec);break}}else l.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield S0(l.sender,l.encodings,u.qualities,this.senderLock,this.log,this.logContext))}}}catch(u){s={error:u}}finally{try{!t&&!A&&(o=r.return)&&(yield o.call(r))}finally{if(s)throw s.error}}return c})}setPublishingLayers(e){return S(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 S0(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Xv()&&this.isInBackground&&this.source===R.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function S0(n,e,t,r,i,A){return S(this,void 0,void 0,function*(){const s=yield r.lock();i.debug("setPublishingLayersForSender",Object.assign(Object.assign({},A),{sender:n,qualities:t,senderEncodings:e}));try{const o=n.getParameters(),{encodings:a}=o;if(!a)return;if(a.length!==e.length){i.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},A),{encodings:a,senderEncodings:e}));return}let c=!1;const u=un();if((u==null?void 0:u.name)==="Chrome"&&Wr(u==null?void 0:u.version,"133")>0&&a[0].scalabilityMode){const d=a[0],h=new ca(d.scalabilityMode);let f=Si.OFF;if(t.forEach(p=>{p.enabled&&(f===Si.OFF||p.quality>f)&&(f=p.quality)}),f===Si.OFF)d.active&&(d.active=!1,c=!0);else if(!d.active||h.spatial!==f+1){c=!0,d.active=!0;const p=new ca(e[0].scalabilityMode);h.spatial=f+1,h.suffix=p.suffix,h.spatial===1&&(h.suffix=void 0),d.scalabilityMode=h.toString(),d.scaleResolutionDownBy=Math.pow(2,2-f),e[0].maxBitrate&&(d.maxBitrate=e[0].maxBitrate/(d.scaleResolutionDownBy*d.scaleResolutionDownBy))}}else a.forEach((d,h)=>{var f;let p=(f=d.rid)!==null&&f!==void 0?f:"";p===""&&(p="q");const g=k0(p),v=t.find(y=>y.quality===g);v&&d.active!==v.enabled&&(c=!0,d.active=v.enabled,i.debug("setting layer ".concat(v.quality," to ").concat(d.active?"enabled":"disabled"),A),Qi()&&(v.enabled?(d.scaleResolutionDownBy=e[h].scaleResolutionDownBy,d.maxBitrate=e[h].maxBitrate,d.maxFrameRate=e[h].maxFrameRate):(d.scaleResolutionDownBy=4,d.maxBitrate=10,d.maxFrameRate=2)))});c&&(o.encodings=a,i.debug("setting encodings",Object.assign(Object.assign({},A),{encodings:o.encodings})),yield n.setParameters(o))}finally{s()}})}function k0(n){switch(n){case"f":return Yt.HIGH;case"h":return Yt.MEDIUM;case"q":return Yt.LOW;default:return Yt.HIGH}}function E0(n,e,t,r){if(!t)return[new Vr({quality:Yt.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(r){const i=t[0].scalabilityMode,A=new ca(i),s=[],o=A.suffix=="h"?1.5:2,a=A.suffix=="h"?2:3;for(let c=0;c<A.spatial;c+=1)s.push(new Vr({quality:Math.min(Yt.HIGH,A.spatial-1)-c,width:Math.ceil(n/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 A,s,o;const a=(A=i.scaleResolutionDownBy)!==null&&A!==void 0?A:1;let c=k0((s=i.rid)!==null&&s!==void 0?s:"");return new Vr({quality:c,width:Math.ceil(n/a),height:Math.ceil(e/a),bitrate:(o=i.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const U0="_lossy",T0="_reliable",Fx=2*1e3,id="leave-reconnect";var dn;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(dn||(dn={}));class xx extends Sn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Zl.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=dn.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=ue,this.handleDataChannel=r=>S(this,[r],void 0,function(i){var A=this;let{channel:s}=i;return function*(){if(s){if(s.label===T0)A.reliableDCSub=s;else if(s.label===U0)A.lossyDCSub=s;else return;A.log.debug("on data channel ".concat(s.id,", ").concat(s.label),A.logContext),s.onmessage=A.handleDataMessage}}()}),this.handleDataMessage=r=>S(this,void 0,void 0,function*(){var i,A;const s=yield this.dataProcessLock.lock();try{let o;if(r.data instanceof ArrayBuffer)o=r.data;else if(r.data instanceof Blob)o=yield r.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:r.data}));return}const a=Dt.fromBinary(new Uint8Array(o));((i=a.value)===null||i===void 0?void 0:i.case)==="speaker"?this.emit(D.ActiveSpeakersUpdate,a.value.value.speakers):(((A=a.value)===null||A===void 0?void 0:A.case)==="user"&&Rx(a,a.value.value),this.emit(D.DataPacketReceived,a))}finally{s()}}),this.handleDataError=r=>{const A=r.currentTarget.maxRetransmits===0?"lossy":"reliable";if(r instanceof ErrorEvent&&r.error){const{error:s}=r.error;this.log.error("DataChannel error on ".concat(A,": ").concat(r.message),Object.assign(Object.assign({},this.logContext),{error:s}))}else this.log.error("Unknown DataChannel error on ".concat(A),Object.assign(Object.assign({},this.logContext),{event:r}))},this.handleBufferedAmountLow=r=>{const A=r.currentTarget.maxRetransmits===0?pe.LOSSY:pe.RELIABLE;this.updateAndEmitDCBufferStatus(A)},this.handleDisconnect=(r,i)=>{if(this._isClosed)return;this.log.warn("".concat(r," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const A=a=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(a,"ms. giving up"),this.logContext),this.emit(D.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});if(o===null){A(s);return}r===id&&(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=wt.setTimeout(()=>this.attemptReconnect(i).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((r,i)=>{this.pcState===dn.Connected&&r();const A=()=>{this.off(D.Disconnected,s),r()},s=()=>{this.off(D.Restarted,A),i()};this.once(D.Restarted,A),this.once(D.Disconnected,s)}),this.updateAndEmitDCBufferStatus=r=>{const i=this.isBufferStatusLow(r);typeof i<"u"&&i!==this.dcBufferStatus.get(r)&&(this.dcBufferStatus.set(r,i),this.emit(D.DCBufferStatusChanged,i,r))},this.isBufferStatusLow=r=>{const i=this.dataChannelForKind(r);if(i)return i.bufferedAmount<=i.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Oe.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ki.RR_SIGNAL_DISCONNECTED))},this.log=Ln((t=e.loggerName)!==null&&t!==void 0?t:cn.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new jl(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Mt,this.dataProcessLock=new Mt,this.dcBufferStatus=new Map([[pe.LOSSY,!0],[pe.RELIABLE,!0]]),this.client.onParticipantUpdate=r=>this.emit(D.ParticipantUpdate,r),this.client.onConnectionQuality=r=>this.emit(D.ConnectionQualityUpdate,r),this.client.onRoomUpdate=r=>this.emit(D.RoomUpdate,r),this.client.onSubscriptionError=r=>this.emit(D.SubscriptionError,r),this.client.onSubscriptionPermissionUpdate=r=>this.emit(D.SubscriptionPermissionUpdate,r),this.client.onSpeakersChanged=r=>this.emit(D.SpeakersChanged,r),this.client.onStreamStateUpdate=r=>this.emit(D.StreamStateChanged,r),this.client.onRequestResponse=r=>this.emit(D.SignalRequestResponse,r)}get logContext(){var e,t,r,i,A,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=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.room)===null||i===void 0?void 0:i.sid,participant:(s=(A=this.latestJoinResponse)===null||A===void 0?void 0:A.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,r,i){return S(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=r,this.maxJoinAttempts=r.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const A=yield this.client.join(e,t,r,i);return this._isClosed=!1,this.latestJoinResponse=A,this.subscriberPrimary=A.subscriberPrimary,this.pcManager||(yield this.configure(A)),(!this.subscriberPrimary||A.fastPublish)&&this.negotiate(),this.clientConfiguration=A.clientConfiguration,setTimeout(()=>{this.emit(D.SignalConnected)},10),A}catch(A){if(A instanceof Fe&&A.reason===de.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,r,i);throw A}})}close(){return S(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(D.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return S(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=r=>{r&&(r.close(),r.onbufferedamountlow=null,r.onclose=null,r.onclosing=null,r.onerror=null,r.onmessage=null,r.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 S(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Dn("a track with the same ID has already been published");return new Promise((t,r)=>{const i=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],r(new Fe("publication of local track timed out, no response from server",de.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:A=>{clearTimeout(i),t(A)},reject:()=>{clearTimeout(i),r(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 S(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 S(this,void 0,void 0,function*(){var t,r;if(this.pcManager&&this.pcManager.currentState!==Ye.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const i=this.makeRTCConfiguration(e);this.pcManager=new mx(i,e.subscriberPrimary,this.loggerOptions),this.emit(D.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(A,s)=>{this.client.sendIceCandidate(A,s)},this.pcManager.onPublisherOffer=A=>{this.client.sendOffer(A)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(A,s,o)=>S(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(A),this.logContext),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),A===Ye.CONNECTED){const u=this.pcState===dn.New;this.pcState=dn.Connected,u&&this.emit(D.Connected,e)}else A===Ye.FAILED&&this.pcState===dn.Connected&&(this.pcState=dn.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?ki.RR_SUBSCRIBER_FAILED:ki.RR_PUBLISHER_FAILED));const a=this.client.isDisconnected||this.client.currentState===Oe.RECONNECTING,c=[Ye.FAILED,Ye.CLOSING,Ye.CLOSED].includes(A);a&&c&&!this._isClosed&&this.emit(D.Offline)}),this.pcManager.onTrack=A=>{this.emit(D.MediaTrackAdded,A.track,A.streams[0],A.receiver)},Qx((r=e.serverInfo)===null||r===void 0?void 0:r.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>S(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=>S(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:r}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],r(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(D.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(D.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(D.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(D.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.emit(D.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",ki.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Ti.DISCONNECT:this.emit(D.Disconnected,e==null?void 0:e.reason),this.close();break;case Ti.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(id);break;case Ti.RESUME:this.handleDisconnect(id)}}}makeRTCConfiguration(e){var t;const r=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),r.encodedInsertableStreams=!0),e.iceServers&&!r.iceServers){const i=[];e.iceServers.forEach(A=>{const s={urls:A.urls};A.username&&(s.username=A.username),A.credential&&(s.credential=A.credential),i.push(s)}),r.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===LA.ENABLED&&(r.iceTransportPolicy="relay"),r.sdpSemantics="unified-plan",r.continualGatheringPolicy="gather_continually",r}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(U0,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(T0,{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,r){return S(this,void 0,void 0,function*(){if(Fl())return yield this.createTransceiverRTCRtpSender(e,t,r);if(xl())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new lt("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,r,i){return S(this,void 0,void 0,function*(){if(Fl())return this.createSimulcastTransceiverSender(e,t,r,i);if(xl())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new lt("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,r){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new lt("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),Pi(e)&&(e.codec=t.videoCodec);const A={direction:"sendonly",streams:i};return r&&(A.sendEncodings=r),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,A)).sender})}createSimulcastTransceiverSender(e,t,r,i){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new lt("publisher is closed");const A={direction:"sendonly"};i&&(A.sendEncodings=i);const s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,A);if(r.videoCodec)return e.setSimulcastTrackSender(r.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new lt("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return S(this,void 0,void 0,function*(){var t,r,i;if(!this._isClosed){if(this.attemptingReconnect){ue.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===LA.DISABLED||((i=(r=this.pcManager)===null||r===void 0?void 0:r.currentState)!==null&&i!==void 0?i:Ye.NEW)===Ye.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(A){this.reconnectAttempts+=1;let s=!0;A instanceof lt?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:A})),s=!1):A instanceof Mi||(this.fullReconnectOnNext=!0),s?this.handleDisconnect("reconnect",ki.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(D.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 S(this,void 0,void 0,function*(){var t,r,i;try{if(!this.url||!this.token)throw new lt("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(D.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let A;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Mi;A=yield this.join(e??this.url,this.token,this.signalOpts)}catch(s){throw s instanceof Fe&&s.reason===de.NotAllowed?new lt("could not reconnect, token might be expired"):new Mi}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(D.SignalRestarted,A),yield this.waitForPCReconnected(),this.client.currentState!==Oe.CONNECTED)throw new Mi("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(D.Restarted)}catch(A){const s=yield(r=this.regionUrlProvider)===null||r===void 0?void 0:r.getNextBestRegionUrl();if(s){yield this.restartConnection(s);return}else throw(i=this.regionUrlProvider)===null||i===void 0||i.resetAttempts(),A}})}resumeConnection(e){return S(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new lt("could not reconnect, url or token not saved");if(!this.pcManager)throw new lt("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(D.Resuming);let r;try{this.setupSignalClientCallbacks(),r=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(i){let A="";throw i instanceof Error&&(A=i.message,this.log.error(i.message,Object.assign(Object.assign({},this.logContext),{error:i}))),i instanceof Fe&&i.reason===de.NotAllowed?new lt("could not reconnect, token might be expired"):i instanceof Fe&&i.reason===de.LeaveRequest?i:new Mi(A)}if(this.emit(D.SignalResumed),r){const i=this.makeRTCConfiguration(r);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!==Oe.CONNECTED)throw new Mi("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(D.Resumed)})}waitForPCInitialConnection(e,t){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new lt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return S(this,void 0,void 0,function*(){this.pcState=dn.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Nt(Fx),!this.pcManager)throw new lt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=dn.Connected}catch(e){throw this.pcState=dn.Disconnected,new Fe("could not establish PC connection, ".concat(e.message),de.InternalError)}})}publishRpcResponse(e,t,r,i){return S(this,void 0,void 0,function*(){const A=new Dt({destinationIdentities:[e],kind:pe.RELIABLE,value:{case:"rpcResponse",value:new Pm({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:r??""}})}});yield this.sendDataPacket(A,pe.RELIABLE)})}publishRpcAck(e,t){return S(this,void 0,void 0,function*(){const r=new Dt({destinationIdentities:[e],kind:pe.RELIABLE,value:{case:"rpcAck",value:new Rm({requestId:t})}});yield this.sendDataPacket(r,pe.RELIABLE)})}sendDataPacket(e,t){return S(this,void 0,void 0,function*(){const r=e.toBinary();yield this.ensurePublisherConnected(t);const i=this.dataChannelForKind(t);i&&i.send(r),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,r)=>S(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const i=()=>r("Engine closed");for(this.once(D.Closing,i);!this.dcBufferStatus.get(e);)yield Nt(10);this.off(D.Closing,i),t()}}))}ensureDataTransportConnected(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var A;if(!r.pcManager)throw new lt("PC manager is closed");const s=i?r.pcManager.subscriber:r.pcManager.publisher,o=i?"Subscriber":"Publisher";if(!s)throw new Fe("".concat(o," connection not set"),de.InternalError);let a=!1;!i&&!r.dataChannelForKind(t,i)&&(r.createDataChannels(),a=!0),!a&&!i&&!r.pcManager.publisher.isICEConnected&&r.pcManager.publisher.getICEConnectionState()!=="checking"&&(a=!0),a&&r.negotiate();const c=r.dataChannelForKind(t,i);if((c==null?void 0:c.readyState)==="open")return;const u=new Date().getTime()+r.peerConnectionTimeout;for(;new Date().getTime()<u;){if(s.isICEConnected&&((A=r.dataChannelForKind(t,i))===null||A===void 0?void 0:A.readyState)==="open")return;yield Nt(50)}throw new Fe("could not establish ".concat(o," connection, state: ").concat(s.getICEConnectionState()),de.InternalError)}()})}ensurePublisherConnected(e){return S(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Ye.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return S(this,void 0,void 0,function*(){return new Promise((e,t)=>S(this,void 0,void 0,function*(){if(!this.pcManager){t(new _l("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const r=new AbortController,i=()=>{r.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(D.Closing,i),this.pcManager.publisher.once(Oi.RTPVideoPayloadTypes,A=>{const s=new Map;A.forEach(o=>{const a=o.codec.toLowerCase();KF(a)&&s.set(o.payload,a)}),this.emit(D.RTPVideoMapUpdate,s)});try{yield this.pcManager.negotiate(r),e()}catch(A){A instanceof _l&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ki.RR_UNKNOWN),t(A)}finally{this.off(D.Closing,i)}}))})}dataChannelForKind(e,t){if(t){if(e===pe.LOSSY)return this.lossyDCSub;if(e===pe.RELIABLE)return this.reliableDCSub}else{if(e===pe.LOSSY)return this.lossyDC;if(e===pe.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var r,i;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const A=this.pcManager.subscriber.getLocalDescription(),s=this.pcManager.subscriber.getRemoteDescription(),o=(i=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&i!==void 0?i:!0,a=new Array,c=new Array;e.forEach(u=>{u.isDesired!==o&&a.push(u.trackSid),u.isEnabled||c.push(u.trackSid)}),this.client.sendSyncState(new $m({answer:A?sa({sdp:A.sdp,type:A.type}):void 0,offer:s?sa({sdp:s.sdp,type:s.type}):void 0,subscription:new Go({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:YF(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(r,i)=>{(r==null?void 0:r.id)!==void 0&&r.id!==null&&e.push(new ev({label:r.label,id:r.id,target:i}))};return t(this.dataChannelForKind(pe.LOSSY),an.PUBLISHER),t(this.dataChannelForKind(pe.RELIABLE),an.PUBLISHER),t(this.dataChannelForKind(pe.LOSSY,!0),an.SUBSCRIBER),t(this.dataChannelForKind(pe.RELIABLE,!0),an.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&wt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ht()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Ht()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Mi extends Error{}function Qx(n){return n!==void 0&&n>13}function Rx(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const r=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=r,e.destinationIdentities=r}class Ad{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 Rl(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return S(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(r=>!this.attemptedRegions.find(i=>i.url===r.url));if(t.length>0){const r=t[0];return this.attemptedRegions.push(r),ue.debug("next region: ".concat(r.region)),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return S(this,void 0,void 0,function*(){const t=yield fetch("".concat(Px(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const r=yield t.json();return this.lastUpdateAt=Date.now(),r}else throw new Fe("Could not fetch region settings: ".concat(t.statusText),t.status===401?de.NotAllowed:de.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function Px(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class I0{get info(){return this._info}constructor(e,t,r){this.reader=t,this.totalByteSize=r,this._info=e,this.bytesReceived=0}}class Ox extends I0{handleChunkReceived(e){var t;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();return{next:()=>S(this,void 0,void 0,function*(){try{const{done:t,value:r}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(r),{done:!1,value:r.content})}catch{return{done:!0,value:void 0}}}),return(){return S(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return S(this,void 0,void 0,function*(){var e,t,r,i;let A=new Set;try{for(var s=!0,o=ur(this),a;a=yield o.next(),e=a.done,!e;s=!0){i=a.value,s=!1;const c=i;A.add(c)}}catch(c){t={error:c}}finally{try{!s&&!e&&(r=o.return)&&(yield r.call(o))}finally{if(t)throw t.error}}return Array.from(A)})}}class Mx extends I0{constructor(e,t,r){super(e,t,r),this.receivedChunks=new Map}handleChunkReceived(e){var t;const r=ia(e.chunkIndex),i=this.receivedChunks.get(r);if(i&&i.version>e.version)return;this.receivedChunks.set(r,e),this.bytesReceived+=e.content.byteLength;const A=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,A)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>S(this,void 0,void 0,function*(){try{const{done:r,value:i}=yield e.read();return r?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:t.decode(i.content)})}catch{return{done:!0,value:void 0}}}),return(){return S(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return S(this,void 0,void 0,function*(){var e,t,r,i;let A="";try{for(var s=!0,o=ur(this),a;a=yield o.next(),e=a.done,!e;s=!0)i=a.value,s=!1,A+=i}catch(c){t={error:c}}finally{try{!s&&!e&&(r=o.return)&&(yield r.call(o))}finally{if(t)throw t.error}}return A})}}class F0{constructor(e,t,r){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=r,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return S(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 Lx extends F0{}class Dx extends F0{}class x0 extends R{constructor(e,t,r,i,A){super(e,r,A),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?L.Muted:L.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=r=>{r.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(L.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return S(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(),ed)),ZF()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const r=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(r){const{timestamp:i,rtpTimestamp:A}=r;A&&this.rtpTimestamp!==A&&(this.emit(L.TimeSyncUpdate,{timestamp:i,rtpTimestamp:A}),this.rtpTimestamp=A)}};e()}}class Nx extends x0{constructor(e,t,r,i,A,s){super(e,t,R.Kind.Audio,r,s),this.monitorReceiver=()=>S(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=oa(o,this.prevStats)),this.prevStats=o}),this.audioContext=i,this.webAudioPluginNodes=[],A&&(this.sinkId=A.deviceId)}setVolume(e){var t;for(const r of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):r.volume=e;kn()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(kn())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return S(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Ql(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Ql(e)&&e.setSinkId(this.sinkId).catch(r=>{this.log.error("Failed to set sink id on remote audio track",r,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 r=this.sourceNode;this.webAudioPluginNodes.forEach(i=>{r.connect(i),r=i}),this.gainNode=e.createGain(),r.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(L.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(i=>{this.emit(L.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 S(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(r=>{r.type==="inbound-rtp"&&(t={type:"audio",streamId:r.id,timestamp:r.timestamp,jitter:r.jitter,bytesReceived:r.bytesReceived,concealedSamples:r.concealedSamples,concealmentEvents:r.concealmentEvents,silentConcealedSamples:r.silentConcealedSamples,silentConcealmentEvents:r.silentConcealmentEvents,totalAudioEnergy:r.totalAudioEnergy,totalSamplesDuration:r.totalSamplesDuration})}),t})}}const sd=100;class Hx extends x0{constructor(e,t,r,i,A){super(e,t,R.Kind.Video,r,A),this.elementInfos=[],this.monitorReceiver=()=>S(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=oa(s,this.prevStats)),this.prevStats=s}),this.debouncedHandleResize=Xl(()=>{this.updateDimensions()},sd),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?xi(this._mediaStreamTrack,t):Fi(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 Kx(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(r=>r===e);for(const r of t)r.stopObserving();this.elementInfos=this.elementInfos.filter(r=>r!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const r of t)this.stopObservingElement(r);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return S(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,r="",i=new Map;return e.forEach(A=>{A.type==="inbound-rtp"?(r=A.codecId,t={type:"video",streamId:A.id,framesDecoded:A.framesDecoded,framesDropped:A.framesDropped,framesReceived:A.framesReceived,packetsReceived:A.packetsReceived,packetsLost:A.packetsLost,frameWidth:A.frameWidth,frameHeight:A.frameHeight,pliCount:A.pliCount,firCount:A.firCount,nackCount:A.nackCount,jitter:A.jitter,timestamp:A.timestamp,bytesReceived:A.bytesReceived,decoderImplementation:A.decoderImplementation}):A.type==="codec"&&i.set(A.id,A)}),t&&r!==""&&i.get(r)&&(t.mimeType=i.get(r).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(r=>r.element===e);for(const r of t)this.stopObservingElementInfo(r)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const r=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,A=this.elementInfos.some(o=>o.pictureInPicture),s=this.elementInfos.some(o=>o.visible)&&!i||A;if(this.lastVisible!==s){if(!s&&Date.now()-r<sd){wt.setTimeout(()=>{this.updateVisibility()},sd);return}this.lastVisible=s,this.emit(L.VisibilityChanged,s,this)}}updateDimensions(){var e,t;let r=0,i=0;const A=this.getPixelDensity();for(const s of this.elementInfos){const o=s.width()*A,a=s.height()*A;o+a>r+i&&(r=o,i=a)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===r&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===i||(this.lastDimensions={width:r,height:i},this.emit(L.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?$v():t||($v()>2?2:1)}}class Kx{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=r=>{var i;const{target:A,isIntersecting:s}=r;A===this.element&&(this.isIntersecting=s,this.isPiP=jA(this.element),this.visibilityChangedAt=Date.now(),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this))},this.onEnterPiP=()=>{var r,i,A;(i=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP),this.isPiP=jA(this.element),(A=this.handleVisibilityChanged)===null||A===void 0||A.call(this)},this.onLeavePiP=()=>{var r;this.isPiP=jA(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.element=e,this.isIntersecting=t??od(e),this.isPiP=Ht()&&jA(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,r;this.isIntersecting=od(this.element),this.isPiP=jA(this.element),this.element.handleResize=()=>{var i;(i=this.handleResize)===null||i===void 0||i.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,t0().observe(this.element),e0().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),(r=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,r,i,A;(e=t0())===null||e===void 0||e.unobserve(this.element),(t=e0())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(r=window.documentPictureInPicture)===null||r===void 0||r.removeEventListener("enter",this.onEnterPiP),(A=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||A===void 0||A.removeEventListener("pagehide",this.onLeavePiP)}}function jA(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?od(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function od(n,e){const t=e||window;let r=n.offsetTop,i=n.offsetLeft;const A=n.offsetWidth,s=n.offsetHeight,{hidden:o}=n,{display:a}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,r+=n.offsetTop,i+=n.offsetLeft;return r<t.pageYOffset+t.innerHeight&&i<t.pageXOffset+t.innerWidth&&r+s>t.pageYOffset&&i+A>t.pageXOffset&&!o&&a!=="none"}class Hn extends Sn.EventEmitter{constructor(e,t,r,i){var A;super(),this.metadataMuted=!1,this.encryption=Wt.NONE,this.log=ue,this.handleMuted=()=>{this.emit(L.Muted)},this.handleUnmuted=()=>{this.emit(L.Unmuted)},this.log=Ln((A=i==null?void 0:i.loggerName)!==null&&A!==void 0?A:cn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=r,this.source=R.Source.Unknown}setTrack(e){this.track&&(this.track.off(L.Muted,this.handleMuted),this.track.off(L.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(L.Muted,this.handleMuted),e.on(L.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),_e(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Wt.NONE}get audioTrack(){if(Nn(this.track))return this.track}get videoTrack(){if(Pi(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=R.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===R.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(n.PermissionStatus||(n.PermissionStatus={}))})(Hn||(Hn={}));class ad extends Hn{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,r,i){super(e,t.sid,t.name,i),this.track=void 0,this.handleTrackEnded=()=>{this.emit(L.Ended)},this.updateInfo(t),this.setTrack(r)}setTrack(e){this.track&&this.track.off(L.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(L.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 S(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return S(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return S(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return S(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Nn(this.track)){const t=this.track.getSourceTrackSettings(),r=new Set;return t.autoGainControl&&r.add(on.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&r.add(on.TF_ECHO_CANCELLATION),t.noiseSuppression&&r.add(on.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&r.add(on.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||r.add(on.TF_NO_DTX),this.track.enhancedNoiseCancellation&&r.add(on.TF_ENHANCED_NOISE_CANCELLATION),Array.from(r.values())}else return[]}}function la(n,e){return S(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:r,videoProcessor:i,optionsWithoutProcessor:A}=a0(n);let s=A.audio,o=A.video;if(r&&typeof A.audio=="object"&&(A.audio.processor=r),i&&typeof A.video=="object"&&(A.video.processor=i),n.audio&&typeof A.audio=="object"&&typeof A.audio.deviceId=="string"){const l=A.audio.deviceId;A.audio.deviceId={exact:l},t=!0,s=Object.assign(Object.assign({},A.audio),{deviceId:{ideal:l}})}if(A.video&&typeof A.video=="object"&&typeof A.video.deviceId=="string"){const l=A.video.deviceId;A.video.deviceId={exact:l},t=!0,o=Object.assign(Object.assign({},A.video),{deviceId:{ideal:l}})}(A.audio===!0||typeof A.audio=="object"&&!A.audio.deviceId)&&(A.audio={deviceId:"default"}),A.video===!0?A.video={deviceId:"default"}:typeof A.video=="object"&&!A.video.deviceId&&(A.video.deviceId="default");const a=i0(A,v0,y0),c=Vl(a),u=navigator.mediaDevices.getUserMedia(c);A.audio&&(ft.userMediaPromiseMap.set("audioinput",u),u.catch(()=>ft.userMediaPromiseMap.delete("audioinput"))),A.video&&(ft.userMediaPromiseMap.set("videoinput",u),u.catch(()=>ft.userMediaPromiseMap.delete("videoinput")));try{const l=yield u;return yield Promise.all(l.getTracks().map(d=>S(this,void 0,void 0,function*(){const h=d.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=d.getSettings().deviceId;p!=null&&p.deviceId&&fr(p.deviceId)!==v?p.deviceId=v:p||(p={deviceId:v});const y=yx(d,p,e);return y.kind===R.Kind.Video?y.source=R.Source.Camera:y.kind===R.Kind.Audio&&(y.source=R.Source.Microphone),y.mediaStream=l,Nn(y)&&r?yield y.setProcessor(r):Pi(y)&&i&&(yield y.setProcessor(i)),y})))}catch(l){if(!t)throw l;return la(Object.assign(Object.assign({},n),{audio:s,video:o}),e)}})}function Vx(n){return S(this,void 0,void 0,function*(){return(yield la({audio:!1,video:n??!0}))[0]})}function Gx(n){return S(this,void 0,void 0,function*(){return(yield la({audio:n??!0,video:!1}))[0]})}var vr;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(vr||(vr={}));function jx(n){switch(n){case MA.EXCELLENT:return vr.Excellent;case MA.GOOD:return vr.Good;case MA.POOR:return vr.Poor;case MA.LOST:return vr.Lost;default:return vr.Unknown}}class Q0 extends Sn.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===Vo.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Ei.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,r,i,A,s){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Vo.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=vr.Unknown,this.log=ue,this.log=Ln((a=s==null?void 0:s.loggerName)!==null&&a!==void 0?a:cn.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=r,this.metadata=i,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=A??{}}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 Ll,this.once(K.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(R.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(R.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(R.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===Ei.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Ei.ACTIVE&&this.emit(K.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,r=this.metadata;this.metadata=e,t&&this.emit(K.ParticipantMetadataChanged,r)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(K.ParticipantNameChanged,e)}_setAttributes(e){const t=$F(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(K.AttributesChanged,t)}setPermissions(e){var t,r,i,A,s,o;const a=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((r=this.permissions)===null||r===void 0?void 0:r.canSubscribe)||e.canPublishData!==((i=this.permissions)===null||i===void 0?void 0:i.canPublishData)||e.hidden!==((A=this.permissions)===null||A===void 0?void 0:A.hidden)||e.recorder!==((s=this.permissions)===null||s===void 0?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,l)=>{var d;return u!==((d=this.permissions)===null||d===void 0?void 0:d.canPublishSources[l])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(K.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(K.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=jx(e),t!==this._connectionQuality&&this.emit(K.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=>Nn(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(L.Muted,()=>{this.emit(K.TrackMuted,e)}),e.on(L.Unmuted,()=>{this.emit(K.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case R.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case R.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Wx(n){var e,t,r;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Ym({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(r=n.allowAll)!==null&&r!==void 0?r:!1,trackSids:n.allowedTrackSids||[]})}const R0=15e3;class qx extends Q0{constructor(e,t,r,i,A){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=Wt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Ll)},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,u=this.pendingSignalRequests.get(o);u&&(a!==dl.OK&&u.reject(new Wv(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=Ze.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,a,c);break;case"rpcAck":let u=s.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(s=>Wx(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),_e(s)));return}this.engine.updateMuteStatus(s.sid,o)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),_e(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),_e(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=>S(this,void 0,void 0,function*(){var o,a,c,u,l,d;if(!(!((l=this.roomOptions)===null||l===void 0)&&l.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=ur(v),g;g=yield p.next(),o=g.done,!o;f=!0){u=g.value,f=!1;const y=u;FF(y)&&(this.log.debug("publish ".concat(y," for ").concat(h.videoTrack.sid),Object.assign(Object.assign({},this.logContext),_e(h))),yield this.publishAdditionalCodecForTrack(h.videoTrack,y,h.options))}}catch(y){a={error:y}}finally{try{!f&&!o&&(c=p.return)&&(yield c.call(p))}finally{if(a)throw a.error}}}else s.subscribedQualities.length>0&&(yield(d=h.videoTrack)===null||d===void 0?void 0:d.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=>S(this,void 0,void 0,function*(){if(s.source===R.Source.ScreenShare||s.source===R.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),_e(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(Jr(s)||gr(s))try{if(Ht())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:s.source===R.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),_e(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),_e(s))),Jr(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),_e(s))),yield s.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=r,this.roomOptions=i,this.setupEngine(r),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=A}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Wt.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(D.RemoteMute,(t,r)=>{const i=this.trackPublications.get(t);!i||!i.track||(r?i.mute():i.unmute())}),this.engine.on(D.Connected,this.handleReconnected).on(D.SignalRestarted,this.handleReconnected).on(D.SignalResumed,this.handleReconnected).on(D.Restarting,this.handleReconnecting).on(D.Resuming,this.handleReconnecting).on(D.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(D.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(D.Disconnected,this.handleDisconnected).on(D.SignalRequestResponse,this.handleSignalRequestResponse).on(D.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return S(this,arguments,void 0,function(t){var r=this;let{metadata:i,name:A,attributes:s}=t;return function*(){return new Promise((o,a)=>S(r,void 0,void 0,function*(){var c,u;try{let l=!1;const d=yield this.engine.client.sendUpdateLocalMetadata((c=i??this.metadata)!==null&&c!==void 0?c:"",(u=A??this.name)!==null&&u!==void 0?u:"",s),h=performance.now();for(this.pendingSignalRequests.set(d,{resolve:o,reject:f=>{a(f),l=!0},values:{name:A,metadata:i,attributes:s}});performance.now()-h<5e3&&!l;){if((!A||this.name===A)&&(!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(d),o();return}yield Nt(50)}a(new Wv("Request to update local metadata timed out","TimeoutError"))}catch(l){l instanceof Error&&a(l)}}))}()})}setCameraEnabled(e,t,r){return this.setTrackEnabled(R.Source.Camera,e,t,r)}setMicrophoneEnabled(e,t,r){return this.setTrackEnabled(R.Source.Microphone,e,t,r)}setScreenShareEnabled(e,t,r){return this.setTrackEnabled(R.Source.ScreenShare,e,t,r)}setPermissions(e){const t=this.permissions,r=super.setPermissions(e);return r&&t&&this.emit(K.ParticipantPermissionsChanged,t),r}setE2EEEnabled(e){return S(this,void 0,void 0,function*(){this.encryptionType=e?Wt.GCM:Wt.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,r,i){return S(this,void 0,void 0,function*(){var A,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==null?void 0:c.unmute(),c}this.pendingPublishing.add(e);try{switch(e){case R.Source.Camera:a=yield this.createTracks({video:(A=r)!==null&&A!==void 0?A:!0});break;case R.Source.Microphone:a=yield this.createTracks({audio:(s=r)!==null&&s!==void 0?s:!0});break;case R.Source.ScreenShare:a=yield this.createScreenTracks(Object.assign({},r));break;default:throw new Dn(e)}}catch(c){throw a==null||a.forEach(u=>{u.stop()}),c instanceof Error&&this.emit(K.MediaDevicesError,c),this.pendingPublishing.delete(e),c}try{const c=[];for(const l of a)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),_e(l))),c.push(this.publishTrack(l,i));[o]=yield Promise.all(c)}catch(c){throw a==null||a.forEach(u=>{u.stop()}),c}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&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===R.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const a=this.getTrackPublication(R.Source.ScreenShareAudio);a&&a.track&&this.unpublishTrack(a.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return S(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(R.Source.Camera)||this.pendingPublishing.has(R.Source.Microphone))){this.pendingPublishing.add(R.Source.Camera),this.pendingPublishing.add(R.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(R.Source.Camera),this.pendingPublishing.delete(R.Source.Microphone)}}})}createTracks(e){return S(this,void 0,void 0,function*(){var t,r;e??(e={});const i=i0(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(r=this.roomOptions)===null||r===void 0?void 0:r.videoCaptureDefaults);try{return(yield la(i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Nn(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=R.Source.Microphone,this.emit(K.AudioStreamAcquired)),Pi(o)&&(this.cameraError=void 0,o.source=R.Source.Camera),o))}catch(A){throw A instanceof Error&&(e.audio&&(this.microphoneError=A),e.video&&(this.cameraError=A)),A}})}createScreenTracks(e){return S(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Cl("getDisplayMedia not supported");e.resolution===void 0&&!MF()&&(e.resolution=Il.h1080fps30.resolution);const t=XF(e),r=yield navigator.mediaDevices.getDisplayMedia(t),i=r.getVideoTracks();if(i.length===0)throw new Dn("no video track found");const A=new ua(i[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});A.source=R.Source.ScreenShare,e.contentHint&&(A.mediaStreamTrack.contentHint=e.contentHint);const s=[A];if(r.getAudioTracks().length>0){this.emit(K.AudioStreamAcquired);const o=new aa(r.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=R.Source.ScreenShareAudio,s.push(o)}return s})}publishTrack(e,t){return S(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,a,c,u;Jr(r)&&r.setAudioContext(A.audioContext),yield(o=A.reconnectFuture)===null||o===void 0?void 0:o.promise,A.republishPromise&&!s&&(yield A.republishPromise),Ri(r)&&A.pendingPublishPromises.has(r)&&(yield A.pendingPublishPromises.get(r));let l;if(r instanceof MediaStreamTrack)l=r.getConstraints();else{l=r.constraints;let v;switch(r.source){case R.Source.Microphone:v="audioinput";break;case R.Source.Camera:v="videoinput"}v&&A.activeDeviceMap.has(v)&&(l=Object.assign(Object.assign({},l),{deviceId:A.activeDeviceMap.get(v)}))}if(r instanceof MediaStreamTrack)switch(r.kind){case"audio":r=new aa(r,l,!0,A.audioContext,{loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});break;case"video":r=new ua(r,l,!0,{loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});break;default:throw new Dn("unsupported MediaStreamTrack kind ".concat(r.kind))}else r.updateLoggerOptions({loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});let d;if(A.trackPublications.forEach(v=>{v.track&&v.track===r&&(d=v)}),d)return A.log.warn("track has already been published, skipping",Object.assign(Object.assign({},A.logContext),_e(d))),d;const h="channelCount"in r.mediaStreamTrack.getSettings()&&r.mediaStreamTrack.getSettings().channelCount===2||r.mediaStreamTrack.getConstraints().channelCount===2,f=(a=i==null?void 0:i.forceStereo)!==null&&a!==void 0?a:h;f&&(i||(i={}),i.dtx===void 0&&A.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},A.logContext),_e(r))),i.red===void 0&&A.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),(u=i.red)!==null&&u!==void 0||(i.red=!1));const p=Object.assign(Object.assign({},A.roomOptions.publishDefaults),i);!LF()&&A.roomOptions.e2ee&&(A.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({},A.logContext)),p.simulcast=!1),p.source&&(r.source=p.source);const g=new Promise((v,y)=>S(A,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Oe.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:_e(r)}));const B=()=>S(this,void 0,void 0,function*(){try{const b=yield this.publish(r,p,f);v(b)}catch(b){y(b)}});setTimeout(()=>{this.engine.off(D.SignalConnected,B),y(new Sl("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(D.SignalConnected,B),this.engine.on(D.Closing,()=>{this.engine.off(D.SignalConnected,B),y(new Sl("publishing rejected as engine closed",499))})}else try{const B=yield this.publish(r,p,f);v(B)}catch(B){y(B)}}catch(B){y(B)}}));A.pendingPublishPromises.set(r,g);try{return yield g}catch(v){throw v}finally{A.pendingPublishPromises.delete(r)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),_e(e))),!1;const{canPublish:t,canPublishSources:r}=this.permissions;return t&&(r.length===0||r.map(i=>ex(i)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),_e(e))),!1)}publish(e,t,r){return S(this,void 0,void 0,function*(){var i,A,s,o,a,c,u,l,d,h;if(!this.hasPermissionsToPublish(e))throw new Sl("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(w=>Ri(e)&&w.source===e.source)&&e.source!==R.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),_e(e))),t.stopMicTrackOnMute&&Nn(e)&&(e.stopOnMute=!0),e.source===R.Source.ScreenShare&&Qi()&&(t.simulcast=!1),t.videoCodec==="av1"&&!RF()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!PF()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Yl),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(w=>t.videoCodec===Aa(w.mime))||(t.videoCodec=Aa(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(L.Muted,this.onTrackMuted),e.on(L.Unmuted,this.onTrackUnmuted),e.on(L.Ended,this.handleTrackEnded),e.on(L.UpstreamPaused,this.onTrackUpstreamPaused),e.on(L.UpstreamResumed,this.onTrackUpstreamResumed),e.on(L.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const g=new ol({cid:e.mediaStreamTrack.id,name:t.name,type:R.kindToProto(e.kind),muted:e.isMuted,source:R.sourceToProto(e.source),disableDtx:!(!((i=t.dtx)!==null&&i!==void 0)||i),encryption:this.encryptionType,stereo:r,disableRed:this.isE2EEEnabled||!(!((A=t.red)!==null&&A!==void 0)||A),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy});let v;if(e.kind===R.Kind.Video){let w={width:0,height:0};try{w=yield e.waitForDimensions()}catch{const k=(o=(s=this.roomOptions.videoCaptureDefaults)===null||s===void 0?void 0:s.resolution)!==null&&o!==void 0?o:HA.h720.resolution;w={width:k.width,height:k.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),_e(e)),{dims:w}))}g.width=w.width,g.height=w.height,gr(e)&&(KA(p)&&(e.source===R.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),_e(e))))),t.scalabilityMode=(a=t.scalabilityMode)!==null&&a!==void 0?a:"L3T3_KEY"),g.simulcastCodecs=[new sl({codec:p,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Yl}),t.backupCodec&&p!==t.backupCodec.codec&&g.encryption===Wt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),g.simulcastCodecs.push(new sl({codec:t.backupCodec.codec,cid:""})))),v=nd(e.source===R.Source.ScreenShare,g.width,g.height,t),g.layers=E0(g.width,g.height,v,KA(t.videoCodec))}else e.kind===R.Kind.Audio&&(v=[{maxBitrate:(c=t.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(l=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&l!==void 0?l:"high",networkPriority:(h=(d=t.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&h!==void 0?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new lt("cannot publish track when not connected");const y=()=>S(this,void 0,void 0,function*(){var w,_,k;if(!this.engine.pcManager)throw new lt("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,v),gr(e)&&((w=t.degradationPreference)!==null&&w!==void 0||(t.degradationPreference=Tx(e)),e.setDegradationPreference(t.degradationPreference)),v)if(Qi()&&e.kind===R.Kind.Audio){let T;for(const x of this.engine.pcManager.publisher.getTransceivers())if(x.sender===e.sender){T=x;break}T&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:T,codec:"opus",maxbr:!((_=v[0])===null||_===void 0)&&_.maxBitrate?v[0].maxBitrate/1e3:0})}else e.codec&&KA(e.codec)&&(!((k=v[0])===null||k===void 0)&&k.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:g.cid,codec:e.codec,maxbr:v[0].maxBitrate/1e3});yield this.engine.negotiate()});let B;if(this.enabledPublishVideoCodecs.length>0)B=(yield Promise.all([this.engine.addTrack(g),y()]))[0];else{B=yield this.engine.addTrack(g);let w;if(B.codecs.forEach(_=>{w===void 0&&(w=_.mimeType)}),w&&e.kind===R.Kind.Video){const _=Aa(w);_!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),_e(e)),{codec:_})),t.videoCodec=_,v=nd(e.source===R.Source.ScreenShare,g.width,g.height,t))}yield y()}const b=new ad(e.kind,B,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return b.options=t,e.sid=B.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:v,trackInfo:B})),gr(e)?e.startMonitor(this.engine.client):Jr(e)&&e.startMonitor(),this.addTrackPublication(b),this.emit(K.LocalTrackPublished,b),b})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,r){return S(this,void 0,void 0,function*(){var i;if(this.encryptionType!==Wt.NONE)return;let A;if(this.trackPublications.forEach(h=>{h.track&&h.track===e&&(A=h)}),!A)throw new Dn("track is not published");if(!gr(e))throw new Dn("track is not a video track");const s=Object.assign(Object.assign({},(i=this.roomOptions)===null||i===void 0?void 0:i.publishDefaults),r),o=kx(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),_e(e)));return}const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new ol({cid:a.mediaStreamTrack.id,type:R.kindToProto(e.kind),muted:e.isMuted,source:R.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=E0(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new lt("cannot publish track when not connected");const u=()=>S(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,s,o),yield this.engine.negotiate()}),d=(yield Promise.all([this.engine.addTrack(c),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))})}unpublishTrack(e,t){return S(this,void 0,void 0,function*(){var r,i;if(Ri(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),_e(e))),yield c)}const A=this.getPublicationForTrack(e),s=A?_e(A):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),s)),!A||!A.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),s));return}e=A.track,e.off(L.Muted,this.onTrackMuted),e.off(L.Unmuted,this.onTrackUnmuted),e.off(L.Ended,this.handleTrackEnded),e.off(L.UpstreamPaused,this.onTrackUpstreamPaused),e.off(L.UpstreamResumed,this.onTrackUpstreamResumed),e.off(L.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(i=(r=this.roomOptions)===null||r===void 0?void 0:r.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<Ye.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),gr(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(A.trackSid),A.kind){case R.Kind.Audio:this.audioTrackPublications.delete(A.trackSid);break;case R.Kind.Video:this.videoTrackPublications.delete(A.trackSid);break}return this.emit(K.LocalTrackUnpublished,A),A.setTrack(void 0),o&&(yield this.engine.negotiate()),A})}unpublishTracks(e){return S(this,void 0,void 0,function*(){return(yield Promise.all(e.map(r=>this.unpublishTrack(r)))).filter(r=>!!r)})}republishAllTracks(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){r.republishPromise&&(yield r.republishPromise),r.republishPromise=new Promise((A,s)=>S(r,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=>S(this,void 0,void 0,function*(){const c=a.track;yield this.unpublishTrack(c,!1),i&&!c.isMuted&&c.source!==R.Source.ScreenShare&&c.source!==R.Source.ScreenShareAudio&&(Jr(c)||gr(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)}))),A()}catch(o){s(o)}finally{this.republishPromise=void 0}})),yield r.republishPromise}()})}publishData(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const A=i.reliable?pe.RELIABLE:pe.LOSSY,s=i.destinationIdentities,o=i.topic,a=new Dt({kind:A,value:{case:"user",value:new Fm({participantIdentity:r.identity,payload:t,destinationIdentities:s,topic:o})}});yield r.engine.sendDataPacket(a,A)}()})}publishDtmf(e,t){return S(this,void 0,void 0,function*(){const r=new Dt({kind:pe.RELIABLE,value:{case:"sipDtmf",value:new xm({code:e,digit:t})}});yield this.engine.sendDataPacket(r,pe.RELIABLE)})}sendChatMessage(e,t){return S(this,void 0,void 0,function*(){const r={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},i=new Dt({value:{case:"chatMessage",value:new el(Object.assign(Object.assign({},r),{timestamp:Ke.parse(r.timestamp)}))}});return yield this.engine.sendDataPacket(i,pe.RELIABLE),this.emit(K.ChatMessage,r),r})}editChatMessage(e,t){return S(this,void 0,void 0,function*(){const r=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),i=new Dt({value:{case:"chatMessage",value:new el(Object.assign(Object.assign({},r),{timestamp:Ke.parse(r.timestamp),editTimestamp:Ke.parse(r.editTimestamp)}))}});return yield this.engine.sendDataPacket(i,pe.RELIABLE),this.emit(K.ChatMessage,r),r})}sendText(e,t){return S(this,void 0,void 0,function*(){var r;const i=crypto.randomUUID(),s=new TextEncoder().encode(e).byteLength,o=(r=t==null?void 0:t.attachments)===null||r===void 0?void 0:r.map(()=>crypto.randomUUID()),a=new Array(o?o.length+1:1).fill(0),c=(l,d)=>{var h;a[d]=l;const f=a.reduce((p,g)=>p+g,0);(h=t==null?void 0:t.onProgress)===null||h===void 0||h.call(t,f)},u=yield this.streamText({streamId:i,totalSize:s,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:o,attributes:t==null?void 0:t.attributes});return yield u.write(e),c(1,0),yield u.close(),t!=null&&t.attachments&&o&&(yield Promise.all(t.attachments.map((l,d)=>S(this,void 0,void 0,function*(){return this._sendFile(o[d],l,{topic:t.topic,mimeType:l.type,onProgress:h=>{c(h,d+1)}})})))),u.info})}streamText(e){return S(this,void 0,void 0,function*(){var t,r;const i=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),A={id:i,mimeType:"text/plain",timestamp:Date.now(),topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},s=new nl({streamId:i,mimeType:A.mimeType,topic:A.topic,timestamp:qr(A.timestamp),totalLength:qr(e==null?void 0:e.totalSize),attributes:A.attributes,contentHeader:{case:"textHeader",value:new Vm({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?tl.UPDATE:tl.CREATE})}}),o=e==null?void 0:e.destinationIdentities,a=new Dt({destinationIdentities:o,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(a,pe.RELIABLE);let c=0;const u=this,l=new WritableStream({write(f){return S(this,void 0,void 0,function*(){for(const p of JF(f,R0)){yield u.engine.waitForBufferStatusLow(pe.RELIABLE);const g=new rl({content:p,streamId:i,chunkIndex:qr(c)}),v=new Dt({destinationIdentities:o,value:{case:"streamChunk",value:g}});yield u.engine.sendDataPacket(v,pe.RELIABLE),c+=1}})},close(){return S(this,void 0,void 0,function*(){const f=new il({streamId:i}),p=new Dt({destinationIdentities:o,value:{case:"streamTrailer",value:f}});yield u.engine.sendDataPacket(p,pe.RELIABLE)})},abort(f){console.log("Sink error:",f)}});let d=()=>S(this,void 0,void 0,function*(){yield h.close()});u.engine.once(D.Closing,d);const h=new Lx(l,A,()=>this.engine.off(D.Closing,d));return h})}sendFile(e,t){return S(this,void 0,void 0,function*(){const r=crypto.randomUUID();return yield this._sendFile(r,e,t),{id:r}})}_sendFile(e,t,r){return S(this,void 0,void 0,function*(){var i;const A=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(i=r==null?void 0:r.mimeType)!==null&&i!==void 0?i:t.type,topic:r==null?void 0:r.topic,destinationIdentities:r==null?void 0:r.destinationIdentities}),s=t.stream().getReader();for(;;){const{done:o,value:a}=yield s.read();if(o)break;yield A.write(a)}return yield A.close(),A.info})}streamBytes(e){return S(this,void 0,void 0,function*(){var t,r,i,A,s;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a=e==null?void 0:e.destinationIdentities,c={id:o,mimeType:(r=e==null?void 0:e.mimeType)!==null&&r!==void 0?r:"application/octet-stream",topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(A=e==null?void 0:e.name)!==null&&A!==void 0?A:"unknown"},u=new nl({totalLength:qr((s=c.size)!==null&&s!==void 0?s:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:qr(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Gm({name:c.name})}}),l=new Dt({destinationIdentities:a,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(l,pe.RELIABLE);let d=0;const h=new Mt,f=this.engine,p=this.log,g=new WritableStream({write(y){return S(this,void 0,void 0,function*(){const B=yield h.lock();let b=0;try{for(;b<y.byteLength;){const w=y.slice(b,b+R0);yield f.waitForBufferStatusLow(pe.RELIABLE);const _=new Dt({destinationIdentities:a,value:{case:"streamChunk",value:new rl({content:w,streamId:o,chunkIndex:qr(d)})}});yield f.sendDataPacket(_,pe.RELIABLE),d+=1,b+=w.byteLength}}finally{B()}})},close(){return S(this,void 0,void 0,function*(){const y=new il({streamId:o}),B=new Dt({destinationIdentities:a,value:{case:"streamTrailer",value:y}});yield f.sendDataPacket(B,pe.RELIABLE)})},abort(y){p.error("Sink error:",y)}});return new Dx(g,c)})}performRpc(e){return S(this,arguments,void 0,function(t){var r=this;let{destinationIdentity:i,method:A,payload:s,responseTimeout:o=1e4}=t;return function*(){return new Promise((c,u)=>S(r,void 0,void 0,function*(){var l,d,h,f;if($l(s)>w0){u(Ze.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((d=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||d===void 0)&&d.version&&Wr((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){u(Ze.builtIn("UNSUPPORTED_SERVER"));return}const p=crypto.randomUUID();yield this.publishRpcRequest(i,p,A,s,o-2e3);const g=setTimeout(()=>{this.pendingAcks.delete(p),u(Ze.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),u(Ze.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(p,{resolve:(y,B)=>{clearTimeout(v),this.pendingAcks.has(p)&&(console.warn("RPC response received before ack",p),this.pendingAcks.delete(p),clearTimeout(g)),B?u(B):c(y??"")},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,r){const i=this.pendingResponses.get(e);i?(i.resolve(t,r),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,r,i,A){return S(this,void 0,void 0,function*(){const s=new Dt({destinationIdentities:[e],kind:pe.RELIABLE,value:{case:"rpcRequest",value:new Qm({id:t,method:r,payload:i,responseTimeoutMs:A,version:1})}});yield this.engine.sendDataPacket(s,pe.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:r}]of this.pendingAcks)r===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:r,resolve:i}]of this.pendingResponses)r===e&&(i(null,Ze.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 r,i;const A=this.trackPublications.get(t.sid);if(A){const s=A.isMuted||((i=(r=A.track)===null||r===void 0?void 0:r.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),_e(A)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(t.sid,s))}}),!0):!1}getPublicationForTrack(e){let t;return this.trackPublications.forEach(r=>{const i=r.track;i&&(e instanceof MediaStreamTrack?(Jr(i)||gr(i))&&i.mediaStreamTrack===e&&(t=r):e===i&&(t=r))}),t}waitForPendingPublicationOfSource(e){return S(this,void 0,void 0,function*(){const r=Date.now();for(;Date.now()<r+1e4;){const i=Array.from(this.pendingPublishPromises.entries()).find(A=>{let[s]=A;return s.source===e});if(i)return i[1];yield Nt(20)}})}}class Jx extends Hn{constructor(e,t,r,i){super(e,t.sid,t.name,i),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Yt.HIGH,this.handleEnded=A=>{this.setTrack(void 0),this.emit(L.Ended,A)},this.handleVisibilityChange=A=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(A),this.logContext),this.disabled=!A,this.emitTrackUpdate()},this.handleVideoDimensionsChange=A=>{this.log.debug("adaptivestream video dimensions ".concat(A.width,"x").concat(A.height),this.logContext),this.videoDimensions=A,this.emitTrackUpdate()},this.subscribed=r,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,r=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const i=new Go({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Mm({participantSid:"",trackSids:[this.trackSid]})]});this.emit(L.UpdateSubscription,i),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(r)}get subscriptionStatus(){return this.subscribed===!1?Hn.SubscriptionStatus.Unsubscribed:super.isSubscribed?Hn.SubscriptionStatus.Subscribed:Hn.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Hn.PermissionStatus.Allowed:Hn.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,r;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((r=this.videoDimensions)===null||r===void 0?void 0:r.height)===e.height||(Hl(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Hl(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,r=this.permissionStatus,i=this.track;i!==e&&(i&&(i.off(L.VideoDimensionsChanged,this.handleVideoDimensionsChange),i.off(L.VisibilityChanged,this.handleVisibilityChange),i.off(L.Ended,this.handleEnded),i.detach(),i.stopMonitor(),this.emit(L.Unsubscribed,i)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(L.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(L.VisibilityChanged,this.handleVisibilityChange),e.on(L.Ended,this.handleEnded),this.emit(L.Subscribed,e)),this.emitPermissionUpdateIfChanged(r),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,r=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(r),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(L.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?L.Muted:L.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(L.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(L.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===R.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 Hl(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Wm({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=Yt.HIGH,this.emit(L.UpdateSettings,e)}}class da extends Q0{static fromParticipantInfo(e,t,r){return new da(e,t.sid,t.identity,t.name,t.metadata,t.attributes,r,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,r,i,A,s,o){let a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Vo.STANDARD;super(t,r||"",i,A,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(L.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),_e(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(L.UpdateSubscription,t=>{t.participantTracks.forEach(r=>{r.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(L.SubscriptionPermissionChanged,t=>{this.emit(K.TrackSubscriptionPermissionChanged,e,t)}),e.on(L.SubscriptionStatusChanged,t=>{this.emit(K.TrackSubscriptionStatusChanged,e,t)}),e.on(L.Subscribed,t=>{this.emit(K.TrackSubscribed,t,e)}),e.on(L.Unsubscribed,t=>{this.emit(K.TrackUnsubscribed,t,e)}),e.on(L.SubscriptionFailed,t=>{this.emit(K.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]:R.Source.Microphone;this.volumeMap.set(t,e);const r=this.getTrackPublication(t);r&&r.track&&r.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:R.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,r,i,A,s){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(u=>{!o&&e.kind===u.kind.toString()&&(o=u)}),!o){if(s===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(K.TrackSubscriptionFailed,t);return}s===void 0&&(s=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,r,i,A,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),_e(o))),this.emit(K.TrackSubscriptionFailed,t);return}const a=e.kind==="video";let c;return a?c=new Hx(e,t,i,A):c=new Nx(e,t,i,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(r),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&Nl(c)&&Nn(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,r=new Map;return e.tracks.forEach(i=>{var A,s;let o=this.getTrackPublicationBySid(i.sid);if(o)o.updateInfo(i);else{const a=R.kindFromProto(i.type);if(!a)return;o=new Jx(a,i,(A=this.signalClient.connectOptions)===null||A===void 0?void 0:A.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(s=this.loggerOptions)===null||s===void 0?void 0:s.loggerName}),o.updateInfo(i),r.set(i.sid,o);const c=Array.from(this.trackPublications.values()).find(u=>u.source===(o==null?void 0:o.source));c&&o.source!==R.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:_e(c),newTrack:_e(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),_e(i))),this.unpublishTrack(i.trackSid,!0))}),r.forEach(i=>{this.emit(K.TrackPublished,i)}),!0}unpublishTrack(e,t){const r=this.trackPublications.get(e);if(!r)return;const{track:i}=r;switch(i&&(i.stop(),r.setTrack(void 0)),this.trackPublications.delete(e),r.kind){case R.Kind.Audio:this.audioTrackPublications.delete(e);break;case R.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(K.TrackUnpublished,r)}setAudioOutput(e){return S(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(r=>{var i;Nn(r.track)&&Nl(r.track)&&t.push(r.track.setSinkId((i=e.deviceId)!==null&&i!==void 0?i:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:r})),super.emit(e,...r)}}var fe;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(fe||(fe={}));const zx=4*1e3;class Li extends Sn.EventEmitter{constructor(e){var t,r,i,A;if(super(),t=this,this.state=fe.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ue,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)=>S(this,void 0,void 0,function*(){var c;if(!OF())throw kn()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const u=yield this.disconnectLock.lock();if(this.state===fe.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(fe.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==s&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Rl(new URL(s))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Ad(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 l=(h,f,p)=>S(this,void 0,void 0,function*(){var g,v;this.abortController&&this.abortController.abort();const y=new AbortController;this.abortController=y,u==null||u();try{yield this.attemptConnection(p??s,o,a,y),this.abortController=void 0,h()}catch(B){if(this.regionUrlProvider&&B instanceof Fe&&B.reason!==de.Cancelled&&B.reason!==de.NotAllowed){let b=null;try{b=yield this.regionUrlProvider.getNextBestRegionUrl((g=this.abortController)===null||g===void 0?void 0:g.signal)}catch(w){if(w instanceof Fe&&(w.status===401||w.reason===de.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),f(w);return}}b&&!(!((v=this.abortController)===null||v===void 0)&&v.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(B.message,". Retrying with another region: ").concat(b),this.logContext),this.recreateEngine(),yield l(h,f,b)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,r0(B)),f(B))}else{let b=sn.UNKNOWN_REASON;B instanceof Fe&&(b=r0(B)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,b),f(B)}}}),d=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ll((h,f)=>{l(h,f,d)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(s,o,a,c,u,l)=>S(this,void 0,void 0,function*(){var d,h,f;const p=yield a.join(s,o,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},l.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[y,B]=v;return"".concat(y,": ").concat(B)}).join(", ")),{room:(d=p.room)===null||d===void 0?void 0:d.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 bF("unknown server version");return g.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.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)=>S(this,void 0,void 0,function*(){var u,l;this.state===fe.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((l=this.regionUrlProvider)===null||l===void 0)&&l.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Zl),a),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const d=yield this.connectSignal(s,o,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(d),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected)}catch(d){yield this.engine.close(),this.recreateEngine();const h=new Fe("could not establish signal connection",de.ServerUnreachable);throw d instanceof Error&&(h.message="".concat(h.message,": ").concat(d.message)),d instanceof Fe&&(h.reason=d.reason,h.status=d.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:d})),h}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new Fe("Connection attempt aborted",de.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(d){throw yield this.engine.close(),this.recreateEngine(),d}Ht()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ht()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(fe.Connected),this.emit(O.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 S(t,[...o],void 0,function(){var c=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var l,d,h,f;const p=yield c.disconnectLock.lock();try{if(c.state===fe.Disconnected){c.log.debug("already disconnected",c.logContext);return}c.log.info("disconnect from room",Object.assign({},c.logContext)),(c.state===fe.Connecting||c.state===fe.Reconnecting||c.isResuming)&&(c.log.warn("abort connection attempt",c.logContext),(l=c.abortController)===null||l===void 0||l.abort(),(h=(d=c.connectFuture)===null||d===void 0?void 0:d.reject)===null||h===void 0||h.call(d,new Fe("Client initiated disconnect",de.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(u,sn.CLIENT_INITIATED),c.engine=void 0}finally{p()}}()})},this.onPageLeave=()=>S(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>S(this,void 0,void 0,function*(){const s=[],o=un();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 u=Ml();u.enabled=!0;const l=new MediaStream([u]);c.srcObject=l,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:l,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(O.Disconnected,()=>{c==null||c.remove(),c=null})}s.push(c)}this.remoteParticipants.forEach(a=>{a.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(u=>{s.push(u)})})});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=()=>S(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(u=>{s.includes(u)||s.push(u)})});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(fe.Reconnecting)&&this.emit(O.Reconnecting)},this.handleSignalRestarted=s=>S(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(fe.Connected),this.emit(O.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===Ei.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 u=this.getRemoteParticipantBySid(c.sid);u&&(u.audioLevel=c.level,u.setIsSpeaking(!0),o.push(u))}}),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(O.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=s=>{const o=new Map;this.activeSpeakers.forEach(c=>{const u=this.remoteParticipants.get(c.identity);u&&u.sid!==c.sid||o.set(c.sid,c)}),s.forEach(c=>{let u=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=c.level,u.setIsSpeaking(c.active),c.active?o.set(c.sid,u):o.delete(c.sid))});const a=Array.from(o.values());a.sort((c,u)=>u.audioLevel-c.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(O.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 u=R.streamStateFromProto(o.state);u!==c.track.streamState&&(c.track.streamState=u,a.emit(K.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(O.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(O.DataReceived,o.payload,s,a,o.topic),s==null||s.emit(K.DataReceived,o.payload,a)},this.handleSipDtmf=(s,o)=>{this.emit(O.SipDTMFReceived,o,s),s==null||s.emit(K.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==null?void 0:a.trackPublications.get(o.trackId),u=GF(o,this.transcriptionReceivedTimes);c==null||c.emit(L.TranscriptionReceived,u),a==null||a.emit(K.TranscriptionReceived,u,c),this.emit(O.TranscriptionReceived,u,a,c)},this.handleChatMessage=(s,o)=>{const a=jF(o);this.emit(O.ChatMessage,a,s)},this.handleMetrics=(s,o)=>{this.emit(O.MetricsReceived,s,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(O.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(O.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(O.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(O.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>S(this,void 0,void 0,function*(){var s,o,a;const c=ft.getInstance().previousDevices,u=yield ft.getInstance().getDevices(void 0,!1),l=un();if((l==null?void 0:l.name)==="Chrome"&&l.os!=="iOS")for(let h of u){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(O.ActiveDeviceChanged,h.kind,h.deviceId)}const d=["audiooutput","audioinput","videoinput"];for(let h of d){const f=zF(h),p=this.localParticipant.getTrackPublication(f);if(p&&(!((s=p.track)===null||s===void 0)&&s.isUserProvided))continue;const g=u.filter(y=>y.kind===h),v=this.getActiveDevice(h);if(v===((o=c.filter(y=>y.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"&&!pr()||h==="videoinput"||g.length>0&&!g.find(y=>y.deviceId===this.getActiveDevice(h))&&(yield this.switchActiveDevice(h,g[0].deviceId))}this.emit(O.MediaDevicesChanged)}),this.handleRoomUpdate=s=>{const o=this.roomInfo;this.roomInfo=s,o&&o.metadata!==s.metadata&&this.emitWhenConnected(O.RoomMetadataChanged,s.metadata),(o==null?void 0:o.activeRecording)!==s.activeRecording&&this.emitWhenConnected(O.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(O.ParticipantMetadataChanged,s,this.localParticipant)},this.onLocalParticipantNameChanged=s=>{this.emit(O.ParticipantNameChanged,s,this.localParticipant)},this.onLocalAttributesChanged=s=>{this.emit(O.ParticipantAttributesChanged,s,this.localParticipant)},this.onLocalTrackMuted=s=>{this.emit(O.TrackMuted,s,this.localParticipant)},this.onLocalTrackUnmuted=s=>{this.emit(O.TrackUnmuted,s,this.localParticipant)},this.onTrackProcessorUpdate=s=>{var o;(o=s==null?void 0:s.onPublish)===null||o===void 0||o.call(s,this)},this.onLocalTrackPublished=s=>S(this,void 0,void 0,function*(){var o,a,c,u,l,d;(o=s.track)===null||o===void 0||o.on(L.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.on(L.Restarted,this.onLocalTrackRestarted),(l=(u=(c=s.track)===null||c===void 0?void 0:c.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||l===void 0||l.call(u,this),this.emit(O.LocalTrackPublished,s,this.localParticipant),Jr(s.track)&&(yield s.track.checkForSilence())&&this.emit(O.LocalAudioSilenceDetected,s);const h=yield(d=s.track)===null||d===void 0?void 0:d.getDeviceId(!1),f=o0(s.source);f&&h&&h!==this.localParticipant.activeDeviceMap.get(f)&&(this.localParticipant.activeDeviceMap.set(f,h),this.emit(O.ActiveDeviceChanged,f,h))}),this.onLocalTrackUnpublished=s=>{var o,a;(o=s.track)===null||o===void 0||o.off(L.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.off(L.Restarted,this.onLocalTrackRestarted),this.emit(O.LocalTrackUnpublished,s,this.localParticipant)},this.onLocalTrackRestarted=s=>S(this,void 0,void 0,function*(){const o=yield s.getDeviceId(!1),a=o0(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(O.ActiveDeviceChanged,a,o))}),this.onLocalConnectionQualityChanged=s=>{this.emit(O.ConnectionQualityChanged,s,this.localParticipant)},this.onMediaDevicesError=s=>{this.emit(O.MediaDevicesError,s)},this.onLocalParticipantPermissionsChanged=s=>{this.emit(O.ParticipantPermissionsChanged,s,this.localParticipant)},this.onLocalChatMessageSent=s=>{this.emit(O.ChatMessage,s,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},gx),e),this.log=Ln((r=this.options.loggerName)!==null&&r!==void 0?r:cn.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},v0),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},y0),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},fx),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Mt,this.localParticipant=new qx("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",fr(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",fr(this.options.audioCaptureDefaults.deviceId)),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&this.switchActiveDevice("audiooutput",fr(this.options.audioOutput.deviceId)).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),Ht()){const s=new AbortController;(A=navigator.mediaDevices)===null||A===void 0||A.addEventListener("devicechange",this.handleDeviceChange,{signal:s.signal}),Li.cleanupRegistry&&Li.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,r,i,A,s){return S(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),s!==1){yield this.engine.publishRpcResponse(e,t,null,Ze.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(r);if(!o){yield this.engine.publishRpcResponse(e,t,null,Ze.builtIn("UNSUPPORTED_METHOD"));return}let a=null,c=null;try{const u=yield o({requestId:t,callerIdentity:e,payload:i,responseTimeout:A});$l(u)>w0?(a=Ze.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(r))):c=u}catch(u){u instanceof Ze?a=u:(console.warn("Uncaught error returned by RPC handler for ".concat(r,". Returning APPLICATION_ERROR instead."),u),a=Ze.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)})}setE2EEEnabled(e){return S(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 tx(this.options.e2ee),this.e2eeManager.on(dr.ParticipantEncryptionStatusChanged,(t,r)=>{qF(r)&&(this.isE2EEEnabled=t),this.emit(O.ParticipantEncryptionStatusChanged,t,r)}),this.e2eeManager.on(dr.EncryptionError,t=>this.emit(O.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 S(this,void 0,void 0,function*(){return this.state===fe.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const r=i=>{i.sid!==""&&(this.engine.off(D.RoomUpdate,r),e(i.sid))};this.engine.on(D.RoomUpdate,r),this.once(O.Disconnected,()=>{this.engine.off(D.RoomUpdate,r),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 xx(this.options),this.engine.on(D.ParticipantUpdate,this.handleParticipantUpdates).on(D.RoomUpdate,this.handleRoomUpdate).on(D.SpeakersChanged,this.handleSpeakersChanged).on(D.StreamStateChanged,this.handleStreamStateUpdate).on(D.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(D.SubscriptionError,this.handleSubscriptionError).on(D.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(D.MediaTrackAdded,(e,t,r)=>{this.onTrackAdded(e,t,r)}).on(D.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(D.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(D.DataPacketReceived,this.handleDataPacket).on(D.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(fe.SignalReconnecting)&&this.emit(O.SignalReconnecting)}).on(D.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(fe.Connected)&&this.emit(O.Reconnected)}).on(D.SignalResumed,()=>{this.bufferedEvents=[],(this.state===fe.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(D.Restarting,this.handleRestarting).on(D.SignalRestarted,this.handleSignalRestarted).on(D.Offline,()=>{this.setAndEmitConnectionState(fe.Reconnecting)&&this.emit(O.Reconnecting)}).on(D.DCBufferStatusChanged,(e,t)=>{this.emit(O.DCBufferStatusChanged,e,t)}).on(D.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(r=>{let{trackSid:i}=r;return i===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(K.LocalTrackSubscribed,t),this.emitWhenConnected(O.LocalTrackSubscribed,t,this.localParticipant)}).on(D.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,r)=>{this.handleParticipantDisconnected(r,t)}),this.emit(O.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 ft.getInstance().getDevices(e,t)}prepareConnection(e,t){return S(this,void 0,void 0,function*(){if(this.state===fe.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Rl(new URL(e))&&t){this.regionUrlProvider=new Ad(e,t);const r=yield this.regionUrlProvider.getNextBestRegionUrl();r&&this.state===fe.Disconnected&&(this.regionUrl=r,yield fetch(Dl(r),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(r),this.logContext))}else yield fetch(Dl(e),{method:"HEAD"})}catch(r){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:r}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return S(this,void 0,void 0,function*(){let r=()=>{},i;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new _n({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new _n({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new _n({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new _n({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":r=()=>S(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new _n({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":r=()=>S(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new _n({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 _n({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),r=()=>S(this,void 0,void 0,function*(){const A=this.engine.client.onLeave;A&&A(new jo({reason:sn.CLIENT_INITIATED,action:Ti.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");i=new _n({scenario:{case:"subscriberBandwidth",value:qr(t)}});break;case"leave-full-reconnect":i=new _n({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield r())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,a,c,u,l,d,h,f;let p=!0,g=!1;const v=s?{exact:i}:i;if(r==="audioinput"){g=A.localParticipant.audioTrackPublications.size===0;const y=(o=A.getActiveDevice(r))!==null&&o!==void 0?o:A.options.audioCaptureDefaults.deviceId;A.options.audioCaptureDefaults.deviceId=v;const B=Array.from(A.localParticipant.audioTrackPublications.values()).filter(b=>b.source===R.Source.Microphone);try{p=(yield Promise.all(B.map(b=>{var w;return(w=b.audioTrack)===null||w===void 0?void 0:w.setDeviceId(v)}))).every(b=>b===!0)}catch(b){throw A.options.audioCaptureDefaults.deviceId=y,b}}else if(r==="videoinput"){g=A.localParticipant.videoTrackPublications.size===0;const y=(a=A.getActiveDevice(r))!==null&&a!==void 0?a:A.options.videoCaptureDefaults.deviceId;A.options.videoCaptureDefaults.deviceId=v;const B=Array.from(A.localParticipant.videoTrackPublications.values()).filter(b=>b.source===R.Source.Camera);try{p=(yield Promise.all(B.map(b=>{var w;return(w=b.videoTrack)===null||w===void 0?void 0:w.setDeviceId(v)}))).every(b=>b===!0)}catch(b){throw A.options.videoCaptureDefaults.deviceId=y,b}}else if(r==="audiooutput"){if(!Ql()&&!A.options.webAudioMix||A.options.webAudioMix&&A.audioContext&&!("setSinkId"in A.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");A.options.webAudioMix&&(i=(c=yield ft.getInstance().normalizeDeviceId("audiooutput",i))!==null&&c!==void 0?c:""),(u=(f=A.options).audioOutput)!==null&&u!==void 0||(f.audioOutput={});const y=(l=A.getActiveDevice(r))!==null&&l!==void 0?l:A.options.audioOutput.deviceId;A.options.audioOutput.deviceId=i;try{A.options.webAudioMix&&((d=A.audioContext)===null||d===void 0||d.setSinkId(i)),yield Promise.all(Array.from(A.remoteParticipants.values()).map(B=>B.setAudioOutput({deviceId:i})))}catch(B){throw A.options.audioOutput.deviceId=y,B}}return(g||r==="audiooutput")&&(A.localParticipant.activeDeviceMap.set(r,r==="audiooutput"&&((h=A.options.audioOutput)===null||h===void 0?void 0:h.deviceId)||i),A.emit(O.ActiveDeviceChanged,r,i)),p}()})}setupLocalParticipantEvents(){this.localParticipant.on(K.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(K.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(K.AttributesChanged,this.onLocalAttributesChanged).on(K.TrackMuted,this.onLocalTrackMuted).on(K.TrackUnmuted,this.onLocalTrackUnmuted).on(K.LocalTrackPublished,this.onLocalTrackPublished).on(K.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(K.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(K.MediaDevicesError,this.onMediaDevicesError).on(K.AudioStreamAcquired,this.startAudio).on(K.ChatMessage,this.onLocalChatMessageSent).on(K.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,r){if(this.state===fe.Connecting||this.state===fe.Reconnecting){const u=()=>{this.onTrackAdded(e,t,r),l()},l=()=>{this.off(O.Reconnected,u),this.off(O.Connected,u),this.off(O.Disconnected,l)};this.once(O.Reconnected,u),this.once(O.Connected,u),this.once(O.Disconnected,l);return}if(this.state===fe.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=QF(t.id),A=i[0];let s=i[1],o=e.id;if(s&&s.startsWith("TR")&&(o=s),A===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const a=Array.from(this.remoteParticipants.values()).find(u=>u.sid===A);if(!a){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(A),this.logContext);return}let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={}),a.addSubscribedMediaTrack(e,o,t,r,c)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==fe.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(i=>{i.trackPublications.forEach(A=>{i.unpublishTrack(A.trackSid)})}),this.localParticipant.trackPublications.forEach(i=>{var A,s,o;i.track&&this.localParticipant.unpublishTrack(i.track,e),e?((A=i.track)===null||A===void 0||A.detach(),(s=i.track)===null||s===void 0||s.stop()):(o=i.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(K.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(K.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(K.AttributesChanged,this.onLocalAttributesChanged).off(K.TrackMuted,this.onLocalTrackMuted).off(K.TrackUnmuted,this.onLocalTrackUnmuted).off(K.LocalTrackPublished,this.onLocalTrackPublished).off(K.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(K.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(K.MediaDevicesError,this.onMediaDevicesError).off(K.AudioStreamAcquired,this.startAudio).off(K.ChatMessage,this.onLocalChatMessageSent).off(K.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),Ht()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(r=navigator.mediaDevices)===null||r===void 0||r.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(fe.Disconnected),this.emit(O.Disconnected,t)}}}handleParticipantDisconnected(e,t){var r;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(i=>{t.unpublishTrack(i.trackSid,!0)}),this.emit(O.ParticipantDisconnected,t),t.setDisconnected(),(r=this.localParticipant)===null||r===void 0||r.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return S(this,void 0,void 0,function*(){var r;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 A;const s={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:ia(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{A=a,this.byteStreamControllers.set(e.streamId,{info:s,controller:A,startTime:Date.now()})}});i(new Ox(s,o,ia(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 A;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=>{A=a,this.textStreamControllers.set(e.streamId,{info:s,controller:A,startTime:Date.now()})}});i(new Mx(s,o,ia(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const r=this.textStreamControllers.get(e.streamId);r&&e.content.length>0&&r.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 r=this.byteStreamControllers.get(e.streamId);r&&(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return S(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=s0())!==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(),Nt(200)])}catch(i){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:i}))}const r=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";r!==this.canPlaybackAudio&&(this.audioEnabled=r,this.emit(O.AudioPlaybackStatusChanged,r))})}createParticipant(e,t){var r;let i;return t?i=da.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):i=new da(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&i.setAudioOutput(this.options.audioOutput).catch(A=>this.log.warn("Could not set audio output: ".concat(A.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 r=this.createParticipant(e,t);return this.remoteParticipants.set(e,r),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(O.ParticipantConnected,r),r.on(K.TrackPublished,i=>{this.emitWhenConnected(O.TrackPublished,i,r)}).on(K.TrackSubscribed,(i,A)=>{i.kind===R.Kind.Audio?(i.on(L.AudioPlaybackStarted,this.handleAudioPlaybackStarted),i.on(L.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):i.kind===R.Kind.Video&&(i.on(L.VideoPlaybackFailed,this.handleVideoPlaybackFailed),i.on(L.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(O.TrackSubscribed,i,A,r)}).on(K.TrackUnpublished,i=>{this.emit(O.TrackUnpublished,i,r)}).on(K.TrackUnsubscribed,(i,A)=>{this.emit(O.TrackUnsubscribed,i,A,r)}).on(K.TrackMuted,i=>{this.emitWhenConnected(O.TrackMuted,i,r)}).on(K.TrackUnmuted,i=>{this.emitWhenConnected(O.TrackUnmuted,i,r)}).on(K.ParticipantMetadataChanged,i=>{this.emitWhenConnected(O.ParticipantMetadataChanged,i,r)}).on(K.ParticipantNameChanged,i=>{this.emitWhenConnected(O.ParticipantNameChanged,i,r)}).on(K.AttributesChanged,i=>{this.emitWhenConnected(O.ParticipantAttributesChanged,i,r)}).on(K.ConnectionQualityChanged,i=>{this.emitWhenConnected(O.ConnectionQualityChanged,i,r)}).on(K.ParticipantPermissionsChanged,i=>{this.emitWhenConnected(O.ParticipantPermissionsChanged,i,r)}).on(K.TrackSubscriptionStatusChanged,(i,A)=>{this.emitWhenConnected(O.TrackSubscriptionStatusChanged,i,A,r)}).on(K.TrackSubscriptionFailed,(i,A)=>{this.emit(O.TrackSubscriptionFailed,i,r,A)}).on(K.TrackSubscriptionPermissionChanged,(i,A)=>{this.emitWhenConnected(O.TrackSubscriptionPermissionChanged,i,A,r)}).on(K.Active,()=>{this.emitWhenConnected(O.ParticipantActive,r)}),t&&r.updateInfo(t),r}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((r,i)=>(r.push(...i.getTrackPublications()),r),[]),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&&WF(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=wt.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,sn.STATE_MISMATCH))):e=0},zx)}clearConnectionReconcile(){this.connectionReconcileInterval&&wt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(O.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,r]=e;this.emit(t,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];if(this.state===fe.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,r]);else if(this.state===fe.Connected)return this.emit(e,...r);return!1}simulateParticipants(e){return S(this,void 0,void 0,function*(){var t,r;const i=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),A=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Ho({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Ke.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Kr({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected),this.emit(O.Connected),this.setAndEmitConnectionState(fe.Connected),i.video){const s=new ad(R.Kind.Video,new Ui({source:at.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:An.AUDIO,name:"video-dummy"}),new ua(i.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:n0(160*((t=A.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(K.LocalTrackPublished,s)}if(i.audio){const s=new ad(R.Kind.Audio,new Ui({source:at.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:An.AUDIO}),new aa(i.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ml(),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(K.LocalTrackPublished,s)}for(let s=0;s<A.count-1;s+=1){let o=new Kr({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(s),state:Ei.ACTIVE,tracks:[],joinedAt:Ke.parse(Date.now())});const a=this.getOrCreateParticipant(o.identity,o);if(A.video){const c=n0(160*((r=A.aspectRatios[s%A.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),u=new Ui({source:at.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:An.AUDIO});a.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}if(A.audio){const c=Ml(),u=new Ui({source:at.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:An.AUDIO});a.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}a.updateInfo(o)}})}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];if(e!==O.ActiveSpeakersChanged&&e!==O.TranscriptionReceived){const A=P0(r).filter(s=>s!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:A}))}return super.emit(e,...r)}}Li.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function P0(n){return n.map(e=>{if(e)return Array.isArray(e)?P0(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var hn;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(hn||(hn={}));class yr extends Sn.EventEmitter{constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=hn.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Li(r.roomOptions),this.connectOptions=r.connectOptions,this.options=r}run(e){return S(this,void 0,void 0,function*(){if(this.status!==hn.IDLE)throw Error("check is running already");this.setStatus(hn.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!==hn.SKIPPED&&this.setStatus(this.isSuccess()?hn.SUCCESS:hn.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return S(this,void 0,void 0,function*(){return this.room.state===fe.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return S(this,void 0,void 0,function*(){this.room&&this.room.state!==fe.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(hn.SKIPPED)}switchProtocol(e){return S(this,void 0,void 0,function*(){let t=!1,r=!1;if(this.room.on(O.Reconnecting,()=>{t=!0}),this.room.once(O.Reconnected,()=>{r=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(A=>setTimeout(A,1e3)),!t)return;const i=Date.now()+1e4;for(;Date.now()<i;){if(r)return;yield Nt(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 Xx extends yr{get description(){return"Cloud regions"}perform(){return S(this,void 0,void 0,function*(){const e=new Ad(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],r=new Set;for(let A=0;A<3;A++){const s=yield e.getNextBestRegionUrl();if(!s)break;if(r.has(s))continue;r.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((A,s)=>(A.duration-s.duration)*.5+(A.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 S(this,void 0,void 0,function*(){var t,r;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 A=yield this.room.localParticipant.streamText({topic:"test"}),s=1e3,a=1e6/s,c="A".repeat(s),u=Date.now();for(let f=0;f<a;f++)yield A.write(c);yield A.close();const l=Date.now(),d=yield(r=this.room.engine.pcManager)===null||r===void 0?void 0:r.publisher.getStats(),h={region:i,rtt:1e4,duration:l-u};return d==null||d.forEach(f=>{f.type==="candidate-pair"&&f.nominated&&(h.rtt=f.currentRoundTripTime*1e3)}),yield this.disconnect(),h})}}const cd=1e4;class Yx extends yr{get description(){return"Connection via UDP vs TCP"}perform(){return S(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 r=this.bestStats;this.appendMessage("upstream bitrate: ".concat((r.bitrateTotal/r.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((r.rttTotal/r.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((r.jitterTotal/r.count*1e3).toFixed(2)," ms")),r.packetsLost>0&&this.appendWarning("packets lost: ".concat((r.packetsLost/r.packetsSent*100).toFixed(2),"%")),r.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((r.qualityLimitationDurations.bandwidth/(cd/1e3)*100).toFixed(2),"%")),r.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((r.qualityLimitationDurations.cpu/(cd/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return S(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 r=t.getContext("2d");if(!r)throw new Error("Could not get canvas context");let i=0;const A=()=>{i=(i+1)%360,r.fillStyle="hsl(".concat(i,", 100%, 50%)"),r.fillRect(0,0,t.width,t.height),requestAnimationFrame(A)};A();const o=t.captureStream(30).getVideoTracks()[0],c=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,u={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},l=setInterval(()=>S(this,void 0,void 0,function*(){const d=yield c.getRTCStatsReport();d==null||d.forEach(h=>{h.type==="outbound-rtp"?(u.packetsSent=h.packetsSent,u.qualityLimitationDurations=h.qualityLimitationDurations,u.bitrateTotal+=h.targetBitrate,u.count++):h.type==="remote-inbound-rtp"&&(u.packetsLost=h.packetsLost,u.rttTotal+=h.roundTripTime,u.jitterTotal+=h.jitter)})}),1e3);return yield new Promise(d=>setTimeout(d,cd)),clearInterval(l),o.stop(),t.remove(),yield this.disconnect(),u})}}class Zx extends yr{get description(){return"Can publish audio"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect(),r=yield Gx();if(yield A0(r,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(r),yield new Promise(o=>setTimeout(o,3e3));const A=yield(e=r.sender)===null||e===void 0?void 0:e.getStats();if(!A)throw new Error("Could not get RTCStats");let s=0;if(A.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 $x extends yr{get description(){return"Can publish video"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect(),r=yield Vx();yield this.checkForVideo(r.mediaStreamTrack),t.localParticipant.publishTrack(r),yield new Promise(s=>setTimeout(s,5e3));const i=yield(e=r.sender)===null||e===void 0?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let A=0;if(i.forEach(s=>{s.type==="outbound-rtp"&&(s.kind==="video"||!s.kind&&s.mediaType==="video")&&(A+=s.packetsSent)}),A===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(A," video packets"))})}checkForVideo(e){return S(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const r=document.createElement("video");r.srcObject=t,r.muted=!0,yield new Promise(i=>{r.onplay=()=>{setTimeout(()=>{var A,s,o,a;const c=document.createElement("canvas"),u=e.getSettings(),l=(s=(A=u.width)!==null&&A!==void 0?A:r.videoWidth)!==null&&s!==void 0?s:1280,d=(a=(o=u.height)!==null&&o!==void 0?o:r.videoHeight)!==null&&a!==void 0?a:720;c.width=l,c.height=d;const h=c.getContext("2d");h.drawImage(r,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)},r.play()}),r.remove()})}}class eQ extends yr{get description(){return"Resuming connection after interruption"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect();let r=!1,i=!1,A;const s=new Promise(c=>{setTimeout(c,5e3),A=c}),o=()=>{r=!0};t.on(O.SignalReconnecting,o).on(O.Reconnecting,o).on(O.Reconnected,()=>{i=!0,A(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const a=t.engine.client.onClose;if(a&&a(""),yield s,r){if(!i||t.state!==fe.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 tQ extends yr{get description(){return"Can connect via TURN"}perform(){return S(this,void 0,void 0,function*(){var e,t;const r=new jl,i=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let A=!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,A=!0),c.startsWith("stun:")&&(o=!0);o?s&&!A&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.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 nQ extends yr{get description(){return"Establishing WebRTC connection"}perform(){return S(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(O.SignalConnected,()=>{const r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,A)=>{if(i.candidate){const s=new RTCIceCandidate(i);let o="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(rQ(s.address)?o+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,o+=" (passive)"):s.protocol==="udp"&&(t=!0)),this.appendMessage(o)}r&&r(i,A)},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(),ue.info("now the room is connected")}catch(r){throw this.appendWarning("ports need to be open on firewall in order to connect."),r}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 rQ(n){const e=n.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class iQ extends yr{get description(){return"Connecting to signal connection via WebSocket"}perform(){return S(this,void 0,void 0,function*(){var e,t,r;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new jl;const A=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(A.serverVersion,".")),((e=A.serverInfo)===null||e===void 0?void 0:e.edition)===Lm.Cloud&&(!((t=A.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((r=A.serverInfo)===null||r===void 0?void 0:r.region)),yield i.close()})}}class Q4 extends Sn.EventEmitter{constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=r}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:hn.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!==hn.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return S(this,void 0,void 0,function*(){const t=this.getNextCheckId(),r=new e(this.url,this.token,this.options),i=s=>{this.updateCheck(t,s)};r.on("update",i);const A=yield r.run();return r.off("update",i),A})}checkWebsocket(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(iQ)})}checkWebRTC(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(nQ)})}checkTURN(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(tQ)})}checkReconnect(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(eQ)})}checkPublishAudio(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Zx)})}checkPublishVideo(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck($x)})}checkConnectionProtocol(){return S(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Yx);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Xx)})}}const AQ=/\{[^{}]+\}/g;function sQ(){return Math.random().toString(36).slice(2,11)}function oQ(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:r=globalThis.fetch,querySerializer:i,bodySerializer:A,headers:s,...o}={...n};e=D0(e);const a=[];async function c(u,l){const{baseUrl:d,fetch:h=r,Request:f=t,headers:p,params:g={},parseAs:v="json",querySerializer:y,bodySerializer:B=A??cQ,body:b,...w}=l||{};d&&(e=D0(d));let _=typeof i=="function"?i:L0(i);y&&(_=typeof y=="function"?y:L0({...typeof i=="object"?i:{},...y}));const k=b===void 0?void 0:B(b),T=k===void 0||k instanceof FormData?{}:{"Content-Type":"application/json"},x={redirect:"follow",...o,...w,body:k,headers:lQ(T,s,p,g.header)};let P,E,F=new t(uQ(u,{baseUrl:e,params:g,querySerializer:_}),x);for(const N in w)N in F||(F[N]=w[N]);if(a.length){P=sQ(),E=Object.freeze({baseUrl:e,fetch:h,parseAs:v,querySerializer:_,bodySerializer:B});for(const N of a)if(N&&typeof N=="object"&&typeof N.onRequest=="function"){const q=await N.onRequest({request:F,schemaPath:u,params:g,options:E,id:P});if(q){if(!(q instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");F=q}}}let M=await h(F);if(a.length)for(let N=a.length-1;N>=0;N--){const q=a[N];if(q&&typeof q=="object"&&typeof q.onResponse=="function"){const ve=await q.onResponse({request:F,response:M,schemaPath:u,params:g,options:E,id:P});if(ve){if(!(ve instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");M=ve}}}if(M.status===204||M.headers.get("Content-Length")==="0")return M.ok?{data:{},response:M}:{error:{},response:M};if(M.ok)return v==="stream"?{data:M.body,response:M}:{data:await M[v](),response:M};let J=await M.text();try{J=JSON.parse(J)}catch{}return{error:J,response:M}}return{GET(u,l){return c(u,{...l,method:"GET"})},PUT(u,l){return c(u,{...l,method:"PUT"})},POST(u,l){return c(u,{...l,method:"POST"})},DELETE(u,l){return c(u,{...l,method:"DELETE"})},OPTIONS(u,l){return c(u,{...l,method:"OPTIONS"})},HEAD(u,l){return c(u,{...l,method:"HEAD"})},PATCH(u,l){return c(u,{...l,method:"PATCH"})},TRACE(u,l){return c(u,{...l,method:"TRACE"})},use(...u){for(const l of u)if(l){if(typeof l!="object"||!("onRequest"in l||"onResponse"in l))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");a.push(l)}},eject(...u){for(const l of u){const d=a.indexOf(l);d!==-1&&a.splice(d,1)}}}}function ha(n,e,t){if(e==null)return"";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${n}=${(t==null?void 0:t.allowReserved)===!0?e:encodeURIComponent(e)}`}function O0(n,e,t){if(!e||typeof e!="object")return"";const r=[],i={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(const o in e)r.push(o,t.allowReserved===!0?e[o]:encodeURIComponent(e[o]));const s=r.join(",");switch(t.style){case"form":return`${n}=${s}`;case"label":return`.${s}`;case"matrix":return`;${n}=${s}`;default:return s}}for(const s in e){const o=t.style==="deepObject"?`${n}[${s}]`:s;r.push(ha(o,e[s],t))}const A=r.join(i);return t.style==="label"||t.style==="matrix"?`${i}${A}`:A}function M0(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){const A={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",s=(t.allowReserved===!0?e:e.map(o=>encodeURIComponent(o))).join(A);switch(t.style){case"simple":return s;case"label":return`.${s}`;case"matrix":return`;${n}=${s}`;default:return`${n}=${s}`}}const r={simple:",",label:".",matrix:";"}[t.style]||"&",i=[];for(const A of e)t.style==="simple"||t.style==="label"?i.push(t.allowReserved===!0?A:encodeURIComponent(A)):i.push(ha(n,A,t));return t.style==="label"||t.style==="matrix"?`${r}${i.join(r)}`:i.join(r)}function L0(n){return function(t){const r=[];if(t&&typeof t=="object")for(const i in t){const A=t[i];if(A!=null){if(Array.isArray(A)){if(A.length===0)continue;r.push(M0(i,A,{style:"form",explode:!0,...n==null?void 0:n.array,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}if(typeof A=="object"){r.push(O0(i,A,{style:"deepObject",explode:!0,...n==null?void 0:n.object,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}r.push(ha(i,A,n))}}return r.join("&")}}function aQ(n,e){let t=n;for(const r of n.match(AQ)??[]){let i=r.substring(1,r.length-1),A=!1,s="simple";if(i.endsWith("*")&&(A=!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(r,M0(i,o,{style:s,explode:A}));continue}if(typeof o=="object"){t=t.replace(r,O0(i,o,{style:s,explode:A}));continue}if(s==="matrix"){t=t.replace(r,`;${ha(i,o)}`);continue}t=t.replace(r,s==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function cQ(n){return n instanceof FormData?n:JSON.stringify(n)}function uQ(n,e){var i;let t=`${e.baseUrl}${n}`;(i=e.params)!=null&&i.path&&(t=aQ(t,e.params.path));let r=e.querySerializer(e.params.query??{});return r.startsWith("?")&&(r=r.substring(1)),r&&(t+=`?${r}`),t}function lQ(...n){const e=new Headers;for(const t of n){if(!t||typeof t!="object")continue;const r=t instanceof Headers?t.entries():Object.entries(t);for(const[i,A]of r)if(A===null)e.delete(i);else if(Array.isArray(A))for(const s of A)e.append(i,s);else A!==void 0&&e.set(i,A)}return e}function D0(n){return n.endsWith("/")?n.substring(0,n.length-1):n}const N0="Onboardee-Session-Token",H0="OnboardeeSessionToken";class K0{constructor(e){this.client=oQ({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch}),this.client.use({onRequest({request:t}){if(window.localStorage){const r=window.localStorage.getItem(H0);r&&t.headers.set(N0,r)}return t},onResponse({response:t}){const r=t.headers.get(N0);return r&&window.localStorage&&window.localStorage.setItem(H0,r),t}})}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 clientInitialise(e,t={}){return await this.client.POST("/api/client/{appToken}/initialise",{params:{path:{appToken:e}},body:t})}async clientStartSession(e,t){return await this.client.POST("/api/client/{appToken}/start-session",{params:{path:{appToken:e}},body:t})}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(e){return await this.client.GET("/api/plans",{params:{query:{...e&&{client_type:e}}}})}async listPlansWithStatus(){return await this.client.GET("/api/plans-with-status")}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 getProductAnalytics(e,t,r,i){return await this.client.GET("/api/products/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...r&&{end_date:r},...i&&{course_id:i}}}})}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 getProductNavigationIndex(e){return await this.client.GET("/api/products/{id}/navigation-index",{params:{path:{id:e}}})}async replaceProductNavigationIndex(e,t){return await this.client.PUT("/api/products/{id}/navigation-index",{params:{path:{id:e}},body:t})}async listProductKnowledgeBlocks(e){return await this.client.GET("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createProductKnowledgeBlock(e,t){return await this.client.POST("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async searchProductKnowledgeBlocks(e,t,r){return await this.client.GET("/api/products/{id}/knowledge-blocks/search",{params:{path:{id:e},query:{q:t,...r&&{limit:r.toString()}}}})}async updateProductKnowledgeBlock(e,t,r){return await this.client.PATCH("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deleteProductKnowledgeBlock(e,t){return await this.client.DELETE("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId: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 getAdminPlan(e){return await this.client.GET("/api/admin/plans/{id}",{params:{path:{id:e}}})}async getPlanAnalytics(e,t,r){return await this.client.GET("/api/plans/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...r&&{end_date:r}}}})}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 getPlanVideoMetadata(e){return await this.client.GET("/api/plans/{id}/video-metadata",{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 listPlanKnowledgeBlocks(e){return await this.client.GET("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createPlanKnowledgeBlock(e,t){return await this.client.POST("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async updatePlanKnowledgeBlock(e,t,r){return await this.client.PUT("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deletePlanKnowledgeBlock(e,t){return await this.client.DELETE("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async getPlanNavigationIndex(e){return await this.client.GET("/api/plans/{id}/navigation-index",{params:{path:{id:e}}})}async replacePlanNavigationIndex(e,t){return await this.client.POST("/api/plans/{id}/navigation-index",{params:{path:{id:e}},body:t})}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 getPlanFAQ(e){return await this.client.GET("/api/plans/{id}/faq",{params:{path:{id:e}}})}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,r){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deleteRevisionKnowledgeBlock(e,t){return await this.client.DELETE("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async listSessions(e,t){const r={token:e};return t!=null&&t.productId&&(r.product_id=t.productId),t!=null&&t.startDate&&(r.start_date=t.startDate),t!=null&&t.endDate&&(r.end_date=t.endDate),await this.client.GET("/api/sessions",{params:{query:r}})}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 getSessionSummary(e){return await this.client.GET("/api/sessions/{id}/summary",{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 listUserSessions(e){const t={};return e!=null&&e.productId&&(t.product_id=e.productId),e!=null&&e.courseId&&(t.course_id=e.courseId),e!=null&&e.startDate&&(t.start_date=e.startDate),e!=null&&e.endDate&&(t.end_date=e.endDate),e!=null&&e.page&&(t.page=e.page),e!=null&&e.limit&&(t.limit=e.limit),e!=null&&e.courseName&&(t.course_name=e.courseName),e!=null&&e.userName&&(t.user_name=e.userName),e!=null&&e.company&&(t.company=e.company),e!=null&&e.email&&(t.email=e.email),e!=null&&e.sortBy&&(t.sort_by=e.sortBy),e!=null&&e.sortOrder&&(t.sort_order=e.sortOrder),await this.client.GET("/api/user-sessions",{params:Object.keys(t).length>0?{query:t}:void 0})}async listUserSessionsAggregate(e){const t={};return e!=null&&e.productId&&(t.product_id=e.productId),e!=null&&e.courseId&&(t.course_id=e.courseId),e!=null&&e.startDate&&(t.start_date=e.startDate),e!=null&&e.endDate&&(t.end_date=e.endDate),await this.client.GET("/api/user-sessions-aggregate",{params:Object.keys(t).length>0?{query:t}:void 0})}async getJoinToken(e,{clientType:t,user:r}={}){return await this.client.GET("/api/join-token",{params:{query:{token:e,...t&&{client_type:t},...r&&{user:encodeURIComponent(r)}}}})}async getSessionPlan(e){return await this.client.GET("/api/sessions/{id}/plan",{params:{path:{id:e}}})}async getPlanSDK(e){return await this.client.GET("/api/plans/{uuid}/sdk",{params:{path:{uuid:e}}})}getClient(){return this.client}}const V0="https://app.coragents.ai";class pa extends jc{constructor(e,t,r,i){super(),this.state=null,this.isPaused=!1,this.speakingState=null,this.captureScreen=null,this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.room=null,this.startedAt=null,this.agentAnalyser=null,this.userAnalyser=null,this.appToken=e,this.planId=t,this.clientType=r,this.api=i.api||new K0({baseUrl:V0}),this.identity=i.identity||null,this.roomFactory=i.roomFactory||(A=>new Li(A)),this.captureScreen=i.captureScreen||null}async start(){this.planId,this.setState("connecting"),this.speakingStateChanged("thinking");try{const t=(await this.api.clientStartSession(this.appToken,{client_type:this.clientType,onboarding_plan:this.planId})).data;if(!(t!=null&&t.url)||!(t!=null&&t.token)||!(t!=null&&t.room)||!(t!=null&&t.session_uuid))throw new Error("Invalid room info");this.sessionUuid=t==null?void 0:t.session_uuid,this.roomId=t==null?void 0:t.room,this.joinToken=t==null?void 0:t.token,this.roomUrl=t==null?void 0:t.url,this.startedAt=Date.now(),await this.joinRoom(),this.setState("connected"),this.planId,this.sessionUuid}catch(e){console.error("[obi] error starting session",{error:e}),this.setState("error")}}async joinRoom({withMicrophone:e=!1,withStateRecovery:t=!1}={}){this.room=this.roomFactory({adaptiveStream:!0,dynacast:!0}),this.room.on(O.Disconnected,r=>{if(!this.room)return;let i=null;switch(r){case 12:i="invalid-room";break}this.shutdown(i)}),this.room.on(O.TrackSubscribed,r=>{r.kind==="audio"&&(r.attach(),r.source===R.Source.Microphone&&(this.agentAnalyser&&this.agentAnalyser.disconnect(),this.agentAnalyser=this.createFFT(r.mediaStream)))}),this.room.on(O.LocalTrackPublished,r=>{r.kind==="audio"&&(this.userAnalyser&&this.userAnalyser.disconnect(),this.userAnalyser=this.createFFT(r.audioTrack.mediaStream))}),this.room.on(O.ParticipantAttributesChanged,r=>{if(!r["lk.agent.state"])return;const i=r["lk.agent.state"];switch(i){case"speaking":this.speakingStateChanged("speaking");break;case"listening":this.state!=="connected"&&this.speakingStateChanged("listening");break;case"thinking":this.speakingStateChanged("thinking");break;default:console.warn("[obi] unknown speaking state",i)}}),this.room.on(O.DataReceived,async r=>{try{const i=new TextDecoder().decode(r),A=JSON.parse(i);switch(A.status||A.request||A.type){case"course_progress":typeof A.current_step=="number"&&typeof A.total_steps=="number"&&Array.isArray(A.step_names)&&this.emit("courseProgress",{currentStep:Math.max(1,A.current_step),totalSteps:Math.max(1,A.total_steps),stepNames:A.step_names});break;case"using_tool":this.speakingStateChanged("busy");break;case"using_tool_ended":this.speakingStateChanged("speaking");break;case"prompt_user":this.setState("volume-check");break;case"mic_check":this.setState("mic-check");break;case"share_mic":this.setState("mic-share");break;case"share_screen":this.setState("screen-share");break;case"navigate":this.setState("navigate");break;case"shutdown":this.shutdown("server-sent");break;default:console.warn("[obi] unknown data received",A)}}catch(i){console.error("[obi] error parsing data",i)}}),this.room.localParticipant.registerRpcMethod("mic_check",async r=>(this.sessionUuid,await this.checkMicrophone()?"ok":"error")),this.room.localParticipant.registerRpcMethod("screen_capture",async r=>{if(!this.captureScreen)return console.error("[obi] no captureScreen function provided"),"error";let i=null,A=null;try{i=await this.captureScreen()}catch(s){i=null,s=s}if(!i||A)return console.error("[obi] error capturing screen",{error:A}),"error";try{return await this.room.localParticipant.sendFile(new File([i],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),"ok"}catch(s){return console.error("[obi] error sending screen capture",{error:s}),"error"}}),await this.room.connect(this.roomUrl,this.joinToken);for(let r=0;r<9&&!(this.room.state===fe.Connected&&this.room.remoteParticipants.size>=1);r++)await new Promise(i=>setTimeout(i,1e3));if(!(this.room.state===fe.Connected&&this.room.remoteParticipants.size>=1)){console.error("[obi] room not connected",{state:this.room.state,numParticipants:this.room.remoteParticipants.size}),this.shutdown("invalid-room");return}if(e&&await this.room.localParticipant.setMicrophoneEnabled(!0),t){let r=!1;for(const i of this.room.remoteParticipants.values())i.isSpeaking&&(r=!0);r?this.speakingState="speaking":this.speakingState="listening"}}async continue(){this.sessionUuid,this.speakingStateChanged("thinking"),await this.sendData({request:"prompt_user",success:!0})}async checkMicrophone(){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?(this.sessionUuid,await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0):this.sessionUuid,e&&this.clientType==="sdk"&&this.setState("in-progress"),this.emit("micCheckComplete",e),e}async shareMicrophone(){this.sessionUuid,this.speakingStateChanged("thinking");let e=null,t=null;try{e=await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0}catch(r){r=r,this.isMicShared=!1}e?this.sessionUuid:console.error("[obi] failed to share microphone",{error:t}),await this.sendData({request:"share_mic",success:!!e}),this.clientType==="sdk"&&this.setState("in-progress")}async shareMicrophoneFailed(){this.isMicShared=!1,await this.sendData({request:"share_mic",success:!1}),this.clientType==="sdk"&&this.setState("in-progress")}async shareScreen(){this.sessionUuid,this.speakingStateChanged("thinking"),await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),await this.sendData({request:"share_screen",success:!0}),this.setState("navigate")}async pause(){this.muteMicrophone(),this.isPaused=!0,this.emit("paused"),await this.sendData({request:"pause"}),console.log("[obi] paused session",{sessionUuid:this.sessionUuid})}async unpause(){this.unmuteMicrophone(),this.isPaused=!1,this.emit("unpaused"),await this.sendData({request:"unpause"}),console.log("[obi] unpaused session",{sessionUuid:this.sessionUuid})}muteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var t,r;e.handleMuted(),(r=(t=e.track)==null?void 0:t.mediaStream)==null||r.getTracks().forEach(i=>i.enabled=!1)})}unmuteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var t,r;e.handleUnmuted(),(r=(t=e.track)==null?void 0:t.mediaStream)==null||r.getTracks().forEach(i=>i.enabled=!0)})}async stop(){this.emit("stopped"),await this.shutdown()}async shutdown(e=null){if(this.room){this.sessionUuid,e!=="server-sent"&&await this.sendData({request:"shutdown"});const t=this.room;this.room=null,await t.disconnect(),this.sessionUuid}this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.emit("shutdown",e)}async say(e){this.speakingStateChanged("thinking"),this.isPaused&&await this.unpause(),await this.sendData({request:"say",message:e})}serialise(){return JSON.stringify({state:this.state,speakingState:this.speakingState,appToken:this.appToken,planId:this.planId,clientType:this.clientType,isPaused:this.isPaused,identity:this.identity,sessionUuid:this.sessionUuid,roomId:this.roomId,joinToken:this.joinToken,roomUrl:this.roomUrl,startedAt:this.startedAt})}audioSpectrum(){return this.speakingState==="speaking"&&this.agentAnalyser?this.normaliseSpectrum(this.agentAnalyser):this.speakingState==="listening"&&this.userAnalyser?this.normaliseSpectrum(this.userAnalyser):null}normaliseSpectrum(e){const r=e.context.sampleRate/2/e.frequencyBinCount,i=new Uint8Array(e.frequencyBinCount);e.getByteFrequencyData(i);const A=[],s=50,o=5e3,a=8,c=Math.pow(o/s,1/a);for(let u=0;u<a;u++){const l=s*Math.pow(c,u),d=s*Math.pow(c,u+1),h=Math.floor(l/r),f=Math.floor(d/r),p=Math.min(f,i.length),g=Math.min(h,p);if(g<p){const v=i.slice(g,p).reduce((y,B)=>y+B,0)/(p-g)/255;A.push(v)}else A.push(0)}return A}setState(e){this.state;const t=this.state;this.state=e,this.emit("stateChanged",e,t)}static deserialise(e,t,r,i={}){const A=JSON.parse(e),s=new pa(t,A.planId,r,i);return s.state=A.state,s.speakingState=A.speakingState,s.identity=A.identity||null,s.isPaused=A.isPaused||!1,s.sessionUuid=A.sessionUuid||null,s.roomId=A.roomId||null,s.joinToken=A.joinToken||null,s.roomUrl=A.roomUrl||null,s.startedAt=A.startedAt||null,s}speakingStateChanged(e){this.speakingState;const t=this.speakingState;this.speakingState=e,this.emit("speakingStateChanged",e,t)}async sendData(e){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0})}createFFT(e){const t=new AudioContext,r=t.createAnalyser();return t.createMediaStreamSource(e).connect(r),r.fftSize=2048,r.smoothingTimeConstant=.6,r}}class fa extends jc{constructor(e,t,r={}){super(),this.state="loading",this.error=null,this.identity=null,this.product=null,this.plans=[],this.planIsCompleted=[],this.selectedPlan=null,this.selectedPlanUuid=null,this.showWidget=!1,this.session=null,this.captureScreen=null,this.appToken=e,this.clientType=t,this.api=r.api||new K0({baseUrl:r.apiBaseUrl||V0}),this.sessionFactory=r.sessionFactory||((i,A,s,o)=>new pa(i,A,s,o)),this.captureScreen=r.captureScreen||null}async initialise(e={}){var t,r,i,A,s,o;if(!this.appToken)throw new Error("App token is required");this.setState("loading");try{const a=await this.api.clientInitialise(this.appToken,{identity:e.identity,client_type:this.clientType});if(this.identity=e.identity||null,this.product=((t=a.data)==null?void 0:t.product)||null,this.plans=((r=a.data)==null?void 0:r.onboarding_plans)||[],this.selectedPlan=((i=a.data)==null?void 0:i.selected_plan)||null,this.planIsCompleted=((A=a.data)==null?void 0:A.plan_is_completed)||[],this.showWidget=((s=a.data)==null?void 0:s.show_widget)||!1,e.planUuid){let c=null;try{const u=await this.api.getPlanSDK(e.planUuid);u.data&&(c=u.data)}catch(u){try{const l=await this.api.getSessionPlan(e.planUuid);(o=l.data)!=null&&o.plan_uuid&&(c={uuid:l.data.plan_uuid})}catch(l){console.error("[obi] error getting plan via both endpoints",{planErr:u,sessionErr:l})}}c?(this.selectedPlan=c,this.selectedPlanUuid=e.planUuid):console.warn("[obi] plan not found",{planUuid:e.planUuid})}this.identity,this.product,this.plans,this.selectedPlan,this.showWidget}catch(a){throw this.error=a instanceof Error?a:new Error(String(a)),this.setState("error"),a}finally{this.setState("ready")}}selectPlan(e){this.selectedPlan=e,this.selectedPlanUuid=(e==null?void 0:e.uuid)||null,this.emit("planSelected",e)}async startSession(e,t){return await this._stopSession(),this.session=this.sessionFactory(this.appToken,e,this.clientType,{api:this.api,identity:this.identity,captureScreen:this.captureScreen}),this.prepareSession(t),this.session.start().then(()=>{this.emit("sessionStarted",this.session)}).catch(r=>{this.session=null,console.error("[obi] error starting session",r)}),this.session}async resumeSession(e){var t,r;return this.state,(t=this.session)==null||t.state,(r=this.session)==null||r.speakingState,this.session.captureScreen=this.captureScreen,this.prepareSession(e),this.session.joinRoom({withMicrophone:!0,withStateRecovery:!0}).then(()=>{this.emit("sessionResumed",this.session)}).catch(i=>{console.error("[obi] error joining room",{error:i}),i instanceof Error&&i.message==="Room is not connected"&&this.session.stop()}),this.session}prepareSession(e){if(!this.session)throw new Error("No session to prepare");return e(this.session),this.session.on("stopped",()=>{this.emit("sessionStopped")}),this.session.on("shutdown",t=>{var r,i,A;if((r=this.session)!=null&&r.startedAt&&this.session.startedAt+5*60*1e3<Date.now()){const s=this.plans.findIndex(o=>{var a;return o.uuid===((a=this.selectedPlan)==null?void 0:a.uuid)});s!==-1&&(this.planIsCompleted[s]=!0)}(A=(i=this.session)==null?void 0:i.removeAllListeners)==null||A.call(i),this.session=null,this.selectedPlan=null,this.selectedPlanUuid=null,this.emit("sessionShutdown",t)}),this.session}async stopSession(){await this._stopSession(),this.selectedPlan&&this.selectPlan(null)}async _stopSession(){this.session&&(this.trackEvent("session-stopped",{sessionUuid:this.session.sessionUuid}),await this.session.stop(),this.session=null)}isLoading(){return this.state==="loading"}isReady(){return this.state==="ready"}serialise(){var e;return JSON.stringify({state:this.state,appToken:this.appToken,clientType:this.clientType,identity:this.identity,product:this.product,plans:this.plans,selectedPlan:this.selectedPlan,selectedPlanUuid:this.selectedPlanUuid,showWidget:this.showWidget,session:(e=this.session)==null?void 0:e.serialise(),serialisedAt:new Date().toISOString()})}static deserialise(e,t,r,i={}){const A=JSON.parse(e);if(A.serialisedAt){const o=new Date(A.serialisedAt);if(new Date().getTime()-o.getTime()>1e3*20)throw new Error("Client was serialised more than 20 seconds ago, assuming it's dead.")}else throw new Error("Client was not serialised, assuming it's dead.");const s=new fa(t,r,i);return s.state=A.state,s.identity=A.identity||null,s.product=A.product||null,s.plans=A.plans||[],s.selectedPlan=A.selectedPlan||null,s.selectedPlanUuid=A.selectedPlanUuid||null,s.showWidget=A.showWidget||!1,A.session&&(s.session=pa.deserialise(A.session,t,r,{api:s.api})),s}setState(e){const t=this.state;this.state=e,this.emit("stateChanged",e,t)}trackEvent(e,t={}){var r,i,A;this.emit("trackEvent",e,{...t,clientType:this.clientType,planId:(r=this.selectedPlan)==null?void 0:r.uuid,productId:(i=this.product)==null?void 0:i.uuid,sessionId:(A=this.session)==null?void 0:A.sessionUuid})}}var ga,ee,G0,zr,j0,W0,q0,J0,ud,ld,dd,z0,WA={},X0=[],dQ=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,qA=Array.isArray;function Kn(n,e){for(var t in e)n[t]=e[t];return n}function hd(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function pd(n,e,t){var r,i,A,s={};for(A in e)A=="key"?r=e[A]:A=="ref"?i=e[A]:s[A]=e[A];if(arguments.length>2&&(s.children=arguments.length>3?ga.call(arguments,2):t),typeof n=="function"&&n.defaultProps!=null)for(A in n.defaultProps)s[A]==null&&(s[A]=n.defaultProps[A]);return ma(n,s,r,i,null)}function ma(n,e,t,r,i){var A={type:n,props:e,key:t,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++G0,__i:-1,__u:0};return i==null&&ee.vnode!=null&&ee.vnode(A),A}function St(n){return n.children}function Vn(n,e){this.props=n,this.context=e}function Di(n,e){if(e==null)return n.__?Di(n.__,n.__i+1):null;for(var t;e<n.__k.length;e++)if((t=n.__k[e])!=null&&t.__e!=null)return t.__e;return typeof n.type=="function"?Di(n):null}function Y0(n){var e,t;if((n=n.__)!=null&&n.__c!=null){for(n.__e=n.__c.base=null,e=0;e<n.__k.length;e++)if((t=n.__k[e])!=null&&t.__e!=null){n.__e=n.__c.base=t.__e;break}return Y0(n)}}function fd(n){(!n.__d&&(n.__d=!0)&&zr.push(n)&&!va.__r++||j0!=ee.debounceRendering)&&((j0=ee.debounceRendering)||W0)(va)}function va(){for(var n,e,t,r,i,A,s,o=1;zr.length;)zr.length>o&&zr.sort(q0),n=zr.shift(),o=zr.length,n.__d&&(t=void 0,i=(r=(e=n).__v).__e,A=[],s=[],e.__P&&((t=Kn({},r)).__v=r.__v+1,ee.vnode&&ee.vnode(t),gd(e.__P,t,r,e.__n,e.__P.namespaceURI,32&r.__u?[i]:null,A,i??Di(r),!!(32&r.__u),s),t.__v=r.__v,t.__.__k[t.__i]=t,ny(A,t,s),t.__e!=i&&Y0(t)));va.__r=0}function Z0(n,e,t,r,i,A,s,o,a,c,u){var l,d,h,f,p,g,v=r&&r.__k||X0,y=e.length;for(a=hQ(t,e,v,a,y),l=0;l<y;l++)(h=t.__k[l])!=null&&(d=h.__i==-1?WA:v[h.__i]||WA,h.__i=l,g=gd(n,h,d,i,A,s,o,a,c,u),f=h.__e,h.ref&&d.ref!=h.ref&&(d.ref&&md(d.ref,null,h),u.push(h.ref,h.__c||f,h)),p==null&&f!=null&&(p=f),4&h.__u||d.__k===h.__k?a=$0(h,a,n):typeof h.type=="function"&&g!==void 0?a=g:f&&(a=f.nextSibling),h.__u&=-7);return t.__e=p,a}function hQ(n,e,t,r,i){var A,s,o,a,c,u=t.length,l=u,d=0;for(n.__k=new Array(i),A=0;A<i;A++)(s=e[A])!=null&&typeof s!="boolean"&&typeof s!="function"?(a=A+d,(s=n.__k[A]=typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?ma(null,s,null,null,null):qA(s)?ma(St,{children:s},null,null,null):s.constructor==null&&s.__b>0?ma(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):s).__=n,s.__b=n.__b+1,o=null,(c=s.__i=pQ(s,t,a,l))!=-1&&(l--,(o=t[c])&&(o.__u|=2)),o==null||o.__v==null?(c==-1&&(i>u?d--:i<u&&d++),typeof s.type!="function"&&(s.__u|=4)):c!=a&&(c==a-1?d--:c==a+1?d++:(c>a?d--:d++,s.__u|=4))):n.__k[A]=null;if(l)for(A=0;A<u;A++)(o=t[A])!=null&&!(2&o.__u)&&(o.__e==r&&(r=Di(o)),iy(o,o));return r}function $0(n,e,t){var r,i;if(typeof n.type=="function"){for(r=n.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=n,e=$0(r[i],e,t));return e}n.__e!=e&&(e&&n.type&&!t.contains(e)&&(e=Di(n)),t.insertBefore(n.__e,e||null),e=n.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ya(n,e){return e=e||[],n==null||typeof n=="boolean"||(qA(n)?n.some(function(t){ya(t,e)}):e.push(n)),e}function pQ(n,e,t,r){var i,A,s=n.key,o=n.type,a=e[t];if(a===null&&n.key==null||a&&s==a.key&&o==a.type&&!(2&a.__u))return t;if(r>(a!=null&&!(2&a.__u)?1:0))for(i=t-1,A=t+1;i>=0||A<e.length;){if(i>=0){if((a=e[i])&&!(2&a.__u)&&s==a.key&&o==a.type)return i;i--}if(A<e.length){if((a=e[A])&&!(2&a.__u)&&s==a.key&&o==a.type)return A;A++}}return-1}function ey(n,e,t){e[0]=="-"?n.setProperty(e,t??""):n[e]=t==null?"":typeof t!="number"||dQ.test(e)?t:t+"px"}function wa(n,e,t,r,i){var A;e:if(e=="style")if(typeof t=="string")n.style.cssText=t;else{if(typeof r=="string"&&(n.style.cssText=r=""),r)for(e in r)t&&e in t||ey(n.style,e,"");if(t)for(e in t)r&&t[e]==r[e]||ey(n.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")A=e!=(e=e.replace(J0,"$1")),e=e.toLowerCase()in n||e=="onFocusOut"||e=="onFocusIn"?e.toLowerCase().slice(2):e.slice(2),n.l||(n.l={}),n.l[e+A]=t,t?r?t.u=r.u:(t.u=ud,n.addEventListener(e,A?dd:ld,A)):n.removeEventListener(e,A?dd:ld,A);else{if(i=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in n)try{n[e]=t??"";break e}catch{}typeof t=="function"||(t==null||t===!1&&e[4]!="-"?n.removeAttribute(e):n.setAttribute(e,e=="popover"&&t==1?"":t))}}function ty(n){return function(e){if(this.l){var t=this.l[e.type+n];if(e.t==null)e.t=ud++;else if(e.t<t.u)return;return t(ee.event?ee.event(e):e)}}}function gd(n,e,t,r,i,A,s,o,a,c){var u,l,d,h,f,p,g,v,y,B,b,w,_,k,T,x,P,E=e.type;if(e.constructor!=null)return null;128&t.__u&&(a=!!(32&t.__u),A=[o=e.__e=t.__e]),(u=ee.__b)&&u(e);e:if(typeof E=="function")try{if(v=e.props,y="prototype"in E&&E.prototype.render,B=(u=E.contextType)&&r[u.__c],b=u?B?B.props.value:u.__:r,t.__c?g=(l=e.__c=t.__c).__=l.__E:(y?e.__c=l=new E(v,b):(e.__c=l=new Vn(v,b),l.constructor=E,l.render=gQ),B&&B.sub(l),l.props=v,l.state||(l.state={}),l.context=b,l.__n=r,d=l.__d=!0,l.__h=[],l._sb=[]),y&&l.__s==null&&(l.__s=l.state),y&&E.getDerivedStateFromProps!=null&&(l.__s==l.state&&(l.__s=Kn({},l.__s)),Kn(l.__s,E.getDerivedStateFromProps(v,l.__s))),h=l.props,f=l.state,l.__v=e,d)y&&E.getDerivedStateFromProps==null&&l.componentWillMount!=null&&l.componentWillMount(),y&&l.componentDidMount!=null&&l.__h.push(l.componentDidMount);else{if(y&&E.getDerivedStateFromProps==null&&v!==h&&l.componentWillReceiveProps!=null&&l.componentWillReceiveProps(v,b),!l.__e&&l.shouldComponentUpdate!=null&&l.shouldComponentUpdate(v,l.__s,b)===!1||e.__v==t.__v){for(e.__v!=t.__v&&(l.props=v,l.state=l.__s,l.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.some(function(F){F&&(F.__=e)}),w=0;w<l._sb.length;w++)l.__h.push(l._sb[w]);l._sb=[],l.__h.length&&s.push(l);break e}l.componentWillUpdate!=null&&l.componentWillUpdate(v,l.__s,b),y&&l.componentDidUpdate!=null&&l.__h.push(function(){l.componentDidUpdate(h,f,p)})}if(l.context=b,l.props=v,l.__P=n,l.__e=!1,_=ee.__r,k=0,y){for(l.state=l.__s,l.__d=!1,_&&_(e),u=l.render(l.props,l.state,l.context),T=0;T<l._sb.length;T++)l.__h.push(l._sb[T]);l._sb=[]}else do l.__d=!1,_&&_(e),u=l.render(l.props,l.state,l.context),l.state=l.__s;while(l.__d&&++k<25);l.state=l.__s,l.getChildContext!=null&&(r=Kn(Kn({},r),l.getChildContext())),y&&!d&&l.getSnapshotBeforeUpdate!=null&&(p=l.getSnapshotBeforeUpdate(h,f)),x=u,u!=null&&u.type===St&&u.key==null&&(x=ry(u.props.children)),o=Z0(n,qA(x)?x:[x],e,t,r,i,A,s,o,a,c),l.base=e.__e,e.__u&=-161,l.__h.length&&s.push(l),g&&(l.__E=l.__=null)}catch(F){if(e.__v=null,a||A!=null)if(F.then){for(e.__u|=a?160:128;o&&o.nodeType==8&&o.nextSibling;)o=o.nextSibling;A[A.indexOf(o)]=null,e.__e=o}else for(P=A.length;P--;)hd(A[P]);else e.__e=t.__e,e.__k=t.__k;ee.__e(F,e,t)}else A==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):o=e.__e=fQ(t.__e,e,t,r,i,A,s,a,c);return(u=ee.diffed)&&u(e),128&e.__u?void 0:o}function ny(n,e,t){for(var r=0;r<t.length;r++)md(t[r],t[++r],t[++r]);ee.__c&&ee.__c(e,n),n.some(function(i){try{n=i.__h,i.__h=[],n.some(function(A){A.call(i)})}catch(A){ee.__e(A,i.__v)}})}function ry(n){return typeof n!="object"||n==null||n.__b&&n.__b>0?n:qA(n)?n.map(ry):Kn({},n)}function fQ(n,e,t,r,i,A,s,o,a){var c,u,l,d,h,f,p,g=t.props,v=e.props,y=e.type;if(y=="svg"?i="http://www.w3.org/2000/svg":y=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),A!=null){for(c=0;c<A.length;c++)if((h=A[c])&&"setAttribute"in h==!!y&&(y?h.localName==y:h.nodeType==3)){n=h,A[c]=null;break}}if(n==null){if(y==null)return document.createTextNode(v);n=document.createElementNS(i,y,v.is&&v),o&&(ee.__m&&ee.__m(e,A),o=!1),A=null}if(y==null)g===v||o&&n.data==v||(n.data=v);else{if(A=A&&ga.call(n.childNodes),g=t.props||WA,!o&&A!=null)for(g={},c=0;c<n.attributes.length;c++)g[(h=n.attributes[c]).name]=h.value;for(c in g)if(h=g[c],c!="children"){if(c=="dangerouslySetInnerHTML")l=h;else if(!(c in v)){if(c=="value"&&"defaultValue"in v||c=="checked"&&"defaultChecked"in v)continue;wa(n,c,null,h,i)}}for(c in v)h=v[c],c=="children"?d=h:c=="dangerouslySetInnerHTML"?u=h:c=="value"?f=h:c=="checked"?p=h:o&&typeof h!="function"||g[c]===h||wa(n,c,h,g[c],i);if(u)o||l&&(u.__html==l.__html||u.__html==n.innerHTML)||(n.innerHTML=u.__html),e.__k=[];else if(l&&(n.innerHTML=""),Z0(e.type=="template"?n.content:n,qA(d)?d:[d],e,t,r,y=="foreignObject"?"http://www.w3.org/1999/xhtml":i,A,s,A?A[0]:t.__k&&Di(t,0),o,a),A!=null)for(c=A.length;c--;)hd(A[c]);o||(c="value",y=="progress"&&f==null?n.removeAttribute("value"):f!=null&&(f!==n[c]||y=="progress"&&!f||y=="option"&&f!=g[c])&&wa(n,c,f,g[c],i),c="checked",p!=null&&p!=n[c]&&wa(n,c,p,g[c],i))}return n}function md(n,e,t){try{if(typeof n=="function"){var r=typeof n.__u=="function";r&&n.__u(),r&&e==null||(n.__u=n(e))}else n.current=e}catch(i){ee.__e(i,t)}}function iy(n,e,t){var r,i;if(ee.unmount&&ee.unmount(n),(r=n.ref)&&(r.current&&r.current!=n.__e||md(r,null,e)),(r=n.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(A){ee.__e(A,e)}r.base=r.__P=null}if(r=n.__k)for(i=0;i<r.length;i++)r[i]&&iy(r[i],e,t||typeof n.type!="function");t||hd(n.__e),n.__c=n.__=n.__e=void 0}function gQ(n,e,t){return this.constructor(n,t)}function mQ(n,e,t){var r,i,A,s;e==document&&(e=document.documentElement),ee.__&&ee.__(n,e),i=(r=typeof t=="function")?null:t&&t.__k||e.__k,A=[],s=[],gd(e,n=(!r&&t||e).__k=pd(St,null,[n]),i||WA,WA,e.namespaceURI,!r&&t?[t]:i?null:e.firstChild?ga.call(e.childNodes):null,A,!r&&t?t:i?i.__e:e.firstChild,r,s),ny(A,n,s)}function Ay(n){function e(t){var r,i;return this.getChildContext||(r=new Set,(i={})[e.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(A){this.props.value!=A.value&&r.forEach(function(s){s.__e=!0,fd(s)})},this.sub=function(A){r.add(A);var s=A.componentWillUnmount;A.componentWillUnmount=function(){r&&r.delete(A),s&&s.call(A)}}),t.children}return e.__c="__cC"+z0++,e.__=n,e.Provider=e.__l=(e.Consumer=function(t,r){return t.children(r)}).contextType=e,e}ga=X0.slice,ee={__e:function(n,e,t,r){for(var i,A,s;e=e.__;)if((i=e.__c)&&!i.__)try{if((A=i.constructor)&&A.getDerivedStateFromError!=null&&(i.setState(A.getDerivedStateFromError(n)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(n,r||{}),s=i.__d),s)return i.__E=i}catch(o){n=o}throw n}},G0=0,Vn.prototype.setState=function(n,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Kn({},this.state),typeof n=="function"&&(n=n(Kn({},t),this.props)),n&&Kn(t,n),n!=null&&this.__v&&(e&&this._sb.push(e),fd(this))},Vn.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),fd(this))},Vn.prototype.render=St,zr=[],W0=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,q0=function(n,e){return n.__v.__b-e.__v.__b},va.__r=0,J0=/(PointerCapture)$|Capture$/i,ud=0,ld=ty(!1),dd=ty(!0),z0=0;var vQ=0;function C(n,e,t,r,i,A){e||(e={});var s,o,a=e;if("ref"in a)for(o in a={},e)o=="ref"?s=e[o]:a[o]=e[o];var c={type:n,props:a,key:t,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--vQ,__i:-1,__u:0,__source:i,__self:A};if(typeof n=="function"&&(s=n.defaultProps))for(o in s)a[o]===void 0&&(a[o]=s[o]);return ee.vnode&&ee.vnode(c),c}var Xr,Ve,vd,sy,JA=0,oy=[],it=ee,ay=it.__b,cy=it.__r,uy=it.diffed,ly=it.__c,dy=it.unmount,hy=it.__;function zA(n,e){it.__h&&it.__h(Ve,n,JA||e),JA=0;var t=Ve.__H||(Ve.__H={__:[],__h:[]});return n>=t.__.length&&t.__.push({}),t.__[n]}function ge(n){return JA=1,yQ(gy,n)}function yQ(n,e,t){var r=zA(Xr++,2);if(r.t=n,!r.__c&&(r.__=[t?t(e):gy(void 0,e),function(o){var a=r.__N?r.__N[0]:r.__[0],c=r.t(a,o);a!==c&&(r.__N=[c,r.__[1]],r.__c.setState({}))}],r.__c=Ve,!Ve.__f)){var i=function(o,a,c){if(!r.__c.__H)return!0;var u=r.__c.__H.__.filter(function(d){return!!d.__c});if(u.every(function(d){return!d.__N}))return!A||A.call(this,o,a,c);var l=r.__c.props!==o;return u.forEach(function(d){if(d.__N){var h=d.__[0];d.__=d.__N,d.__N=void 0,h!==d.__[0]&&(l=!0)}}),A&&A.call(this,o,a,c)||l};Ve.__f=!0;var A=Ve.shouldComponentUpdate,s=Ve.componentWillUpdate;Ve.componentWillUpdate=function(o,a,c){if(this.__e){var u=A;A=void 0,i(o,a,c),A=u}s&&s.call(this,o,a,c)},Ve.shouldComponentUpdate=i}return r.__N||r.__}function Kt(n,e){var t=zA(Xr++,3);!it.__s&&Bd(t.__H,e)&&(t.__=n,t.u=e,Ve.__H.__h.push(t))}function yd(n,e){var t=zA(Xr++,4);!it.__s&&Bd(t.__H,e)&&(t.__=n,t.u=e,Ve.__h.push(t))}function En(n){return JA=5,wd(function(){return{current:n}},[])}function wd(n,e){var t=zA(Xr++,7);return Bd(t.__H,e)&&(t.__=n(),t.__H=e,t.__h=n),t.__}function wQ(n,e){return JA=8,wd(function(){return n},e)}function py(n){var e=Ve.context[n.__c],t=zA(Xr++,9);return t.c=n,e?(t.__==null&&(t.__=!0,e.sub(Ve)),e.props.value):n.__}function bQ(){for(var n;n=oy.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(ba),n.__H.__h.forEach(bd),n.__H.__h=[]}catch(e){n.__H.__h=[],it.__e(e,n.__v)}}it.__b=function(n){Ve=null,ay&&ay(n)},it.__=function(n,e){n&&e.__k&&e.__k.__m&&(n.__m=e.__k.__m),hy&&hy(n,e)},it.__r=function(n){cy&&cy(n),Xr=0;var e=(Ve=n.__c).__H;e&&(vd===Ve?(e.__h=[],Ve.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.forEach(ba),e.__h.forEach(bd),e.__h=[],Xr=0)),vd=Ve},it.diffed=function(n){uy&&uy(n);var e=n.__c;e&&e.__H&&(e.__H.__h.length&&(oy.push(e)!==1&&sy===it.requestAnimationFrame||((sy=it.requestAnimationFrame)||BQ)(bQ)),e.__H.__.forEach(function(t){t.u&&(t.__H=t.u),t.u=void 0})),vd=Ve=null},it.__c=function(n,e){e.some(function(t){try{t.__h.forEach(ba),t.__h=t.__h.filter(function(r){return!r.__||bd(r)})}catch(r){e.some(function(i){i.__h&&(i.__h=[])}),e=[],it.__e(r,t.__v)}}),ly&&ly(n,e)},it.unmount=function(n){dy&&dy(n);var e,t=n.__c;t&&t.__H&&(t.__H.__.forEach(function(r){try{ba(r)}catch(i){e=i}}),t.__H=void 0,e&&it.__e(e,t.__v))};var fy=typeof requestAnimationFrame=="function";function BQ(n){var e,t=function(){clearTimeout(r),fy&&cancelAnimationFrame(e),setTimeout(n)},r=setTimeout(t,100);fy&&(e=requestAnimationFrame(t))}function ba(n){var e=Ve,t=n.__c;typeof t=="function"&&(n.__c=void 0,t()),Ve=e}function bd(n){var e=Ve;n.__c=n.__(),Ve=e}function Bd(n,e){return!n||n.length!==e.length||e.some(function(t,r){return t!==n[r]})}function gy(n,e){return typeof e=="function"?e(n):e}function CQ({size:n=24,color:e="#000"}){return C("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:e,"stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"lucide lucide-x-icon lucide-x",children:[C("path",{d:"M18 6 6 18"}),C("path",{d:"m6 6 12 12"})]})}function my({onClose:n}){return C("button",{class:"obi-button obi-close-button",onClick:n,"aria-label":"Close",type:"button",children:C(CQ,{})})}function vy({open:n=!1,children:e,onClose:t,size:r="medium"}){const i=En(null),A=En(null);Kt(()=>{const c=i.current;c&&(n&&!c.open?c.showModal():!n&&c.open&&(A.current="programmatic",c.close()))},[n]);const s=c=>{const u=i.current;c.target===u&&(A.current="user-initiated",u==null||u.close())},o=c=>{c.preventDefault(),A.current||(A.current="user-initiated");const u=A.current;A.current=null,t==null||t(u)},a=()=>{var c;A.current="user-initiated",(c=i.current)==null||c.close()};return Kt(()=>{const c=i.current;if(c)return c.addEventListener("click",s),c.addEventListener("close",o),()=>{c.removeEventListener("click",s),c.removeEventListener("close",o)}},[t]),C("dialog",{ref:i,className:`modal-${r}`,children:[C(my,{onClose:a}),C("div",{class:"modal-content",children:n?typeof e=="function"?e():e:null})]})}function Cd(n){const{children:e,className:t="",...r}=n;return C("div",{className:`${t} obi-panel`,...r,children:e})}function _d({className:n="",isActive:e=!1,speakingStatus:t,onClick:r,onMouseEnter:i,onMouseLeave:A,children:s}){let o=`obi-pill container ${e&&"active"}`;return t==="user-speaking"&&(o+=" user-speaking"),t==="busy"&&(o+=" busy"),C("div",{className:o,onMouseEnter:i,onMouseLeave:A,children:C("div",{className:`obi-pill pill ${n}`,onClick:r,children:s})})}function yy({className:n="",active:e,speakingStatus:t,onClick:r,onMouseEnter:i,onMouseLeave:A,children:s,...o}){const a=`obi-pill2 container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return C("div",{className:a,...o,children:C("div",{className:"pill",onClick:r,onMouseEnter:i,onMouseLeave:A,children:s})})}function Yr({type:n,size:e=24}){return C("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:_Q(n)})}function _Q(n){switch(n){case"pause":return C(St,{children:[C("rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}),C("rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"})]});case"play":return C(St,{children:C("path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"})});case"close":return C(St,{children:[C("path",{d:"M18 6 6 18"}),C("path",{d:"m6 6 12 12"})]});case"message":return C(St,{children:C("path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"})});case"minimize":return C(St,{children:[C("path",{d:"m14 10 7-7"}),C("path",{d:"M20 10h-6V4"}),C("path",{d:"m3 21 7-7"}),C("path",{d:"M4 14h6v6"})]});case"voice":return C(St,{children:[C("path",{d:"M2 10v3"}),C("path",{d:"M6 6v11"}),C("path",{d:"M10 3v18"}),C("path",{d:"M14 8v7"}),C("path",{d:"M18 5v13"}),C("path",{d:"M22 10v3"})]});case"open":return C(St,{children:[C("path",{d:"M12 7v14"}),C("path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"})]})}}const Sd=Ay(null);function SQ({children:n}){const e=py(Sd);if(!e)throw new Error("PopoutTarget must be used within a Popout component");const{controlledOpen:t,isOpen:r,setIsOpen:i,setAnimating:A,targetRef:s,trigger:o,onChange:a,delayMs:c}=e,u=En(null),l=wy(s,A),[d,h]=ge(!1);Kt(()=>{t!==void 0&&t!==d&&(t?p():g()),h(t)},[t]),Kt(()=>()=>{u.current&&clearTimeout(u.current)},[]);function f(){u.current&&(clearTimeout(u.current),u.current=null)}function p(){f(),c>0?u.current=setTimeout(()=>{a==null||a(!0),i(!0),u.current=null},c):(a==null||a(!0),i(!0))}function g(){f(),a==null||a(!1),i(!1)}const v=()=>{o==="click"&&(r?g():p())};function y(){o==="hover"&&p()}function B(){o==="hover"&&g()}return C("div",{ref:l,class:"target",onClick:v,onMouseEnter:y,onMouseLeave:B,children:n})}function kQ({children:n}){const e=py(Sd);if(!e)throw new Error("PopoutContent must be used within a Popout component");const{isOpen:t,animating:r,setAnimating:i,targetRef:A,contentRef:s}=e,o=wy(s,i);return yd(()=>{if(t&&!r&&A.current&&s.current){const a=s.current;if(!a)return;const c=A.current;if(!c)return;const u=a.getBoundingClientRect(),l=c.getBoundingClientRect(),d=l.right-l.left;a.style.top=`${u.top-u.bottom-(8+e.offset)}px`,a.style.left=`${-(u.right-u.left-d)/2}px`}},[t,r]),t?C("div",{ref:o,class:"content",style:{opacity:r?0:1},children:n}):null}function Vt({trigger:n="click",open:e,onChange:t,children:r,delayMs:i=0,offset:A=0,className:s=""}){const[o,a]=ge(!1),[c,u]=ge(!1),l=En(null),d=En(null),h={controlledOpen:e,isOpen:o,setIsOpen:a,animating:c,setAnimating:u,targetRef:l,contentRef:d,trigger:n,onChange:t,delayMs:i,offset:A};return C(Sd.Provider,{value:h,children:C("div",{class:`obi-popout ${s}`,children:r})})}Vt.Target=SQ,Vt.Content=kQ;function wy(n,e){const t=En(null),r=En(null),i=En(!0),A=wQ(s=>{if(n.current=s,!s){r.current&&(r.current.disconnect(),r.current=null),i.current=!0;return}function o(){if(i.current){i.current=!1;return}t.current?clearTimeout(t.current):e(!0),t.current=setTimeout(()=>{e(!1),t.current=null},200)}r.current=new ResizeObserver(o),r.current.observe(s,{box:"border-box"})},[]);return Kt(()=>()=>{r.current&&(r.current.disconnect(),r.current=null)},[]),A}function pn({className:n,onClick:e,type:t,disabled:r,title:i}){const A={cancel:C(Yr,{type:"close",size:16}),pause:C(Yr,{type:"pause",size:16}),play:C(Yr,{type:"play",size:16}),message:C(Yr,{type:"message",size:16}),minimize:C(Yr,{type:"minimize",size:16}),voice:C(Yr,{type:"voice",size:16}),open:C(Yr,{type:"open",size:16})}[t],s={cancel:"",pause:"",play:"",message:"",minimize:"",voice:"",open:""}[t],o=C("button",{class:`obi-button obi-round-button ${s} ${n}`,onClick:r?void 0:e,disabled:r,children:A});return i?C(Vt,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[C(Vt.Target,{children:o}),C(Vt.Content,{children:C("div",{className:"obi-round-button-title",children:i})})]}):o}const by=8,Ba=8,EQ=50,UQ=.7,Ni=3;function By({getBands:n,color:e="white"}){const t=En(null);return Kt(()=>{if(!n)return;const r=setInterval(()=>{try{const i=n();if(!t.current)return;const A=t.current.querySelectorAll(".bar"),s=i&&i.length>0?i.slice(0,Ba).map(o=>{const a=Math.abs(o);return Math.min(a/UQ*by,by)||Ni}):Array(Ba).fill(Ni);for(;s.length<Ba;)s.push(Ni);s.forEach((o,a)=>{if(o<Ni&&(o=Ni),A[a]){const c=o*2;A[a].style.height=`${c}px`,A[a].style.display=o>0?"block":"none"}})}catch(i){console.warn("Error updating equaliser:",i)}},EQ);return()=>{clearInterval(r)}},[n]),C("div",{className:"obi-equaliser",ref:t,children:Array.from({length:Ba},(r,i)=>C("div",{className:"column",children:C("div",{className:"bar",style:{height:`${Ni}px`,backgroundColor:e,display:"block"}})},i))})}function XA({className:n,children:e,onClick:t}){return t?C("button",{class:`obi-button obi-message ${n} clickable`,onClick:t,children:e}):C("div",{class:`obi-message ${n}`,children:e})}const TQ=8;function Cy({color:n="white"}){return C("div",{className:"obi-loading-dots",children:Array.from({length:TQ},(e,t)=>C("div",{className:"column",children:[C("div",{className:"bar",style:{backgroundColor:n,animationDelay:`${t*.15}s`}}),C("div",{className:"dot",style:{backgroundColor:n}})]},t))})}function IQ({onContinue:n,onWrapUp:e}){return C(Cd,{className:"obi-exit-survey",children:C(xQ,{onContinue:n,onWrapUp:()=>{e()}})})}function FQ({onOtherSelect:n,onReasonSelect:e,onClose:t}){const[r,i]=ge("reason"),A=s=>{s==="other"?(n(),i("other-reason")):e(s)};return C(Cd,{className:`obi-exit-survey ${r==="reason"?"obi-exit-survey-reason":""}`,children:r==="reason"?C(QQ,{onReasonSelect:A}):C(RQ,{onReasonSelect:A,onClose:t})})}function xQ({onContinue:n,onWrapUp:e}){return C("div",{className:"obi-exit-survey-container",children:[C("h2",{className:"obi-exit-survey-title",children:"Wrapping up early?"}),C("div",{className:"obi-exit-survey-options",children:[C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-continue",onClick:n,type:"button",children:"No, let's continue"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:e,type:"button",children:"Yes, let's wrap up"})]})]})}function QQ({onReasonSelect:n}){return C("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[C("div",{className:"obi-exit-survey-header",children:C("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Quick feedback?"})}),C("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("do-later"),type:"button",children:"Will do later"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("cant-talk"),type:"button",children:"Can't talk right now"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("prefer-written"),type:"button",children:"Prefer written instructions"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("technical-issues"),type:"button",children:"Experienced technical issues"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("other"),type:"button",children:"Other"})]})]})}function RQ({onReasonSelect:n,onClose:e}){const[t,r]=ge("");return C("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[C("div",{className:"obi-exit-survey-header",children:[C(my,{onClose:e}),C("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Tell us more"})]}),C("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[C("textarea",{className:"obi-exit-survey-button obi-exit-survey-reason-button",placeholder:"What's on your mind?",value:t,onChange:i=>r(i.target.value)}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:()=>n("other-feedback",t),type:"button",children:"Send feedback"})]})]})}function PQ(n,e){for(var t in e)n[t]=e[t];return n}function _y(n,e){for(var t in n)if(t!=="__source"&&!(t in e))return!0;for(var r in e)if(r!=="__source"&&n[r]!==e[r])return!0;return!1}function Sy(n,e){this.props=n,this.context=e}(Sy.prototype=new Vn).isPureReactComponent=!0,Sy.prototype.shouldComponentUpdate=function(n,e){return _y(this.props,n)||_y(this.state,e)};var ky=ee.__b;ee.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),ky&&ky(n)};var OQ=ee.__e;ee.__e=function(n,e,t,r){if(n.then){for(var i,A=e;A=A.__;)if((i=A.__c)&&i.__c)return e.__e==null&&(e.__e=t.__e,e.__k=t.__k),i.__c(n,e)}OQ(n,e,t,r)};var Ey=ee.unmount;function Uy(n,e,t){return n&&(n.__c&&n.__c.__H&&(n.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),n.__c.__H=null),(n=PQ({},n)).__c!=null&&(n.__c.__P===t&&(n.__c.__P=e),n.__c.__e=!0,n.__c=null),n.__k=n.__k&&n.__k.map(function(r){return Uy(r,e,t)})),n}function Ty(n,e,t){return n&&t&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(r){return Ty(r,e,t)}),n.__c&&n.__c.__P===e&&(n.__e&&t.appendChild(n.__e),n.__c.__e=!0,n.__c.__P=t)),n}function kd(){this.__u=0,this.o=null,this.__b=null}function Iy(n){var e=n.__.__c;return e&&e.__a&&e.__a(n)}function Ca(){this.i=null,this.l=null}ee.unmount=function(n){var e=n.__c;e&&e.__R&&e.__R(),e&&32&n.__u&&(n.type=null),Ey&&Ey(n)},(kd.prototype=new Vn).__c=function(n,e){var t=e.__c,r=this;r.o==null&&(r.o=[]),r.o.push(t);var i=Iy(r.__v),A=!1,s=function(){A||(A=!0,t.__R=null,i?i(o):o())};t.__R=s;var o=function(){if(!--r.__u){if(r.state.__a){var a=r.state.__a;r.__v.__k[0]=Ty(a,a.__c.__P,a.__c.__O)}var c;for(r.setState({__a:r.__b=null});c=r.o.pop();)c.forceUpdate()}};r.__u++||32&e.__u||r.setState({__a:r.__b=r.__v.__k[0]}),n.then(s,s)},kd.prototype.componentWillUnmount=function(){this.o=[]},kd.prototype.render=function(n,e){if(this.__b){if(this.__v.__k){var t=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=Uy(this.__b,t,r.__O=r.__P)}this.__b=null}var i=e.__a&&pd(St,null,n.fallback);return i&&(i.__u&=-33),[pd(St,null,e.__a?null:n.children),i]};var Fy=function(n,e,t){if(++t[1]===t[0]&&n.l.delete(e),n.props.revealOrder&&(n.props.revealOrder[0]!=="t"||!n.l.size))for(t=n.i;t;){for(;t.length>3;)t.pop()();if(t[1]<t[0])break;n.i=t=t[2]}};(Ca.prototype=new Vn).__a=function(n){var e=this,t=Iy(e.__v),r=e.l.get(n);return r[0]++,function(i){var A=function(){e.props.revealOrder?(r.push(i),Fy(e,n,r)):i()};t?t(A):A()}},Ca.prototype.render=function(n){this.i=null,this.l=new Map;var e=ya(n.children);n.revealOrder&&n.revealOrder[0]==="b"&&e.reverse();for(var t=e.length;t--;)this.l.set(e[t],this.i=[1,0,this.i]);return n.children},Ca.prototype.componentDidUpdate=Ca.prototype.componentDidMount=function(){var n=this;this.l.forEach(function(e,t){Fy(n,t,e)})};var MQ=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,LQ=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,DQ=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,NQ=/[A-Z0-9]/g,HQ=typeof document<"u",KQ=function(n){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(n)};Vn.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(n){Object.defineProperty(Vn.prototype,n,{configurable:!0,get:function(){return this["UNSAFE_"+n]},set:function(e){Object.defineProperty(this,n,{configurable:!0,writable:!0,value:e})}})});var xy=ee.event;function VQ(){}function GQ(){return this.cancelBubble}function jQ(){return this.defaultPrevented}ee.event=function(n){return xy&&(n=xy(n)),n.persist=VQ,n.isPropagationStopped=GQ,n.isDefaultPrevented=jQ,n.nativeEvent=n};var WQ={enumerable:!1,configurable:!0,get:function(){return this.class}},Qy=ee.vnode;ee.vnode=function(n){typeof n.type=="string"&&function(e){var t=e.props,r=e.type,i={},A=r.indexOf("-")===-1;for(var s in t){var o=t[s];if(!(s==="value"&&"defaultValue"in t&&o==null||HQ&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var a=s.toLowerCase();s==="defaultValue"&&"value"in t&&t.value==null?s="value":s==="download"&&o===!0?o="":a==="translate"&&o==="no"?o=!1:a[0]==="o"&&a[1]==="n"?a==="ondoubleclick"?s="ondblclick":a!=="onchange"||r!=="input"&&r!=="textarea"||KQ(t.type)?a==="onfocus"?s="onfocusin":a==="onblur"?s="onfocusout":DQ.test(s)&&(s=a):a=s="oninput":A&&LQ.test(s)?s=s.replace(NQ,"-$&").toLowerCase():o===null&&(o=void 0),a==="oninput"&&i[s=a]&&(s="oninputCapture"),i[s]=o}}r=="select"&&i.multiple&&Array.isArray(i.value)&&(i.value=ya(t.children).forEach(function(c){c.props.selected=i.value.indexOf(c.props.value)!=-1})),r=="select"&&i.defaultValue!=null&&(i.value=ya(t.children).forEach(function(c){c.props.selected=i.multiple?i.defaultValue.indexOf(c.props.value)!=-1:i.defaultValue==c.props.value})),t.class&&!t.className?(i.class=t.class,Object.defineProperty(i,"className",WQ)):(t.className&&!t.class||t.class&&t.className)&&(i.class=i.className=t.className),e.props=i}(n),n.$$typeof=MQ,Qy&&Qy(n)};var Ry=ee.__r;ee.__r=function(n){Ry&&Ry(n),n.__c};var Py=ee.diffed;ee.diffed=function(n){Py&&Py(n);var e=n.props,t=n.__e;t!=null&&n.type==="textarea"&&"value"in e&&e.value!==t.value&&(t.value=e.value==null?"":e.value)};function qQ(n){const{placeholder:e="Type your message...",value:t,defaultValue:r,onChange:i,onSend:A,onCancel:s,onExpand:o,isLoading:a=!1,disabled:c=!1,maxLength:u=500,children:l}=n,[d,h]=ge(t||r||""),[f,p]=ge((t||r||"").length>24),g=En(null);yd(()=>{f&&(o==null||o(!0))},[]);const v=t!==void 0?t:d,y=w=>{const _=w.currentTarget.value;t===void 0&&h(_),i==null||i(_)},B=w=>{w.key==="Escape"&&(h(t||r||""),p(!1),s==null||s()),w.key==="Enter"&&!w.shiftKey&&v.trim()&&(w.preventDefault(),h(t||r||""),p(!1),b()),(v||"").length>=24&&!f&&(p(!0),o==null||o(!0))};Kt(()=>{g.current&&g.current.focus()},[g.current]);const b=()=>{!v.trim()||a||c||(A==null||A(v.trim()),t===void 0&&h(""))};return C("div",{className:`obi-message-input ${f?"expanded":""}`,children:[C("div",{className:"container",children:C("textarea",{ref:g,className:"field",placeholder:e,value:v,onInput:y,onKeyDown:B,disabled:c||a,maxLength:u,rows:1})}),C("div",{className:"button-container",children:[f&&C("div",{children:l}),C("button",{className:"obi-button send",onClick:b,disabled:!v.trim()||a||c,type:"button",children:C("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:C("path",{d:"M6.00016 10.6673V1.33398M6.00016 1.33398L1.3335 6.00065M6.00016 1.33398L10.6668 6.00065",stroke:"#F3F3F3","stroke-width":"1.6","stroke-linecap":"round","stroke-linejoin":"round"})})})]})]})}function JQ(n){const{currentStep:e,totalSteps:t,stepNames:r,className:i}=n,A=Array.from({length:t},(a,c)=>({isCompleted:c<e,stepNumber:c+1})),s=r[e-1]||`Step ${e}`,o=`${e}/${t} \u2022 ${s}`;return C("div",{class:`obi-course-progress ${i||""}`,children:[C("div",{class:"obi-course-progress-steps",children:A.map((a,c)=>C("div",{class:"obi-course-progress-container",children:C("div",{class:`obi-course-progress-step ${a.isCompleted?"completed":""}`})},c))}),C("div",{class:"obi-course-progress-description",children:o})]})}function Ed({className:n="",size:e=64}){return C("svg",{width:e,height:e,viewBox:"0 0 256 256",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:n,children:C("path",{d:"M158.803 0L160.352 0.0399439C176.267 0.844061 188.922 13.9634 188.922 30.0311C188.922 46.6174 175.438 60.0653 158.803 60.0656H99.0263L98.9061 60.0722C78.8071 61.4795 62.6269 77.004 60.2644 96.7673L60.241 96.9704V158.93L60.2644 159.13C62.7406 179.86 80.4234 195.934 101.881 195.935H153.842C176.993 195.935 195.759 177.223 195.759 154.14V96.9138L195.799 95.3693C196.606 79.5009 209.766 66.8827 225.881 66.8827C242.515 66.8834 256 80.328 256 96.9138V159.086L255.963 160.564C255.225 175.748 243.176 187.971 228.038 189.038V189.214C207.121 190.591 190.4 207.263 189.019 228.119H188.842C187.738 243.7 174.712 256 158.803 256H96.4491C79.8147 256 66.3309 242.555 66.3302 225.969C66.3302 225.673 66.3349 225.375 66.3436 225.077H66.3503H66.3035C63.3344 206.008 47.4427 190.589 27.8321 189.231L27.8354 189.031C12.2702 187.868 0.000167669 174.905 0 159.086V96.9138L0.0367222 95.4192C0.791087 80.0787 13.0909 67.7634 28.453 66.9293C47.7697 65.3039 63.3522 50.3234 66.2969 31.4658L66.3469 31.1595L66.3369 30.85C66.3301 30.5933 66.3302 30.3238 66.3302 30.0311C66.3309 13.4454 79.8148 0.000165137 96.4491 0H158.803Z",fill:"currentColor"})})}function zQ({children:n}){const e={container:{position:"relative",width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},logo:{display:"flex",width:"120px",height:"120px",justifyContent:"center",alignItems:"center",aspectRatio:"1/1",borderRadius:"8px",color:"#FFFFFF",position:"relative",overflow:"hidden",background:"var(--obi-color-primary)",boxShadow:`
|
|
43
43
|
0 0 20px color-mix(in srgb, var(--obi-color-primary) 20%, transparent),
|
|
44
44
|
0 0 40px color-mix(in srgb, var(--obi-color-primary) 15%, transparent),
|
|
45
45
|
0 0 60px color-mix(in srgb, var(--obi-color-primary) 8%, transparent)
|