obi-sdk 0.19.40-beta.1 → 0.19.41
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 +2 -2
- package/dist/obi-sdk.standalone.iife.js +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -39,7 +39,7 @@ a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
|
|
|
39
39
|
`).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
|
|
40
40
|
`);n.RTCSessionDescription&&r instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:r.type,sdp:s}):r.sdp=s}return t.apply(this,arguments)}}function zs(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 Hs(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 r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return t.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?t.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}var yS=Object.freeze({__proto__:null,removeExtmapAllowMixed:Vo,shimAddIceCandidateNullOrEmpty:zs,shimConnectionState:jo,shimMaxMessageSize:Vs,shimParameterlessSetLocalDescription:Hs,shimRTCIceCandidate:js,shimRTCIceCandidateRelayProtocol:Fo,shimSendThrowTypeError:Gs});function TS(){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=vh,i=mS(n),r={browserDetails:i,commonShim:yS,extractVersion:Fs,disableLog:fS,disableWarnings:pS,sdp:bS};switch(i.browser){case"chrome":if(!Ih||!Do||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),r;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),r;t("adapter.js shimming chrome."),r.browserShim=Ih,zs(n,i),Hs(n),Sh(n,i),Ch(n),Do(n,i),wh(n),Rh(n,i),xh(n),_h(n),Ph(n,i),js(n),Fo(n),jo(n),Vs(n,i),Gs(n),Vo(n,i);break;case"firefox":if(!Vh||!Uo||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),r;t("adapter.js shimming firefox."),r.browserShim=Vh,zs(n,i),Hs(n),Oh(n,i),Uo(n,i),Ah(n),Lh(n),Nh(n),Mh(n),Dh(n),Uh(n),Bh(n),Fh(n),jh(n),js(n),jo(n),Vs(n,i),Gs(n);break;case"safari":if(!Jh||!e.shimSafari)return t("Safari shim is not included in this adapter release."),r;t("adapter.js shimming safari."),r.browserShim=Jh,zs(n,i),Hs(n),Kh(n),Yh(n),Hh(n),Gh(n),zh(n),$h(n),Wh(n),Xh(n),js(n),Fo(n),Vs(n,i),Gs(n),Vo(n,i);break;default:t("Unsupported browser!");break}return r}TS({window:typeof window>"u"?void 0:window});const kS=10,Ws="lk_e2ee",SS={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:kS,keyringSize:16};var An;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(An||(An={}));var ef;(function(n){n.KeyRatcheted="keyRatcheted"})(ef||(ef={}));var Nn;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(Nn||(Nn={}));var tf;(function(n){n.Error="cryptorError"})(tf||(tf={}));function CS(){return wS()||Go()}function Go(){return typeof window.RTCRtpScriptTransform<"u"}function wS(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class k_ extends Yt.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,i,r)=>{re.debug("key ratcheted event received",{ratchetResult:t,participantId:i,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},SS),e),this.on(An.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){const r={key:e,participantIdentity:t,keyIndex:i};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(i??0),r),this.emit(An.SetKey,r)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(An.RatchetRequest,e,t)}}class Mn extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var se;(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"})(se||(se={}));class me extends Mn{constructor(e,t,i,r){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=r,this.reasonName=se[t]}}class zo extends Mn{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class sn extends Mn{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class xS extends Mn{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class Ge extends Mn{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Ho extends Mn{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Wo extends Mn{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class nf extends Mn{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:Ao[t]}}var qs;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(qs||(qs={})),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}(qs||(qs={}));var rf;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(rf||(rf={}));var M;(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"})(M||(M={}));var j;(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"})(j||(j={}));var U;(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"})(U||(U={}));var D;(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"})(D||(D={}));function _S(n){return typeof n>"u"?n:typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}const ES=/version\/(\d+(\.?_?\d+)+)/i;let qo;function Lt(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(qo===void 0||e){const i=RS.find(r=>{let{test:s}=r;return s.test(t)});qo=i==null?void 0:i.describe(t)}return qo}const RS=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:Ks(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Ko(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:Ks(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Ko(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:Ks(ES,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:Ko(n)}}}];function Ks(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(n);return i&&i.length>=t&&i[t]||""}function Ko(n){return n.includes("mac os")?Ks(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var PS="2.13.0";const IS=PS,OS=16;class Je{}Je.setTimeout=function(){return setTimeout(...arguments)},Je.setInterval=function(){return setInterval(...arguments)},Je.clearTimeout=function(){return clearTimeout(...arguments)},Je.clearInterval=function(){return clearInterval(...arguments)};const AS=5e3,lr=[];var Ct;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Ct||(Ct={}));class I extends Yt.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=I.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=re,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),AS):this.handleAppVisibilityChanged()},this.log=rn((r=i.loggerName)!==null&&r!==void 0?r:Mt.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=I.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),ue(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===I.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===I.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(lr.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&lr.splice(lr.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),_i(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),r=i.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?D.AudioPlaybackStarted:D.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?D.AudioPlaybackFailed:D.VideoPlaybackFailed,s):s.name==="AbortError"?re.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):re.warn("could not playback ".concat(r?"audio":"video"),s),r&&e&&i.some(a=>a.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(D.ElementAttached,e),e}detach(e){try{if(e){Ei(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(D.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(i=>{Ei(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(D.ElementDetached,i)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=rn(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),lr.forEach(i=>{i.parentElement||(t=!1)}),t&&lr.push(e)}}handleAppVisibilityChanged(){return y(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===I.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){pt()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){pt()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function _i(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let i;n.kind==="audio"?i=t.getAudioTracks():i=t.getVideoTracks(),i.includes(n)||(i.forEach(r=>{t.removeTrack(r)}),t.addTrack(n)),(!Ln()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(Ln()||Ri())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Ei(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(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(t=n.Source||(n.Source={}));let i;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(i=n.StreamState||(n.StreamState={}));function r(l){switch(l){case e.Audio:return It.AUDIO;case e.Video:return It.VIDEO;default:return It.DATA}}n.kindToProto=r;function s(l){switch(l){case It.AUDIO:return e.Audio;case It.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=s;function a(l){switch(l){case t.Camera:return Ue.CAMERA;case t.Microphone:return Ue.MICROPHONE;case t.ScreenShare:return Ue.SCREEN_SHARE;case t.ScreenShareAudio:return Ue.SCREEN_SHARE_AUDIO;default:return Ue.UNKNOWN}}n.sourceToProto=a;function o(l){switch(l){case Ue.CAMERA:return t.Camera;case Ue.MICROPHONE:return t.Microphone;case Ue.SCREEN_SHARE:return t.ScreenShare;case Ue.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function c(l){switch(l){case xo.ACTIVE:return i.Active;case xo.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=c})(I||(I={}));class pe{constructor(e,t,i,r,s){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&i!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:r,priority:s};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 NS=["vp8","h264"],MS=["vp8","h264","vp9","av1"];function LS(n){return!!NS.find(e=>e===n)}var sf;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(sf||(sf={}));var $o;(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}})($o||($o={}));const ur={h90:new pe(160,90,9e4,20),h180:new pe(320,180,16e4,20),h216:new pe(384,216,18e4,20),h360:new pe(640,360,45e4,20),h540:new pe(960,540,8e5,25),h720:new pe(1280,720,17e5,30),h1080:new pe(1920,1080,3e6,30),h1440:new pe(2560,1440,5e6,30),h2160:new pe(3840,2160,8e6,30)},Yo={h120:new pe(160,120,7e4,20),h180:new pe(240,180,125e3,20),h240:new pe(320,240,14e4,20),h360:new pe(480,360,33e4,20),h480:new pe(640,480,5e5,20),h540:new pe(720,540,6e5,25),h720:new pe(960,720,13e5,30),h1080:new pe(1440,1080,23e5,30),h1440:new pe(1920,1440,38e5,30)},Xo={h360fps3:new pe(640,360,2e5,3,"medium"),h360fps15:new pe(640,360,4e5,15,"medium"),h720fps5:new pe(1280,720,8e5,5,"medium"),h720fps15:new pe(1280,720,15e5,15,"medium"),h720fps30:new pe(1280,720,2e6,30,"medium"),h1080fps15:new pe(1920,1080,25e5,15,"medium"),h1080fps30:new pe(1920,1080,5e6,30,"medium"),original:new pe(0,0,7e6,30,"medium")},DS="|",af="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function US(n){const e=n.split(DS);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function ft(n){return y(this,void 0,void 0,function*(){return new Promise(e=>Je.setTimeout(e,n))})}function Jo(){return"addTransceiver"in RTCPeerConnection.prototype}function Qo(){return"addTrack"in RTCPeerConnection.prototype}function BS(){if(!("getCapabilities"in RTCRtpSender)||Ln())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 FS(){if(!("getCapabilities"in RTCRtpSender)||Ri())return!1;if(Ln()){const t=Lt();if(t!=null&&t.version&&Jn(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 dr(n){return n==="av1"||n==="vp9"}function Zo(n){return document?(n||(n=document.createElement("audio")),"setSinkId"in n):!1}function jS(){return typeof RTCPeerConnection>"u"?!1:Jo()||Qo()}function Ri(){var n;return((n=Lt())===null||n===void 0?void 0:n.name)==="Firefox"}function Ln(){var n;return((n=Lt())===null||n===void 0?void 0:n.name)==="Safari"}function VS(){const n=Lt();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")}function of(){var n,e;return pt()?(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 GS(){const n=Lt(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&Jn(e,n.osVersion)>=0?!0:n.name==="Safari"&&Jn(e,n.version)>=0}function pt(){return typeof document<"u"}function Xt(){return navigator.product=="ReactNative"}function ec(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function cf(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function lf(){if(!Xt())return;let n=cf();if(n)return n.platform}function uf(){if(pt())return window.devicePixelRatio;if(Xt()){let n=cf();if(n)return n.devicePixelRatio}return 1}function Jn(n,e){const t=n.split("."),i=e.split("."),r=Math.min(t.length,i.length);for(let s=0;s<r;++s){const a=parseInt(t[s],10),o=parseInt(i[s],10);if(a>o)return 1;if(a<o)return-1;if(s===r-1&&a===o)return 0}return n===""&&e!==""?-1:e===""?1:t.length==i.length?0:t.length<i.length?-1:1}function zS(n){for(const e of n)e.target.handleResize(e)}function HS(n){for(const e of n)e.target.handleVisibilityChanged(e)}let tc=null;const df=()=>(tc||(tc=new ResizeObserver(zS)),tc);let nc=null;const hf=()=>(nc||(nc=new IntersectionObserver(HS,{root:null,rootMargin:"0px"})),nc);function WS(){var n;const e=new Mk({sdk:Yd.JS,protocol:OS,version:IS});return Xt()&&(e.os=(n=lf())!==null&&n!==void 0?n:""),e}function ff(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const r=document.createElement("canvas");r.width=n,r.height=e;const s=r.getContext("2d");s==null||s.fillRect(0,0,r.width,r.height),i&&s&&(s.beginPath(),s.arc(n/2,e/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());const a=r.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let hr;function ic(){if(!hr){const n=new AudioContext,e=n.createOscillator(),t=n.createGain();t.gain.setValueAtTime(0,0);const i=n.createMediaStreamDestination();if(e.connect(t),t.connect(i),e.start(),[hr]=i.stream.getAudioTracks(),!hr)throw Error("Could not get empty media stream audio track");hr.enabled=!1}return hr.clone()}class rc{constructor(e,t){this.onFinally=t,this.promise=new Promise((i,r)=>y(this,void 0,void 0,function*(){this.resolve=i,this.reject=r,e&&(yield e(i,r))})).finally(()=>{var i;return(i=this.onFinally)===null||i===void 0?void 0:i.call(this)})}}function qS(n){return MS.includes(n)}function Dn(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 KS(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function sc(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function $S(n,e){return n.segments.map(t=>{let{id:i,text:r,language:s,startTime:a,endTime:o,final:c}=t;var l;const u=(l=e.get(i))!==null&&l!==void 0?l:Date.now(),d=Date.now();return c?e.delete(i):e.set(i,u),{id:i,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:c,language:s,firstReceivedTime:u,lastReceivedTime:d}})}function YS(n){const{id:e,timestamp:t,message:i,editTimestamp:r}=n;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:i}}function pf(n){switch(n.reason){case se.LeaveRequest:return n.context;case se.Cancelled:return Ot.CLIENT_INITIATED;case se.NotAllowed:return Ot.USER_REJECTED;case se.ServerUnreachable:return Ot.JOIN_FAILURE;default:return Ot.UNKNOWN_REASON}}function $s(n){return n!==void 0?Number(n):void 0}function Qn(n){return n!==void 0?BigInt(n):void 0}function Pi(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function an(n){return!!n&&n.kind==I.Kind.Audio}function Ii(n){return!!n&&n.kind==I.Kind.Video}function Un(n){return Pi(n)&&Ii(n)}function Zn(n){return Pi(n)&&an(n)}function ac(n){return!!n&&!n.isLocal}function XS(n){return!!n&&!n.isLocal}function oc(n){return ac(n)&&Ii(n)}function JS(n){return n.isLocal}function QS(n,e){const t=[];let i=new TextEncoder().encode(n);for(;i.length>e;){let r=e;for(;r>0;){const s=i[r];if(s!==void 0&&(s&192)!==128)break;r--}t.push(i.slice(0,r)),i=i.slice(r)}return i.length>0&&t.push(i),t}function mf(n,e,t){var i,r,s,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:l}=yf(n??{}),u=e==null?void 0:e.processor,d=t==null?void 0:t.processor,h=o??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(cc(h.audio,e),(i=(s=h.audio).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||u)&&(h.audio.processor=c??u)),h.video&&(cc(h.video,t),(r=(a=h.video).deviceId)!==null&&r!==void 0||(a.deviceId={ideal:"default"}),(l||d)&&(h.video.processor=l??d)),h}function cc(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function lc(n){var e,t,i,r;const s={};if(n.video)if(typeof n.video=="object"){const a={},o=a,c=n.video;Object.keys(c).forEach(l=>{switch(l){case"resolution":cc(o,c.resolution);break;default:o[l]=c[l]}}),s.video=a,(e=(i=s.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else s.video=n.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return n.audio?typeof n.audio=="object"?(s.audio=n.audio,(t=(r=s.audio).deviceId)!==null&&t!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function gf(n){return y(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const i=vf();if(i){const r=i.createAnalyser();r.fftSize=2048;const s=r.frequencyBinCount,a=new Uint8Array(s);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield ft(t),r.getByteTimeDomainData(a);const c=a.some(l=>l!==128&&l!==0);return i.close(),!c}return!1}()})}function vf(){var n;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((n=window.document)===null||n===void 0)&&n.body)){const i=()=>y(this,void 0,void 0,function*(){var r;try{t.state==="suspended"&&(yield t.resume())}catch(s){console.warn("Error trying to auto-resume audio context",s)}(r=window.document.body)===null||r===void 0||r.removeEventListener("click",i)});window.document.body.addEventListener("click",i)}return t}}function ZS(n){return n==="audioinput"?I.Source.Microphone:n==="videoinput"?I.Source.Camera:I.Source.Unknown}function bf(n){return n===I.Source.Microphone?"audioinput":n===I.Source.Camera?"videoinput":void 0}function eC(n){var e,t;let i=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(i=typeof i=="boolean"?{}:i,Ln()?i=Object.assign(Object.assign({},i),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:n.resolution.width},height:{ideal:n.resolution.height},frameRate:n.resolution.frameRate})),{audio:(t=n.audio)!==null&&t!==void 0?t:!1,video:i,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function Ys(n){return n.split("/")[1].toLowerCase()}function tC(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new Io({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function ue(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?ue(n.track):{})}}function nC(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function iC(n,e){var t;n===void 0&&(n={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(n)],r={};for(const s of i)n[s]!==e[s]&&(r[s]=(t=e[s])!==null&&t!==void 0?t:"");return r}function yf(n){const e=Object.assign({},n);let t,i;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(i=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:_S(e)}}function rC(n){switch(n){case Ue.CAMERA:return I.Source.Camera;case Ue.MICROPHONE:return I.Source.Microphone;case Ue.SCREEN_SHARE:return I.Source.ScreenShare;case Ue.SCREEN_SHARE_AUDIO:return I.Source.ScreenShareAudio;default:return I.Source.Unknown}}class sC extends Yt.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var i,r;const{kind:s,data:a}=t.data;switch(s){case"error":re.error(a.error.message),this.emit(Nn.EncryptionError,a.error);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)}),this.encryptionEnabled!==a.enabled&&a.participantIdentity===((i=this.room)===null||i===void 0?void 0:i.localParticipant.identity))this.emit(Nn.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const o=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(a.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit(Nn.ParticipantEncryptionStatusChanged,a.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(An.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break}},this.onWorkerError=t=>{re.error("e2ee worker encountered an error:",{error:t.error}),this.emit(Nn.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!CS())throw new zo("tried to setup end-to-end encryption on an unsupported browser");if(re.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:cS.getLevel()}};this.worker&&(re.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){re.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?re.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(U.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(M.TrackPublished,(i,r)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==vt.NONE,r.identity)),e.on(M.ConnectionStateChanged,i=>{i===ce.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==vt.NONE,r.identity)})})}).on(M.TrackUnsubscribed,(i,r,s)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:i.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(M.TrackSubscribed,(i,r,s)=>{this.setupE2EEReceiver(i,s.identity,r.trackInfo)}).on(M.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(j.LocalTrackPublished,i=>y(this,void 0,void 0,function*(){this.setupE2EESender(i.track,i.track.sender)})),t.on(An.SetKey,i=>this.postKey(i)).on(An.RatchetRequest,(i,r)=>this.postRatchetRequest(i,r))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:r}=e;var s;if(!this.worker)throw Error("could not set key, worker is missing");const a={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity),key:t,keyIndex:r}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){const i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(i!=null&&i.mimeType)||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?Ys(i.mimeType):void 0)}}setupE2EESender(e,t){if(!Pi(e)||!t){t||re.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,r){return y(this,void 0,void 0,function*(){if(this.worker){if(Go()){const s={kind:"decode",participantIdentity:i,trackId:t,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{if(Ws in e&&r){const c={kind:"updateCodec",data:{trackId:t,codec:r,participantIdentity:i}};this.worker.postMessage(c);return}let s=e.writableStream,a=e.readableStream;if(!s||!a){const c=e.createEncodedStreams();e.writableStream=c.writable,s=c.writable,e.readableStream=c.readable,a=c.readable}const o={kind:"decode",data:{readableStream:a,writableStream:s,trackId:t,codec:r,participantIdentity:i}};this.worker.postMessage(o,[a,s])}e[Ws]=!0}})}handleSender(e,t,i){var r;if(!(Ws in e||!this.worker)){if(!(!((r=this.room)===null||r===void 0)&&r.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Go()){re.info("initialize script transform");const s={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,s)}else{re.info("initialize encoded streams");const s=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:s.readable,writableStream:s.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(a,[s.readable,s.writable])}e[Ws]=!0}}}const uc="default";class He{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new He),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;if(((s=He.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){re.debug("awaiting getUserMedia promise");try{t?yield He.userMediaPromiseMap.get(t):yield Promise.all(He.userMediaPromiseMap.values())}catch{re.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(r&&!(Ln()&&i.hasDeviceInUse(t))&&(a.filter(c=>c.kind===t).length===0||a.some(c=>{const l=c.label==="",u=t?c.kind===t:!0;return l&&u}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(c);a=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEach(u=>{u.stop()})}return i._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a}()})}normalizeDeviceId(e,t,i){return y(this,void 0,void 0,function*(){if(t!==uc)return t;const r=yield this.getDevices(e),s=r.find(o=>o.deviceId===uc);if(!s){re.warn("could not reliably determine default device");return}const a=r.find(o=>o.deviceId!==uc&&o.groupId===(i??s.groupId));if(!a){re.warn("could not reliably determine default device");return}return a==null?void 0:a.deviceId})}hasDeviceInUse(e){return e?He.userMediaPromiseMap.has(e):He.userMediaPromiseMap.size>0}}He.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],He.userMediaPromiseMap=new Map;var fr;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(fr||(fr={}));class aC{constructor(){this.pendingTasks=new Map,this.taskMutex=new ut,this.nextTaskIndex=0}run(e){return y(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:fr.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=fr.RUNNING,yield e()}finally{t.status=fr.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return y(this,void 0,void 0,function*(){return this.run(()=>y(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function oC(n,e){const t=new URL(KS(n));return e.forEach((i,r)=>{t.searchParams.set(r,i)}),Tf(t,"rtc")}function cC(n){const e=new URL(sc(n));return Tf(e,"validate")}function lC(n){return n.endsWith("/")?n:"".concat(n,"/")}function Tf(n,e){return n.pathname="".concat(lC(n.pathname)).concat(e),n.toString()}const uC=["syncState","trickle","offer","answer","simulate","leave"];function dC(n){const e=uC.indexOf(n.case)>=0;return re.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var be;(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"})(be||(be={}));class dc{get currentState(){return this.state}get isDisconnected(){return this.state===be.DISCONNECTING||this.state===be.DISCONNECTED}get isEstablishingConnection(){return this.state===be.CONNECTING||this.state===be.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=be.DISCONNECTED,this.log=re,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=rn((i=t.loggerName)!==null&&i!==void 0?i:Mt.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new aC,this.queuedRequests=[],this.closingLock=new ut,this.connectionLock=new ut,this.state=be.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,i,r){return y(this,void 0,void 0,function*(){return this.state=be.CONNECTING,this.options=i,yield this.connect(e,t,i,r)})}reconnect(e,t,i,r){return y(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=be.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:r}))})}connect(e,t,i,r){this.connectOptions=i;const s=WS(),a=hC(t,s,i),o=oC(e,a),c=cC(o);return new Promise((l,u)=>y(this,void 0,void 0,function*(){const d=yield this.connectionLock.lock();try{const h=()=>y(this,void 0,void 0,function*(){this.close(),clearTimeout(f),u(new me("room connection has been cancelled (signal)",se.Cancelled))}),f=setTimeout(()=>{this.close(),u(new me("room connection has timed out (signal)",se.ServerUnreachable))},i.websocketTimeout);r!=null&&r.aborted&&h(),r==null||r.addEventListener("abort",h);const m=new URL(o);m.searchParams.has("access_token")&&m.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(m),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(f)},this.ws.onerror=p=>y(this,void 0,void 0,function*(){if(this.state!==be.CONNECTED){this.state=be.DISCONNECTED,clearTimeout(f);try{const v=yield fetch(c);if(v.status.toFixed(0).startsWith("4")){const b=yield v.text();u(new me(b,se.NotAllowed,v.status))}else u(new me("Encountered unknown websocket error during connection: ".concat(p.toString()),se.InternalError,v.status))}catch(v){u(new me(v instanceof Error?v.message:"server was not reachable",se.ServerUnreachable))}return}this.handleWSError(p)}),this.ws.onmessage=p=>y(this,void 0,void 0,function*(){var v,b,C;let x;if(typeof p.data=="string"){const k=JSON.parse(p.data);x=th.fromJson(k,{ignoreUnknownFields:!0})}else if(p.data instanceof ArrayBuffer)x=th.fromBinary(new Uint8Array(p.data));else{this.log.error("could not decode websocket message: ".concat(typeof p.data),this.logContext);return}if(this.state!==be.CONNECTED){let k=!1;if(((v=x.message)===null||v===void 0?void 0:v.case)==="join"?(this.state=be.CONNECTED,r==null||r.removeEventListener("abort",h),this.pingTimeoutDuration=x.message.value.pingTimeout,this.pingIntervalDuration=x.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()),l(x.message.value)):this.state===be.RECONNECTING&&x.message.case!=="leave"?(this.state=be.CONNECTED,r==null||r.removeEventListener("abort",h),this.startPingInterval(),((b=x.message)===null||b===void 0?void 0:b.case)==="reconnect"?l(x.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),l(void 0),k=!0)):this.isEstablishingConnection&&x.message.case==="leave"?u(new me("Received leave request while trying to (re)connect",se.LeaveRequest,void 0,x.message.value.reason)):i.reconnect||u(new me("did not receive join response, got ".concat((C=x.message)===null||C===void 0?void 0:C.case," instead"),se.InternalError)),!k)return}this.signalLatency&&(yield ft(this.signalLatency)),this.handleSignalResponse(x)}),this.ws.onclose=p=>{this.isEstablishingConnection&&u(new me("Websocket got closed during a (re)connection attempt",se.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:p.reason,code:p.code,wasClean:p.wasClean,state:this.state})),this.handleOnClose(p.reason)}}finally{d()}}))}close(){return y(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=be.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const r=new Promise(s=>{e.ws?e.ws.onclose=()=>{s()}:s()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([r,ft(250)])),e.ws=void 0}}finally{t&&(e.state=be.DISCONNECTED),i()}}()})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Xs(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Xs(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 Ro({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Po({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return y(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const o=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new sh({requestId:o,metadata:i,name:r,attributes:a})}),o}()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new rh({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new ch({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:we.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new dh({timestamp:we.parse(Date.now()),rtt:we.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new ih({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Ls({reason:Ot.CLIENT_INITIATED,action:wi.DISCONNECT})})}sendRequest(e){return y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!r&&!dC(t)&&i.state===be.RECONNECTING){i.queuedRequests.push(()=>y(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(r||(yield i.requestQueue.flush()),i.signalLatency&&(yield ft(i.signalLatency)),!i.ws||i.ws.readyState!==i.ws.OPEN){i.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),i.logContext);return}const a=new Uk({message:t});try{i.useJSON?i.ws.send(a.toJsonString()):i.ws.send(a.toBinary())}catch(o){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:o}))}}()})}handleSignalResponse(e){var t,i;const r=e.message;if(r==null){this.log.debug("received unsupported message",this.logContext);return}let s=!1;if(r.case==="answer"){const a=kf(r.value);this.onAnswer&&this.onAnswer(a)}else if(r.case==="offer"){const a=kf(r.value);this.onOffer&&this.onOffer(a)}else if(r.case==="trickle"){const a=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(a,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=r.value.participants)!==null&&t!==void 0?t:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((i=r.value.speakers)!==null&&i!==void 0?i:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):r.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(r.value):r.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(r.value.trackSid):r.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(r.value.token),this.onRoomMoved&&this.onRoomMoved(r.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:r.case})));s||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return y(this,void 0,void 0,function*(){if(this.state===be.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=Je.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&&Je.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=Je.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Je.clearInterval(this.pingInterval)}}function kf(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 Xs(n){return new Yn({sdp:n.sdp,type:n.type})}function hC(n,e,t){var i;const r=new URLSearchParams;return r.set("access_token",n),t.reconnect&&(r.set("reconnect","1"),t.sid&&r.set("sid",t.sid)),r.set("auto_subscribe",t.autoSubscribe?"1":"0"),r.set("sdk",Xt()?"reactnative":"js"),r.set("version",e.version),r.set("protocol",e.protocol.toString()),e.deviceModel&&r.set("device_model",e.deviceModel),e.os&&r.set("os",e.os),e.osVersion&&r.set("os_version",e.osVersion),e.browser&&r.set("browser",e.browser),e.browserVersion&&r.set("browser_version",e.browserVersion),t.adaptiveStream&&r.set("adaptive_stream","1"),t.reconnectReason&&r.set("reconnect_reason",t.reconnectReason.toString()),!((i=navigator.connection)===null||i===void 0)&&i.type&&r.set("network",navigator.connection.type),r}var Dt={},hc={},fc={exports:{}},Sf;function pc(){if(Sf)return fc.exports;Sf=1;var n=fc.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(n).forEach(function(e){var t=n[e];t.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),fc.exports}var Cf;function fC(){return Cf||(Cf=1,function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,l,u){if(u&&!l)c[u]=e(o[1]);else for(var d=0;d<l.length;d+=1)o[d+1]!=null&&(c[l[d]]=e(o[d+1]))},i=function(o,c,l){var u=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:u&&!c[o.name]&&(c[o.name]={});var d=o.push?{}:u?c[o.name]:c;t(l.match(o.reg),d,o.names,o.name),o.push&&c[o.push].push(d)},r=pc(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var c={},l=[],u=c;return o.split(/(\r\n|\r|\n)/).filter(s).forEach(function(d){var h=d[0],f=d.slice(2);h==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var m=0;m<(r[h]||[]).length;m+=1){var p=r[h][m];if(p.reg.test(f))return i(p,u,f)}}),c.media=l,c};var a=function(o,c){var l=c.split(/=(.+)/,2);return l.length===2?o[l[0]]=e(l[1]):l.length===1&&c.length>1&&(o[l[0]]=void 0),o};n.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(o){return o.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(o){for(var c=[],l=o.split(" ").map(e),u=0;u<l.length;u+=3)c.push({component:l[u],ip:l[u+1],port:l[u+2]});return c},n.parseImageAttributes=function(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},n.parseSimulcastStreamList=function(o){return o.split(";").map(function(c){return c.split(",").map(function(l){var u,d=!1;return l[0]!=="~"?u=e(l):(u=e(l.substring(1,l.length)),d=!0),{scid:u,paused:d}})})}}(hc)),hc}var mc,wf;function pC(){if(wf)return mc;wf=1;var n=pc(),e=/%[sdv%]/g,t=function(a){var o=1,c=arguments,l=c.length;return a.replace(e,function(u){if(o>=l)return u;var d=c[o];switch(o+=1,u){case"%%":return"%";case"%s":return String(d);case"%d":return Number(d);case"%v":return""}})},i=function(a,o,c){var l=o.format instanceof Function?o.format(o.push?c:c[o.name]):o.format,u=[a+"="+l];if(o.names)for(var d=0;d<o.names.length;d+=1){var h=o.names[d];o.name?u.push(c[o.name][h]):u.push(c[o.names[d]])}else u.push(c[o.name]);return t.apply(null,u)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return mc=function(a,o){o=o||{},a.version==null&&(a.version=0),a.name==null&&(a.name=" "),a.media.forEach(function(d){d.payloads==null&&(d.payloads="")});var c=o.outerOrder||r,l=o.innerOrder||s,u=[];return c.forEach(function(d){n[d].forEach(function(h){h.name in a&&a[h.name]!=null?u.push(i(d,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(f){u.push(i(d,h,f))})})}),a.media.forEach(function(d){u.push(i("m",n.m[0],d)),l.forEach(function(h){n[h].forEach(function(f){f.name in d&&d[f.name]!=null?u.push(i(h,f,d)):f.push in d&&d[f.push]!=null&&d[f.push].forEach(function(m){u.push(i(h,f,m))})})})}),u.join(`\r
|
|
41
41
|
`)+`\r
|
|
42
|
-
`},mc}var xf;function mC(){if(xf)return Dt;xf=1;var n=fC(),e=pC(),t=pc();return Dt.grammar=t,Dt.write=e,Dt.parse=n.parse,Dt.parseParams=n.parseParams,Dt.parseFmtpConfig=n.parseFmtpConfig,Dt.parsePayloads=n.parsePayloads,Dt.parseRemoteCandidates=n.parseRemoteCandidates,Dt.parseImageAttributes=n.parseImageAttributes,Dt.parseSimulcastStreamList=n.parseSimulcastStreamList,Dt}var Bn=mC();function gc(n,e,t){var i,r,s;e===void 0&&(e=50),t===void 0&&(t={});var a=(i=t.isImmediate)!=null&&i,o=(r=t.callback)!=null&&r,c=t.maxWait,l=Date.now(),u=[];function d(){if(c!==void 0){var f=Date.now()-l;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),m=this;return new Promise(function(p,v){var b=a&&s===void 0;if(s!==void 0&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,l=Date.now(),!a){var x=n.apply(m,f);o&&o(x),u.forEach(function(k){return(0,k.resolve)(x)}),u=[]}},d()),b){var C=n.apply(m,f);return o&&o(C),p(C)}u.push({resolve:p,reject:v})})};return h.cancel=function(f){s!==void 0&&clearTimeout(s),u.forEach(function(m){return(0,m.reject)(f)}),u=[]},h}const gC=.7,vC=20,Oi={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class _f extends Yt.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=re,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=gc(r=>y(this,void 0,void 0,function*(){this.emit(Oi.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),vC),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=rn((i=t.loggerName)!==null&&i!==void 0?i:Mt.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return y(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return y(this,void 0,void 0,function*(){var t;let i;if(e.type==="offer"){let{stereoMids:r,nackMids:s}=bC(e);this.remoteStereoMids=r,this.remoteNackMids=s}else if(e.type==="answer"){const r=Bn.parse((t=e.sdp)!==null&&t!==void 0?t:"");r.media.forEach(s=>{s.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||s.mid!=a.transceiver.mid)return!1;let o=0;if(s.rtp.some(l=>l.codec.toUpperCase()===a.codec.toUpperCase()?(o=l.payload,!0):!1),o===0)return!0;let c=!1;for(const l of s.fmtp)if(l.payload===o){l.config=l.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(l.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),c=!0;break}return c||a.maxbr>0&&s.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),i=Bn.write(r)}yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Oi.NegotiationComplete),e.sdp&&Bn.parse(e.sdp).media.forEach(s=>{s.type==="video"&&this.emit(Oi.RTPVideoPayloadTypes,s.rtp)}))})}createAndSendOffer(e){return y(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 s=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&s)yield this._pc.setRemoteDescription(s);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 i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const r=Bn.parse((t=i.sdp)!==null&&t!==void 0?t:"");r.media.forEach(s=>{Rf(s),s.type==="audio"?Ef(s,[],[]):s.type==="video"&&this.trackBitrates.some(a=>{if(!s.msid||!a.cid||!s.msid.includes(a.cid))return!1;let o=0;if(s.rtp.some(l=>l.codec.toUpperCase()===a.codec.toUpperCase()?(o=l.payload,!0):!1),o===0||(dr(a.codec)&&this.ensureVideoDDExtensionForSVC(s,r),a.codec!=="av1"))return!0;const c=Math.round(a.maxbr*gC);for(const l of s.fmtp)if(l.payload===o){l.config.includes("x-google-start-bitrate")||(l.config+=";x-google-start-bitrate=".concat(c));break}return!0})}),yield this.setMungedSDP(i,Bn.write(r)),this.onOffer(i)})}createAndSetAnswer(){return y(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=Bn.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{Rf(r),r.type==="audio"&&Ef(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Bn.write(i)),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 Ge("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 Ge("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 y(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),i.set(o.id,o);break;case"remote-candidate":r.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return r.get(a)})}setMungedSDP(e,t,i){return y(this,void 0,void 0,function*(){if(t){const r=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(s){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:s,sdp:t})),e.sdp=r}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let s="unknown error";r instanceof Error?s=r.message:typeof r=="string"&&(s=r);const a={error:s,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new Ho(s)}})}ensureVideoDDExtensionForSVC(e,t){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===af))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var c;o.type==="video"&&((c=o.ext)===null||c===void 0||c.forEach(l=>{l.value>a&&(a=l.value)}))}),this.ddExtID=a+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:af})}}}function Ef(n,e,t){let i=0;n.rtp.some(r=>r.codec==="opus"?(i=r.payload,!0):!1),i>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(n.mid)&&!n.rtcpFb.some(r=>r.payload===i&&r.type==="nack")&&n.rtcpFb.push({payload:i,type:"nack"}),e.includes(n.mid)&&n.fmtp.some(r=>r.payload===i?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function bC(n){var e;const t=[],i=[],r=Bn.parse((e=n.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(a=>{var o;a.type==="audio"&&(a.rtp.some(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===s&&c.type==="nack")&&i.push(a.mid),a.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&t.push(a.mid),!0):!1))}),{stereoMids:t,nackMids:i}}function Rf(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 vc="vp8",yC={audioPreset:$o.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Xo.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:vc,backupCodec:!0},Pf={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},If={deviceId:{ideal:"default"},resolution:ur.h720.resolution},TC={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new uS,disconnectOnPageLeave:!0,webAudioMix:!1},bc={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Re;(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"})(Re||(Re={}));class kC{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var r;this.peerConnectionTimeout=bc.peerConnectionTimeout,this.log=re,this.updateState=()=>{var s;const a=this.state,o=this.requiredTransports.map(c=>c.getConnectionState());o.every(c=>c==="connected")?this.state=Re.CONNECTED:o.some(c=>c==="failed")?this.state=Re.FAILED:o.some(c=>c==="connecting")?this.state=Re.CONNECTING:o.every(c=>c==="closed")?this.state=Re.CLOSED:o.some(c=>c==="closed")?this.state=Re.CLOSING:o.every(c=>c==="new")&&(this.state=Re.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(Re[a]," to ").concat(Re[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=rn((r=i.loggerName)!==null&&r!==void 0?r:Mt.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new _f(e,i),this.subscriber=new _f(e,i),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=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,Nt.PUBLISHER)},this.subscriber.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,Nt.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,s)},this.subscriber.onTrack=s=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,s)},this.publisher.onOffer=s=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,s)},this.state=Re.NEW,this.connectionLock=new ut,this.remoteOfferLock=new ut}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 y(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(i){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:i}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return y(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return y(this,void 0,void 0,function*(){t===Nt.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return y(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 y(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,e,t)))}finally{r()}})}negotiate(e){return y(this,void 0,void 0,function*(){return new Promise((t,i)=>y(this,void 0,void 0,function*(){const r=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),s=()=>{clearTimeout(r),i("negotiation aborted")};e.signal.addEventListener("abort",s),this.publisher.once(Oi.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Oi.NegotiationComplete,()=>{clearTimeout(r),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(r),i(a)})}))})}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===Nt.PUBLISHER?this.publisher.getConnectedAddress():e===Nt.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 y(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(i.getConnectionState()!=="connected")return new Promise((c,l)=>y(s,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),Je.clearTimeout(d),l(new me("room connection has been cancelled",se.Cancelled))};r!=null&&r.signal.aborted&&u(),r==null||r.signal.addEventListener("abort",u);const d=Je.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",u),l(new me("could not establish pc connection",se.InternalError))},a);for(;this.state!==Re.CONNECTED;)if(yield ft(50),r!=null&&r.signal.aborted){l(new me("room connection has been cancelled",se.Cancelled));return}Je.clearTimeout(d),r==null||r.signal.removeEventListener("abort",u),c()}))}()})}}class Pe extends Error{constructor(e,t,i){super(t),this.code=e,this.message=Af(t,Pe.MAX_MESSAGE_BYTES),this.data=i?Af(i,Pe.MAX_DATA_BYTES):void 0}static fromProto(e){return new Pe(e.code,e.message,e.data)}toProto(){return new qd({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new Pe(Pe.ErrorCode[e],Pe.ErrorMessage[e],t)}}Pe.MAX_MESSAGE_BYTES=256,Pe.MAX_DATA_BYTES=15360,Pe.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},Pe.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 Of=15360;function yc(n){return new TextEncoder().encode(n).length}function Af(n,e){if(yc(n)<=e)return n;let t=0,i=n.length;const r=new TextEncoder;for(;t<i;){const s=Math.floor((t+i+1)/2);r.encode(n.slice(0,s)).length<=e?t=s:i=s-1}return n.slice(0,t)}const Tc=2e3;function Js(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}const SC=1e3;class Nf extends I{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(e,t,s),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=gc(()=>y(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>y(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(D.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new ut,this.pauseUpstreamLock=new ut,this.processorLock=new ut,this.restartLock=new ut,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==I.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 y(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{Ei(this._mediaStreamTrack,s)}),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 r;if(this.processor&&e){const s=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&&(_i(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}finally{s()}}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{_i(r??e,s)}))})}waitForDimensions(){return y(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:SC;return function*(){var i;if(e.kind===I.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=Lt())===null||i===void 0?void 0:i.os)==="iOS"&&(yield ft(10));const r=Date.now();for(;Date.now()-r<t;){const s=e.dimensions;if(s)return s;yield ft(50)}throw new sn("unable to get track dimensions after timeout")}()})}setDeviceId(e){return y(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Dn(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Dn(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return y(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===I.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),s=e.kind===I.Kind.Audio?"audioinput":"videoinput";return t?He.getInstance().normalizeDeviceId(s,i,r):i}()})}mute(){return y(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return y(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return y(this,void 0,void 0,function*(){if(!this.sender)throw new sn("unable to replace an unpublished track");let i,r;return typeof t=="boolean"?i=t:t!==void 0&&(i=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=i??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return y(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:r}=e,s=dS(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===I.Kind.Video?a.video=i||r?{deviceId:i,facingMode:r}:!0:a.audio=i?{deviceId:i}:!0,this.attachedElements.forEach(l=>{Ei(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return yield c.applyConstraints(s),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(D.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?D.Muted:D.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 y(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),of()&&(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 y(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(D.UpstreamPaused,this);const i=Lt();if((i==null?void 0:i.name)==="Safari"&&Jn(i.version,"12.0")<0)throw new zo("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 y(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(D.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 y(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 y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;const a=yield i.processorLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext};if(yield t.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.stopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(_i(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(l=>i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:l}))),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const l of i.attachedElements)l!==i.processorElement&&r&&(Ei(i._mediaStreamTrack,l),_i(i.processor.processedTrack,l));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(D.TrackProcessorUpdate,i.processor)}finally{a()}}()})}getProcessor(){return this.processor}stopProcessor(){return y(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var i,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(D.TrackProcessorUpdate))}()})}}class Qs extends Nf{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,I.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>y(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=Js(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(D.AudioTrackFeatureUpdate,this,At.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(D.AudioTrackFeatureUpdate,this,At.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return y(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===I.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 y(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Dn(this._constraints.deviceId);return this.source===I.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return y(this,void 0,void 0,function*(){let t;if(e){const i=lc({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return y(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){pt()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Tc)))}setProcessor(e){return y(this,void 0,void 0,function*(){var t;const i=yield this.processorLock.lock();try{if(!Xt()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(r),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(D.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return y(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return y(this,void 0,void 0,function*(){const e=yield gf(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(D.AudioSilenceDetected)),e})}}function CC(n,e,t){switch(n.kind){case"audio":return new Qs(n,e,!1,void 0,t);case"video":return new ea(n,e,!1,t);default:throw new sn("unsupported track type: ".concat(n.kind))}}const wC=Object.values(ur),xC=Object.values(Yo),_C=Object.values(Xo),EC=[ur.h180,ur.h360],RC=[Yo.h180,Yo.h360],PC=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,r;return new pe(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=t.fps)!==null&&r!==void 0?r:30))))),t.fps,n.encoding.priority)}),kc=["q","h","f"];function Sc(n,e,t,i){var r,s;let a=i==null?void 0:i.videoEncoding;n&&(a=i==null?void 0:i.screenShareEncoding);const o=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,l=i==null?void 0:i.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=OC(n,e,t,l),re.debug("using video encoding",a));const u=a.maxFramerate,d=new pe(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&dr(l)){const m=new Zs(c),p=[];if(m.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const v=Lt();if(Ln()||Xt()||(v==null?void 0:v.name)==="Chrome"&&Jn(v==null?void 0:v.version,"113")<0){const b=m.suffix=="h"?2:3;for(let C=0;C<m.spatial;C+=1)p.push({rid:kc[2-C],maxBitrate:a.maxBitrate/Math.pow(b,C),maxFramerate:d.encoding.maxFramerate});p[0].scalabilityMode=c}else p.push({maxBitrate:a.maxBitrate,maxFramerate:d.encoding.maxFramerate,scalabilityMode:c});return d.encoding.priority&&(p[0].priority=d.encoding.priority,p[0].networkPriority=d.encoding.priority),re.debug("using svc encoding",{encodings:p}),p}if(!o)return[a];let h=[];n?h=(r=Lf(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:Mf(n,d):h=(s=Lf(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:Mf(n,d);let f;if(h.length>0){const m=h[0];h.length>1&&([,f]=h);const p=Math.max(e,t);if(p>=960&&f)return Cc(e,t,[m,f,d],u);if(p>=480)return Cc(e,t,[m,d],u)}return Cc(e,t,[d])}function IC(n,e,t){var i,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&re.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),c=(i=o.width)!==null&&i!==void 0?i:(r=n.dimensions)===null||r===void 0?void 0:r.width,l=(s=o.height)!==null&&s!==void 0?s:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===I.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Sc(n.source===I.Source.ScreenShare,c,l,t)}function OC(n,e,t,i){const r=AC(n,e,t);let{encoding:s}=r[0];const a=Math.max(e,t);for(let o=0;o<r.length;o+=1){const c=r[o];if(s=c.encoding,c.width>=a)break}if(i)switch(i){case"av1":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function AC(n,e,t){if(n)return _C;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?wC:xC}function Mf(n,e){if(n)return PC(e);const{width:t,height:i}=e,r=t>i?t/i:i/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?EC:RC}function Cc(n,e,t,i){const r=[];if(t.forEach((s,a)=>{if(a>=kc.length)return;const o=Math.min(n,e),l={rid:kc[a],scaleResolutionDownBy:Math.max(1,o/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},u=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;u&&(l.maxFramerate=u);const d=Ri()||a===0;s.encoding.priority&&d&&(l.priority=s.encoding.priority,l.networkPriority=s.encoding.priority),r.push(l)}),Xt()&&lf()==="ios"){let s;r.forEach(o=>{s?o.maxFramerate&&o.maxFramerate>s&&(s=o.maxFramerate):s=o.maxFramerate});let a=!0;r.forEach(o=>{var c;o.maxFramerate!=s&&(a&&(a=!1,re.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),re.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function Lf(n){if(n)return n.sort((e,t)=>{const{encoding:i}=e,{encoding:r}=t;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class Zs{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 NC(n){return n.source===I.Source.ScreenShare||n.constraints.height&&Dn(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const MC=5e3;class ea extends Nf{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,I.Kind.Video,t,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>y(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}const a=new Map(s.map(o=>[o.rid,o]));if(this.prevStats){let o=0;a.forEach((c,l)=>{var u;const d=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);o+=Js(c,d)}),this._currentBitrate=o}this.prevStats=a}),this.senderLock=new ut}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!pt())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Tc))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return y(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=On(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;o=!0)s=l.value,o=!1,yield(a=s.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(u){i={error:u}}finally{try{!o&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return y(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=On(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;o=!0){s=l.value,o=!1;const u=s;yield(a=u.sender)===null||a===void 0?void 0:a.replaceTrack(u.mediaStreamTrack)}}catch(u){i={error:u}}finally{try{!o&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return y(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===I.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 y(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===I.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 y(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){const a={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},o=i.get(r.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((r,s)=>{var a,o;return((a=s.frameWidth)!==null&&a!==void 0?a:0)-((o=r.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=Ct.LOW;i<=Ct.HIGH;i+=1)t.push(new Oo({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return y(this,void 0,void 0,function*(){var t,i,r,s,a;let o;if(e){const d=lc({video:e});typeof d.video!="boolean"&&(o=d.video)}yield this.restart(o);try{for(var c=!0,l=On(this.simulcastCodecs.values()),u;u=yield l.next(),t=u.done,!t;c=!0){s=u.value,c=!1;const d=s;d.sender&&((a=d.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(d.mediaStreamTrack=this.mediaStreamTrack.clone(),yield d.sender.replaceTrack(d.mediaStreamTrack))}}catch(d){i={error:d}}finally{try{!c&&!t&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return y(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var a,o,c,l,u,d;if(yield t.setProcessor.call(r,i,s),!((u=r.processor)===null||u===void 0)&&u.processedTrack)try{for(var h=!0,f=On(r.simulcastCodecs.values()),m;m=yield f.next(),a=m.done,!a;h=!0)l=m.value,h=!1,yield(d=l.sender)===null||d===void 0?void 0:d.replaceTrack(r.processor.processedTrack)}catch(p){o={error:p}}finally{try{!h&&!a&&(c=f.return)&&(yield c.call(f))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return y(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},MC))}setPublishingCodecs(e){return y(this,void 0,void 0,function*(){var t,i,r,s,a,o,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(t=!0,i=On(e);r=yield i.next(),s=r.done,!s;t=!0){c=r.value,t=!1;const u=c;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(u.qualities);else{const d=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:d})),!d||!d.sender){for(const h of u.qualities)if(h.enabled){l.push(u.codec);break}}else d.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield Df(d.sender,d.encodings,u.qualities,this.senderLock,this.log,this.logContext))}}}catch(u){a={error:u}}finally{try{!t&&!s&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return l})}setPublishingLayers(e){return y(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 Df(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return y(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),of()&&this.isInBackground&&this.source===I.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Df(n,e,t,i,r,s){return y(this,void 0,void 0,function*(){const a=yield i.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},s),{sender:n,qualities:t,senderEncodings:e}));try{const o=n.getParameters(),{encodings:c}=o;if(!c)return;if(c.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},s),{encodings:c,senderEncodings:e}));return}let l=!1;const u=Lt();if((u==null?void 0:u.name)==="Chrome"&&Jn(u==null?void 0:u.version,"133")>0&&c[0].scalabilityMode){const h=c[0],f=new Zs(h.scalabilityMode);let m=Ti.OFF;if(t.forEach(p=>{p.enabled&&(m===Ti.OFF||p.quality>m)&&(m=p.quality)}),m===Ti.OFF)h.active&&(h.active=!1,l=!0);else if(!h.active||f.spatial!==m+1){l=!0,h.active=!0;const p=new Zs(e[0].scalabilityMode);f.spatial=m+1,f.suffix=p.suffix,f.spatial===1&&(f.suffix=void 0),h.scalabilityMode=f.toString(),h.scaleResolutionDownBy=Math.pow(2,2-m),e[0].maxBitrate&&(h.maxBitrate=e[0].maxBitrate/(h.scaleResolutionDownBy*h.scaleResolutionDownBy))}}else c.forEach((h,f)=>{var m;let p=(m=h.rid)!==null&&m!==void 0?m:"";p===""&&(p="q");const v=Uf(p),b=t.find(C=>C.quality===v);b&&h.active!==b.enabled&&(l=!0,h.active=b.enabled,r.debug("setting layer ".concat(b.quality," to ").concat(h.active?"enabled":"disabled"),s),Ri()&&(b.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))});l&&(o.encodings=c,r.debug("setting encodings",Object.assign(Object.assign({},s),{encodings:o.encodings})),yield n.setParameters(o))}finally{a()}})}function Uf(n){switch(n){case"f":return Ct.HIGH;case"h":return Ct.MEDIUM;case"q":return Ct.LOW;default:return Ct.HIGH}}function Bf(n,e,t,i){if(!t)return[new $n({quality:Ct.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const r=t[0].scalabilityMode,s=new Zs(r),a=[],o=s.suffix=="h"?1.5:2,c=s.suffix=="h"?2:3;for(let l=0;l<s.spatial;l+=1)a.push(new $n({quality:Math.min(Ct.HIGH,s.spatial-1)-l,width:Math.ceil(n/Math.pow(o,l)),height:Math.ceil(e/Math.pow(o,l)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return a}return t.map(r=>{var s,a,o;const c=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let l=Uf((a=r.rid)!==null&&a!==void 0?a:"");return new $n({quality:l,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(o=r.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const Ff="_lossy",jf="_reliable",LC=2*1e3,wc="leave-reconnect";var Ut;(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"})(Ut||(Ut={}));class DC extends Yt.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=bc.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Ut.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=re,this.handleDataChannel=i=>y(this,[i],void 0,function(r){var s=this;let{channel:a}=r;return function*(){if(a){if(a.label===jf)s.reliableDCSub=a;else if(a.label===Ff)s.lossyDCSub=a;else return;s.log.debug("on data channel ".concat(a.id,", ").concat(a.label),s.logContext),a.onmessage=s.handleDataMessage}}()}),this.handleDataMessage=i=>y(this,void 0,void 0,function*(){var r,s;const a=yield this.dataProcessLock.lock();try{let o;if(i.data instanceof ArrayBuffer)o=i.data;else if(i.data instanceof Blob)o=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const c=ht.fromBinary(new Uint8Array(o));((r=c.value)===null||r===void 0?void 0:r.case)==="speaker"?this.emit(U.ActiveSpeakersUpdate,c.value.value.speakers):(((s=c.value)===null||s===void 0?void 0:s.case)==="user"&&BC(c,c.value.value),this.emit(U.DataPacketReceived,c))}finally{a()}}),this.handleDataError=i=>{const s=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:a}=i.error;this.log.error("DataChannel error on ".concat(s,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:a}))}else this.log.error("Unknown DataChannel error on ".concat(s),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const s=i.currentTarget.maxRetransmits===0?ae.LOSSY:ae.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(U.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){s(a);return}i===wc&&(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=Je.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===Ut.Connected&&i();const s=()=>{this.off(U.Disconnected,a),i()},a=()=>{this.off(U.Restarted,s),r()};this.once(U.Restarted,s),this.once(U.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(U.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===be.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ki.RR_SIGNAL_DISCONNECTED))},this.log=rn((t=e.loggerName)!==null&&t!==void 0?t:Mt.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new dc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new ut,this.dataProcessLock=new ut,this.dcBufferStatus=new Map([[ae.LOSSY,!0],[ae.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(U.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(U.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(U.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(U.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(U.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(U.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(U.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(U.SignalRequestResponse,i)}get logContext(){var e,t,i,r,s,a,o,c;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(a=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||a===void 0?void 0:a.identity,pID:(c=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||c===void 0?void 0:c.sid}}join(e,t,i,r){return y(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,i,r);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),(!this.subscriberPrimary||s.fastPublish)&&this.negotiate(),this.clientConfiguration=s.clientConfiguration,setTimeout(()=>{this.emit(U.SignalConnected)},10),s}catch(s){if(s instanceof me&&s.reason===se.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,i,r);throw s}})}close(){return y(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(U.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return y(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0})}cleanupClient(){return y(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new sn("a track with the same ID has already been published");return new Promise((t,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(new me("publication of local track timed out, no response from server",se.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),t(s)},reject:()=>{clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return y(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 y(this,void 0,void 0,function*(){var t,i;if(this.pcManager&&this.pcManager.currentState!==Re.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new kC(r,e.subscriberPrimary,this.loggerOptions),this.emit(U.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,a)=>{this.client.sendIceCandidate(s,a)},this.pcManager.onPublisherOffer=s=>{this.client.sendOffer(s)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,a,o)=>y(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s),this.logContext),["closed","disconnected","failed"].includes(a)&&(this.publisherConnectionPromise=void 0),s===Re.CONNECTED){const u=this.pcState===Ut.New;this.pcState=Ut.Connected,u&&this.emit(U.Connected,e)}else s===Re.FAILED&&this.pcState===Ut.Connected&&(this.pcState=Ut.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?ki.RR_SUBSCRIBER_FAILED:ki.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===be.RECONNECTING,l=[Re.FAILED,Re.CLOSING,Re.CLOSED].includes(s);c&&l&&!this._isClosed&&this.emit(U.Offline)}),this.pcManager.onTrack=s=>{this.emit(U.MediaTrackAdded,s.track,s.streams[0],s.receiver)},UC((i=e.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>y(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=>y(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:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(U.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(U.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(U.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(U.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.emit(U.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 wi.DISCONNECT:this.emit(U.Disconnected,e==null?void 0:e.reason),this.close();break;case wi.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(wc);break;case wi.RESUME:this.handleDisconnect(wc)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const r=[];e.iceServers.forEach(s=>{const a={urls:s.urls};s.username&&(a.username=s.username),s.credential&&(a.credential=s.credential),r.push(a)}),i.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===or.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Ff,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(jf,{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,i){return y(this,void 0,void 0,function*(){if(Jo())return yield this.createTransceiverRTCRtpSender(e,t,i);if(Qo())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Ge("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,r){return y(this,void 0,void 0,function*(){if(Jo())return this.createSimulcastTransceiverSender(e,t,i,r);if(Qo())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Ge("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ge("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),Ii(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,i,r){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ge("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ge("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return y(this,void 0,void 0,function*(){var t,i,r;if(!this._isClosed){if(this.attemptingReconnect){re.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===or.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:Re.NEW)===Re.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let a=!0;s instanceof Ge?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),a=!1):s instanceof Ai||(this.fullReconnectOnNext=!0),a?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(U.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 y(this,void 0,void 0,function*(){var t,i,r;try{if(!this.url||!this.token)throw new Ge("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(U.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Ai;s=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof me&&a.reason===se.NotAllowed?new Ge("could not reconnect, token might be expired"):new Ai}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(U.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==be.CONNECTED)throw new Ai("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(U.Restarted)}catch(s){const a=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return y(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new Ge("could not reconnect, url or token not saved");if(!this.pcManager)throw new Ge("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(U.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,Object.assign(Object.assign({},this.logContext),{error:r}))),r instanceof me&&r.reason===se.NotAllowed?new Ge("could not reconnect, token might be expired"):r instanceof me&&r.reason===se.LeaveRequest?r:new Ai(s)}if(this.emit(U.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r)}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!==be.CONNECTED)throw new Ai("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(U.Resumed)})}waitForPCInitialConnection(e,t){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ge("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return y(this,void 0,void 0,function*(){this.pcState=Ut.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield ft(LC),!this.pcManager)throw new Ge("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ut.Connected}catch(e){throw this.pcState=Ut.Disconnected,new me("could not establish PC connection, ".concat(e.message),se.InternalError)}})}publishRpcResponse(e,t,i,r){return y(this,void 0,void 0,function*(){const s=new ht({destinationIdentities:[e],kind:ae.RELIABLE,value:{case:"rpcResponse",value:new Wd({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(s,ae.RELIABLE)})}publishRpcAck(e,t){return y(this,void 0,void 0,function*(){const i=new ht({destinationIdentities:[e],kind:ae.RELIABLE,value:{case:"rpcAck",value:new Hd({requestId:t})}});yield this.sendDataPacket(i,ae.RELIABLE)})}sendDataPacket(e,t){return y(this,void 0,void 0,function*(){const i=e.toBinary();yield this.ensurePublisherConnected(t);const r=this.dataChannelForKind(t);r&&r.send(i),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,i)=>y(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const r=()=>i("Engine closed");for(this.once(U.Closing,r);!this.dcBufferStatus.get(e);)yield ft(10);this.off(U.Closing,r),t()}}))}ensureDataTransportConnected(e){return y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var s;if(!i.pcManager)throw new Ge("PC manager is closed");const a=r?i.pcManager.subscriber:i.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw new me("".concat(o," connection not set"),se.InternalError);let c=!1;!r&&!i.dataChannelForKind(t,r)&&(i.createDataChannels(),c=!0),!c&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate();const l=i.dataChannelForKind(t,r);if((l==null?void 0:l.readyState)==="open")return;const u=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<u;){if(a.isICEConnected&&((s=i.dataChannelForKind(t,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield ft(50)}throw new me("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()),se.InternalError)}()})}ensurePublisherConnected(e){return y(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Re.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return y(this,void 0,void 0,function*(){return new Promise((e,t)=>y(this,void 0,void 0,function*(){if(!this.pcManager){t(new Ho("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(U.Closing,r),this.pcManager.publisher.once(Oi.RTPVideoPayloadTypes,s=>{const a=new Map;s.forEach(o=>{const c=o.codec.toLowerCase();qS(c)&&a.set(o.payload,c)}),this.emit(U.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof Ho&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ki.RR_UNKNOWN),t(s)}finally{this.off(U.Closing,r)}}))})}dataChannelForKind(e,t){if(t){if(e===ae.LOSSY)return this.lossyDCSub;if(e===ae.RELIABLE)return this.reliableDCSub}else{if(e===ae.LOSSY)return this.lossyDC;if(e===ae.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,r;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const s=this.pcManager.subscriber.getLocalDescription(),a=this.pcManager.subscriber.getRemoteDescription(),o=(r=(i=this.signalOpts)===null||i===void 0?void 0:i.autoSubscribe)!==null&&r!==void 0?r:!0,c=new Array,l=new Array;e.forEach(u=>{u.isDesired!==o&&c.push(u.trackSid),u.isEnabled||l.push(u.trackSid)}),this.client.sendSyncState(new lh({answer:s?Xs({sdp:s.sdp,type:s.type}):void 0,offer:a?Xs({sdp:a.sdp,type:a.type}):void 0,subscription:new Ms({trackSids:c,subscribe:!o,participantTracks:[]}),publishTracks:tC(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new uh({label:i.label,id:i.id,target:r}))};return t(this.dataChannelForKind(ae.LOSSY),Nt.PUBLISHER),t(this.dataChannelForKind(ae.RELIABLE),Nt.PUBLISHER),t(this.dataChannelForKind(ae.LOSSY,!0),Nt.SUBSCRIBER),t(this.dataChannelForKind(ae.RELIABLE,!0),Nt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Je.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){pt()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){pt()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Ai extends Error{}function UC(n){return n!==void 0&&n>13}function BC(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}class xc{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 ec(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return y(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(i=>!this.attemptedRegions.find(r=>r.url===i.url));if(t.length>0){const i=t[0];return this.attemptedRegions.push(i),re.debug("next region: ".concat(i.region)),i.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return y(this,void 0,void 0,function*(){const t=yield fetch("".concat(FC(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const i=yield t.json();return this.lastUpdateAt=Date.now(),i}else throw new me("Could not fetch region settings: ".concat(t.statusText),t.status===401?se.NotAllowed:se.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function FC(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class Vf{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class jC extends Vf{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>y(this,void 0,void 0,function*(){try{const{done:t,value:i}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch{return{done:!0,value:void 0}}}),return(){return y(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return y(this,void 0,void 0,function*(){var e,t,i,r;let s=new Set;try{for(var a=!0,o=On(this),c;c=yield o.next(),e=c.done,!e;a=!0){r=c.value,a=!1;const l=r;s.add(l)}}catch(l){t={error:l}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return Array.from(s)})}}class VC extends Vf{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=$s(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>y(this,void 0,void 0,function*(){try{const{done:i,value:r}=yield e.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(r),{done:!1,value:t.decode(r.content)})}catch{return{done:!0,value:void 0}}}),return(){return y(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return y(this,void 0,void 0,function*(){var e,t,i,r;let s="";try{for(var a=!0,o=On(this),c;c=yield o.next(),e=c.done,!e;a=!0)r=c.value,a=!1,s+=r}catch(l){t={error:l}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return s})}}class Gf{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return y(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 GC extends Gf{}class zC extends Gf{}class zf extends I{constructor(e,t,i,r,s){super(e,i,s),this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?D.Muted:D.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(D.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return y(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(),Tc)),nC()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:r,rtpTimestamp:s}=i;s&&this.rtpTimestamp!==s&&(this.emit(D.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}class HC extends zf{constructor(e,t,i,r,s,a){super(e,t,I.Kind.Audio,i,a),this.monitorReceiver=()=>y(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=Js(o,this.prevStats)),this.prevStats=o}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Xt()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Xt())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return y(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Zo(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Zo(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{i.connect(r),i=r}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(D.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(D.AudioPlaybackFailed,r)})}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 y(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}}const _c=100;class WC extends zf{constructor(e,t,i,r,s){super(e,t,I.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>y(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=Js(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=gc(()=>{this.updateDimensions()},_c),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Ei(this._mediaStreamTrack,t):_i(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 qC(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return y(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(i=s.codecId,t={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),t&&i!==""&&r.get(i)&&(t.mimeType=r.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return y(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const i=this.elementInfos.reduce((o,c)=>Math.max(o,c.visibilityChangedAt||0),0),r=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,s=this.elementInfos.some(o=>o.pictureInPicture),a=this.elementInfos.some(o=>o.visible)&&!r||s;if(this.lastVisible!==a){if(!a&&Date.now()-i<_c){Je.setTimeout(()=>{this.updateVisibility()},_c);return}this.lastVisible=a,this.emit(D.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let i=0,r=0;const s=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*s,c=a.height()*s;o+c>i+r&&(i=o,r=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===r||(this.lastDimensions={width:i,height:r},this.emit(D.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?uf():t||(uf()>2?2:1)}}class qC{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var r;const{target:s,isIntersecting:a}=i;s===this.element&&(this.isIntersecting=a,this.isPiP=pr(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r,s;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),this.isPiP=pr(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=pr(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??Ec(e),this.isPiP=pt()&&pr(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Ec(this.element),this.isPiP=pr(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,hf().observe(this.element),df().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,r,s;(e=hf())===null||e===void 0||e.unobserve(this.element),(t=df())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}}function pr(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Ec(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Ec(n,e){const t=e||window;let i=n.offsetTop,r=n.offsetLeft;const s=n.offsetWidth,a=n.offsetHeight,{hidden:o}=n,{display:c}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,r+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&r<t.pageXOffset+t.innerWidth&&i+a>t.pageYOffset&&r+s>t.pageXOffset&&!o&&c!=="none"}class on extends Yt.EventEmitter{constructor(e,t,i,r){var s;super(),this.metadataMuted=!1,this.encryption=vt.NONE,this.log=re,this.handleMuted=()=>{this.emit(D.Muted)},this.handleUnmuted=()=>{this.emit(D.Unmuted)},this.log=rn((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:Mt.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=I.Source.Unknown}setTrack(e){this.track&&(this.track.off(D.Muted,this.handleMuted),this.track.off(D.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(D.Muted,this.handleMuted),e.on(D.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),ue(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==vt.NONE}get audioTrack(){if(an(this.track))return this.track}get videoTrack(){if(Ii(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=I.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===I.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={}))})(on||(on={}));class Rc extends on{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(D.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(D.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(D.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 y(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return y(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return y(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return y(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(an(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(At.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(At.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(At.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(At.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(At.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(At.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function ta(n,e){return y(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=yf(n);let a=s.audio,o=s.video;if(i&&typeof s.audio=="object"&&(s.audio.processor=i),r&&typeof s.video=="object"&&(s.video.processor=r),n.audio&&typeof s.audio=="object"&&typeof s.audio.deviceId=="string"){const d=s.audio.deviceId;s.audio.deviceId={exact:d},t=!0,a=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:d}})}if(s.video&&typeof s.video=="object"&&typeof s.video.deviceId=="string"){const d=s.video.deviceId;s.video.deviceId={exact:d},t=!0,o=Object.assign(Object.assign({},s.video),{deviceId:{ideal:d}})}(s.audio===!0||typeof s.audio=="object"&&!s.audio.deviceId)&&(s.audio={deviceId:"default"}),s.video===!0?s.video={deviceId:"default"}:typeof s.video=="object"&&!s.video.deviceId&&(s.video.deviceId="default");const c=mf(s,Pf,If),l=lc(c),u=navigator.mediaDevices.getUserMedia(l);s.audio&&(He.userMediaPromiseMap.set("audioinput",u),u.catch(()=>He.userMediaPromiseMap.delete("audioinput"))),s.video&&(He.userMediaPromiseMap.set("videoinput",u),u.catch(()=>He.userMediaPromiseMap.delete("videoinput")));try{const d=yield u;return yield Promise.all(d.getTracks().map(h=>y(this,void 0,void 0,function*(){const f=h.kind==="audio";let m=f?c.audio:c.video;(typeof m=="boolean"||!m)&&(m={});let p;const v=f?l.audio:l.video;typeof v!="boolean"&&(p=v);const b=h.getSettings().deviceId;p!=null&&p.deviceId&&Dn(p.deviceId)!==b?p.deviceId=b:p||(p={deviceId:b});const C=CC(h,p,e);return C.kind===I.Kind.Video?C.source=I.Source.Camera:C.kind===I.Kind.Audio&&(C.source=I.Source.Microphone),C.mediaStream=d,an(C)&&i?yield C.setProcessor(i):Ii(C)&&r&&(yield C.setProcessor(r)),C})))}catch(d){if(!t)throw d;return ta(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function KC(n){return y(this,void 0,void 0,function*(){return(yield ta({audio:!1,video:n??!0}))[0]})}function $C(n){return y(this,void 0,void 0,function*(){return(yield ta({audio:n??!0,video:!1}))[0]})}var Fn;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(Fn||(Fn={}));function YC(n){switch(n){case ar.EXCELLENT:return Fn.Excellent;case ar.GOOD:return Fn.Good;case ar.POOR:return Fn.Poor;case ar.LOST:return Fn.Lost;default:return Fn.Unknown}}class Hf extends Yt.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===Ns.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Si.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,r,s,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Ns.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Fn.Unknown,this.log=re,this.log=rn((c=a==null?void 0:a.loggerName)!==null&&c!==void 0?c:Mt.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=s??{}}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 rc,this.once(j.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(I.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(I.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(I.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===Si.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Si.ACTIVE&&this.emit(j.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(j.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(j.ParticipantNameChanged,e)}_setAttributes(e){const t=iC(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(j.AttributesChanged,t)}setPermissions(e){var t,i,r,s,a,o;const c=this.permissions,l=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,d)=>{var h;return u!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[d])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,l&&this.emit(j.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(j.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=YC(e),t!==this._connectionQuality&&this.emit(j.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=>an(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(D.Muted,()=>{this.emit(j.TrackMuted,e)}),e.on(D.Unmuted,()=>{this.emit(j.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case I.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case I.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function XC(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new oh({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}const Wf=15e3;class JC extends Hf{constructor(e,t,i,r,s){super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=vt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new rc)},this.handleReconnected=()=>{var a,o;(o=(a=this.reconnectFuture)===null||a===void 0?void 0:a.resolve)===null||o===void 0||o.call(a),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var a,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(c=>this.log.warn(c.message,this.logContext)),(o=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||o===void 0||o.call(a,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=a=>{const{requestId:o,reason:c,message:l}=a,u=this.pendingSignalRequests.get(o);u&&(c!==Ao.OK&&u.reject(new nf(l,c)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let o=a.value.value,c=null,l=null;o.value.case==="payload"?c=o.value.value:o.value.case==="error"&&(l=Pe.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,c,l);break;case"rpcAck":let u=a.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(a=>XC(a)))},this.onTrackUnmuted=a=>{this.onTrackMuted(a,a.isUpstreamPaused)},this.onTrackMuted=(a,o)=>{if(o===void 0&&(o=!0),!a.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),ue(a)));return}this.engine.updateMuteStatus(a.sid,o)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ue(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ue(a))),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{const o=this.audioTrackPublications.get(a.sid);if(!o){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(a.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.handleSubscribedQualityUpdate=a=>y(this,void 0,void 0,function*(){var o,c,l,u,d,h;if(!(!((d=this.roomOptions)===null||d===void 0)&&d.dynacast))return;const f=this.videoTrackPublications.get(a.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}if(a.subscribedCodecs.length>0){if(!f.videoTrack)return;const b=yield f.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var m=!0,p=On(b),v;v=yield p.next(),o=v.done,!o;m=!0){u=v.value,m=!1;const C=u;LS(C)&&(this.log.debug("publish ".concat(C," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ue(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,C,f.options))}}catch(C){c={error:C}}finally{try{!m&&!o&&(l=p.return)&&(yield l.call(p))}finally{if(c)throw c.error}}}else a.subscribedQualities.length>0&&(yield(h=f.videoTrack)===null||h===void 0?void 0:h.setPublishingLayers(a.subscribedQualities))}),this.handleLocalTrackUnpublished=a=>{const o=this.trackPublications.get(a.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=a=>y(this,void 0,void 0,function*(){if(a.source===I.Source.ScreenShare||a.source===I.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),ue(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(Zn(a)||Un(a))try{if(pt())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:a.source===I.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),Object.assign(Object.assign({},this.logContext),ue(a))),o.onchange=()=>{o.state!=="denied"&&(a.isMuted||a.restartTrack(),o.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}a.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),ue(a))),Zn(a)?yield a.restartTrack({deviceId:"default"}):yield a.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),ue(a))),yield a.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==vt.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(U.RemoteMute,(t,i)=>{const r=this.trackPublications.get(t);!r||!r.track||(i?r.mute():r.unmute())}),this.engine.on(U.Connected,this.handleReconnected).on(U.SignalRestarted,this.handleReconnected).on(U.SignalResumed,this.handleReconnected).on(U.Restarting,this.handleReconnecting).on(U.Resuming,this.handleReconnecting).on(U.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(U.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(U.Disconnected,this.handleDisconnected).on(U.SignalRequestResponse,this.handleSignalRequestResponse).on(U.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return y(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return y(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return y(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return y(this,arguments,void 0,function(t){var i=this;let{metadata:r,name:s,attributes:a}=t;return function*(){return new Promise((o,c)=>y(i,void 0,void 0,function*(){var l,u;try{let d=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((l=r??this.metadata)!==null&&l!==void 0?l:"",(u=s??this.name)!==null&&u!==void 0?u:"",a),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:m=>{c(m),d=!0},values:{name:s,metadata:r,attributes:a}});performance.now()-f<5e3&&!d;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!a||Object.entries(a).every(m=>{let[p,v]=m;return this.attributes[p]===v||v===""&&!this.attributes[p]}))){this.pendingSignalRequests.delete(h),o();return}yield ft(50)}c(new nf("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error&&c(d)}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(I.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(I.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(I.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(j.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return y(this,void 0,void 0,function*(){this.encryptionType=e?vt.GCM:vt.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,r){return y(this,void 0,void 0,function*(){var s,a;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let c;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case I.Source.Camera:c=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case I.Source.Microphone:c=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case I.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new sn(e)}}catch(l){throw c==null||c.forEach(u=>{u.stop()}),l instanceof Error&&this.emit(j.MediaDevicesError,l),this.pendingPublishing.delete(e),l}try{const l=[];for(const d of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),ue(d))),l.push(this.publishTrack(d,r));[o]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(u=>{u.stop()}),l}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===I.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(I.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return y(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(I.Source.Camera)||this.pendingPublishing.has(I.Source.Microphone))){this.pendingPublishing.add(I.Source.Camera),this.pendingPublishing.add(I.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(I.Source.Camera),this.pendingPublishing.delete(I.Source.Microphone)}}})}createTracks(e){return y(this,void 0,void 0,function*(){var t,i;e??(e={});const r=mf(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield ta(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(an(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=I.Source.Microphone,this.emit(j.AudioStreamAcquired)),Ii(o)&&(this.cameraError=void 0,o.source=I.Source.Camera),o))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return y(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new zo("getDisplayMedia not supported");e.resolution===void 0&&!VS()&&(e.resolution=Xo.h1080fps30.resolution);const t=eC(e),i=yield navigator.mediaDevices.getDisplayMedia(t),r=i.getVideoTracks();if(r.length===0)throw new sn("no video track found");const s=new ea(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=I.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const a=[s];if(i.getAudioTracks().length>0){this.emit(j.AudioStreamAcquired);const o=new Qs(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=I.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return y(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return y(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,c,l,u;Zn(i)&&i.setAudioContext(s.audioContext),yield(o=s.reconnectFuture)===null||o===void 0?void 0:o.promise,s.republishPromise&&!a&&(yield s.republishPromise),Pi(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i));let d;if(i instanceof MediaStreamTrack)d=i.getConstraints();else{d=i.constraints;let b;switch(i.source){case I.Source.Microphone:b="audioinput";break;case I.Source.Camera:b="videoinput"}b&&s.activeDeviceMap.has(b)&&(d=Object.assign(Object.assign({},d),{deviceId:s.activeDeviceMap.get(b)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Qs(i,d,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new ea(i,d,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new sn("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let h;if(s.trackPublications.forEach(b=>{b.track&&b.track===i&&(h=b)}),h)return s.log.warn("track has already been published, skipping",Object.assign(Object.assign({},s.logContext),ue(h))),h;const f="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,m=(c=r==null?void 0:r.forceStereo)!==null&&c!==void 0?c:f;m&&(r||(r={}),r.dtx===void 0&&s.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},s.logContext),ue(i))),r.red===void 0&&s.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=r.dtx)!==null&&l!==void 0||(r.dtx=!1),(u=r.red)!==null&&u!==void 0||(r.red=!1));const p=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r);!GS()&&s.roomOptions.e2ee&&(s.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({},s.logContext)),p.simulcast=!1),p.source&&(i.source=p.source);const v=new Promise((b,C)=>y(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==be.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:ue(i)}));const x=()=>y(this,void 0,void 0,function*(){try{const k=yield this.publish(i,p,m);b(k)}catch(k){C(k)}});setTimeout(()=>{this.engine.off(U.SignalConnected,x),C(new Wo("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(U.SignalConnected,x),this.engine.on(U.Closing,()=>{this.engine.off(U.SignalConnected,x),C(new Wo("publishing rejected as engine closed",499))})}else try{const x=yield this.publish(i,p,m);b(x)}catch(x){C(x)}}catch(x){C(x)}}));s.pendingPublishPromises.set(i,v);try{return yield v}catch(b){throw b}finally{s.pendingPublishPromises.delete(i)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),ue(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(r=>rC(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),ue(e))),!1)}publish(e,t,i){return y(this,void 0,void 0,function*(){var r,s,a,o,c,l,u,d,h,f;if(!this.hasPermissionsToPublish(e))throw new Wo("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(S=>Pi(e)&&S.source===e.source)&&e.source!==I.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),ue(e))),t.stopMicTrackOnMute&&an(e)&&(e.stopOnMute=!0),e.source===I.Source.ScreenShare&&Ri()&&(t.simulcast=!1),t.videoCodec==="av1"&&!BS()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!FS()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=vc),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(S=>t.videoCodec===Ys(S.mime))||(t.videoCodec=Ys(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(D.Muted,this.onTrackMuted),e.on(D.Unmuted,this.onTrackUnmuted),e.on(D.Ended,this.handleTrackEnded),e.on(D.UpstreamPaused,this.onTrackUpstreamPaused),e.on(D.UpstreamResumed,this.onTrackUpstreamResumed),e.on(D.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=new Eo({cid:e.mediaStreamTrack.id,name:t.name,type:I.kindToProto(e.kind),muted:e.isMuted,source:I.sourceToProto(e.source),disableDtx:!(!((r=t.dtx)!==null&&r!==void 0)||r),encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((s=t.red)!==null&&s!==void 0)||s),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy});let b;if(e.kind===I.Kind.Video){let S={width:0,height:0};try{S=yield e.waitForDimensions()}catch{const E=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:ur.h720.resolution;S={width:E.width,height:E.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),ue(e)),{dims:S}))}v.width=S.width,v.height=S.height,Un(e)&&(dr(p)&&(e.source===I.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),ue(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),v.simulcastCodecs=[new _o({codec:p,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:vc}),t.backupCodec&&p!==t.backupCodec.codec&&v.encryption===vt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new _o({codec:t.backupCodec.codec,cid:""})))),b=Sc(e.source===I.Source.ScreenShare,v.width,v.height,t),v.layers=Bf(v.width,v.height,b,dr(t.videoCodec))}else e.kind===I.Kind.Audio&&(b=[{maxBitrate:(l=t.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(d=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&d!==void 0?d:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new Ge("cannot publish track when not connected");const C=()=>y(this,void 0,void 0,function*(){var S,w,E;if(!this.engine.pcManager)throw new Ge("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),Un(e)&&((S=t.degradationPreference)!==null&&S!==void 0||(t.degradationPreference=NC(e)),e.setDegradationPreference(t.degradationPreference)),b)if(Ri()&&e.kind===I.Kind.Audio){let A;for(const O of this.engine.pcManager.publisher.getTransceivers())if(O.sender===e.sender){A=O;break}A&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:A,codec:"opus",maxbr:!((w=b[0])===null||w===void 0)&&w.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&dr(e.codec)&&(!((E=b[0])===null||E===void 0)&&E.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let x;if(this.enabledPublishVideoCodecs.length>0)x=(yield Promise.all([this.engine.addTrack(v),C()]))[0];else{x=yield this.engine.addTrack(v);let S;if(x.codecs.forEach(w=>{S===void 0&&(S=w.mimeType)}),S&&e.kind===I.Kind.Video){const w=Ys(S);w!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ue(e)),{codec:w})),t.videoCodec=w,b=Sc(e.source===I.Source.ScreenShare,v.width,v.height,t))}yield C()}const k=new Rc(e.kind,x,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return k.options=t,e.sid=x.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:x})),Un(e)?e.startMonitor(this.engine.client):Zn(e)&&e.startMonitor(),this.addTrackPublication(k),this.emit(j.LocalTrackPublished,k),k})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return y(this,void 0,void 0,function*(){var r;if(this.encryptionType!==vt.NONE)return;let s;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(s=f)}),!s)throw new sn("track is not published");if(!Un(e))throw new sn("track is not a video track");const a=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),o=IC(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),ue(e)));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const l=new Eo({cid:c.mediaStreamTrack.id,type:I.kindToProto(e.kind),muted:e.isMuted,source:I.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=Bf(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new Ge("cannot publish track when not connected");const u=()=>y(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:h}))})}unpublishTrack(e,t){return y(this,void 0,void 0,function*(){var i,r;if(Pi(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),ue(e))),yield l)}const s=this.getPublicationForTrack(e),a=s?ue(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));return}e=s.track,e.off(D.Muted,this.onTrackMuted),e.off(D.Unmuted,this.onTrackUnmuted),e.off(D.Ended,this.handleTrackEnded),e.off(D.UpstreamPaused,this.onTrackUpstreamPaused),e.off(D.UpstreamResumed,this.onTrackUpstreamResumed),e.off(D.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),t?e.stop():e.stopMonitor();let o=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Re.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),Un(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(o=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:l}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case I.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case I.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(j.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return y(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Promise((s,a)=>y(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),o.push(c))}),yield Promise.all(o.map(c=>y(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),r&&!l.isMuted&&l.source!==I.Source.ScreenShare&&l.source!==I.Source.ScreenShareAudio&&(Zn(l)||Un(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),s()}catch(o){a(o)}finally{this.republishPromise=void 0}})),yield i.republishPromise}()})}publishData(e){return y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const s=r.reliable?ae.RELIABLE:ae.LOSSY,a=r.destinationIdentities,o=r.topic,c=new ht({kind:s,value:{case:"user",value:new Vd({participantIdentity:i.identity,payload:t,destinationIdentities:a,topic:o})}});yield i.engine.sendDataPacket(c,s)}()})}publishDtmf(e,t){return y(this,void 0,void 0,function*(){const i=new ht({kind:ae.RELIABLE,value:{case:"sipDtmf",value:new Gd({code:e,digit:t})}});yield this.engine.sendDataPacket(i,ae.RELIABLE)})}sendChatMessage(e,t){return y(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},r=new ht({value:{case:"chatMessage",value:new To(Object.assign(Object.assign({},i),{timestamp:we.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,ae.RELIABLE),this.emit(j.ChatMessage,i),i})}editChatMessage(e,t){return y(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new ht({value:{case:"chatMessage",value:new To(Object.assign(Object.assign({},i),{timestamp:we.parse(i.timestamp),editTimestamp:we.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,ae.RELIABLE),this.emit(j.ChatMessage,i),i})}sendText(e,t){return y(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(i=t==null?void 0:t.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(o?o.length+1:1).fill(0),l=(d,h)=>{var f;c[h]=d;const m=c.reduce((p,v)=>p+v,0);(f=t==null?void 0:t.onProgress)===null||f===void 0||f.call(t,m)},u=yield this.streamText({streamId:r,totalSize:a,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),l(1,0),yield u.close(),t!=null&&t.attachments&&o&&(yield Promise.all(t.attachments.map((d,h)=>y(this,void 0,void 0,function*(){return this._sendFile(o[h],d,{topic:t.topic,mimeType:d.type,onProgress:f=>{l(f,h+1)}})})))),u.info})}streamText(e){return y(this,void 0,void 0,function*(){var t,i;const r=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),s={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},a=new So({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:Qn(s.timestamp),totalLength:Qn(e==null?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new Zd({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"?ko.UPDATE:ko.CREATE})}}),o=e==null?void 0:e.destinationIdentities,c=new ht({destinationIdentities:o,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(c,ae.RELIABLE);let l=0;const u=this,d=new WritableStream({write(m){return y(this,void 0,void 0,function*(){for(const p of QS(m,Wf)){yield u.engine.waitForBufferStatusLow(ae.RELIABLE);const v=new Co({content:p,streamId:r,chunkIndex:Qn(l)}),b=new ht({destinationIdentities:o,value:{case:"streamChunk",value:v}});yield u.engine.sendDataPacket(b,ae.RELIABLE),l+=1}})},close(){return y(this,void 0,void 0,function*(){const m=new wo({streamId:r}),p=new ht({destinationIdentities:o,value:{case:"streamTrailer",value:m}});yield u.engine.sendDataPacket(p,ae.RELIABLE)})},abort(m){console.log("Sink error:",m)}});let h=()=>y(this,void 0,void 0,function*(){yield f.close()});u.engine.once(U.Closing,h);const f=new GC(d,s,()=>this.engine.off(U.Closing,h));return f})}sendFile(e,t){return y(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return y(this,void 0,void 0,function*(){var r;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:t.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),a=t.stream().getReader();for(;;){const{done:o,value:c}=yield a.read();if(o)break;yield s.write(c)}return yield s.close(),s.info})}streamBytes(e){return y(this,void 0,void 0,function*(){var t,i,r,s,a;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),c=e==null?void 0:e.destinationIdentities,l={id:o,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(s=e==null?void 0:e.name)!==null&&s!==void 0?s:"unknown"},u=new So({totalLength:Qn((a=l.size)!==null&&a!==void 0?a:0),mimeType:l.mimeType,streamId:o,topic:l.topic,timestamp:Qn(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new eh({name:l.name})}}),d=new ht({destinationIdentities:c,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(d,ae.RELIABLE);let h=0;const f=new ut,m=this.engine,p=this.log,v=new WritableStream({write(C){return y(this,void 0,void 0,function*(){const x=yield f.lock();let k=0;try{for(;k<C.byteLength;){const S=C.slice(k,k+Wf);yield m.waitForBufferStatusLow(ae.RELIABLE);const w=new ht({destinationIdentities:c,value:{case:"streamChunk",value:new Co({content:S,streamId:o,chunkIndex:Qn(h)})}});yield m.sendDataPacket(w,ae.RELIABLE),h+=1,k+=S.byteLength}}finally{x()}})},close(){return y(this,void 0,void 0,function*(){const C=new wo({streamId:o}),x=new ht({destinationIdentities:c,value:{case:"streamTrailer",value:C}});yield m.sendDataPacket(x,ae.RELIABLE)})},abort(C){p.error("Sink error:",C)}});return new zC(v,l)})}performRpc(e){return y(this,arguments,void 0,function(t){var i=this;let{destinationIdentity:r,method:s,payload:a,responseTimeout:o=1e4}=t;return function*(){return new Promise((l,u)=>y(i,void 0,void 0,function*(){var d,h,f,m;if(yc(a)>Of){u(Pe.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((h=(d=this.engine.latestJoinResponse)===null||d===void 0?void 0:d.serverInfo)===null||h===void 0)&&h.version&&Jn((m=(f=this.engine.latestJoinResponse)===null||f===void 0?void 0:f.serverInfo)===null||m===void 0?void 0:m.version,"1.8.0")<0){u(Pe.builtIn("UNSUPPORTED_SERVER"));return}const p=crypto.randomUUID();yield this.publishRpcRequest(r,p,s,a,o-2e3);const v=setTimeout(()=>{this.pendingAcks.delete(p),u(Pe.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(p),clearTimeout(b)},2e3);this.pendingAcks.set(p,{resolve:()=>{clearTimeout(v)},participantIdentity:r});const b=setTimeout(()=>{this.pendingResponses.delete(p),u(Pe.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(p,{resolve:(C,x)=>{clearTimeout(b),this.pendingAcks.has(p)&&(console.warn("RPC response received before ack",p),this.pendingAcks.delete(p),clearTimeout(v)),x?u(x):l(C??"")},participantIdentity:r})}))}()})}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const r=this.pendingResponses.get(e);r?(r.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,r,s){return y(this,void 0,void 0,function*(){const a=new ht({destinationIdentities:[e],kind:ae.RELIABLE,value:{case:"rpcRequest",value:new zd({id:t,method:i,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(a,ae.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:r}]of this.pendingResponses)i===e&&(r(null,Pe.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var i,r;const s=this.trackPublications.get(t.sid);if(s){const a=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),ue(s)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(Zn(r)||Un(r))&&r.mediaStreamTrack===e&&(t=i):e===r&&(t=i))}),t}waitForPendingPublicationOfSource(e){return y(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>{let[a]=s;return a.source===e});if(r)return r[1];yield ft(20)}})}}class QC extends on{constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Ct.HIGH,this.handleEnded=s=>{this.setTrack(void 0),this.emit(D.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.disabled=!s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensions=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new Ms({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Kd({participantSid:"",trackSids:[this.trackSid]})]});this.emit(D.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?on.SubscriptionStatus.Unsubscribed:super.isSubscribed?on.SubscriptionStatus.Subscribed:on.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?on.PermissionStatus.Allowed:on.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,i;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.videoDimensions)===null||i===void 0?void 0:i.height)===e.height||(oc(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&oc(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(D.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(D.VisibilityChanged,this.handleVisibilityChange),r.off(D.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(D.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(D.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(D.VisibilityChanged,this.handleVisibilityChange),e.on(D.Ended,this.handleEnded),this.emit(D.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(D.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?D.Muted:D.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(D.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(D.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===I.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 oc(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new nh({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=Ct.HIGH,this.emit(D.UpdateSettings,e)}}class na extends Hf{static fromParticipantInfo(e,t,i){return new na(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,r,s,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ns.STANDARD;super(t,i||"",r,s,a,o,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(D.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),ue(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(D.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(D.SubscriptionPermissionChanged,t=>{this.emit(j.TrackSubscriptionPermissionChanged,e,t)}),e.on(D.SubscriptionStatusChanged,t=>{this.emit(j.TrackSubscriptionStatusChanged,e,t)}),e.on(D.Subscribed,t=>{this.emit(j.TrackSubscribed,t,e)}),e.on(D.Unsubscribed,t=>{this.emit(j.TrackUnsubscribed,t,e)}),e.on(D.SubscriptionFailed,t=>{this.emit(j.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]:I.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:I.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,r,s,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(u=>{!o&&e.kind===u.kind.toString()&&(o=u)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(j.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,r,s,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),ue(o))),this.emit(j.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let l;return c?l=new WC(e,t,r,s):l=new HC(e,t,r,this.audioContext,this.audioOutput),l.source=o.source,l.isMuted=o.isMuted,l.setMediaStream(i),l.start(),o.setTrack(l),this.volumeMap.has(o.source)&&ac(l)&&an(l)&&l.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach(r=>{var s,a;let o=this.getTrackPublicationBySid(r.sid);if(o)o.updateInfo(r);else{const c=I.kindFromProto(r.type);if(!c)return;o=new QC(c,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(r),i.set(r.sid,o);const l=Array.from(this.trackPublications.values()).find(u=>u.source===(o==null?void 0:o.source));l&&o.source!==I.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:ue(l),newTrack:ue(o)})),this.addTrackPublication(o)}t.set(r.sid,o)}),this.trackPublications.forEach(r=>{t.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),ue(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(j.TrackPublished,r)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:r}=i;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case I.Kind.Audio:this.audioTrackPublications.delete(e);break;case I.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(j.TrackUnpublished,i)}setAudioOutput(e){return y(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var r;an(i.track)&&ac(i.track)&&t.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var ce;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(ce||(ce={}));const ZC=4*1e3;class Ni extends Yt.EventEmitter{constructor(e){var t,i,r,s;if(super(),t=this,this.state=ce.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=re,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=(a,o,c)=>y(this,void 0,void 0,function*(){var l;if(!jS())throw Xt()?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===ce.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(ce.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==a&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ec(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new xc(a,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(f=>{var m;(m=this.regionUrlProvider)===null||m===void 0||m.setServerReportedRegions(f)}).catch(f=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:f}))}));const d=(f,m,p)=>y(this,void 0,void 0,function*(){var v,b;this.abortController&&this.abortController.abort();const C=new AbortController;this.abortController=C,u==null||u();try{yield this.attemptConnection(p??a,o,c,C),this.abortController=void 0,f()}catch(x){if(this.regionUrlProvider&&x instanceof me&&x.reason!==se.Cancelled&&x.reason!==se.NotAllowed){let k=null;try{k=yield this.regionUrlProvider.getNextBestRegionUrl((v=this.abortController)===null||v===void 0?void 0:v.signal)}catch(S){if(S instanceof me&&(S.status===401||S.reason===se.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),m(S);return}}k&&!(!((b=this.abortController)===null||b===void 0)&&b.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(x.message,". Retrying with another region: ").concat(k),this.logContext),this.recreateEngine(),yield d(f,m,k)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,pf(x)),m(x))}else{let k=Ot.UNKNOWN_REASON;x instanceof me&&(k=pf(x)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,k),m(x)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new rc((f,m)=>{d(f,m,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,o,c,l,u,d)=>y(this,void 0,void 0,function*(){var h,f,m;const p=yield c.join(a,o,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},d.signal);let v=p.serverInfo;if(v||(v={version:p.serverVersion,region:p.serverRegion}),this.serverInfo=v,this.log.debug("connected to Livekit Server ".concat(Object.entries(v).map(b=>{let[C,x]=b;return"".concat(C,": ").concat(x)}).join(", ")),{room:(h=p.room)===null||h===void 0?void 0:h.name,roomSid:(f=p.room)===null||f===void 0?void 0:f.sid,identity:(m=p.participant)===null||m===void 0?void 0:m.identity}),!v.version)throw new xS("unknown server version");return v.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),p}),this.applyJoinResponse=a=>{const o=a.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(a.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(a.sifTrailer)}catch(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([o,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,o,c,l)=>y(this,void 0,void 0,function*(){var u,d;this.state===ce.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(),!((d=this.regionUrlProvider)===null||d===void 0)&&d.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},bc),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(a,o,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(M.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new me("could not establish signal connection",se.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof me&&(f.reason=h.reason,f.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),f}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new me("Connection attempt aborted",se.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}pt()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),pt()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ce.Connected),this.emit(M.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var a=arguments.length,o=new Array(a),c=0;c<a;c++)o[c]=arguments[c];return y(t,[...o],void 0,function(){var l=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var d,h,f,m;const p=yield l.disconnectLock.lock();try{if(l.state===ce.Disconnected){l.log.debug("already disconnected",l.logContext);return}l.log.info("disconnect from room",Object.assign({},l.logContext)),(l.state===ce.Connecting||l.state===ce.Reconnecting||l.isResuming)&&(l.log.warn("abort connection attempt",l.logContext),(d=l.abortController)===null||d===void 0||d.abort(),(f=(h=l.connectFuture)===null||h===void 0?void 0:h.reject)===null||f===void 0||f.call(h,new me("Client initiated disconnect",se.Cancelled)),l.connectFuture=void 0),!((m=l.engine)===null||m===void 0)&&m.client.isDisconnected||(yield l.engine.client.sendLeave()),l.engine&&(yield l.engine.close()),l.handleDisconnect(u,Ot.CLIENT_INITIATED),l.engine=void 0}finally{p()}}()})},this.onPageLeave=()=>y(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>y(this,void 0,void 0,function*(){const a=[],o=Lt();if(o&&o.os==="iOS"){const c="livekit-dummy-audio-el";let l=document.getElementById(c);if(!l){l=document.createElement("audio"),l.id=c,l.autoplay=!0,l.hidden=!0;const u=ic();u.enabled=!0;const d=new MediaStream([u]);l.srcObject=d,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:d,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(M.Disconnected,()=>{l==null||l.remove(),l=null})}a.push(l)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(u=>{a.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>y(this,void 0,void 0,function*(){const a=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(c=>{var l;(l=c.track)===null||l===void 0||l.attachedElements.forEach(u=>{a.includes(u)||a.push(u)})});yield Promise.all(a.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 a of this.remoteParticipants.values())this.handleParticipantDisconnected(a.identity,a);this.setAndEmitConnectionState(ce.Reconnecting)&&this.emit(M.Reconnecting)},this.handleSignalRestarted=a=>y(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(a.serverRegion),Object.assign(Object.assign({},this.logContext),{region:a.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(a);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:a.serverRegion}))}catch{return}this.setAndEmitConnectionState(ce.Connected),this.emit(M.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(o=>{var c;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(c=this.sidToIdentity.get(o.sid))!==null&&c!==void 0?c:"");let l=this.remoteParticipants.get(o.identity);o.state===Si.DISCONNECTED?this.handleParticipantDisconnected(o.identity,l):l=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=a=>{const o=[],c={};a.forEach(l=>{if(c[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(l.sid);u&&(u.audioLevel=l.level,u.setIsSpeaking(!0),o.push(u))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{c[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(M.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=a=>{const o=new Map;this.activeSpeakers.forEach(l=>{const u=this.remoteParticipants.get(l.identity);u&&u.sid!==l.sid||o.set(l.sid,l)}),a.forEach(l=>{let u=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=l.level,u.setIsSpeaking(l.active),l.active?o.set(l.sid,u):o.delete(l.sid))});const c=Array.from(o.values());c.sort((l,u)=>u.audioLevel-l.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(M.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(o=>{const c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(o.trackSid);if(!l||!l.track)return;const u=I.streamStateFromProto(o.state);u!==l.track.streamState&&(l.track.streamState=u,c.emit(j.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(M.TrackStreamStateChanged,l,l.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=a=>{const o=this.getRemoteParticipantBySid(a.participantSid);if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const o=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(a.trackSid));if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.setSubscriptionError(a.err)},this.handleDataPacket=a=>{const o=this.remoteParticipants.get(a.participantIdentity);if(a.value.case==="user")this.handleUserPacket(o,a.value.value,a.kind);else if(a.value.case==="transcription")this.handleTranscription(o,a.value.value);else if(a.value.case==="sipDtmf")this.handleSipDtmf(o,a.value.value);else if(a.value.case==="chatMessage")this.handleChatMessage(o,a.value.value);else if(a.value.case==="metrics")this.handleMetrics(a.value.value,o);else if(a.value.case==="streamHeader")this.handleStreamHeader(a.value.value,a.participantIdentity);else if(a.value.case==="streamChunk")this.handleStreamChunk(a.value.value);else if(a.value.case==="streamTrailer")this.handleStreamTrailer(a.value.value);else if(a.value.case==="rpcRequest"){const c=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(a,o,c)=>{this.emit(M.DataReceived,o.payload,a,c,o.topic),a==null||a.emit(j.DataReceived,o.payload,c)},this.handleSipDtmf=(a,o)=>{this.emit(M.SipDTMFReceived,o,a),a==null||a.emit(j.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(a,o)=>{const c=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),l=c==null?void 0:c.trackPublications.get(o.trackId),u=$S(o,this.transcriptionReceivedTimes);l==null||l.emit(D.TranscriptionReceived,u),c==null||c.emit(j.TranscriptionReceived,u,l),this.emit(M.TranscriptionReceived,u,c,l)},this.handleChatMessage=(a,o)=>{const c=YS(o);this.emit(M.ChatMessage,c,a)},this.handleMetrics=(a,o)=>{this.emit(M.MetricsReceived,a,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(M.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=a=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:a})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(M.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(M.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(M.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>y(this,void 0,void 0,function*(){var a,o,c;const l=He.getInstance().previousDevices,u=yield He.getInstance().getDevices(void 0,!1),d=Lt();if((d==null?void 0:d.name)==="Chrome"&&d.os!=="iOS")for(let f of u){const m=l.find(p=>p.deviceId===f.deviceId);m&&m.label!==""&&m.kind===f.kind&&m.label!==f.label&&this.getActiveDevice(f.kind)==="default"&&this.emit(M.ActiveDeviceChanged,f.kind,f.deviceId)}const h=["audiooutput","audioinput","videoinput"];for(let f of h){const m=ZS(f),p=this.localParticipant.getTrackPublication(m);if(p&&(!((a=p.track)===null||a===void 0)&&a.isUserProvided))continue;const v=u.filter(C=>C.kind===f),b=this.getActiveDevice(f);if(b===((o=l.filter(C=>C.kind===f)[0])===null||o===void 0?void 0:o.deviceId)&&v.length>0&&((c=v[0])===null||c===void 0?void 0:c.deviceId)!==b){yield this.switchActiveDevice(f,v[0].deviceId);continue}f==="audioinput"&&!Ln()||f==="videoinput"||v.length>0&&!v.find(C=>C.deviceId===this.getActiveDevice(f))&&(yield this.switchActiveDevice(f,v[0].deviceId))}this.emit(M.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const o=this.roomInfo;this.roomInfo=a,o&&o.metadata!==a.metadata&&this.emitWhenConnected(M.RoomMetadataChanged,a.metadata),(o==null?void 0:o.activeRecording)!==a.activeRecording&&this.emitWhenConnected(M.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>{a.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const c=this.getRemoteParticipantBySid(o.participantSid);c&&c.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=a=>{this.emit(M.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(M.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(M.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(M.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(M.TrackUnmuted,a,this.localParticipant)},this.onTrackProcessorUpdate=a=>{var o;(o=a==null?void 0:a.onPublish)===null||o===void 0||o.call(a,this)},this.onLocalTrackPublished=a=>y(this,void 0,void 0,function*(){var o,c,l,u,d,h;(o=a.track)===null||o===void 0||o.on(D.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.on(D.Restarted,this.onLocalTrackRestarted),(d=(u=(l=a.track)===null||l===void 0?void 0:l.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||d===void 0||d.call(u,this),this.emit(M.LocalTrackPublished,a,this.localParticipant),Zn(a.track)&&(yield a.track.checkForSilence())&&this.emit(M.LocalAudioSilenceDetected,a);const f=yield(h=a.track)===null||h===void 0?void 0:h.getDeviceId(!1),m=bf(a.source);m&&f&&f!==this.localParticipant.activeDeviceMap.get(m)&&(this.localParticipant.activeDeviceMap.set(m,f),this.emit(M.ActiveDeviceChanged,m,f))}),this.onLocalTrackUnpublished=a=>{var o,c;(o=a.track)===null||o===void 0||o.off(D.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.off(D.Restarted,this.onLocalTrackRestarted),this.emit(M.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>y(this,void 0,void 0,function*(){const o=yield a.getDeviceId(!1),c=bf(a.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,o),this.emit(M.ActiveDeviceChanged,c,o))}),this.onLocalConnectionQualityChanged=a=>{this.emit(M.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=a=>{this.emit(M.MediaDevicesError,a)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(M.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(M.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},TC),e),this.log=rn((i=this.options.loggerName)!==null&&i!==void 0?i:Mt.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Pf),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},If),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},yC),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new ut,this.localParticipant=new JC("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Dn(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Dn(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",Dn(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),pt()){const a=new AbortController;(s=navigator.mediaDevices)===null||s===void 0||s.addEventListener("devicechange",this.handleDeviceChange,{signal:a.signal}),Ni.cleanupRegistry&&Ni.cleanupRegistry.register(this,()=>{a.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,i,r,s,a){return y(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,Pe.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,Pe.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const u=yield o({requestId:t,callerIdentity:e,payload:r,responseTimeout:s});yc(u)>Of?(c=Pe.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):l=u}catch(u){u instanceof Pe?c=u:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),u),c=Pe.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,l,c)})}setE2EEEnabled(e){return y(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 sC(this.options.e2ee),this.e2eeManager.on(Nn.ParticipantEncryptionStatusChanged,(t,i)=>{JS(i)&&(this.isE2EEEnabled=t),this.emit(M.ParticipantEncryptionStatusChanged,t,i)}),this.e2eeManager.on(Nn.EncryptionError,t=>this.emit(M.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 y(this,void 0,void 0,function*(){return this.state===ce.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const i=r=>{r.sid!==""&&(this.engine.off(U.RoomUpdate,i),e(r.sid))};this.engine.on(U.RoomUpdate,i),this.once(M.Disconnected,()=>{this.engine.off(U.RoomUpdate,i),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 DC(this.options),this.engine.on(U.ParticipantUpdate,this.handleParticipantUpdates).on(U.RoomUpdate,this.handleRoomUpdate).on(U.SpeakersChanged,this.handleSpeakersChanged).on(U.StreamStateChanged,this.handleStreamStateUpdate).on(U.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(U.SubscriptionError,this.handleSubscriptionError).on(U.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(U.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(U.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(U.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(U.DataPacketReceived,this.handleDataPacket).on(U.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ce.SignalReconnecting)&&this.emit(M.SignalReconnecting)}).on(U.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ce.Connected)&&this.emit(M.Reconnected)}).on(U.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ce.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(U.Restarting,this.handleRestarting).on(U.SignalRestarted,this.handleSignalRestarted).on(U.Offline,()=>{this.setAndEmitConnectionState(ce.Reconnecting)&&this.emit(M.Reconnecting)}).on(U.DCBufferStatusChanged,(e,t)=>{this.emit(M.DCBufferStatusChanged,e,t)}).on(U.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:r}=i;return r===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(j.LocalTrackSubscribed,t),this.emitWhenConnected(M.LocalTrackSubscribed,t,this.localParticipant)}).on(U.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(M.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 He.getInstance().getDevices(e,t)}prepareConnection(e,t){return y(this,void 0,void 0,function*(){if(this.state===ce.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(ec(new URL(e))&&t){this.regionUrlProvider=new xc(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===ce.Disconnected&&(this.regionUrl=i,yield fetch(sc(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(sc(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return y(this,void 0,void 0,function*(){let i=()=>{},r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new $t({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new $t({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new $t({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new $t({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>y(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new $t({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>y(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new $t({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":r=new $t({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>y(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new Ls({reason:Ot.CLIENT_INITIATED,action:wi.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new $t({scenario:{case:"subscriberBandwidth",value:Qn(t)}});break;case"leave-full-reconnect":r=new $t({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return y(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,c,l,u,d,h,f,m;let p=!0,v=!1;const b=a?{exact:r}:r;if(i==="audioinput"){v=s.localParticipant.audioTrackPublications.size===0;const C=(o=s.getActiveDevice(i))!==null&&o!==void 0?o:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=b;const x=Array.from(s.localParticipant.audioTrackPublications.values()).filter(k=>k.source===I.Source.Microphone);try{p=(yield Promise.all(x.map(k=>{var S;return(S=k.audioTrack)===null||S===void 0?void 0:S.setDeviceId(b)}))).every(k=>k===!0)}catch(k){throw s.options.audioCaptureDefaults.deviceId=C,k}}else if(i==="videoinput"){v=s.localParticipant.videoTrackPublications.size===0;const C=(c=s.getActiveDevice(i))!==null&&c!==void 0?c:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=b;const x=Array.from(s.localParticipant.videoTrackPublications.values()).filter(k=>k.source===I.Source.Camera);try{p=(yield Promise.all(x.map(k=>{var S;return(S=k.videoTrack)===null||S===void 0?void 0:S.setDeviceId(b)}))).every(k=>k===!0)}catch(k){throw s.options.videoCaptureDefaults.deviceId=C,k}}else if(i==="audiooutput"){if(!Zo()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");s.options.webAudioMix&&(r=(l=yield He.getInstance().normalizeDeviceId("audiooutput",r))!==null&&l!==void 0?l:""),(u=(m=s.options).audioOutput)!==null&&u!==void 0||(m.audioOutput={});const C=(d=s.getActiveDevice(i))!==null&&d!==void 0?d:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((h=s.audioContext)===null||h===void 0||h.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(x=>x.setAudioOutput({deviceId:r})))}catch(x){throw s.options.audioOutput.deviceId=C,x}}return(v||i==="audiooutput")&&(s.localParticipant.activeDeviceMap.set(i,i==="audiooutput"&&((f=s.options.audioOutput)===null||f===void 0?void 0:f.deviceId)||r),s.emit(M.ActiveDeviceChanged,i,r)),p}()})}setupLocalParticipantEvents(){this.localParticipant.on(j.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(j.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(j.AttributesChanged,this.onLocalAttributesChanged).on(j.TrackMuted,this.onLocalTrackMuted).on(j.TrackUnmuted,this.onLocalTrackUnmuted).on(j.LocalTrackPublished,this.onLocalTrackPublished).on(j.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(j.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(j.MediaDevicesError,this.onMediaDevicesError).on(j.AudioStreamAcquired,this.startAudio).on(j.ChatMessage,this.onLocalChatMessageSent).on(j.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===ce.Connecting||this.state===ce.Reconnecting){const u=()=>{this.onTrackAdded(e,t,i),d()},d=()=>{this.off(M.Reconnected,u),this.off(M.Connected,u),this.off(M.Disconnected,d)};this.once(M.Reconnected,u),this.once(M.Connected,u),this.once(M.Disconnected,d);return}if(this.state===ce.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 r=US(t.id),s=r[0];let a=r[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===s);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={}),c.addSubscribedMediaTrack(e,o,t,i,l)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==ce.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{r.unpublishTrack(s.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var s,a,o;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((s=r.track)===null||s===void 0||s.detach(),(a=r.track)===null||a===void 0||a.stop()):(o=r.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(j.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(j.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(j.AttributesChanged,this.onLocalAttributesChanged).off(j.TrackMuted,this.onLocalTrackMuted).off(j.TrackUnmuted,this.onLocalTrackUnmuted).off(j.LocalTrackPublished,this.onLocalTrackPublished).off(j.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(j.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(j.MediaDevicesError,this.onMediaDevicesError).off(j.AudioStreamAcquired,this.startAudio).off(j.ChatMessage,this.onLocalChatMessageSent).off(j.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),pt()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(i=navigator.mediaDevices)===null||i===void 0||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ce.Disconnected),this.emit(M.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(r=>{t.unpublishTrack(r.trackSid,!0)}),this.emit(M.ParticipantDisconnected,t),t.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return y(this,void 0,void 0,function*(){var i;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let s;const a={id:e.streamId,name:(i=e.contentHeader.value.name)!==null&&i!==void 0?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:$s(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:c=>{s=c,this.byteStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now()})}});r(new jC(a,o,$s(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let s;const a={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:c=>{s=c,this.textStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now()})}});r(new VC(a,o,$s(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.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 i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return y(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=vf())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),ft(200)])}catch(r){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(M.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let r;return t?r=na.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new na(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),r}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return t&&r.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),r}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(M.ParticipantConnected,i),i.on(j.TrackPublished,r=>{this.emitWhenConnected(M.TrackPublished,r,i)}).on(j.TrackSubscribed,(r,s)=>{r.kind===I.Kind.Audio?(r.on(D.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(D.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===I.Kind.Video&&(r.on(D.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(D.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(M.TrackSubscribed,r,s,i)}).on(j.TrackUnpublished,r=>{this.emit(M.TrackUnpublished,r,i)}).on(j.TrackUnsubscribed,(r,s)=>{this.emit(M.TrackUnsubscribed,r,s,i)}).on(j.TrackMuted,r=>{this.emitWhenConnected(M.TrackMuted,r,i)}).on(j.TrackUnmuted,r=>{this.emitWhenConnected(M.TrackUnmuted,r,i)}).on(j.ParticipantMetadataChanged,r=>{this.emitWhenConnected(M.ParticipantMetadataChanged,r,i)}).on(j.ParticipantNameChanged,r=>{this.emitWhenConnected(M.ParticipantNameChanged,r,i)}).on(j.AttributesChanged,r=>{this.emitWhenConnected(M.ParticipantAttributesChanged,r,i)}).on(j.ConnectionQualityChanged,r=>{this.emitWhenConnected(M.ConnectionQualityChanged,r,i)}).on(j.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(M.ParticipantPermissionsChanged,r,i)}).on(j.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(M.TrackSubscriptionStatusChanged,r,s,i)}).on(j.TrackSubscriptionFailed,(r,s)=>{this.emit(M.TrackSubscriptionFailed,r,i,s)}).on(j.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(M.TrackSubscriptionPermissionChanged,r,s,i)}).on(j.Active,()=>{this.emitWhenConnected(M.ParticipantActive,i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,r)=>(i.push(...r.getTrackPublications()),i),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&XS(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=Je.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,Ot.STATE_MISMATCH))):e=0},ZC)}clearConnectionReconcile(){this.connectionReconcileInterval&&Je.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(M.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(this.state===ce.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===ce.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return y(this,void 0,void 0,function*(){var t,i;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Os({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:we.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Kn({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(M.SignalConnected),this.emit(M.Connected),this.setAndEmitConnectionState(ce.Connected),r.video){const a=new Rc(I.Kind.Video,new Ci({source:Ue.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:It.AUDIO,name:"video-dummy"}),new ea(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:ff(160*((t=s.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(a),this.localParticipant.emit(j.LocalTrackPublished,a)}if(r.audio){const a=new Rc(I.Kind.Audio,new Ci({source:Ue.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:It.AUDIO}),new Qs(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:ic(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit(j.LocalTrackPublished,a)}for(let a=0;a<s.count-1;a+=1){let o=new Kn({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:Si.ACTIVE,tracks:[],joinedAt:we.parse(Date.now())});const c=this.getOrCreateParticipant(o.identity,o);if(s.video){const l=ff(160*((i=s.aspectRatios[a%s.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),u=new Ci({source:Ue.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:It.AUDIO});c.addSubscribedMediaTrack(l,u.sid,new MediaStream([l]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}if(s.audio){const l=ic(),u=new Ci({source:Ue.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:It.AUDIO});c.addSubscribedMediaTrack(l,u.sid,new MediaStream([l]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}c.updateInfo(o)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(e!==M.ActiveSpeakersChanged&&e!==M.TranscriptionReceived){const s=qf(i).filter(a=>a!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:s}))}return super.emit(e,...i)}}Ni.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function qf(n){return n.map(e=>{if(e)return Array.isArray(e)?qf(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Bt;(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"})(Bt||(Bt={}));class jn extends Yt.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Bt.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Ni(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return y(this,void 0,void 0,function*(){if(this.status!==Bt.IDLE)throw Error("check is running already");this.setStatus(Bt.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!==Bt.SKIPPED&&this.setStatus(this.isSuccess()?Bt.SUCCESS:Bt.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return y(this,void 0,void 0,function*(){return this.room.state===ce.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return y(this,void 0,void 0,function*(){this.room&&this.room.state!==ce.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Bt.SKIPPED)}switchProtocol(e){return y(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(M.Reconnecting,()=>{t=!0}),this.room.once(M.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!t)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield ft(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 e1 extends jn{get description(){return"Cloud regions"}perform(){return y(this,void 0,void 0,function*(){const e=new xc(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let s=0;s<3;s++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((s,a)=>(s.duration-a.duration)*.5+(s.rtt-a.rtt)*.5);const r=t[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return y(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,c=1e6/a,l="A".repeat(a),u=Date.now();for(let m=0;m<c;m++)yield s.write(l);yield s.close();const d=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:r,rtt:1e4,duration:d-u};return h==null||h.forEach(m=>{m.type==="candidate-pair"&&m.nominated&&(f.rtt=m.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const Pc=1e4;class t1 extends jn{get description(){return"Connection via UDP vs TCP"}perform(){return y(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(Pc/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Pc/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return y(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(s)};s();const o=t.captureStream(30).getVideoTracks()[0],l=(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},d=setInterval(()=>y(this,void 0,void 0,function*(){const h=yield l.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(u.packetsSent=f.packetsSent,u.qualityLimitationDurations=f.qualityLimitationDurations,u.bitrateTotal+=f.targetBitrate,u.count++):f.type==="remote-inbound-rtp"&&(u.packetsLost=f.packetsLost,u.rttTotal+=f.roundTripTime,u.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Pc)),clearInterval(d),o.stop(),t.remove(),yield this.disconnect(),u})}}class n1 extends jn{get description(){return"Can publish audio"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield $C();if(yield gf(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let a=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class i1 extends jn{get description(){return"Can publish video"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield KC();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(s+=a.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return y(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var s,a,o,c;const l=document.createElement("canvas"),u=e.getSettings(),d=(a=(s=u.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&a!==void 0?a:1280,h=(c=(o=u.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&c!==void 0?c:720;l.width=d,l.height=h;const f=l.getContext("2d");f.drawImage(i,0,0);const p=f.getImageData(0,0,l.width,l.height).data;let v=!0;for(let b=0;b<p.length;b+=4)if(p[b]!==0||p[b+1]!==0||p[b+2]!==0){v=!1;break}v?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),i.remove()})}}class r1 extends jn{get description(){return"Resuming connection after interruption"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,r=!1,s;const a=new Promise(l=>{setTimeout(l,5e3),s=l}),o=()=>{i=!0};t.on(M.SignalReconnecting,o).on(M.Reconnecting,o).on(M.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield a,i){if(!r||t.state!==ce.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 s1 extends jn{get description(){return"Can connect via TURN"}perform(){return y(this,void 0,void 0,function*(){var e,t;const i=new dc,r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,a=!1,o=!1;for(let c of r.iceServers)for(let l of c.urls)l.startsWith("turn:")?(a=!0,o=!0):l.startsWith("turns:")&&(a=!0,o=!0,s=!0),l.startsWith("stun:")&&(o=!0);o?a&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class a1 extends jn{get description(){return"Establishing WebRTC connection"}perform(){return y(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(M.SignalConnected,()=>{const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,s)=>{if(r.candidate){const a=new RTCIceCandidate(r);let o="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(o1(a.address)?o+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,o+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(o)}i&&i(r,s)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),re.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function o1(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 c1 extends jn{get description(){return"Connecting to signal connection via WebSocket"}perform(){return y(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new dc;const s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===$d.Cloud&&(!((t=s.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region)),yield r.close()})}}class S_ extends Yt.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Bt.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!==Bt.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return y(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=a=>{this.updateCheck(t,a)};i.on("update",r);const s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(c1)})}checkWebRTC(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(a1)})}checkTURN(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(s1)})}checkReconnect(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(r1)})}checkPublishAudio(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(n1)})}checkPublishVideo(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(i1)})}checkConnectionProtocol(){return y(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(t1);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(e1)})}}const l1=/\{[^{}]+\}/g;function u1(){return Math.random().toString(36).slice(2,11)}function d1(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:i=globalThis.fetch,querySerializer:r,bodySerializer:s,headers:a,...o}={...n};e=Xf(e);const c=[];async function l(u,d){const{baseUrl:h,fetch:f=i,Request:m=t,headers:p,params:v={},parseAs:b="json",querySerializer:C,bodySerializer:x=s??f1,body:k,...S}=d||{};h&&(e=Xf(h));let w=typeof r=="function"?r:Yf(r);C&&(w=typeof C=="function"?C:Yf({...typeof r=="object"?r:{},...C}));const E=k===void 0?void 0:x(k),A=E===void 0||E instanceof FormData?{}:{"Content-Type":"application/json"},O={redirect:"follow",...o,...S,body:E,headers:m1(A,a,p,v.header)};let B,L,R=new t(p1(u,{baseUrl:e,params:v,querySerializer:w}),O);for(const X in S)X in R||(R[X]=S[X]);if(c.length){B=u1(),L=Object.freeze({baseUrl:e,fetch:f,parseAs:b,querySerializer:w,bodySerializer:x});for(const X of c)if(X&&typeof X=="object"&&typeof X.onRequest=="function"){const K=await X.onRequest({request:R,schemaPath:u,params:v,options:L,id:B});if(K){if(!(K instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");R=K}}}let H=await f(R);if(c.length)for(let X=c.length-1;X>=0;X--){const K=c[X];if(K&&typeof K=="object"&&typeof K.onResponse=="function"){const ye=await K.onResponse({request:R,response:H,schemaPath:u,params:v,options:L,id:B});if(ye){if(!(ye instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");H=ye}}}if(H.status===204||H.headers.get("Content-Length")==="0")return H.ok?{data:{},response:H}:{error:{},response:H};if(H.ok)return b==="stream"?{data:H.body,response:H}:{data:await H[b](),response:H};let Q=await H.text();try{Q=JSON.parse(Q)}catch{}return{error:Q,response:H}}return{GET(u,d){return l(u,{...d,method:"GET"})},PUT(u,d){return l(u,{...d,method:"PUT"})},POST(u,d){return l(u,{...d,method:"POST"})},DELETE(u,d){return l(u,{...d,method:"DELETE"})},OPTIONS(u,d){return l(u,{...d,method:"OPTIONS"})},HEAD(u,d){return l(u,{...d,method:"HEAD"})},PATCH(u,d){return l(u,{...d,method:"PATCH"})},TRACE(u,d){return l(u,{...d,method:"TRACE"})},use(...u){for(const d of u)if(d){if(typeof d!="object"||!("onRequest"in d||"onResponse"in d))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");c.push(d)}},eject(...u){for(const d of u){const h=c.indexOf(d);h!==-1&&c.splice(h,1)}}}}function ia(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 Kf(n,e,t){if(!e||typeof e!="object")return"";const i=[],r={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(const o in e)i.push(o,t.allowReserved===!0?e[o]:encodeURIComponent(e[o]));const a=i.join(",");switch(t.style){case"form":return`${n}=${a}`;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return a}}for(const a in e){const o=t.style==="deepObject"?`${n}[${a}]`:a;i.push(ia(o,e[a],t))}const s=i.join(r);return t.style==="label"||t.style==="matrix"?`${r}${s}`:s}function $f(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){const s={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",a=(t.allowReserved===!0?e:e.map(o=>encodeURIComponent(o))).join(s);switch(t.style){case"simple":return a;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return`${n}=${a}`}}const i={simple:",",label:".",matrix:";"}[t.style]||"&",r=[];for(const s of e)t.style==="simple"||t.style==="label"?r.push(t.allowReserved===!0?s:encodeURIComponent(s)):r.push(ia(n,s,t));return t.style==="label"||t.style==="matrix"?`${i}${r.join(i)}`:r.join(i)}function Yf(n){return function(t){const i=[];if(t&&typeof t=="object")for(const r in t){const s=t[r];if(s!=null){if(Array.isArray(s)){if(s.length===0)continue;i.push($f(r,s,{style:"form",explode:!0,...n==null?void 0:n.array,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}if(typeof s=="object"){i.push(Kf(r,s,{style:"deepObject",explode:!0,...n==null?void 0:n.object,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}i.push(ia(r,s,n))}}return i.join("&")}}function h1(n,e){let t=n;for(const i of n.match(l1)??[]){let r=i.substring(1,i.length-1),s=!1,a="simple";if(r.endsWith("*")&&(s=!0,r=r.substring(0,r.length-1)),r.startsWith(".")?(a="label",r=r.substring(1)):r.startsWith(";")&&(a="matrix",r=r.substring(1)),!e||e[r]===void 0||e[r]===null)continue;const o=e[r];if(Array.isArray(o)){t=t.replace(i,$f(r,o,{style:a,explode:s}));continue}if(typeof o=="object"){t=t.replace(i,Kf(r,o,{style:a,explode:s}));continue}if(a==="matrix"){t=t.replace(i,`;${ia(r,o)}`);continue}t=t.replace(i,a==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function f1(n){return n instanceof FormData?n:JSON.stringify(n)}function p1(n,e){var r;let t=`${e.baseUrl}${n}`;(r=e.params)!=null&&r.path&&(t=h1(t,e.params.path));let i=e.querySerializer(e.params.query??{});return i.startsWith("?")&&(i=i.substring(1)),i&&(t+=`?${i}`),t}function m1(...n){const e=new Headers;for(const t of n){if(!t||typeof t!="object")continue;const i=t instanceof Headers?t.entries():Object.entries(t);for(const[r,s]of i)if(s===null)e.delete(r);else if(Array.isArray(s))for(const a of s)e.append(r,a);else s!==void 0&&e.set(r,s)}return e}function Xf(n){return n.endsWith("/")?n.substring(0,n.length-1):n}const Jf="Onboardee-Session-Token",Qf="OnboardeeSessionToken";class Zf{constructor(e){this.client=d1({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch}),this.client.use({onRequest({request:t}){if(window.localStorage){const i=window.localStorage.getItem(Qf);i&&t.headers.set(Jf,i)}return t},onResponse({response:t}){const i=t.headers.get(Jf);return i&&window.localStorage&&window.localStorage.setItem(Qf,i),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 listUsers(){return await this.client.GET("/api/users")}async createUser(e){return await this.client.POST("/api/users",{body:e})}async updateUser(e,t){return await this.client.PATCH("/api/users/{id}",{params:{path:{id:e}},body:t})}async deleteUser(e){return await this.client.DELETE("/api/users/{id}",{params:{path:{id:e}}})}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,i,r){return await this.client.GET("/api/products/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...i&&{end_date:i},...r&&{course_id:r}}}})}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 getProductAppToken(e){return await this.client.GET("/api/products/{id}/app-token",{params:{path:{id:e}}})}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:{content:t.content||""}})}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,i){return await this.client.GET("/api/products/{id}/knowledge-blocks/search",{params:{path:{id:e},query:{q:t,...i&&{limit:i.toString()}}}})}async listAudiences(e){return await this.client.GET("/api/products/{id}/audiences",{params:{path:{id:String(e)}}})}async createAudience(e,t){return await this.client.POST("/api/products/{id}/audiences",{params:{path:{id:String(e)}},body:t})}async getAudience(e,t){return await this.client.GET("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:t}}})}async updateAudience(e,t,i){return await this.client.PATCH("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:t}},body:i})}async deleteAudience(e,t){return await this.client.DELETE("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:t}}})}async replaceAudiencePlans(e,t,i){return await this.client.PUT("/api/products/{id}/audiences/{audienceId}/plans",{params:{path:{id:String(e),audienceId:t}},body:{plans:i}})}async updateProductKnowledgeBlock(e,t,i){return await this.client.PATCH("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:i})}async deleteProductKnowledgeBlock(e,t){return await this.client.DELETE("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async listProductPronunciationRules(e){return await this.client.GET("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}}})}async bulkCreateProductPronunciationRules(e,t){return await this.client.POST("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}},body:t})}async bulkUpdateProductPronunciationRules(e,t){return await this.client.PATCH("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}},body:t})}async deleteProductPronunciationRule(e,t){return await this.client.DELETE("/api/products/{id}/pronunciation-dictionary/{ruleId}",{params:{path:{id:e,ruleId:t}}})}async listProductExternalKnowledge(e){return await this.client.GET("/api/products/{id}/external-knowledge",{params:{path:{id:e}}})}async createProductExternalKnowledge(e,t){return await this.client.POST("/api/products/{id}/external-knowledge",{params:{path:{id:e}},body:t})}async updateProductExternalKnowledge(e,t,i){return await this.client.PATCH("/api/products/{id}/external-knowledge/{entryId}",{params:{path:{id:e,entryId:t}},body:i})}async deleteProductExternalKnowledge(e,t){return await this.client.DELETE("/api/products/{id}/external-knowledge/{entryId}",{params:{path:{id:e,entryId:t}}})}async refreshProductExternalKnowledge(e,t){return await this.client.POST("/api/products/{id}/external-knowledge/{entryId}/refresh",{params:{path:{id:e,entryId:t}}})}async listExternalKnowledgePages(e,t){return await this.client.GET("/api/products/{id}/external-knowledge/{entryId}/pages",{params:{path:{id:e,entryId: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,i){return await this.client.GET("/api/plans/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...i&&{end_date:i}}}})}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 duplicatePlan(e){return await this.client.POST("/api/plans/{id}/duplicate",{params:{path:{id:e}}})}async listAdminUsers(e){const t={};return e!=null&&e.search&&(t.search=e.search),e!=null&&e.page&&(t.page=e.page),e!=null&&e.limit&&(t.limit=e.limit),await this.client.GET("/api/admin/users",{params:Object.keys(t).length>0?{query:t}:void 0})}async createAdminUser(e){return await this.client.POST("/api/users",{body:e})}async publishPlanRevision(e,t){return await this.client.POST("/api/plans/{id}/publish",{params:{path:{id:e}},body:t})}async getPlanAutosave(e){return await this.client.GET("/api/plans/{id}/autosave",{params:{path:{id:e}}})}async upsertPlanAutosave(e,t,i){return await this.client.PUT("/api/plans/{id}/autosave",{params:{path:{id:e}},body:t,signal:i})}async deletePlanAutosave(e){return await this.client.DELETE("/api/plans/{id}/autosave",{params:{path:{id:e}}})}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,i){return await this.client.PUT("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:i})}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:{content:t.content||""}})}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 listPlanFAQs(e,t=!1){return await this.client.GET("/api/plans/{id}/faqs",{params:{path:{id:e},query:{include_drafts:String(t)}}})}async listPlanDraftFAQs(e){return await this.client.GET("/api/plans/{id}/draft-faqs",{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 listRevisionFAQs(e,t){return await this.client.GET("/api/revisions/{id}/faqs",{params:{path:{id:e},query:{...t!==void 0&&{include_drafts:t.toString()}}}})}async createRevisionFAQ(e,t){return await this.client.POST("/api/revisions/{id}/faqs",{params:{path:{id:e}},body:t})}async updateFAQ(e,t){return await this.client.PUT("/api/faqs/{id}",{params:{path:{id:e}},body:t})}async deleteFAQ(e){return await this.client.DELETE("/api/faqs/{id}",{params:{path:{id:e}}})}async promoteFAQ(e){return await this.client.POST("/api/faqs/{id}/promote",{params:{path:{id:e}}})}async promoteFAQs(e){return await this.client.POST("/api/faqs/promote",{body:{faq_ids:e}})}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,i){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:i})}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 i={token:e};return t!=null&&t.productId&&(i.product_id=t.productId),t!=null&&t.startDate&&(i.start_date=t.startDate),t!=null&&t.endDate&&(i.end_date=t.endDate),await this.client.GET("/api/sessions",{params:{query:i}})}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:i}={}){return await this.client.GET("/api/join-token",{params:{query:{token:e,...t&&{client_type:t},...i&&{user:encodeURIComponent(i)}}}})}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}}})}async getGraphemes(){return await this.client.GET("/api/graphemes")}async listVoices(){return await this.client.GET("/api/voices")}async generateVoiceSample(e,t){return await this.client.POST("/api/voices/generate-sample",{body:{product_id:t,voice_id:e},parseAs:"stream"})}async getFeatureFlags(e){return await this.client.GET("/api/features",{params:e?{query:e}:void 0})}getClient(){return this.client}}const ep="https://app.coragents.ai";class ra extends Pa{constructor(e,t,i,r){super(),this.state=null,this.isPaused=!1,this.isAudioTrackPublished=!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.agentAudioContext=null,this.userAudioContext=null,this.frequencyDataBuffer=null,this.publishedAudioStream=null,this.publishedAudioTrack=null,this.appToken=e,this.planId=t,this.clientType=i,this.api=r.api||new Zf({baseUrl:ep}),this.identity=r.identity||null,this.roomFactory=r.roomFactory||(s=>new Ni(s)),this.captureScreen=r.captureScreen||null}async start(e){this.planId,e==null||e.roomId,this.setState("connecting"),this.speakingStateChanged("thinking");try{const i=(await this.api.clientStartSession(this.appToken,{client_type:this.clientType,onboarding_plan:this.planId,...(e==null?void 0:e.roomId)&&{room_id:e.roomId}})).data;if(!(i!=null&&i.url)||!(i!=null&&i.token)||!(i!=null&&i.room)||!(i!=null&&i.session_uuid))throw new Error("Invalid room info");this.sessionUuid=i==null?void 0:i.session_uuid,this.roomId=i==null?void 0:i.room,this.joinToken=i==null?void 0:i.token,this.roomUrl=i==null?void 0:i.url,this.startedAt=Date.now(),await this.joinRoom(),this.setState("volume-check"),this.planId,this.sessionUuid}catch(t){console.error("[obi] error starting session",{error:t}),this.setState("error")}}async joinRoom({withMicrophone:e=!1,withStateRecovery:t=!1}={}){if(this.room=this.roomFactory({adaptiveStream:!0,dynacast:!0}),this.room.on(M.Disconnected,i=>{if(!this.room)return;let r=null;switch(i){case 12:r="invalid-room";break}this.shutdown(r)}),this.room.on(M.TrackSubscribed,i=>{if(i.kind==="audio"&&(i.attach(),i.source===I.Source.Microphone)){this.agentAnalyser&&(this.agentAnalyser.disconnect(),this.agentAnalyser=null),this.agentAudioContext&&(this.agentAudioContext.close(),this.agentAudioContext=null);const{analyser:r,context:s}=this.createFFT(i.mediaStream);this.agentAnalyser=r,this.agentAudioContext=s}}),this.room.on(M.LocalTrackPublished,i=>{if(i.kind==="audio"){this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null);const{analyser:r,context:s}=this.createFFT(i.audioTrack.mediaStream);this.userAnalyser=r,this.userAudioContext=s}}),this.room.on(M.ParticipantAttributesChanged,i=>{if(!i["lk.agent.state"])return;const r=i["lk.agent.state"];switch(r){case"speaking":this.speakingStateChanged("speaking");break;case"listening":this.speakingStateChanged("listening");break;case"thinking":this.speakingStateChanged("thinking");break;default:console.warn("[obi] unknown speaking state",r)}}),this.room.on(M.DataReceived,async i=>{try{const r=new TextDecoder().decode(i),s=JSON.parse(r);switch(s.status||s.request||s.type){case"course_progress":typeof s.current_step=="number"&&typeof s.total_steps=="number"&&Array.isArray(s.step_names)&&this.emit("courseProgress",{currentStep:Math.max(1,s.current_step),totalSteps:Math.max(1,s.total_steps),stepNames:s.step_names});break;case"open_text_input":this.emit("textInputRequested");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"in_progress":this.setState("in-progress");break;case"shutdown":this.shutdown("server-sent");break;case"mute_microphone":this.muteMicrophone();break;case"unmute_microphone":this.unmuteMicrophone();break;case"transcript":this.emit("transcript",s.transcript,s.role);break;default:console.warn("[obi] unknown data received",s)}}catch(r){console.error("[obi] error parsing data",r)}}),this.room.localParticipant.registerRpcMethod("mic_check",async i=>(this.sessionUuid,await this.checkMicrophone()?"ok":"error")),this.room.localParticipant.registerRpcMethod("screen_capture",async i=>{if(!this.captureScreen)return console.error("[obi] no captureScreen function provided"),"error";let r=null,s=null;try{r=await this.captureScreen()}catch(a){r=null,a=a}if(!r||s)return console.error("[obi] error capturing screen",{error:s}),"error";try{return await this.room.localParticipant.sendFile(new File([r],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),"ok"}catch(a){return console.error("[obi] error sending screen capture",{error:a}),"error"}}),await this.room.connect(this.roomUrl,this.joinToken),e&&await this.room.localParticipant.setMicrophoneEnabled(!0),t){let i=!1;for(const r of this.room.remoteParticipants.values())r.isSpeaking&&(i=!0);i?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(i){i=i,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 publishAudioTrack(){if(this.sessionUuid,!this.room)return console.error("[obi] cannot publish audio track: room not connected"),!1;let e=!1;try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia){const l=!!navigator.mediaDevices;return console.error("[obi] getUserMedia not available in this environment",l),!1}console.log("[obi] requesting audio track via getUserMedia"),this.publishedAudioStream=await navigator.mediaDevices.getUserMedia({audio:!0});const t=this.publishedAudioStream.getAudioTracks().map(l=>{var u,d;return{id:l.id,label:l.label,enabled:l.enabled,muted:l.muted,readyState:l.readyState,constraints:(u=l.getConstraints)==null?void 0:u.call(l),settings:(d=l.getSettings)==null?void 0:d.call(l)}});console.log("[obi] getUserMedia resolved",t);const i=this.publishedAudioStream.getAudioTracks()[0];if(!i){const l=this.publishedAudioStream.getAudioTracks().length;return console.warn("[obi] no audio track found from getUserMedia stream",l),!1}this.publishedAudioTrack=i;const r={id:i.id,label:i.label,kind:i.kind,readyState:i.readyState},s=this.room.localParticipant.identity;console.log("[obi] publishing audio track to LiveKit",r,s);const a=await this.room.localParticipant.publishTrack(i,{name:"microphone",source:I.Source.Microphone});console.log("[obi] published audio track to LiveKit",i.id,s,a.isEnabled),this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null);const{analyser:o,context:c}=this.createFFT(this.publishedAudioStream);this.userAnalyser=o,this.userAudioContext=c,this.isAudioTrackPublished=!0,e=!0}catch(t){if(console.error("[obi] failed to publish audio track",t),this.isAudioTrackPublished=!1,this.publishedAudioStream){try{this.publishedAudioStream.getTracks().forEach(i=>i.stop())}catch(i){console.warn("[obi] error stopping tracks during cleanup",i)}this.publishedAudioStream=null}this.publishedAudioTrack=null}return e}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,i;e.handleMuted(),(i=(t=e.track)==null?void 0:t.mediaStream)==null||i.getTracks().forEach(r=>r.enabled=!1)})}unmuteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var t,i;e.handleUnmuted(),(i=(t=e.track)==null?void 0:t.mediaStream)==null||i.getTracks().forEach(r=>r.enabled=!0)})}async stop(){this.emit("stopped"),await this.shutdown()}async shutdown(e=null){if(this.room){if(this.sessionUuid,this.publishedAudioTrack&&this.isAudioTrackPublished)try{console.log("[obi] unpublishing audio track",this.publishedAudioTrack.id,this.room.localParticipant.identity),this.room.localParticipant.unpublishTrack(this.publishedAudioTrack)}catch(i){console.warn("[obi] failed to unpublish audio track",i)}if(this.publishedAudioStream)try{const i=this.publishedAudioStream.getAudioTracks().length;console.log("[obi] stopping published audio stream tracks",i),this.publishedAudioStream.getTracks().forEach(r=>r.stop())}catch(i){console.warn("[obi] error stopping published audio tracks",i)}e!=="server-sent"&&await this.sendData({request:"shutdown"});const t=this.room;this.room=null,await t.disconnect(),this.sessionUuid}this.agentAnalyser&&(this.agentAnalyser.disconnect(),this.agentAnalyser=null),this.agentAudioContext&&(this.agentAudioContext.close(),this.agentAudioContext=null),this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null),this.isAudioTrackPublished=!1,this.publishedAudioStream=null,this.publishedAudioTrack=null,this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.frequencyDataBuffer=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}agentAudioSpectrum(){return this.agentAnalyser?this.normaliseSpectrum(this.agentAnalyser):null}normaliseSpectrum(e){const i=e.context.sampleRate/2/e.frequencyBinCount;(!this.frequencyDataBuffer||this.frequencyDataBuffer.length!==e.frequencyBinCount)&&(this.frequencyDataBuffer=new Uint8Array(new ArrayBuffer(e.frequencyBinCount))),e.getByteFrequencyData(this.frequencyDataBuffer);const r=[],s=50,a=5e3,o=8,c=Math.pow(a/s,1/o);for(let l=0;l<o;l++){const u=s*Math.pow(c,l),d=s*Math.pow(c,l+1),h=Math.floor(u/i),f=Math.floor(d/i),m=Math.min(f,this.frequencyDataBuffer.length),p=Math.min(h,m);if(p<m){let v=0;for(let C=p;C<m;C++)v+=this.frequencyDataBuffer[C];const b=v/(m-p)/255;r.push(b)}else r.push(0)}return r}setState(e){this.state;const t=this.state;this.state=e,this.emit("stateChanged",e,t)}static deserialise(e,t,i,r={}){const s=JSON.parse(e),a=new ra(t,s.planId,i,r);return a.state=s.state,a.speakingState=s.speakingState,a.identity=s.identity||null,a.isPaused=s.isPaused||!1,a.sessionUuid=s.sessionUuid||null,a.roomId=s.roomId||null,a.joinToken=s.joinToken||null,a.roomUrl=s.roomUrl||null,a.startedAt=s.startedAt||null,a}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,i=t.createAnalyser();return t.createMediaStreamSource(e).connect(i),i.fftSize=2048,i.smoothingTimeConstant=.6,{analyser:i,context:t}}}class sa extends Pa{constructor(e,t,i={}){super(),this.state="loading",this.error=null,this.identity=null,this.product=null,this.engagement=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=i.api||new Zf({baseUrl:i.apiBaseUrl||ep}),this.sessionFactory=i.sessionFactory||((r,s,a,o)=>new ra(r,s,a,o)),this.captureScreen=i.captureScreen||null}async initialise(e={}){var t,i,r,s,a,o;if(!this.appToken)throw new Error("App token is required");this.setState("loading");try{const c=await this.api.clientInitialise(this.appToken,{identity:e.identity,client_type:this.clientType});if(this.identity=e.identity||null,this.product=((t=c.data)==null?void 0:t.product)||null,this.plans=((i=c.data)==null?void 0:i.onboarding_plans)||[],this.selectedPlan=((r=c.data)==null?void 0:r.selected_plan)||null,this.planIsCompleted=((s=c.data)==null?void 0:s.plan_is_completed)||[],this.showWidget=((a=c.data)==null?void 0:a.show_widget)||!1,this.engagement=((o=c.data)==null?void 0:o.engagement)||null,e.planUuid){let l=null;try{const u=await this.api.getPlanSDK(e.planUuid);if(u.error)throw new Error(`Plan not found: ${u.error}`);u.data&&(l=u.data)}catch(u){try{const d=await this.api.getSessionPlan(e.planUuid);if(d.error)throw new Error(`Session plan not found: ${d.error}`);d.data&&(l=d.data)}catch(d){console.error("[obi] error getting plan via both endpoints",{planErr:u,sessionErr:d})}}l?(this.selectedPlan=l,this.selectedPlanUuid=e.planUuid):console.warn("[obi] plan not found",{planUuid:e.planUuid})}this.identity,this.product,this.plans,this.selectedPlan,this.showWidget}catch(c){throw this.error=c instanceof Error?c:new Error(String(c)),this.setState("error"),c}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,i){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(i).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,i;return this.state,(t=this.session)==null||t.state,(i=this.session)==null||i.speakingState,this.session.captureScreen=this.captureScreen,this.prepareSession(e),this.session.joinRoom({withMicrophone:!0,withStateRecovery:!0}).then(()=>{this.emit("sessionResumed",this.session)}).catch(r=>{console.error("[obi] error joining room",{error:r}),r instanceof Error&&r.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 i,r,s;if((i=this.session)!=null&&i.startedAt&&this.session.startedAt+5*60*1e3<Date.now()){const a=this.plans.findIndex(o=>{var c;return o.uuid===((c=this.selectedPlan)==null?void 0:c.uuid)});a!==-1&&(this.planIsCompleted[a]=!0)}(s=(r=this.session)==null?void 0:r.removeAllListeners)==null||s.call(r),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,engagement:this.engagement,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,i,r={}){const s=JSON.parse(e),a=new sa(t,i,r);return a.state=s.state,a.identity=s.identity||null,a.product=s.product||null,a.engagement=s.engagement||null,a.plans=s.plans||[],a.selectedPlan=s.selectedPlan||null,a.selectedPlanUuid=s.selectedPlanUuid||null,a.showWidget=s.showWidget||!1,s.session&&(a.session=ra.deserialise(s.session,t,i,{api:a.api})),a}setState(e){const t=this.state;this.state=e,this.emit("stateChanged",e,t)}trackEvent(e,t={}){var i,r,s;this.emit("trackEvent",e,{...t,clientType:this.clientType,planId:(i=this.selectedPlan)==null?void 0:i.uuid,productId:(r=this.product)==null?void 0:r.uuid,sessionId:(s=this.session)==null?void 0:s.sessionUuid})}}var aa,J,tp,ei,np,ip,rp,sp,Ic,Oc,Ac,ap,mr={},op=[],g1=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,gr=Array.isArray;function cn(n,e){for(var t in e)n[t]=e[t];return n}function Nc(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function Mc(n,e,t){var i,r,s,a={};for(s in e)s=="key"?i=e[s]:s=="ref"?r=e[s]:a[s]=e[s];if(arguments.length>2&&(a.children=arguments.length>3?aa.call(arguments,2):t),typeof n=="function"&&n.defaultProps!=null)for(s in n.defaultProps)a[s]==null&&(a[s]=n.defaultProps[s]);return oa(n,a,i,r,null)}function oa(n,e,t,i,r){var s={type:n,props:e,key:t,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:r??++tp,__i:-1,__u:0};return r==null&&J.vnode!=null&&J.vnode(s),s}function nt(n){return n.children}function ln(n,e){this.props=n,this.context=e}function Mi(n,e){if(e==null)return n.__?Mi(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"?Mi(n):null}function cp(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 cp(n)}}function Lc(n){(!n.__d&&(n.__d=!0)&&ei.push(n)&&!ca.__r++||np!=J.debounceRendering)&&((np=J.debounceRendering)||ip)(ca)}function ca(){for(var n,e,t,i,r,s,a,o=1;ei.length;)ei.length>o&&ei.sort(rp),n=ei.shift(),o=ei.length,n.__d&&(t=void 0,r=(i=(e=n).__v).__e,s=[],a=[],e.__P&&((t=cn({},i)).__v=i.__v+1,J.vnode&&J.vnode(t),Dc(e.__P,t,i,e.__n,e.__P.namespaceURI,32&i.__u?[r]:null,s,r??Mi(i),!!(32&i.__u),a),t.__v=i.__v,t.__.__k[t.__i]=t,fp(s,t,a),t.__e!=r&&cp(t)));ca.__r=0}function lp(n,e,t,i,r,s,a,o,c,l,u){var d,h,f,m,p,v,b=i&&i.__k||op,C=e.length;for(c=v1(t,e,b,c,C),d=0;d<C;d++)(f=t.__k[d])!=null&&(h=f.__i==-1?mr:b[f.__i]||mr,f.__i=d,v=Dc(n,f,h,r,s,a,o,c,l,u),m=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&Uc(h.ref,null,f),u.push(f.ref,f.__c||m,f)),p==null&&m!=null&&(p=m),4&f.__u||h.__k===f.__k?c=up(f,c,n):typeof f.type=="function"&&v!==void 0?c=v:m&&(c=m.nextSibling),f.__u&=-7);return t.__e=p,c}function v1(n,e,t,i,r){var s,a,o,c,l,u=t.length,d=u,h=0;for(n.__k=new Array(r),s=0;s<r;s++)(a=e[s])!=null&&typeof a!="boolean"&&typeof a!="function"?(c=s+h,(a=n.__k[s]=typeof a=="string"||typeof a=="number"||typeof a=="bigint"||a.constructor==String?oa(null,a,null,null,null):gr(a)?oa(nt,{children:a},null,null,null):a.constructor==null&&a.__b>0?oa(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):a).__=n,a.__b=n.__b+1,o=null,(l=a.__i=b1(a,t,c,d))!=-1&&(d--,(o=t[l])&&(o.__u|=2)),o==null||o.__v==null?(l==-1&&(r>u?h--:r<u&&h++),typeof a.type!="function"&&(a.__u|=4)):l!=c&&(l==c-1?h--:l==c+1?h++:(l>c?h--:h++,a.__u|=4))):n.__k[s]=null;if(d)for(s=0;s<u;s++)(o=t[s])!=null&&!(2&o.__u)&&(o.__e==i&&(i=Mi(o)),mp(o,o));return i}function up(n,e,t){var i,r;if(typeof n.type=="function"){for(i=n.__k,r=0;i&&r<i.length;r++)i[r]&&(i[r].__=n,e=up(i[r],e,t));return e}n.__e!=e&&(e&&n.type&&!t.contains(e)&&(e=Mi(n)),t.insertBefore(n.__e,e||null),e=n.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function la(n,e){return e=e||[],n==null||typeof n=="boolean"||(gr(n)?n.some(function(t){la(t,e)}):e.push(n)),e}function b1(n,e,t,i){var r,s,a=n.key,o=n.type,c=e[t];if(c===null&&n.key==null||c&&a==c.key&&o==c.type&&!(2&c.__u))return t;if(i>(c!=null&&!(2&c.__u)?1:0))for(r=t-1,s=t+1;r>=0||s<e.length;){if(r>=0){if((c=e[r])&&!(2&c.__u)&&a==c.key&&o==c.type)return r;r--}if(s<e.length){if((c=e[s])&&!(2&c.__u)&&a==c.key&&o==c.type)return s;s++}}return-1}function dp(n,e,t){e[0]=="-"?n.setProperty(e,t??""):n[e]=t==null?"":typeof t!="number"||g1.test(e)?t:t+"px"}function ua(n,e,t,i,r){var s;e:if(e=="style")if(typeof t=="string")n.style.cssText=t;else{if(typeof i=="string"&&(n.style.cssText=i=""),i)for(e in i)t&&e in t||dp(n.style,e,"");if(t)for(e in t)i&&t[e]==i[e]||dp(n.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(sp,"$1")),e=e.toLowerCase()in n||e=="onFocusOut"||e=="onFocusIn"?e.toLowerCase().slice(2):e.slice(2),n.l||(n.l={}),n.l[e+s]=t,t?i?t.u=i.u:(t.u=Ic,n.addEventListener(e,s?Ac:Oc,s)):n.removeEventListener(e,s?Ac:Oc,s);else{if(r=="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 hp(n){return function(e){if(this.l){var t=this.l[e.type+n];if(e.t==null)e.t=Ic++;else if(e.t<t.u)return;return t(J.event?J.event(e):e)}}}function Dc(n,e,t,i,r,s,a,o,c,l){var u,d,h,f,m,p,v,b,C,x,k,S,w,E,A,O,B,L=e.type;if(e.constructor!=null)return null;128&t.__u&&(c=!!(32&t.__u),s=[o=e.__e=t.__e]),(u=J.__b)&&u(e);e:if(typeof L=="function")try{if(b=e.props,C="prototype"in L&&L.prototype.render,x=(u=L.contextType)&&i[u.__c],k=u?x?x.props.value:u.__:i,t.__c?v=(d=e.__c=t.__c).__=d.__E:(C?e.__c=d=new L(b,k):(e.__c=d=new ln(b,k),d.constructor=L,d.render=T1),x&&x.sub(d),d.props=b,d.state||(d.state={}),d.context=k,d.__n=i,h=d.__d=!0,d.__h=[],d._sb=[]),C&&d.__s==null&&(d.__s=d.state),C&&L.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=cn({},d.__s)),cn(d.__s,L.getDerivedStateFromProps(b,d.__s))),f=d.props,m=d.state,d.__v=e,h)C&&L.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),C&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(C&&L.getDerivedStateFromProps==null&&b!==f&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(b,k),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(b,d.__s,k)===!1||e.__v==t.__v){for(e.__v!=t.__v&&(d.props=b,d.state=d.__s,d.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.some(function(R){R&&(R.__=e)}),S=0;S<d._sb.length;S++)d.__h.push(d._sb[S]);d._sb=[],d.__h.length&&a.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(b,d.__s,k),C&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(f,m,p)})}if(d.context=k,d.props=b,d.__P=n,d.__e=!1,w=J.__r,E=0,C){for(d.state=d.__s,d.__d=!1,w&&w(e),u=d.render(d.props,d.state,d.context),A=0;A<d._sb.length;A++)d.__h.push(d._sb[A]);d._sb=[]}else do d.__d=!1,w&&w(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++E<25);d.state=d.__s,d.getChildContext!=null&&(i=cn(cn({},i),d.getChildContext())),C&&!h&&d.getSnapshotBeforeUpdate!=null&&(p=d.getSnapshotBeforeUpdate(f,m)),O=u,u!=null&&u.type===nt&&u.key==null&&(O=pp(u.props.children)),o=lp(n,gr(O)?O:[O],e,t,i,r,s,a,o,c,l),d.base=e.__e,e.__u&=-161,d.__h.length&&a.push(d),v&&(d.__E=d.__=null)}catch(R){if(e.__v=null,c||s!=null)if(R.then){for(e.__u|=c?160:128;o&&o.nodeType==8&&o.nextSibling;)o=o.nextSibling;s[s.indexOf(o)]=null,e.__e=o}else for(B=s.length;B--;)Nc(s[B]);else e.__e=t.__e,e.__k=t.__k;J.__e(R,e,t)}else s==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):o=e.__e=y1(t.__e,e,t,i,r,s,a,c,l);return(u=J.diffed)&&u(e),128&e.__u?void 0:o}function fp(n,e,t){for(var i=0;i<t.length;i++)Uc(t[i],t[++i],t[++i]);J.__c&&J.__c(e,n),n.some(function(r){try{n=r.__h,r.__h=[],n.some(function(s){s.call(r)})}catch(s){J.__e(s,r.__v)}})}function pp(n){return typeof n!="object"||n==null||n.__b&&n.__b>0?n:gr(n)?n.map(pp):cn({},n)}function y1(n,e,t,i,r,s,a,o,c){var l,u,d,h,f,m,p,v=t.props,b=e.props,C=e.type;if(C=="svg"?r="http://www.w3.org/2000/svg":C=="math"?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),s!=null){for(l=0;l<s.length;l++)if((f=s[l])&&"setAttribute"in f==!!C&&(C?f.localName==C:f.nodeType==3)){n=f,s[l]=null;break}}if(n==null){if(C==null)return document.createTextNode(b);n=document.createElementNS(r,C,b.is&&b),o&&(J.__m&&J.__m(e,s),o=!1),s=null}if(C==null)v===b||o&&n.data==b||(n.data=b);else{if(s=s&&aa.call(n.childNodes),v=t.props||mr,!o&&s!=null)for(v={},l=0;l<n.attributes.length;l++)v[(f=n.attributes[l]).name]=f.value;for(l in v)if(f=v[l],l!="children"){if(l=="dangerouslySetInnerHTML")d=f;else if(!(l in b)){if(l=="value"&&"defaultValue"in b||l=="checked"&&"defaultChecked"in b)continue;ua(n,l,null,f,r)}}for(l in b)f=b[l],l=="children"?h=f:l=="dangerouslySetInnerHTML"?u=f:l=="value"?m=f:l=="checked"?p=f:o&&typeof f!="function"||v[l]===f||ua(n,l,f,v[l],r);if(u)o||d&&(u.__html==d.__html||u.__html==n.innerHTML)||(n.innerHTML=u.__html),e.__k=[];else if(d&&(n.innerHTML=""),lp(e.type=="template"?n.content:n,gr(h)?h:[h],e,t,i,C=="foreignObject"?"http://www.w3.org/1999/xhtml":r,s,a,s?s[0]:t.__k&&Mi(t,0),o,c),s!=null)for(l=s.length;l--;)Nc(s[l]);o||(l="value",C=="progress"&&m==null?n.removeAttribute("value"):m!=null&&(m!==n[l]||C=="progress"&&!m||C=="option"&&m!=v[l])&&ua(n,l,m,v[l],r),l="checked",p!=null&&p!=n[l]&&ua(n,l,p,v[l],r))}return n}function Uc(n,e,t){try{if(typeof n=="function"){var i=typeof n.__u=="function";i&&n.__u(),i&&e==null||(n.__u=n(e))}else n.current=e}catch(r){J.__e(r,t)}}function mp(n,e,t){var i,r;if(J.unmount&&J.unmount(n),(i=n.ref)&&(i.current&&i.current!=n.__e||Uc(i,null,e)),(i=n.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(s){J.__e(s,e)}i.base=i.__P=null}if(i=n.__k)for(r=0;r<i.length;r++)i[r]&&mp(i[r],e,t||typeof n.type!="function");t||Nc(n.__e),n.__c=n.__=n.__e=void 0}function T1(n,e,t){return this.constructor(n,t)}function k1(n,e,t){var i,r,s,a;e==document&&(e=document.documentElement),J.__&&J.__(n,e),r=(i=typeof t=="function")?null:t&&t.__k||e.__k,s=[],a=[],Dc(e,n=(!i&&t||e).__k=Mc(nt,null,[n]),r||mr,mr,e.namespaceURI,!i&&t?[t]:r?null:e.firstChild?aa.call(e.childNodes):null,s,!i&&t?t:r?r.__e:e.firstChild,i,a),fp(s,n,a)}function S1(n){function e(t){var i,r;return this.getChildContext||(i=new Set,(r={})[e.__c]=this,this.getChildContext=function(){return r},this.componentWillUnmount=function(){i=null},this.shouldComponentUpdate=function(s){this.props.value!=s.value&&i.forEach(function(a){a.__e=!0,Lc(a)})},this.sub=function(s){i.add(s);var a=s.componentWillUnmount;s.componentWillUnmount=function(){i&&i.delete(s),a&&a.call(s)}}),t.children}return e.__c="__cC"+ap++,e.__=n,e.Provider=e.__l=(e.Consumer=function(t,i){return t.children(i)}).contextType=e,e}aa=op.slice,J={__e:function(n,e,t,i){for(var r,s,a;e=e.__;)if((r=e.__c)&&!r.__)try{if((s=r.constructor)&&s.getDerivedStateFromError!=null&&(r.setState(s.getDerivedStateFromError(n)),a=r.__d),r.componentDidCatch!=null&&(r.componentDidCatch(n,i||{}),a=r.__d),a)return r.__E=r}catch(o){n=o}throw n}},tp=0,ln.prototype.setState=function(n,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=cn({},this.state),typeof n=="function"&&(n=n(cn({},t),this.props)),n&&cn(t,n),n!=null&&this.__v&&(e&&this._sb.push(e),Lc(this))},ln.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),Lc(this))},ln.prototype.render=nt,ei=[],ip=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,rp=function(n,e){return n.__v.__b-e.__v.__b},ca.__r=0,sp=/(PointerCapture)$|Capture$/i,Ic=0,Oc=hp(!1),Ac=hp(!0),ap=0;var C1=0;function g(n,e,t,i,r,s){e||(e={});var a,o,c=e;if("ref"in c)for(o in c={},e)o=="ref"?a=e[o]:c[o]=e[o];var l={type:n,props:c,key:t,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--C1,__i:-1,__u:0,__source:r,__self:s};if(typeof n=="function"&&(a=n.defaultProps))for(o in a)c[o]===void 0&&(c[o]=a[o]);return J.vnode&&J.vnode(l),l}var ti,xe,Bc,gp,vr=0,vp=[],Me=J,bp=Me.__b,yp=Me.__r,Tp=Me.diffed,kp=Me.__c,Sp=Me.unmount,Cp=Me.__;function br(n,e){Me.__h&&Me.__h(xe,n,vr||e),vr=0;var t=xe.__H||(xe.__H={__:[],__h:[]});return n>=t.__.length&&t.__.push({}),t.__[n]}function Y(n){return vr=1,w1(_p,n)}function w1(n,e,t){var i=br(ti++,2);if(i.t=n,!i.__c&&(i.__=[t?t(e):_p(void 0,e),function(o){var c=i.__N?i.__N[0]:i.__[0],l=i.t(c,o);c!==l&&(i.__N=[l,i.__[1]],i.__c.setState({}))}],i.__c=xe,!xe.__f)){var r=function(o,c,l){if(!i.__c.__H)return!0;var u=i.__c.__H.__.filter(function(h){return!!h.__c});if(u.every(function(h){return!h.__N}))return!s||s.call(this,o,c,l);var d=i.__c.props!==o;return u.forEach(function(h){if(h.__N){var f=h.__[0];h.__=h.__N,h.__N=void 0,f!==h.__[0]&&(d=!0)}}),s&&s.call(this,o,c,l)||d};xe.__f=!0;var s=xe.shouldComponentUpdate,a=xe.componentWillUpdate;xe.componentWillUpdate=function(o,c,l){if(this.__e){var u=s;s=void 0,r(o,c,l),s=u}a&&a.call(this,o,c,l)},xe.shouldComponentUpdate=r}return i.__N||i.__}function Qe(n,e){var t=br(ti++,3);!Me.__s&&jc(t.__H,e)&&(t.__=n,t.u=e,xe.__H.__h.push(t))}function da(n,e){var t=br(ti++,4);!Me.__s&&jc(t.__H,e)&&(t.__=n,t.u=e,xe.__h.push(t))}function Be(n){return vr=5,ha(function(){return{current:n}},[])}function ha(n,e){var t=br(ti++,7);return jc(t.__H,e)&&(t.__=n(),t.__H=e,t.__h=n),t.__}function x1(n,e){return vr=8,ha(function(){return n},e)}function wp(n){var e=xe.context[n.__c],t=br(ti++,9);return t.c=n,e?(t.__==null&&(t.__=!0,e.sub(xe)),e.props.value):n.__}function _1(){for(var n;n=vp.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(fa),n.__H.__h.forEach(Fc),n.__H.__h=[]}catch(e){n.__H.__h=[],Me.__e(e,n.__v)}}Me.__b=function(n){xe=null,bp&&bp(n)},Me.__=function(n,e){n&&e.__k&&e.__k.__m&&(n.__m=e.__k.__m),Cp&&Cp(n,e)},Me.__r=function(n){yp&&yp(n),ti=0;var e=(xe=n.__c).__H;e&&(Bc===xe?(e.__h=[],xe.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.forEach(fa),e.__h.forEach(Fc),e.__h=[],ti=0)),Bc=xe},Me.diffed=function(n){Tp&&Tp(n);var e=n.__c;e&&e.__H&&(e.__H.__h.length&&(vp.push(e)!==1&&gp===Me.requestAnimationFrame||((gp=Me.requestAnimationFrame)||E1)(_1)),e.__H.__.forEach(function(t){t.u&&(t.__H=t.u),t.u=void 0})),Bc=xe=null},Me.__c=function(n,e){e.some(function(t){try{t.__h.forEach(fa),t.__h=t.__h.filter(function(i){return!i.__||Fc(i)})}catch(i){e.some(function(r){r.__h&&(r.__h=[])}),e=[],Me.__e(i,t.__v)}}),kp&&kp(n,e)},Me.unmount=function(n){Sp&&Sp(n);var e,t=n.__c;t&&t.__H&&(t.__H.__.forEach(function(i){try{fa(i)}catch(r){e=r}}),t.__H=void 0,e&&Me.__e(e,t.__v))};var xp=typeof requestAnimationFrame=="function";function E1(n){var e,t=function(){clearTimeout(i),xp&&cancelAnimationFrame(e),setTimeout(n)},i=setTimeout(t,100);xp&&(e=requestAnimationFrame(t))}function fa(n){var e=xe,t=n.__c;typeof t=="function"&&(n.__c=void 0,t()),xe=e}function Fc(n){var e=xe;n.__c=n.__(),xe=e}function jc(n,e){return!n||n.length!==e.length||e.some(function(t,i){return t!==n[i]})}function _p(n,e){return typeof e=="function"?e(n):e}function R1({size:n=24,color:e="#000"}){return g("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:[g("path",{d:"M18 6 6 18"}),g("path",{d:"m6 6 12 12"})]})}function Ep({onClose:n}){return g("button",{class:"obi-button obi-close-button",onClick:n,"aria-label":"Close",type:"button",children:g(R1,{})})}function Rp({open:n=!1,children:e,onClose:t,size:i="medium",preventOutsideClick:r=!1}){const s=Be(null),a=Be(null);Qe(()=>{const u=s.current;u&&(n&&!u.open?u.showModal():!n&&u.open&&(a.current="programmatic",u.close()))},[n]);const o=u=>{const d=s.current;u.target===d&&!r&&(a.current="user-initiated",d==null||d.close())},c=u=>{u.preventDefault(),a.current||(a.current="user-initiated");const d=a.current;a.current=null,t==null||t(d)},l=()=>{var u;a.current="user-initiated",(u=s.current)==null||u.close()};return Qe(()=>{const u=s.current;if(u)return u.addEventListener("click",o),u.addEventListener("close",c),()=>{u.removeEventListener("click",o),u.removeEventListener("close",c)}},[t]),g("dialog",{ref:s,className:`modal-${i}`,children:[g(Ep,{onClose:l}),g("div",{class:"modal-content",children:n?typeof e=="function"?e():e:null})]})}function Vc({className:n="",isActive:e=!1,speakingStatus:t,onClick:i,onMouseEnter:r,onMouseLeave:s,children:a}){let o=`obi-pill container ${e&&"active"}`;return t==="user-speaking"&&(o+=" user-speaking"),t==="busy"&&(o+=" busy"),g("div",{className:o,onMouseEnter:r,onMouseLeave:s,children:g("div",{className:`obi-pill pill ${n}`,onClick:i,children:a})})}function P1({className:n="",active:e,speakingStatus:t,onClick:i,onMouseEnter:r,onMouseLeave:s,children:a,...o}){const c=`obi-pill2 container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return g("div",{className:c,...o,children:g("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:s,children:a})})}function I1({className:n="",active:e,speakingStatus:t,onClick:i,onMouseEnter:r,onMouseLeave:s,children:a,...o}){const c=`obi-pill-up container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return g("div",{className:c,...o,children:g("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:s,children:a})})}const Pp=8,pa=8,O1=100,A1=.7,Li=3;function Ip({getBands:n,color:e="white"}){const t=Be(null);return Qe(()=>{if(!n)return;let i=0,r;const s=a=>{try{if(a-i>=O1){const o=n();if(t.current){const c=t.current.querySelectorAll(".bar"),l=o&&o.length>0?o.slice(0,pa).map(u=>{const d=Math.abs(u);return Math.min(d/A1*Pp,Pp)||Li}):Array(pa).fill(Li);for(;l.length<pa;)l.push(Li);l.forEach((u,d)=>{if(u<Li&&(u=Li),c[d]){const h=u*2;c[d].style.height=`${h}px`,c[d].style.display=u>0?"block":"none"}})}i=a}r=requestAnimationFrame(s)}catch(o){console.warn("Error updating equaliser:",o),r=requestAnimationFrame(s)}};return r=requestAnimationFrame(s),()=>{cancelAnimationFrame(r)}},[n]),g("div",{className:"obi-equaliser",ref:t,children:Array.from({length:pa},(i,r)=>g("div",{className:"column",children:g("div",{className:"bar",style:{height:`${Li}px`,backgroundColor:e,display:"block"}})},r))})}function N1(n){const{spectrum:e}=n;return g(Vc,{isActive:!0,children:g(Ip,{getBands:e})})}function Gc(n){const{children:e,className:t="",...i}=n;return g("div",{className:`${t} obi-panel`,...i,children:e})}function ni({type:n,size:e=24}){return g("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:M1(n)})}function M1(n){switch(n){case"pause":return g(nt,{children:[g("rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}),g("rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"})]});case"play":return g(nt,{children:g("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 g(nt,{children:[g("path",{d:"M18 6 6 18"}),g("path",{d:"m6 6 12 12"})]});case"message":return g(nt,{children:g("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 g(nt,{children:[g("path",{d:"m14 10 7-7"}),g("path",{d:"M20 10h-6V4"}),g("path",{d:"m3 21 7-7"}),g("path",{d:"M4 14h6v6"})]});case"voice":return g(nt,{children:[g("path",{d:"M2 10v3"}),g("path",{d:"M6 6v11"}),g("path",{d:"M10 3v18"}),g("path",{d:"M14 8v7"}),g("path",{d:"M18 5v13"}),g("path",{d:"M22 10v3"})]});case"open":return g(nt,{children:[g("path",{d:"M12 7v14"}),g("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 zc=S1(null);function L1({children:n}){const e=wp(zc);if(!e)throw new Error("PopoutTarget must be used within a Popout component");const{controlledOpen:t,isOpen:i,setIsOpen:r,setAnimating:s,targetRef:a,trigger:o,onChange:c,delayMs:l}=e,u=Be(null),d=Op(a,s),[h,f]=Y(!1);Qe(()=>{t!==void 0&&t!==h&&(t?p():v()),f(t)},[t]),Qe(()=>()=>{u.current&&clearTimeout(u.current)},[]);function m(){u.current&&(clearTimeout(u.current),u.current=null)}function p(){m(),l>0?u.current=setTimeout(()=>{c==null||c(!0),r(!0),u.current=null},l):(c==null||c(!0),r(!0))}function v(){m(),c==null||c(!1),r(!1)}const b=()=>{o==="click"&&(i?v():p())};function C(){o==="hover"&&p()}function x(){o==="hover"&&v()}return g("div",{ref:d,class:"target",onClick:b,onMouseEnter:C,onMouseLeave:x,children:n})}function D1({children:n}){const e=wp(zc);if(!e)throw new Error("PopoutContent must be used within a Popout component");const{isOpen:t,animating:i,setAnimating:r,targetRef:s,contentRef:a}=e,o=Op(a,r);return da(()=>{if(t&&!i&&s.current&&a.current){const c=a.current;if(!c)return;const l=s.current;if(!l)return;const u=c.getBoundingClientRect(),d=l.getBoundingClientRect(),h=d.right-d.left;c.style.top=`${u.top-u.bottom-(8+e.offset)}px`,c.style.left=`${-(u.right-u.left-h)/2}px`}},[t,i]),t?g("div",{ref:o,class:"content",style:{opacity:i?0:1},children:n}):null}function mt({trigger:n="click",open:e,onChange:t,children:i,delayMs:r=0,offset:s=0,className:a=""}){const[o,c]=Y(!1),[l,u]=Y(!1),d=Be(null),h=Be(null),f={controlledOpen:e,isOpen:o,setIsOpen:c,animating:l,setAnimating:u,targetRef:d,contentRef:h,trigger:n,onChange:t,delayMs:r,offset:s};return g(zc.Provider,{value:f,children:g("div",{class:`obi-popout ${a}`,children:i})})}mt.Target=L1,mt.Content=D1;function Op(n,e){const t=Be(null),i=Be(null),r=Be(!0),s=x1(a=>{if(n.current=a,!a){i.current&&(i.current.disconnect(),i.current=null),r.current=!0;return}function o(){if(r.current){r.current=!1;return}t.current?clearTimeout(t.current):e(!0),t.current=setTimeout(()=>{e(!1),t.current=null},200)}i.current=new ResizeObserver(o),i.current.observe(a,{box:"border-box"})},[]);return Qe(()=>()=>{i.current&&(i.current.disconnect(),i.current=null)},[]),s}function Ft({className:n,onClick:e,type:t,disabled:i,title:r}){const s={cancel:g(ni,{type:"close",size:16}),pause:g(ni,{type:"pause",size:16}),play:g(ni,{type:"play",size:16}),message:g(ni,{type:"message",size:16}),minimize:g(ni,{type:"minimize",size:16}),voice:g(ni,{type:"voice",size:16}),open:g(ni,{type:"open",size:16})}[t],a={cancel:"",pause:"",play:"",message:"",minimize:"",voice:"",open:""}[t],o=g("button",{class:`obi-button obi-round-button ${a} ${n}`,onClick:i?void 0:e,disabled:i,children:s});return r?g(mt,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[g(mt.Target,{children:o}),g(mt.Content,{children:g("div",{className:"obi-round-button-title",children:r})})]}):o}function un({className:n,children:e,onClick:t}){return t?g("button",{class:`obi-button obi-message ${n} clickable`,onClick:t,children:e}):g("div",{class:`obi-message ${n}`,children:e})}const U1=8;function B1({color:n="white"}){return g("div",{className:"obi-loading-dots",children:Array.from({length:U1},(e,t)=>g("div",{className:"column",children:[g("div",{className:"bar",style:{backgroundColor:n,animationDelay:`${t*.15}s`}}),g("div",{className:"dot",style:{backgroundColor:n}})]},t))})}function F1({onContinue:n,onWrapUp:e}){return g(Gc,{className:"obi-exit-survey",children:g(V1,{onContinue:n,onWrapUp:()=>{e()}})})}function j1({onOtherSelect:n,onReasonSelect:e,onClose:t}){const[i,r]=Y("reason"),s=a=>{a==="other"?(n(),r("other-reason")):e(a)};return g(Gc,{className:`obi-exit-survey ${i==="reason"?"obi-exit-survey-reason":""}`,children:i==="reason"?g(G1,{onReasonSelect:s}):g(z1,{onReasonSelect:s,onClose:t})})}function V1({onContinue:n,onWrapUp:e}){return g("div",{className:"obi-exit-survey-container",children:[g("h2",{className:"obi-exit-survey-title",children:"Wrapping up early?"}),g("div",{className:"obi-exit-survey-options",children:[g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-continue",onClick:n,type:"button",children:"No, let's continue"}),g("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 G1({onReasonSelect:n}){return g("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[g("div",{className:"obi-exit-survey-header",children:g("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Quick feedback?"})}),g("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("do-later"),type:"button",children:"Will do later"}),g("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"}),g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("prefer-written"),type:"button",children:"Prefer written instructions"}),g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("technical-issues"),type:"button",children:"Experienced technical issues"})]})]})}function z1({onReasonSelect:n,onClose:e}){const[t,i]=Y("");return g("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[g("div",{className:"obi-exit-survey-header",children:[g(Ep,{onClose:e}),g("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Tell us more"})]}),g("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[g("textarea",{className:"obi-exit-survey-button obi-exit-survey-reason-button",placeholder:"What's on your mind?",value:t,onChange:r=>i(r.target.value)}),g("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 H1(n,e){for(var t in e)n[t]=e[t];return n}function Ap(n,e){for(var t in n)if(t!=="__source"&&!(t in e))return!0;for(var i in e)if(i!=="__source"&&n[i]!==e[i])return!0;return!1}function Np(n,e){this.props=n,this.context=e}(Np.prototype=new ln).isPureReactComponent=!0,Np.prototype.shouldComponentUpdate=function(n,e){return Ap(this.props,n)||Ap(this.state,e)};var Mp=J.__b;J.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),Mp&&Mp(n)};var W1=J.__e;J.__e=function(n,e,t,i){if(n.then){for(var r,s=e;s=s.__;)if((r=s.__c)&&r.__c)return e.__e==null&&(e.__e=t.__e,e.__k=t.__k),r.__c(n,e)}W1(n,e,t,i)};var Lp=J.unmount;function Dp(n,e,t){return n&&(n.__c&&n.__c.__H&&(n.__c.__H.__.forEach(function(i){typeof i.__c=="function"&&i.__c()}),n.__c.__H=null),(n=H1({},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(i){return Dp(i,e,t)})),n}function Up(n,e,t){return n&&t&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(i){return Up(i,e,t)}),n.__c&&n.__c.__P===e&&(n.__e&&t.appendChild(n.__e),n.__c.__e=!0,n.__c.__P=t)),n}function Hc(){this.__u=0,this.o=null,this.__b=null}function Bp(n){var e=n.__.__c;return e&&e.__a&&e.__a(n)}function ma(){this.i=null,this.l=null}J.unmount=function(n){var e=n.__c;e&&e.__R&&e.__R(),e&&32&n.__u&&(n.type=null),Lp&&Lp(n)},(Hc.prototype=new ln).__c=function(n,e){var t=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(t);var r=Bp(i.__v),s=!1,a=function(){s||(s=!0,t.__R=null,r?r(o):o())};t.__R=a;var o=function(){if(!--i.__u){if(i.state.__a){var c=i.state.__a;i.__v.__k[0]=Up(c,c.__c.__P,c.__c.__O)}var l;for(i.setState({__a:i.__b=null});l=i.o.pop();)l.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),n.then(a,a)},Hc.prototype.componentWillUnmount=function(){this.o=[]},Hc.prototype.render=function(n,e){if(this.__b){if(this.__v.__k){var t=document.createElement("div"),i=this.__v.__k[0].__c;this.__v.__k[0]=Dp(this.__b,t,i.__O=i.__P)}this.__b=null}var r=e.__a&&Mc(nt,null,n.fallback);return r&&(r.__u&=-33),[Mc(nt,null,e.__a?null:n.children),r]};var Fp=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]}};(ma.prototype=new ln).__a=function(n){var e=this,t=Bp(e.__v),i=e.l.get(n);return i[0]++,function(r){var s=function(){e.props.revealOrder?(i.push(r),Fp(e,n,i)):r()};t?t(s):s()}},ma.prototype.render=function(n){this.i=null,this.l=new Map;var e=la(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},ma.prototype.componentDidUpdate=ma.prototype.componentDidMount=function(){var n=this;this.l.forEach(function(e,t){Fp(n,t,e)})};var q1=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,K1=/^(?: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]/,$1=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Y1=/[A-Z0-9]/g,X1=typeof document<"u",J1=function(n){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(n)};ln.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(n){Object.defineProperty(ln.prototype,n,{configurable:!0,get:function(){return this["UNSAFE_"+n]},set:function(e){Object.defineProperty(this,n,{configurable:!0,writable:!0,value:e})}})});var jp=J.event;function Q1(){}function Z1(){return this.cancelBubble}function ew(){return this.defaultPrevented}J.event=function(n){return jp&&(n=jp(n)),n.persist=Q1,n.isPropagationStopped=Z1,n.isDefaultPrevented=ew,n.nativeEvent=n};var tw={enumerable:!1,configurable:!0,get:function(){return this.class}},Vp=J.vnode;J.vnode=function(n){typeof n.type=="string"&&function(e){var t=e.props,i=e.type,r={},s=i.indexOf("-")===-1;for(var a in t){var o=t[a];if(!(a==="value"&&"defaultValue"in t&&o==null||X1&&a==="children"&&i==="noscript"||a==="class"||a==="className")){var c=a.toLowerCase();a==="defaultValue"&&"value"in t&&t.value==null?a="value":a==="download"&&o===!0?o="":c==="translate"&&o==="no"?o=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?a="ondblclick":c!=="onchange"||i!=="input"&&i!=="textarea"||J1(t.type)?c==="onfocus"?a="onfocusin":c==="onblur"?a="onfocusout":$1.test(a)&&(a=c):c=a="oninput":s&&K1.test(a)?a=a.replace(Y1,"-$&").toLowerCase():o===null&&(o=void 0),c==="oninput"&&r[a=c]&&(a="oninputCapture"),r[a]=o}}i=="select"&&r.multiple&&Array.isArray(r.value)&&(r.value=la(t.children).forEach(function(l){l.props.selected=r.value.indexOf(l.props.value)!=-1})),i=="select"&&r.defaultValue!=null&&(r.value=la(t.children).forEach(function(l){l.props.selected=r.multiple?r.defaultValue.indexOf(l.props.value)!=-1:r.defaultValue==l.props.value})),t.class&&!t.className?(r.class=t.class,Object.defineProperty(r,"className",tw)):(t.className&&!t.class||t.class&&t.className)&&(r.class=r.className=t.className),e.props=r}(n),n.$$typeof=q1,Vp&&Vp(n)};var Gp=J.__r;J.__r=function(n){Gp&&Gp(n),n.__c};var zp=J.diffed;J.diffed=function(n){zp&&zp(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 nw(n){const{placeholder:e="Type your message...",value:t,defaultValue:i,onChange:r,onSend:s,onCancel:a,onExpand:o,isLoading:c=!1,disabled:l=!1,maxLength:u=500,children:d}=n,[h,f]=Y(t||i||""),[m,p]=Y((t||i||"").length>24),v=Be(null);da(()=>{m&&(o==null||o(!0))},[]);const b=t!==void 0?t:h,C=S=>{const w=S.currentTarget.value;t===void 0&&f(w),r==null||r(w)},x=S=>{S.key==="Escape"&&(f(t||i||""),p(!1),a==null||a()),S.key==="Enter"&&!S.shiftKey&&b.trim()&&(S.preventDefault(),f(t||i||""),p(!1),k()),(b||"").length>=24&&!m&&(p(!0),o==null||o(!0))};Qe(()=>{v.current&&v.current.focus()},[v.current]);const k=()=>{!b.trim()||c||l||(s==null||s(b.trim()),t===void 0&&f(""))};return g("div",{className:`obi-message-input ${m?"expanded":""}`,children:[g("div",{className:"container",children:g("textarea",{ref:v,className:"field",placeholder:e,value:b,onInput:C,onKeyDown:x,disabled:l||c,maxLength:u,rows:1})}),g("div",{className:"button-container",children:[m&&g("div",{children:d}),g("button",{className:"obi-button send",onClick:k,disabled:!b.trim()||c||l,type:"button",children:g("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:g("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 iw(n){const{currentStep:e,totalSteps:t,stepNames:i,className:r,onStepClick:s}=n,[a,o]=Y(null),c=Array.from({length:t},(d,h)=>({isCompleted:h<e,isFuture:h>=e,stepNumber:h+1})),l=i[e-1]&&i[e-1].trim().length>0?i[e-1]:`Step ${e}`,u=(()=>{if(a!==null){const d=i[a]&&i[a].trim().length>0?i[a]:`Step ${a+1}`;return`${a+1}/${t} \u2022 ${d}`}return`${e}/${t} \u2022 ${l}`})();return g("div",{class:`obi-course-progress ${r||""}`,children:[g("div",{class:"obi-course-progress-steps",children:c.map((d,h)=>{const f=i[h]&&i[h].trim().length>0?i[h]:`Step ${h+1}`,m=d.isCompleted?"completed":"future";function p(){s&&s(h,f)}function v(b){s&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),p())}return g("div",{class:"obi-course-progress-container","data-testid":`course-progress-step-${h}`,onMouseEnter:()=>o(h),onMouseLeave:()=>o(null),onClick:s?p:void 0,onKeyDown:s?v:void 0,role:s?"button":void 0,tabIndex:s?0:void 0,children:g("div",{class:`obi-course-progress-step ${m}`,"aria-label":f})},h)})}),g("div",{class:"obi-course-progress-description",children:u})]})}function Hp({className:n="",size:e=64}){return g("svg",{width:e,height:e,viewBox:"0 0 256 256",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:n,children:g("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 rw(n){const{disabled:e,inPlan:t,isPaused:i}=n,[r,s]=Y(null),[a,o]=Y(n.isActive??n.defaultIsActive??!1),[c,l]=Y(!1),[u,d]=Y(n.cancelling??!1),[h,f]=Y(n.messaging??!1),[m,p]=Y(!1),[v,b]=Y(h),[C,x]=Y(!1);function k(){o(!0),l(!1),x(!0)}function S(){}function w(){r&&(clearTimeout(r),s(null))}function E(){s(setTimeout(()=>{o(n.defaultIsActive??!1),x(!1)},400))}function A(ne){var je;p(!1),(je=n.onMessage)==null||je.call(n,ne)}function O(){var ne;f(!1),p(!1),o(!1),l(!0),(ne=n.onMinimize)==null||ne.call(n)}function B(){var ne;f(!1),d(!0),p(!1),(ne=n.onCancelClick)==null||ne.call(n)}function L(){var ne;t||((ne=n.onOpen)==null||ne.call(n))}function R(ne){var je,We,xt,hn,_t,Jt;switch(ne){case"need-help":(je=n.onMessage)==null||je.call(n,"I'm struggling, can you look at my screen and help me out."),(We=n.onOneClickAction)==null||We.call(n,"need-help");break;case"continue":(xt=n.onMessage)==null||xt.call(n,"Okay, let's continue."),(hn=n.onOneClickAction)==null||hn.call(n,"continue");break;case"say-again":(_t=n.onMessage)==null||_t.call(n,"Please say that again."),(Jt=n.onOneClickAction)==null||Jt.call(n,"say-again");break}}function H(ne){var je,We;n.messaging===void 0?((je=n.onMessagingChange)==null||je.call(n,ne),f(ne)):((We=n.onMessagingChange)==null||We.call(n,!n.messaging),f(!n.messaging)),ne||p(!1)}const Q=n.isActive??((a||t)&&!c&&!e),X=Q&&t,K=Q&&t&&!m,ye=n.speakingStatus==="user-speaking",Te=n.speakingStatus==="thinking",W=n.speakingStatus==="busy",de=Q&&!t&&!u&&C,te=Q&&t&&i&&!ye&&!u,ge=Q&&t&&!te&&!ye&&h!==v&&!u,oe=Q&&t&&i&&ye&&!u,Fe=Q&&t&&!i&&ye&&!u,$=Q&&t&&!i&&W&&!u,ke=n.messaging!==void 0?n.messaging:h,Le=ke&&ye,gt=de||te||oe||Fe||ge||u,bt=400,Fi=!!n.courseProgress&&!c,ai=de?5:10;return da(()=>{b(h)},[ye]),!t&&!u?g(sw,{...n}):!t&&u?g(aw,{onOtherSelect:()=>{var ne;(ne=n.onCancelReasonOther)==null||ne.call(n)},onCancelReason:ne=>{var je;o(n.defaultIsActive??!1),d(!1),(je=n.onCancelReason)==null||je.call(n,ne)},onClose:()=>{o(n.defaultIsActive??!1),d(!1)}}):g(Gc,{className:`obi-widget-panel ${X?"expanded":""} ${m?"maximized":""} ${ke?"messaging":""} ${W?"tool-usage":""}`,children:[g("div",{className:`obi-widget ${Q?"active":""} ${t?"in-plan":""}`,onMouseEnter:w,onMouseLeave:E,children:[K&&g(Ft,{type:"cancel",onClick:B,disabled:u,title:"Cancel session"}),K&&!i&&g(Ft,{type:"pause",onClick:n.onPause,title:"Pause session"}),K&&i&&g(Ft,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),g(mt,{className:"obi-widget-popout",open:gt,trigger:null,delayMs:bt,offset:ai,children:[g(mt.Target,{children:[Le&&g(nw,{value:n.message,onCancel:()=>H(!1),onSend:A,onExpand:p,onChange:n.onMessageChange,children:g("div",{className:"obi-widget-buttons",children:[g(Ft,{type:"cancel",onClick:B,disabled:u,title:"Cancel session"}),!i&&g(Ft,{type:"pause",onClick:n.onPause,title:"Pause session"}),i&&g(Ft,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),g(Ft,{type:ke?"voice":"message",onClick:()=>H(!ke),title:ke?"Voice input":"Text input"}),g(Ft,{type:"minimize",onClick:O,title:"Minimize widget"})]})}),!Le&&g(Vc,{className:Q&&!t?"button":"",isActive:Q,speakingStatus:n.speakingStatus,onClick:L,onMouseEnter:k,onMouseLeave:S,children:[Q&&!t&&!$&&g("span",{className:"obi-widget-pill-text",children:"Tutorials"}),Q&&t&&$&&g("span",{className:"obi-widget-pill-text",children:"Searching knowledge ..."}),Q&&t&&!Te&&!$&&g(Ip,{getBands:n.spectrum}),Q&&Te&&!$&&g(B1,{})]})]}),g(mt.Content,{children:g("div",{onMouseLeave:E,children:[de&&g(un,{onClick:L,children:"Click to see all"}),te&&g(un,{children:"Session will pause shortly"}),ge&&g(un,{children:["Switched to ",ke?"chat":"voice"]}),oe&&g(un,{children:"Paused"}),Fe&&g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},children:[g(un,{onClick:()=>R("need-help"),children:"Need help"}),g(un,{onClick:()=>R("continue"),children:"Continue"}),g(un,{onClick:()=>R("say-again"),children:"Say again"})]}),u&&g(F1,{onContinue:()=>{var ne;(ne=n.onCancelAbort)==null||ne.call(n),d(!1),n.messaging!==void 0&&f(n.messaging)},onWrapUp:()=>{var ne;(ne=n.onCancel)==null||ne.call(n)}})]})})]}),K&&g(Ft,{type:ke?"voice":"message",onClick:()=>H(!ke),title:ke?"Voice input":"Text input"}),K&&g(Ft,{type:"minimize",onClick:O,title:"Minimize widget"})]}),Fi&&n.courseProgress&&g("div",{className:`obi-widget-course-progress ${ke?"expanded":""}`,children:g(iw,{currentStep:n.courseProgress.currentStep,totalSteps:n.courseProgress.totalSteps,stepNames:n.courseProgress.stepNames,onStepClick:(ne,je)=>{var xt;const We=`Can we please jump to the steps related to: ${je}`;(xt=n.onMessage)==null||xt.call(n,We)}})})]})}function sw(n){const{disabled:e,completedTutorials:t,totalTutorials:i,agentName:r}=n,[s,a]=Y(null),[o,c]=Y(n.isActive??n.defaultIsActive??!1),[l,u]=Y(!1),[d,h]=Y(n.hovered??!1),[f,m]=Y(null),[p,v]=Y(null);function b(){p&&(clearTimeout(p),v(null)),f&&m(null)}function C(){var H;c(!0),u(!1),h(!0),(H=n.onHover)==null||H.call(n,!0)}function x(){}function k(){s&&(clearTimeout(s),a(null))}function S(){o&&a(setTimeout(()=>{var H;c(n.defaultIsActive??!1),h(!1),(H=n.onHover)==null||H.call(n,!1)},400))}function w(){b(),c(!1),u(!0)}function E(){var H;b(),(H=n.onOpen)==null||H.call(n)}const A=n.hovered??(d&&!l),O=n.isActive??(o&&!e&&!l),B=O&&A||!!f,L=`round-button ${O?"active":""}`;let R=`${r||"Obi"}`;return t!==void 0&&i!==void 0&&t>=0&&i>0&&(R=`${t}/${i} completed`),da(()=>{if(n.toastMessage&&n.toastMessage.text){p&&clearTimeout(p);const H=n.toastMessage.autoCloseMs??3e3;m({text:n.toastMessage.text,autoCloseMs:H});const Q=setTimeout(()=>{m(null)},H);v(Q)}else n.toastMessage===null&&(p&&clearTimeout(p),m(null))},[n.toastMessage]),g("div",{className:"obi-widget-out-of-plan-container",children:g("div",{className:`obi-widget-out-of-plan ${A?"hover":""} ${O?"active":""}`,onMouseEnter:k,onMouseLeave:S,onClickCapture:b,children:[g("div",{className:L,style:{width:"30px",height:"30px"}}),g(mt,{className:"obi-widget-popout",open:B,trigger:null,delayMs:400,offset:5,children:[g(mt.Target,{children:g(I1,{className:O?"button":"",active:O,onClick:E,onMouseEnter:C,onMouseLeave:x,children:g("span",{className:"text",children:[g(Hp,{size:16}),R]})})}),g(mt.Content,{children:[!!f&&g(un,{onClick:()=>{b(),E()},children:f.text}),!f&&g("div",{onMouseLeave:S,children:g(un,{className:"message",onClick:E,children:"Click to see all"})})]})]}),g(Ft,{className:L,type:"minimize",onClick:w,title:"Minimize widget"})]})})}function aw(n){return g("div",{className:"obi-widget-out-of-plan-container",children:g("div",{className:"obi-widget-out-of-plan",children:g(mt,{className:"obi-widget-popout",open:!0,trigger:null,delayMs:100,offset:5,children:[g(mt.Target,{children:g(P1,{active:!1})}),g(mt.Content,{children:g(j1,{onOtherSelect:()=>{var e;(e=n.onOtherSelect)==null||e.call(n)},onReasonSelect:(e,t)=>{var i;(i=n.onCancelReason)==null||i.call(n,e,t)},onClose:()=>{var e;(e=n.onClose)==null||e.call(n)}})})]})})})}function ow({open:n=!1,children:e,onClose:t,preventOutsideClick:i=!1}){return g(Rp,{open:n,onClose:t,preventOutsideClick:i,size:"medium",children:g("div",{className:"tour content-area",children:n?typeof e=="function"?e():e:null})})}function cw(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Wp={exports:{}};(function(n){(function(){var e={}.hasOwnProperty;function t(){for(var s="",a=0;a<arguments.length;a++){var o=arguments[a];o&&(s=r(s,i(o)))}return s}function i(s){if(typeof s=="string"||typeof s=="number")return s;if(typeof s!="object")return"";if(Array.isArray(s))return t.apply(null,s);if(s.toString!==Object.prototype.toString&&!s.toString.toString().includes("[native code]"))return s.toString();var a="";for(var o in s)e.call(s,o)&&s[o]&&(a=r(a,o));return a}function r(s,a){return a?s?s+" "+a:s+a:s}n.exports?(t.default=t,n.exports=t):window.classNames=t})()})(Wp);var lw=Wp.exports;const uw=cw(lw);function Di({className:n,title:e="",agentName:t="Obi",buttonText:i="Continue",speakingState:r=null,actionDisabled:s=!1,footer:a,href:o=null,glow:c=!1,centerVisual:l,description:u,button:d,onAction:h}){const[f,m]=Y(s),[p,v]=Y(!1),[b,C]=Y(r);Qe(()=>{p||(r==="listening"&&b!=="listening"&&f&&m(!1),r!=="listening"&&!f&&m(!0)),C(r)},[r,f]),Qe(()=>{m(s)},[s]);const x=()=>{f||(m(!0),v(!0),h==null||h())},k=()=>{switch(r){case"thinking":return"Loading...";case"speaking":return`${t} is speaking`;default:return i}},S=o?"a":"button",w=o?{href:o,target:"_blank",rel:"noopener noreferrer"}:{type:"button"};return g("div",{className:uw("tour-content",n),children:g("div",{className:"container",children:[g("div",{className:`visual ${c?"glow":""}`,children:l}),g("div",{className:"header",children:[g("h1",{className:"title",children:e}),g("div",{className:"description",children:u})]}),g("div",{className:"button-container",children:d||g(S,{className:`action-button ${f?"disabled":""}`,onClick:x,disabled:f,...w,children:g("span",{className:"button-text",children:k()})})}),a&&g("div",{className:"tour-footer",children:a})]})})}function dw({logoUrl:n="",appName:e="App"}){const[t,i]=Y(!1),[r,s]=Y(!1),a=()=>{i(!0)},o=()=>{s(!0),i(!1)},c={container:{display:"block"},logoContainer:{width:"480px",height:"240px",borderRadius:"12px",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",overflow:"hidden"},backgroundPattern:{position:"absolute",inset:0,zIndex:0,background:"#F5F5F5",backgroundImage:`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='277' height='195' viewBox='0 0 277 195' fill='none'%3E%3Cpath opacity='0.4' d='M341.308 0.75C380.279 0.750001 411.872 24.3772 411.872 53.5229C411.872 82.6685 380.279 106.296 341.308 106.296H215.792C176.964 108.335 145.691 130.837 141.128 159.475V256.616C145.912 286.659 180.089 309.954 221.548 309.954H330.872C375.607 309.954 411.872 282.833 411.872 249.377V159.069C411.872 129.923 443.465 106.296 482.436 106.296C521.407 106.296 553 129.923 553 159.069V257.181C553 285.058 524.099 307.88 487.483 309.815C489.264 309.902 491.061 309.954 492.871 309.954C448.137 309.954 411.872 337.076 411.872 370.532C411.872 369.177 411.803 367.834 411.686 366.502C409.098 393.885 378.582 415.5 341.308 415.5H210.118C171.147 415.5 139.554 391.873 139.554 362.727C139.554 362.204 139.565 361.683 139.585 361.163C133.564 332.156 100.023 309.954 59.5488 309.954C61.4544 309.954 63.3441 309.9 65.2169 309.803C28.7434 307.76 -8.57239e-07 284.982 0 257.181V159.069C1.64632e-06 130.901 29.5078 107.89 66.6662 106.377C64.3207 106.224 61.9472 106.141 59.5488 106.141C100.012 106.141 133.54 83.951 139.575 54.9552C139.558 54.4793 139.554 54.0018 139.554 53.5229C139.554 24.3772 171.147 0.75 210.118 0.75H341.308Z' fill='white'/%3E%3C/svg%3E")`,backgroundRepeat:"no-repeat",backgroundPosition:"190px 60px",backgroundSize:"300px 225px"},logoWrapper:{background:"#888888",width:"120px",height:"120px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"4px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",zIndex:10,overflow:"hidden"},appLogo:{width:"120px",height:"120px",objectFit:"cover",display:n&&!t&&r?"block":"none"},placeholderLogo:{width:"60px",height:"60px",background:"rgba(255, 255, 255, 0.2)",borderRadius:"4px",display:!n||t||!r?"flex":"none",alignItems:"center",justifyContent:"center",color:"rgba(255, 255, 255, 0.8)",fontSize:"24px",fontWeight:"bold"}};return g("div",{style:c.container,children:g("div",{style:c.logoContainer,children:[g("div",{style:c.backgroundPattern}),g("div",{style:c.logoWrapper,children:[n&&g("img",{style:c.appLogo,src:n,alt:`${e} logo`,onError:a,onLoad:o}),g("div",{style:c.placeholderLogo,children:e.charAt(0).toUpperCase()})]})]})})}function hw({session:n,speakingState:e,onAction:t}){const i=n.appName?`Navigate to ${n.appName}`:"Navigate to app",r=n.appName?`Open ${n.appName}`:"Open app",s=n.appName?`Enjoy the tutorial in ${n.appName}`:"Enjoy the tutorial";return g(Di,{title:i,subtitle:"Click the button below to open the app",agentName:n.agentName||"Obi",buttonText:r,speakingState:e,actionDisabled:!0,href:n.url,description:s,centerVisual:g(dw,{logoUrl:n.appLogoUrl,appName:n.appName}),onAction:t})}const{entries:qp,setPrototypeOf:Kp,isFrozen:fw,getPrototypeOf:pw,getOwnPropertyDescriptor:mw}=Object;let{freeze:st,seal:wt,create:$p}=Object,{apply:Wc,construct:qc}=typeof Reflect<"u"&&Reflect;st||(st=function(n){return n}),wt||(wt=function(n){return n}),Wc||(Wc=function(n,e,t){return n.apply(e,t)}),qc||(qc=function(n,e){return new n(...e)});const ga=ot(Array.prototype.forEach),gw=ot(Array.prototype.lastIndexOf),Yp=ot(Array.prototype.pop),yr=ot(Array.prototype.push),vw=ot(Array.prototype.splice),va=ot(String.prototype.toLowerCase),Kc=ot(String.prototype.toString),Xp=ot(String.prototype.match),Tr=ot(String.prototype.replace),bw=ot(String.prototype.indexOf),yw=ot(String.prototype.trim),jt=ot(Object.prototype.hasOwnProperty),at=ot(RegExp.prototype.test),kr=Tw(TypeError);function ot(n){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return Wc(n,e,i)}}function Tw(n){return function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return qc(n,t)}}function ee(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:va;Kp&&Kp(n,null);let i=e.length;for(;i--;){let r=e[i];if(typeof r=="string"){const s=t(r);s!==r&&(fw(e)||(e[i]=s),r=s)}n[r]=!0}return n}function kw(n){for(let e=0;e<n.length;e++)jt(n,e)||(n[e]=null);return n}function dn(n){const e=$p(null);for(const[t,i]of qp(n))jt(n,t)&&(Array.isArray(i)?e[t]=kw(i):i&&typeof i=="object"&&i.constructor===Object?e[t]=dn(i):e[t]=i);return e}function Sr(n,e){for(;n!==null;){const i=mw(n,e);if(i){if(i.get)return ot(i.get);if(typeof i.value=="function")return ot(i.value)}n=pw(n)}function t(){return null}return t}const Jp=st(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),$c=st(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Yc=st(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Sw=st(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Xc=st(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Cw=st(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Qp=st(["#text"]),Zp=st(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Jc=st(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),em=st(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),ba=st(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),ww=wt(/\{\{[\w\W]*|[\w\W]*\}\}/gm),xw=wt(/<%[\w\W]*|[\w\W]*%>/gm),_w=wt(/\$\{[\w\W]*/gm),Ew=wt(/^data-[\-\w.\u00B7-\uFFFF]+$/),Rw=wt(/^aria-[\-\w]+$/),tm=wt(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Pw=wt(/^(?:\w+script|data):/i),Iw=wt(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),nm=wt(/^html$/i),Ow=wt(/^[a-z][.\w]*(-[.\w]+)+$/i);var im=Object.freeze({__proto__:null,ARIA_ATTR:Rw,ATTR_WHITESPACE:Iw,CUSTOM_ELEMENT:Ow,DATA_ATTR:Ew,DOCTYPE_NAME:nm,ERB_EXPR:xw,IS_ALLOWED_URI:tm,IS_SCRIPT_OR_DATA:Pw,MUSTACHE_EXPR:ww,TMPLIT_EXPR:_w});const Cr={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Aw=function(){return typeof window>"u"?null:window},Nw=function(n,e){if(typeof n!="object"||typeof n.createPolicy!="function")return null;let t=null;const i="data-tt-policy-suffix";e&&e.hasAttribute(i)&&(t=e.getAttribute(i));const r="dompurify"+(t?"#"+t:"");try{return n.createPolicy(r,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+r+" could not be created."),null}},rm=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function sm(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Aw();const e=T=>sm(T);if(e.version="3.2.6",e.removed=[],!n||!n.document||n.document.nodeType!==Cr.document||!n.Element)return e.isSupported=!1,e;let{document:t}=n;const i=t,r=i.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:o,Element:c,NodeFilter:l,NamedNodeMap:u=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:d,DOMParser:h,trustedTypes:f}=n,m=c.prototype,p=Sr(m,"cloneNode"),v=Sr(m,"remove"),b=Sr(m,"nextSibling"),C=Sr(m,"childNodes"),x=Sr(m,"parentNode");if(typeof a=="function"){const T=t.createElement("template");T.content&&T.content.ownerDocument&&(t=T.content.ownerDocument)}let k,S="";const{implementation:w,createNodeIterator:E,createDocumentFragment:A,getElementsByTagName:O}=t,{importNode:B}=i;let L=rm();e.isSupported=typeof qp=="function"&&typeof x=="function"&&w&&w.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:R,ERB_EXPR:H,TMPLIT_EXPR:Q,DATA_ATTR:X,ARIA_ATTR:K,IS_SCRIPT_OR_DATA:ye,ATTR_WHITESPACE:Te,CUSTOM_ELEMENT:W}=im;let{IS_ALLOWED_URI:de}=im,te=null;const ge=ee({},[...Jp,...$c,...Yc,...Xc,...Qp]);let oe=null;const Fe=ee({},[...Zp,...Jc,...em,...ba]);let $=Object.seal($p(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ke=null,Le=null,gt=!0,bt=!0,Fi=!1,ai=!0,ne=!1,je=!0,We=!1,xt=!1,hn=!1,_t=!1,Jt=!1,oi=!1,_r=!0,Er=!1;const _a="user-content-";let ji=!0,Vn=!1,fn={},N=null;const q=ee({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Z=null;const Se=ee({},["audio","video","img","source","image","track"]);let qe=null;const Qt=ee({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),pn="http://www.w3.org/1998/Math/MathML",Vi="http://www.w3.org/2000/svg",Et="http://www.w3.org/1999/xhtml";let mn=Et,Gi=!1,gn=null;const h_=ee({},[pn,Vi,Et],Kc);let Ea=ee({},["mi","mo","mn","ms","mtext"]),Ra=ee({},["annotation-xml"]);const f_=ee({},["title","style","font","a","script"]);let Rr=null;const p_=["application/xhtml+xml","text/html"],m_="text/html";let Ke=null,zi=null;const g_=t.createElement("form"),Am=function(T){return T instanceof RegExp||T instanceof Function},sl=function(){let T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(zi&&zi===T)){if((!T||typeof T!="object")&&(T={}),T=dn(T),Rr=p_.indexOf(T.PARSER_MEDIA_TYPE)===-1?m_:T.PARSER_MEDIA_TYPE,Ke=Rr==="application/xhtml+xml"?Kc:va,te=jt(T,"ALLOWED_TAGS")?ee({},T.ALLOWED_TAGS,Ke):ge,oe=jt(T,"ALLOWED_ATTR")?ee({},T.ALLOWED_ATTR,Ke):Fe,gn=jt(T,"ALLOWED_NAMESPACES")?ee({},T.ALLOWED_NAMESPACES,Kc):h_,qe=jt(T,"ADD_URI_SAFE_ATTR")?ee(dn(Qt),T.ADD_URI_SAFE_ATTR,Ke):Qt,Z=jt(T,"ADD_DATA_URI_TAGS")?ee(dn(Se),T.ADD_DATA_URI_TAGS,Ke):Se,N=jt(T,"FORBID_CONTENTS")?ee({},T.FORBID_CONTENTS,Ke):q,ke=jt(T,"FORBID_TAGS")?ee({},T.FORBID_TAGS,Ke):dn({}),Le=jt(T,"FORBID_ATTR")?ee({},T.FORBID_ATTR,Ke):dn({}),fn=jt(T,"USE_PROFILES")?T.USE_PROFILES:!1,gt=T.ALLOW_ARIA_ATTR!==!1,bt=T.ALLOW_DATA_ATTR!==!1,Fi=T.ALLOW_UNKNOWN_PROTOCOLS||!1,ai=T.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ne=T.SAFE_FOR_TEMPLATES||!1,je=T.SAFE_FOR_XML!==!1,We=T.WHOLE_DOCUMENT||!1,_t=T.RETURN_DOM||!1,Jt=T.RETURN_DOM_FRAGMENT||!1,oi=T.RETURN_TRUSTED_TYPE||!1,hn=T.FORCE_BODY||!1,_r=T.SANITIZE_DOM!==!1,Er=T.SANITIZE_NAMED_PROPS||!1,ji=T.KEEP_CONTENT!==!1,Vn=T.IN_PLACE||!1,de=T.ALLOWED_URI_REGEXP||tm,mn=T.NAMESPACE||Et,Ea=T.MATHML_TEXT_INTEGRATION_POINTS||Ea,Ra=T.HTML_INTEGRATION_POINTS||Ra,$=T.CUSTOM_ELEMENT_HANDLING||{},T.CUSTOM_ELEMENT_HANDLING&&Am(T.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&($.tagNameCheck=T.CUSTOM_ELEMENT_HANDLING.tagNameCheck),T.CUSTOM_ELEMENT_HANDLING&&Am(T.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&($.attributeNameCheck=T.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),T.CUSTOM_ELEMENT_HANDLING&&typeof T.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&($.allowCustomizedBuiltInElements=T.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ne&&(bt=!1),Jt&&(_t=!0),fn&&(te=ee({},Qp),oe=[],fn.html===!0&&(ee(te,Jp),ee(oe,Zp)),fn.svg===!0&&(ee(te,$c),ee(oe,Jc),ee(oe,ba)),fn.svgFilters===!0&&(ee(te,Yc),ee(oe,Jc),ee(oe,ba)),fn.mathMl===!0&&(ee(te,Xc),ee(oe,em),ee(oe,ba))),T.ADD_TAGS&&(te===ge&&(te=dn(te)),ee(te,T.ADD_TAGS,Ke)),T.ADD_ATTR&&(oe===Fe&&(oe=dn(oe)),ee(oe,T.ADD_ATTR,Ke)),T.ADD_URI_SAFE_ATTR&&ee(qe,T.ADD_URI_SAFE_ATTR,Ke),T.FORBID_CONTENTS&&(N===q&&(N=dn(N)),ee(N,T.FORBID_CONTENTS,Ke)),ji&&(te["#text"]=!0),We&&ee(te,["html","head","body"]),te.table&&(ee(te,["tbody"]),delete ke.tbody),T.TRUSTED_TYPES_POLICY){if(typeof T.TRUSTED_TYPES_POLICY.createHTML!="function")throw kr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof T.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw kr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');k=T.TRUSTED_TYPES_POLICY,S=k.createHTML("")}else k===void 0&&(k=Nw(f,r)),k!==null&&typeof S=="string"&&(S=k.createHTML(""));st&&st(T),zi=T}},Nm=ee({},[...$c,...Yc,...Sw]),Mm=ee({},[...Xc,...Cw]),v_=function(T){let z=x(T);(!z||!z.tagName)&&(z={namespaceURI:mn,tagName:"template"});const F=va(T.tagName),fe=va(z.tagName);return gn[T.namespaceURI]?T.namespaceURI===Vi?z.namespaceURI===Et?F==="svg":z.namespaceURI===pn?F==="svg"&&(fe==="annotation-xml"||Ea[fe]):!!Nm[F]:T.namespaceURI===pn?z.namespaceURI===Et?F==="math":z.namespaceURI===Vi?F==="math"&&Ra[fe]:!!Mm[F]:T.namespaceURI===Et?z.namespaceURI===Vi&&!Ra[fe]||z.namespaceURI===pn&&!Ea[fe]?!1:!Mm[F]&&(f_[F]||!Nm[F]):!!(Rr==="application/xhtml+xml"&&gn[T.namespaceURI]):!1},ci=function(T){yr(e.removed,{element:T});try{x(T).removeChild(T)}catch{v(T)}},Hi=function(T,z){try{yr(e.removed,{attribute:z.getAttributeNode(T),from:z})}catch{yr(e.removed,{attribute:null,from:z})}if(z.removeAttribute(T),T==="is")if(_t||Jt)try{ci(z)}catch{}else try{z.setAttribute(T,"")}catch{}},Lm=function(T){let z=null,F=null;if(hn)T="<remove></remove>"+T;else{const Ie=Xp(T,/^[\r\n\t ]+/);F=Ie&&Ie[0]}Rr==="application/xhtml+xml"&&mn===Et&&(T='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+T+"</body></html>");const fe=k?k.createHTML(T):T;if(mn===Et)try{z=new h().parseFromString(fe,Rr)}catch{}if(!z||!z.documentElement){z=w.createDocument(mn,"template",null);try{z.documentElement.innerHTML=Gi?S:fe}catch{}}const Ze=z.body||z.documentElement;return T&&F&&Ze.insertBefore(t.createTextNode(F),Ze.childNodes[0]||null),mn===Et?O.call(z,We?"html":"body")[0]:We?z.documentElement:Ze},Dm=function(T){return E.call(T.ownerDocument||T,T,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},al=function(T){return T instanceof d&&(typeof T.nodeName!="string"||typeof T.textContent!="string"||typeof T.removeChild!="function"||!(T.attributes instanceof u)||typeof T.removeAttribute!="function"||typeof T.setAttribute!="function"||typeof T.namespaceURI!="string"||typeof T.insertBefore!="function"||typeof T.hasChildNodes!="function")},Um=function(T){return typeof o=="function"&&T instanceof o};function vn(T,z,F){ga(T,fe=>{fe.call(e,z,F,zi)})}const Bm=function(T){let z=null;if(vn(L.beforeSanitizeElements,T,null),al(T))return ci(T),!0;const F=Ke(T.nodeName);if(vn(L.uponSanitizeElement,T,{tagName:F,allowedTags:te}),je&&T.hasChildNodes()&&!Um(T.firstElementChild)&&at(/<[/\w!]/g,T.innerHTML)&&at(/<[/\w!]/g,T.textContent)||T.nodeType===Cr.progressingInstruction||je&&T.nodeType===Cr.comment&&at(/<[/\w]/g,T.data))return ci(T),!0;if(!te[F]||ke[F]){if(!ke[F]&&jm(F)&&($.tagNameCheck instanceof RegExp&&at($.tagNameCheck,F)||$.tagNameCheck instanceof Function&&$.tagNameCheck(F)))return!1;if(ji&&!N[F]){const fe=x(T)||T.parentNode,Ze=C(T)||T.childNodes;if(Ze&&fe){const Ie=Ze.length;for(let bn=Ie-1;bn>=0;--bn){const Vt=p(Ze[bn],!0);Vt.__removalCount=(T.__removalCount||0)+1,fe.insertBefore(Vt,b(T))}}}return ci(T),!0}return T instanceof c&&!v_(T)||(F==="noscript"||F==="noembed"||F==="noframes")&&at(/<\/no(script|embed|frames)/i,T.innerHTML)?(ci(T),!0):(ne&&T.nodeType===Cr.text&&(z=T.textContent,ga([R,H,Q],fe=>{z=Tr(z,fe," ")}),T.textContent!==z&&(yr(e.removed,{element:T.cloneNode()}),T.textContent=z)),vn(L.afterSanitizeElements,T,null),!1)},Fm=function(T,z,F){if(_r&&(z==="id"||z==="name")&&(F in t||F in g_))return!1;if(!(bt&&!Le[z]&&at(X,z))&&!(gt&&at(K,z))){if(!oe[z]||Le[z]){if(!(jm(T)&&($.tagNameCheck instanceof RegExp&&at($.tagNameCheck,T)||$.tagNameCheck instanceof Function&&$.tagNameCheck(T))&&($.attributeNameCheck instanceof RegExp&&at($.attributeNameCheck,z)||$.attributeNameCheck instanceof Function&&$.attributeNameCheck(z))||z==="is"&&$.allowCustomizedBuiltInElements&&($.tagNameCheck instanceof RegExp&&at($.tagNameCheck,F)||$.tagNameCheck instanceof Function&&$.tagNameCheck(F))))return!1}else if(!qe[z]&&!at(de,Tr(F,Te,""))&&!((z==="src"||z==="xlink:href"||z==="href")&&T!=="script"&&bw(F,"data:")===0&&Z[T])&&!(Fi&&!at(ye,Tr(F,Te,"")))&&F)return!1}return!0},jm=function(T){return T!=="annotation-xml"&&Xp(T,W)},Vm=function(T){vn(L.beforeSanitizeAttributes,T,null);const{attributes:z}=T;if(!z||al(T))return;const F={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:oe,forceKeepAttr:void 0};let fe=z.length;for(;fe--;){const Ze=z[fe],{name:Ie,namespaceURI:bn,value:Vt}=Ze,Zt=Ke(Ie),ol=Vt;let it=Ie==="value"?ol:yw(ol);if(F.attrName=Zt,F.attrValue=it,F.keepAttr=!0,F.forceKeepAttr=void 0,vn(L.uponSanitizeAttribute,T,F),it=F.attrValue,Er&&(Zt==="id"||Zt==="name")&&(Hi(Ie,T),it=_a+it),je&&at(/((--!?|])>)|<\/(style|title)/i,it)){Hi(Ie,T);continue}if(F.forceKeepAttr)continue;if(!F.keepAttr){Hi(Ie,T);continue}if(!ai&&at(/\/>/i,it)){Hi(Ie,T);continue}ne&&ga([R,H,Q],y_=>{it=Tr(it,y_," ")});const Gm=Ke(T.nodeName);if(!Fm(Gm,Zt,it)){Hi(Ie,T);continue}if(k&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!bn)switch(f.getAttributeType(Gm,Zt)){case"TrustedHTML":{it=k.createHTML(it);break}case"TrustedScriptURL":{it=k.createScriptURL(it);break}}if(it!==ol)try{bn?T.setAttributeNS(bn,Ie,it):T.setAttribute(Ie,it),al(T)?ci(T):Yp(e.removed)}catch{Hi(Ie,T)}}vn(L.afterSanitizeAttributes,T,null)},b_=function T(z){let F=null;const fe=Dm(z);for(vn(L.beforeSanitizeShadowDOM,z,null);F=fe.nextNode();)vn(L.uponSanitizeShadowNode,F,null),Bm(F),Vm(F),F.content instanceof s&&T(F.content);vn(L.afterSanitizeShadowDOM,z,null)};return e.sanitize=function(T){let z=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},F=null,fe=null,Ze=null,Ie=null;if(Gi=!T,Gi&&(T="<!-->"),typeof T!="string"&&!Um(T))if(typeof T.toString=="function"){if(T=T.toString(),typeof T!="string")throw kr("dirty is not a string, aborting")}else throw kr("toString is not a function");if(!e.isSupported)return T;if(xt||sl(z),e.removed=[],typeof T=="string"&&(Vn=!1),Vn){if(T.nodeName){const Zt=Ke(T.nodeName);if(!te[Zt]||ke[Zt])throw kr("root node is forbidden and cannot be sanitized in-place")}}else if(T instanceof o)F=Lm("<!---->"),fe=F.ownerDocument.importNode(T,!0),fe.nodeType===Cr.element&&fe.nodeName==="BODY"||fe.nodeName==="HTML"?F=fe:F.appendChild(fe);else{if(!_t&&!ne&&!We&&T.indexOf("<")===-1)return k&&oi?k.createHTML(T):T;if(F=Lm(T),!F)return _t?null:oi?S:""}F&&hn&&ci(F.firstChild);const bn=Dm(Vn?T:F);for(;Ze=bn.nextNode();)Bm(Ze),Vm(Ze),Ze.content instanceof s&&b_(Ze.content);if(Vn)return T;if(_t){if(Jt)for(Ie=A.call(F.ownerDocument);F.firstChild;)Ie.appendChild(F.firstChild);else Ie=F;return(oe.shadowroot||oe.shadowrootmode)&&(Ie=B.call(i,Ie,!0)),Ie}let Vt=We?F.outerHTML:F.innerHTML;return We&&te["!doctype"]&&F.ownerDocument&&F.ownerDocument.doctype&&F.ownerDocument.doctype.name&&at(nm,F.ownerDocument.doctype.name)&&(Vt="<!DOCTYPE "+F.ownerDocument.doctype.name+`>
|
|
42
|
+
`},mc}var xf;function mC(){if(xf)return Dt;xf=1;var n=fC(),e=pC(),t=pc();return Dt.grammar=t,Dt.write=e,Dt.parse=n.parse,Dt.parseParams=n.parseParams,Dt.parseFmtpConfig=n.parseFmtpConfig,Dt.parsePayloads=n.parsePayloads,Dt.parseRemoteCandidates=n.parseRemoteCandidates,Dt.parseImageAttributes=n.parseImageAttributes,Dt.parseSimulcastStreamList=n.parseSimulcastStreamList,Dt}var Bn=mC();function gc(n,e,t){var i,r,s;e===void 0&&(e=50),t===void 0&&(t={});var a=(i=t.isImmediate)!=null&&i,o=(r=t.callback)!=null&&r,c=t.maxWait,l=Date.now(),u=[];function d(){if(c!==void 0){var f=Date.now()-l;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),m=this;return new Promise(function(p,v){var b=a&&s===void 0;if(s!==void 0&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,l=Date.now(),!a){var x=n.apply(m,f);o&&o(x),u.forEach(function(k){return(0,k.resolve)(x)}),u=[]}},d()),b){var C=n.apply(m,f);return o&&o(C),p(C)}u.push({resolve:p,reject:v})})};return h.cancel=function(f){s!==void 0&&clearTimeout(s),u.forEach(function(m){return(0,m.reject)(f)}),u=[]},h}const gC=.7,vC=20,Oi={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class _f extends Yt.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=re,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=gc(r=>y(this,void 0,void 0,function*(){this.emit(Oi.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),vC),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=rn((i=t.loggerName)!==null&&i!==void 0?i:Mt.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var i;(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return y(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return y(this,void 0,void 0,function*(){var t;let i;if(e.type==="offer"){let{stereoMids:r,nackMids:s}=bC(e);this.remoteStereoMids=r,this.remoteNackMids=s}else if(e.type==="answer"){const r=Bn.parse((t=e.sdp)!==null&&t!==void 0?t:"");r.media.forEach(s=>{s.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||s.mid!=a.transceiver.mid)return!1;let o=0;if(s.rtp.some(l=>l.codec.toUpperCase()===a.codec.toUpperCase()?(o=l.payload,!0):!1),o===0)return!0;let c=!1;for(const l of s.fmtp)if(l.payload===o){l.config=l.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(l.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),c=!0;break}return c||a.maxbr>0&&s.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),i=Bn.write(r)}yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Oi.NegotiationComplete),e.sdp&&Bn.parse(e.sdp).media.forEach(s=>{s.type==="video"&&this.emit(Oi.RTPVideoPayloadTypes,s.rtp)}))})}createAndSendOffer(e){return y(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 s=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&s)yield this._pc.setRemoteDescription(s);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 i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const r=Bn.parse((t=i.sdp)!==null&&t!==void 0?t:"");r.media.forEach(s=>{Rf(s),s.type==="audio"?Ef(s,[],[]):s.type==="video"&&this.trackBitrates.some(a=>{if(!s.msid||!a.cid||!s.msid.includes(a.cid))return!1;let o=0;if(s.rtp.some(l=>l.codec.toUpperCase()===a.codec.toUpperCase()?(o=l.payload,!0):!1),o===0||(dr(a.codec)&&this.ensureVideoDDExtensionForSVC(s,r),a.codec!=="av1"))return!0;const c=Math.round(a.maxbr*gC);for(const l of s.fmtp)if(l.payload===o){l.config.includes("x-google-start-bitrate")||(l.config+=";x-google-start-bitrate=".concat(c));break}return!0})}),yield this.setMungedSDP(i,Bn.write(r)),this.onOffer(i)})}createAndSetAnswer(){return y(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=Bn.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(r=>{Rf(r),r.type==="audio"&&Ef(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Bn.write(i)),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 Ge("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 Ge("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 y(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const i=new Map,r=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),i.set(o.id,o);break;case"remote-candidate":r.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return r.get(a)})}setMungedSDP(e,t,i){return y(this,void 0,void 0,function*(){if(t){const r=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(s){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:s,sdp:t})),e.sdp=r}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let s="unknown error";r instanceof Error?s=r.message:typeof r=="string"&&(s=r);const a={error:s,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new Ho(s)}})}ensureVideoDDExtensionForSVC(e,t){var i,r;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===af))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var c;o.type==="video"&&((c=o.ext)===null||c===void 0||c.forEach(l=>{l.value>a&&(a=l.value)}))}),this.ddExtID=a+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:af})}}}function Ef(n,e,t){let i=0;n.rtp.some(r=>r.codec==="opus"?(i=r.payload,!0):!1),i>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(n.mid)&&!n.rtcpFb.some(r=>r.payload===i&&r.type==="nack")&&n.rtcpFb.push({payload:i,type:"nack"}),e.includes(n.mid)&&n.fmtp.some(r=>r.payload===i?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function bC(n){var e;const t=[],i=[],r=Bn.parse((e=n.sdp)!==null&&e!==void 0?e:"");let s=0;return r.media.forEach(a=>{var o;a.type==="audio"&&(a.rtp.some(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===s&&c.type==="nack")&&i.push(a.mid),a.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&t.push(a.mid),!0):!1))}),{stereoMids:t,nackMids:i}}function Rf(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 vc="vp8",yC={audioPreset:$o.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Xo.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:vc,backupCodec:!0},Pf={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},If={deviceId:{ideal:"default"},resolution:ur.h720.resolution},TC={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new uS,disconnectOnPageLeave:!0,webAudioMix:!1},bc={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Re;(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"})(Re||(Re={}));class kC{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var r;this.peerConnectionTimeout=bc.peerConnectionTimeout,this.log=re,this.updateState=()=>{var s;const a=this.state,o=this.requiredTransports.map(c=>c.getConnectionState());o.every(c=>c==="connected")?this.state=Re.CONNECTED:o.some(c=>c==="failed")?this.state=Re.FAILED:o.some(c=>c==="connecting")?this.state=Re.CONNECTING:o.every(c=>c==="closed")?this.state=Re.CLOSED:o.some(c=>c==="closed")?this.state=Re.CLOSING:o.every(c=>c==="new")&&(this.state=Re.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(Re[a]," to ").concat(Re[this.state]),this.logContext),(s=this.onStateChange)===null||s===void 0||s.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=rn((r=i.loggerName)!==null&&r!==void 0?r:Mt.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new _f(e,i),this.subscriber=new _f(e,i),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=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,Nt.PUBLISHER)},this.subscriber.onIceCandidate=s=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,s,Nt.SUBSCRIBER)},this.subscriber.onDataChannel=s=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,s)},this.subscriber.onTrack=s=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,s)},this.publisher.onOffer=s=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,s)},this.state=Re.NEW,this.connectionLock=new ut,this.remoteOfferLock=new ut}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 y(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(i){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:i}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return y(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return y(this,void 0,void 0,function*(){t===Nt.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return y(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 y(this,void 0,void 0,function*(){var i;const r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((i=this.requiredTransports)===null||i===void 0?void 0:i.map(s=>this.ensureTransportConnected(s,e,t)))}finally{r()}})}negotiate(e){return y(this,void 0,void 0,function*(){return new Promise((t,i)=>y(this,void 0,void 0,function*(){const r=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),s=()=>{clearTimeout(r),i("negotiation aborted")};e.signal.addEventListener("abort",s),this.publisher.once(Oi.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Oi.NegotiationComplete,()=>{clearTimeout(r),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(r),i(a)})}))})}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===Nt.PUBLISHER?this.publisher.getConnectedAddress():e===Nt.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 y(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(i.getConnectionState()!=="connected")return new Promise((c,l)=>y(s,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),Je.clearTimeout(d),l(new me("room connection has been cancelled",se.Cancelled))};r!=null&&r.signal.aborted&&u(),r==null||r.signal.addEventListener("abort",u);const d=Je.setTimeout(()=>{r==null||r.signal.removeEventListener("abort",u),l(new me("could not establish pc connection",se.InternalError))},a);for(;this.state!==Re.CONNECTED;)if(yield ft(50),r!=null&&r.signal.aborted){l(new me("room connection has been cancelled",se.Cancelled));return}Je.clearTimeout(d),r==null||r.signal.removeEventListener("abort",u),c()}))}()})}}class Pe extends Error{constructor(e,t,i){super(t),this.code=e,this.message=Af(t,Pe.MAX_MESSAGE_BYTES),this.data=i?Af(i,Pe.MAX_DATA_BYTES):void 0}static fromProto(e){return new Pe(e.code,e.message,e.data)}toProto(){return new qd({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new Pe(Pe.ErrorCode[e],Pe.ErrorMessage[e],t)}}Pe.MAX_MESSAGE_BYTES=256,Pe.MAX_DATA_BYTES=15360,Pe.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},Pe.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 Of=15360;function yc(n){return new TextEncoder().encode(n).length}function Af(n,e){if(yc(n)<=e)return n;let t=0,i=n.length;const r=new TextEncoder;for(;t<i;){const s=Math.floor((t+i+1)/2);r.encode(n.slice(0,s)).length<=e?t=s:i=s-1}return n.slice(0,t)}const Tc=2e3;function Js(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}const SC=1e3;class Nf extends I{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,i){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,s=arguments.length>4?arguments[4]:void 0;super(e,t,s),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=gc(()=>y(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>y(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(D.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new ut,this.pauseUpstreamLock=new ut,this.processorLock=new ut,this.restartLock=new ut,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==I.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 y(this,void 0,void 0,function*(){var i;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(s=>{Ei(this._mediaStreamTrack,s)}),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 r;if(this.processor&&e){const s=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&&(_i(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),r=this.processor.processedTrack}finally{s()}}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(s=>{_i(r??e,s)}))})}waitForDimensions(){return y(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:SC;return function*(){var i;if(e.kind===I.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=Lt())===null||i===void 0?void 0:i.os)==="iOS"&&(yield ft(10));const r=Date.now();for(;Date.now()-r<t;){const s=e.dimensions;if(s)return s;yield ft(50)}throw new sn("unable to get track dimensions after timeout")}()})}setDeviceId(e){return y(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Dn(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Dn(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return y(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===I.Source.ScreenShare)return;const{deviceId:i,groupId:r}=e._mediaStreamTrack.getSettings(),s=e.kind===I.Kind.Audio?"audioinput":"videoinput";return t?He.getInstance().normalizeDeviceId(s,i,r):i}()})}mute(){return y(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return y(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return y(this,void 0,void 0,function*(){if(!this.sender)throw new sn("unable to replace an unpublished track");let i,r;return typeof t=="boolean"?i=t:t!==void 0&&(i=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=i??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return y(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:r}=e,s=dS(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===I.Kind.Video?a.video=i||r?{deviceId:i,facingMode:r}:!0:a.audio=i?{deviceId:i}:!0,this.attachedElements.forEach(l=>{Ei(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return yield c.applyConstraints(s),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(D.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?D.Muted:D.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 y(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),of()&&(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 y(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(D.UpstreamPaused,this);const i=Lt();if((i==null?void 0:i.name)==="Safari"&&Jn(i.version,"12.0")<0)throw new zo("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 y(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(D.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 y(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 y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s;const a=yield i.processorLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext};if(yield t.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.stopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(_i(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(l=>i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:l}))),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const l of i.attachedElements)l!==i.processorElement&&r&&(Ei(i._mediaStreamTrack,l),_i(i.processor.processedTrack,l));yield(s=i.sender)===null||s===void 0?void 0:s.replaceTrack(i.processor.processedTrack)}i.emit(D.TrackProcessorUpdate,i.processor)}finally{a()}}()})}getProcessor(){return this.processor}stopProcessor(){return y(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var i,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)===null||r===void 0||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(D.TrackProcessorUpdate))}()})}}class Qs extends Nf{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,s=arguments.length>4?arguments[4]:void 0;super(e,I.Kind.Audio,t,i,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>y(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=Js(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(D.AudioTrackFeatureUpdate,this,At.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(D.AudioTrackFeatureUpdate,this,At.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return y(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===I.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 y(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Dn(this._constraints.deviceId);return this.source===I.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return y(this,void 0,void 0,function*(){let t;if(e){const i=lc({audio:e});typeof i.audio!="boolean"&&(t=i.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return y(this,void 0,void 0,function*(){const i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){pt()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Tc)))}setProcessor(e){return y(this,void 0,void 0,function*(){var t;const i=yield this.processorLock.lock();try{if(!Xt()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const r={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(r),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(D.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return y(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let i;return t.forEach(r=>{r.type==="outbound-rtp"&&(i={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),i})}checkForSilence(){return y(this,void 0,void 0,function*(){const e=yield gf(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(D.AudioSilenceDetected)),e})}}function CC(n,e,t){switch(n.kind){case"audio":return new Qs(n,e,!1,void 0,t);case"video":return new ea(n,e,!1,t);default:throw new sn("unsupported track type: ".concat(n.kind))}}const wC=Object.values(ur),xC=Object.values(Yo),_C=Object.values(Xo),EC=[ur.h180,ur.h360],RC=[Yo.h180,Yo.h360],PC=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,r;return new pe(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((r=t.fps)!==null&&r!==void 0?r:30))))),t.fps,n.encoding.priority)}),kc=["q","h","f"];function Sc(n,e,t,i){var r,s;let a=i==null?void 0:i.videoEncoding;n&&(a=i==null?void 0:i.screenShareEncoding);const o=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,l=i==null?void 0:i.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=OC(n,e,t,l),re.debug("using video encoding",a));const u=a.maxFramerate,d=new pe(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&dr(l)){const m=new Zs(c),p=[];if(m.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const v=Lt();if(Ln()||Xt()||(v==null?void 0:v.name)==="Chrome"&&Jn(v==null?void 0:v.version,"113")<0){const b=m.suffix=="h"?2:3;for(let C=0;C<m.spatial;C+=1)p.push({rid:kc[2-C],maxBitrate:a.maxBitrate/Math.pow(b,C),maxFramerate:d.encoding.maxFramerate});p[0].scalabilityMode=c}else p.push({maxBitrate:a.maxBitrate,maxFramerate:d.encoding.maxFramerate,scalabilityMode:c});return d.encoding.priority&&(p[0].priority=d.encoding.priority,p[0].networkPriority=d.encoding.priority),re.debug("using svc encoding",{encodings:p}),p}if(!o)return[a];let h=[];n?h=(r=Lf(i==null?void 0:i.screenShareSimulcastLayers))!==null&&r!==void 0?r:Mf(n,d):h=(s=Lf(i==null?void 0:i.videoSimulcastLayers))!==null&&s!==void 0?s:Mf(n,d);let f;if(h.length>0){const m=h[0];h.length>1&&([,f]=h);const p=Math.max(e,t);if(p>=960&&f)return Cc(e,t,[m,f,d],u);if(p>=480)return Cc(e,t,[m,d],u)}return Cc(e,t,[d])}function IC(n,e,t){var i,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&re.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),c=(i=o.width)!==null&&i!==void 0?i:(r=n.dimensions)===null||r===void 0?void 0:r.width,l=(s=o.height)!==null&&s!==void 0?s:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===I.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Sc(n.source===I.Source.ScreenShare,c,l,t)}function OC(n,e,t,i){const r=AC(n,e,t);let{encoding:s}=r[0];const a=Math.max(e,t);for(let o=0;o<r.length;o+=1){const c=r[o];if(s=c.encoding,c.width>=a)break}if(i)switch(i){case"av1":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.7;break;case"vp9":s=Object.assign({},s),s.maxBitrate=s.maxBitrate*.85;break}return s}function AC(n,e,t){if(n)return _C;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?wC:xC}function Mf(n,e){if(n)return PC(e);const{width:t,height:i}=e,r=t>i?t/i:i/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?EC:RC}function Cc(n,e,t,i){const r=[];if(t.forEach((s,a)=>{if(a>=kc.length)return;const o=Math.min(n,e),l={rid:kc[a],scaleResolutionDownBy:Math.max(1,o/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},u=i&&s.encoding.maxFramerate?Math.min(i,s.encoding.maxFramerate):s.encoding.maxFramerate;u&&(l.maxFramerate=u);const d=Ri()||a===0;s.encoding.priority&&d&&(l.priority=s.encoding.priority,l.networkPriority=s.encoding.priority),r.push(l)}),Xt()&&lf()==="ios"){let s;r.forEach(o=>{s?o.maxFramerate&&o.maxFramerate>s&&(s=o.maxFramerate):s=o.maxFramerate});let a=!0;r.forEach(o=>{var c;o.maxFramerate!=s&&(a&&(a=!1,re.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),re.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function Lf(n){if(n)return n.sort((e,t)=>{const{encoding:i}=e,{encoding:r}=t;return i.maxBitrate>r.maxBitrate?1:i.maxBitrate<r.maxBitrate?-1:i.maxBitrate===r.maxBitrate&&i.maxFramerate&&r.maxFramerate?i.maxFramerate>r.maxFramerate?1:-1:0})}class Zs{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 NC(n){return n.source===I.Source.ScreenShare||n.constraints.height&&Dn(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const MC=5e3;class ea extends Nf{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,I.Kind.Video,t,i,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>y(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}const a=new Map(s.map(o=>[o.rid,o]));if(this.prevStats){let o=0;a.forEach((c,l)=>{var u;const d=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);o+=Js(c,d)}),this._currentBitrate=o}this.prevStats=a}),this.senderLock=new ut}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!pt())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Tc))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return y(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=On(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;o=!0)s=l.value,o=!1,yield(a=s.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(u){i={error:u}}finally{try{!o&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return y(this,void 0,void 0,function*(){var t,i,r,s,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=On(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;o=!0){s=l.value,o=!1;const u=s;yield(a=u.sender)===null||a===void 0?void 0:a.replaceTrack(u.mediaStreamTrack)}}catch(u){i={error:u}}finally{try{!o&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(i)throw i.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return y(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===I.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 y(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===I.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 y(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],i=yield this.sender.getStats();return i.forEach(r=>{var s;if(r.type==="outbound-rtp"){const a={type:"video",streamId:r.id,frameHeight:r.frameHeight,frameWidth:r.frameWidth,framesPerSecond:r.framesPerSecond,framesSent:r.framesSent,firCount:r.firCount,pliCount:r.pliCount,nackCount:r.nackCount,packetsSent:r.packetsSent,bytesSent:r.bytesSent,qualityLimitationReason:r.qualityLimitationReason,qualityLimitationDurations:r.qualityLimitationDurations,qualityLimitationResolutionChanges:r.qualityLimitationResolutionChanges,rid:(s=r.rid)!==null&&s!==void 0?s:r.id,retransmittedPacketsSent:r.retransmittedPacketsSent,targetBitrate:r.targetBitrate,timestamp:r.timestamp},o=i.get(r.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((r,s)=>{var a,o;return((a=s.frameWidth)!==null&&a!==void 0?a:0)-((o=r.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let i=Ct.LOW;i<=Ct.HIGH;i+=1)t.push(new Oo({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return y(this,void 0,void 0,function*(){var t,i,r,s,a;let o;if(e){const d=lc({video:e});typeof d.video!="boolean"&&(o=d.video)}yield this.restart(o);try{for(var c=!0,l=On(this.simulcastCodecs.values()),u;u=yield l.next(),t=u.done,!t;c=!0){s=u.value,c=!1;const d=s;d.sender&&((a=d.sender.transport)===null||a===void 0?void 0:a.state)!=="closed"&&(d.mediaStreamTrack=this.mediaStreamTrack.clone(),yield d.sender.replaceTrack(d.mediaStreamTrack))}}catch(d){i={error:d}}finally{try{!c&&!t&&(r=l.return)&&(yield r.call(l))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return y(this,arguments,void 0,function(i){var r=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var a,o,c,l,u,d;if(yield t.setProcessor.call(r,i,s),!((u=r.processor)===null||u===void 0)&&u.processedTrack)try{for(var h=!0,f=On(r.simulcastCodecs.values()),m;m=yield f.next(),a=m.done,!a;h=!0)l=m.value,h=!1,yield(d=l.sender)===null||d===void 0?void 0:d.replaceTrack(r.processor.processedTrack)}catch(p){o={error:p}}finally{try{!h&&!a&&(c=f.return)&&(yield c.call(f))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return y(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},MC))}setPublishingCodecs(e){return y(this,void 0,void 0,function*(){var t,i,r,s,a,o,c;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(t=!0,i=On(e);r=yield i.next(),s=r.done,!s;t=!0){c=r.value,t=!1;const u=c;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(u.qualities);else{const d=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:d})),!d||!d.sender){for(const h of u.qualities)if(h.enabled){l.push(u.codec);break}}else d.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield Df(d.sender,d.encodings,u.qualities,this.senderLock,this.log,this.logContext))}}}catch(u){a={error:u}}finally{try{!t&&!s&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return l})}setPublishingLayers(e){return y(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 Df(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return y(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),of()&&this.isInBackground&&this.source===I.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Df(n,e,t,i,r,s){return y(this,void 0,void 0,function*(){const a=yield i.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},s),{sender:n,qualities:t,senderEncodings:e}));try{const o=n.getParameters(),{encodings:c}=o;if(!c)return;if(c.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},s),{encodings:c,senderEncodings:e}));return}let l=!1;const u=Lt();if((u==null?void 0:u.name)==="Chrome"&&Jn(u==null?void 0:u.version,"133")>0&&c[0].scalabilityMode){const h=c[0],f=new Zs(h.scalabilityMode);let m=Ti.OFF;if(t.forEach(p=>{p.enabled&&(m===Ti.OFF||p.quality>m)&&(m=p.quality)}),m===Ti.OFF)h.active&&(h.active=!1,l=!0);else if(!h.active||f.spatial!==m+1){l=!0,h.active=!0;const p=new Zs(e[0].scalabilityMode);f.spatial=m+1,f.suffix=p.suffix,f.spatial===1&&(f.suffix=void 0),h.scalabilityMode=f.toString(),h.scaleResolutionDownBy=Math.pow(2,2-m),e[0].maxBitrate&&(h.maxBitrate=e[0].maxBitrate/(h.scaleResolutionDownBy*h.scaleResolutionDownBy))}}else c.forEach((h,f)=>{var m;let p=(m=h.rid)!==null&&m!==void 0?m:"";p===""&&(p="q");const v=Uf(p),b=t.find(C=>C.quality===v);b&&h.active!==b.enabled&&(l=!0,h.active=b.enabled,r.debug("setting layer ".concat(b.quality," to ").concat(h.active?"enabled":"disabled"),s),Ri()&&(b.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))});l&&(o.encodings=c,r.debug("setting encodings",Object.assign(Object.assign({},s),{encodings:o.encodings})),yield n.setParameters(o))}finally{a()}})}function Uf(n){switch(n){case"f":return Ct.HIGH;case"h":return Ct.MEDIUM;case"q":return Ct.LOW;default:return Ct.HIGH}}function Bf(n,e,t,i){if(!t)return[new $n({quality:Ct.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const r=t[0].scalabilityMode,s=new Zs(r),a=[],o=s.suffix=="h"?1.5:2,c=s.suffix=="h"?2:3;for(let l=0;l<s.spatial;l+=1)a.push(new $n({quality:Math.min(Ct.HIGH,s.spatial-1)-l,width:Math.ceil(n/Math.pow(o,l)),height:Math.ceil(e/Math.pow(o,l)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return a}return t.map(r=>{var s,a,o;const c=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1;let l=Uf((a=r.rid)!==null&&a!==void 0?a:"");return new $n({quality:l,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(o=r.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const Ff="_lossy",jf="_reliable",LC=2*1e3,wc="leave-reconnect";var Ut;(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"})(Ut||(Ut={}));class DC extends Yt.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=bc.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Ut.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=re,this.handleDataChannel=i=>y(this,[i],void 0,function(r){var s=this;let{channel:a}=r;return function*(){if(a){if(a.label===jf)s.reliableDCSub=a;else if(a.label===Ff)s.lossyDCSub=a;else return;s.log.debug("on data channel ".concat(a.id,", ").concat(a.label),s.logContext),a.onmessage=s.handleDataMessage}}()}),this.handleDataMessage=i=>y(this,void 0,void 0,function*(){var r,s;const a=yield this.dataProcessLock.lock();try{let o;if(i.data instanceof ArrayBuffer)o=i.data;else if(i.data instanceof Blob)o=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const c=ht.fromBinary(new Uint8Array(o));((r=c.value)===null||r===void 0?void 0:r.case)==="speaker"?this.emit(U.ActiveSpeakersUpdate,c.value.value.speakers):(((s=c.value)===null||s===void 0?void 0:s.case)==="user"&&BC(c,c.value.value),this.emit(U.DataPacketReceived,c))}finally{a()}}),this.handleDataError=i=>{const s=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:a}=i.error;this.log.error("DataChannel error on ".concat(s,": ").concat(i.message),Object.assign(Object.assign({},this.logContext),{error:a}))}else this.log.error("Unknown DataChannel error on ".concat(s),Object.assign(Object.assign({},this.logContext),{event:i}))},this.handleBufferedAmountLow=i=>{const s=i.currentTarget.maxRetransmits===0?ae.LOSSY:ae.RELIABLE;this.updateAndEmitDCBufferStatus(s)},this.handleDisconnect=(i,r)=>{if(this._isClosed)return;this.log.warn("".concat(i," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const s=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(U.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){s(a);return}i===wc&&(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=Je.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,r)=>{this.pcState===Ut.Connected&&i();const s=()=>{this.off(U.Disconnected,a),i()},a=()=>{this.off(U.Restarted,s),r()};this.once(U.Restarted,s),this.once(U.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{const r=this.isBufferStatusLow(i);typeof r<"u"&&r!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,r),this.emit(U.DCBufferStatusChanged,r,i))},this.isBufferStatusLow=i=>{const r=this.dataChannelForKind(i);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===be.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ki.RR_SIGNAL_DISCONNECTED))},this.log=rn((t=e.loggerName)!==null&&t!==void 0?t:Mt.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new dc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new ut,this.dataProcessLock=new ut,this.dcBufferStatus=new Map([[ae.LOSSY,!0],[ae.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(U.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(U.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(U.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(U.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(U.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(U.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(U.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(U.SignalRequestResponse,i)}get logContext(){var e,t,i,r,s,a,o,c;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(r=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.room)===null||r===void 0?void 0:r.sid,participant:(a=(s=this.latestJoinResponse)===null||s===void 0?void 0:s.participant)===null||a===void 0?void 0:a.identity,pID:(c=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||c===void 0?void 0:c.sid}}join(e,t,i,r){return y(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const s=yield this.client.join(e,t,i,r);return this._isClosed=!1,this.latestJoinResponse=s,this.subscriberPrimary=s.subscriberPrimary,this.pcManager||(yield this.configure(s)),(!this.subscriberPrimary||s.fastPublish)&&this.negotiate(),this.clientConfiguration=s.clientConfiguration,setTimeout(()=>{this.emit(U.SignalConnected)},10),s}catch(s){if(s instanceof me&&s.reason===se.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,i,r);throw s}})}close(){return y(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(U.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return y(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0})}cleanupClient(){return y(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new sn("a track with the same ID has already been published");return new Promise((t,i)=>{const r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(new me("publication of local track timed out, no response from server",se.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),t(s)},reject:()=>{clearTimeout(r),i(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return y(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 y(this,void 0,void 0,function*(){var t,i;if(this.pcManager&&this.pcManager.currentState!==Re.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const r=this.makeRTCConfiguration(e);this.pcManager=new kC(r,e.subscriberPrimary,this.loggerOptions),this.emit(U.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,a)=>{this.client.sendIceCandidate(s,a)},this.pcManager.onPublisherOffer=s=>{this.client.sendOffer(s)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,a,o)=>y(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s),this.logContext),["closed","disconnected","failed"].includes(a)&&(this.publisherConnectionPromise=void 0),s===Re.CONNECTED){const u=this.pcState===Ut.New;this.pcState=Ut.Connected,u&&this.emit(U.Connected,e)}else s===Re.FAILED&&this.pcState===Ut.Connected&&(this.pcState=Ut.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?ki.RR_SUBSCRIBER_FAILED:ki.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===be.RECONNECTING,l=[Re.FAILED,Re.CLOSING,Re.CLOSED].includes(s);c&&l&&!this._isClosed&&this.emit(U.Offline)}),this.pcManager.onTrack=s=>{this.emit(U.MediaTrackAdded,s.track,s.streams[0],s.receiver)},UC((i=e.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>y(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=>y(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:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(U.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(U.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(U.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(U.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.emit(U.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 wi.DISCONNECT:this.emit(U.Disconnected,e==null?void 0:e.reason),this.close();break;case wi.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(wc);break;case wi.RESUME:this.handleDisconnect(wc)}}}makeRTCConfiguration(e){var t;const i=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){const r=[];e.iceServers.forEach(s=>{const a={urls:s.urls};s.username&&(a.username=s.username),s.credential&&(a.credential=s.credential),r.push(a)}),i.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===or.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(Ff,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(jf,{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,i){return y(this,void 0,void 0,function*(){if(Jo())return yield this.createTransceiverRTCRtpSender(e,t,i);if(Qo())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Ge("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,r){return y(this,void 0,void 0,function*(){if(Jo())return this.createSimulcastTransceiverSender(e,t,i,r);if(Qo())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Ge("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ge("publisher is closed");const r=[];e.mediaStream&&r.push(e.mediaStream),Ii(e)&&(e.codec=t.videoCodec);const s={direction:"sendonly",streams:r};return i&&(s.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,i,r){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ge("publisher is closed");const s={direction:"sendonly"};r&&(s.sendEncodings=r);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ge("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return y(this,void 0,void 0,function*(){var t,i,r;if(!this._isClosed){if(this.attemptingReconnect){re.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===or.DISABLED||((r=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&r!==void 0?r:Re.NEW)===Re.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let a=!0;s instanceof Ge?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:s})),a=!1):s instanceof Ai||(this.fullReconnectOnNext=!0),a?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(U.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 y(this,void 0,void 0,function*(){var t,i,r;try{if(!this.url||!this.token)throw new Ge("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(U.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let s;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Ai;s=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof me&&a.reason===se.NotAllowed?new Ge("could not reconnect, token might be expired"):new Ai}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(U.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==be.CONNECTED)throw new Ai("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(U.Restarted)}catch(s){const a=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(r=this.regionUrlProvider)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return y(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new Ge("could not reconnect, url or token not saved");if(!this.pcManager)throw new Ge("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(U.Resuming);let i;try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(r){let s="";throw r instanceof Error&&(s=r.message,this.log.error(r.message,Object.assign(Object.assign({},this.logContext),{error:r}))),r instanceof me&&r.reason===se.NotAllowed?new Ge("could not reconnect, token might be expired"):r instanceof me&&r.reason===se.LeaveRequest?r:new Ai(s)}if(this.emit(U.SignalResumed),i){const r=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(r)}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!==be.CONNECTED)throw new Ai("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(U.Resumed)})}waitForPCInitialConnection(e,t){return y(this,void 0,void 0,function*(){if(!this.pcManager)throw new Ge("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return y(this,void 0,void 0,function*(){this.pcState=Ut.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield ft(LC),!this.pcManager)throw new Ge("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Ut.Connected}catch(e){throw this.pcState=Ut.Disconnected,new me("could not establish PC connection, ".concat(e.message),se.InternalError)}})}publishRpcResponse(e,t,i,r){return y(this,void 0,void 0,function*(){const s=new ht({destinationIdentities:[e],kind:ae.RELIABLE,value:{case:"rpcResponse",value:new Wd({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(s,ae.RELIABLE)})}publishRpcAck(e,t){return y(this,void 0,void 0,function*(){const i=new ht({destinationIdentities:[e],kind:ae.RELIABLE,value:{case:"rpcAck",value:new Hd({requestId:t})}});yield this.sendDataPacket(i,ae.RELIABLE)})}sendDataPacket(e,t){return y(this,void 0,void 0,function*(){const i=e.toBinary();yield this.ensurePublisherConnected(t);const r=this.dataChannelForKind(t);r&&r.send(i),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,i)=>y(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const r=()=>i("Engine closed");for(this.once(U.Closing,r);!this.dcBufferStatus.get(e);)yield ft(10);this.off(U.Closing,r),t()}}))}ensureDataTransportConnected(e){return y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var s;if(!i.pcManager)throw new Ge("PC manager is closed");const a=r?i.pcManager.subscriber:i.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw new me("".concat(o," connection not set"),se.InternalError);let c=!1;!r&&!i.dataChannelForKind(t,r)&&(i.createDataChannels(),c=!0),!c&&!r&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate();const l=i.dataChannelForKind(t,r);if((l==null?void 0:l.readyState)==="open")return;const u=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<u;){if(a.isICEConnected&&((s=i.dataChannelForKind(t,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield ft(50)}throw new me("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()),se.InternalError)}()})}ensurePublisherConnected(e){return y(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Re.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return y(this,void 0,void 0,function*(){return new Promise((e,t)=>y(this,void 0,void 0,function*(){if(!this.pcManager){t(new Ho("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,r=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(U.Closing,r),this.pcManager.publisher.once(Oi.RTPVideoPayloadTypes,s=>{const a=new Map;s.forEach(o=>{const c=o.codec.toLowerCase();qS(c)&&a.set(o.payload,c)}),this.emit(U.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(s){s instanceof Ho&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ki.RR_UNKNOWN),t(s)}finally{this.off(U.Closing,r)}}))})}dataChannelForKind(e,t){if(t){if(e===ae.LOSSY)return this.lossyDCSub;if(e===ae.RELIABLE)return this.reliableDCSub}else{if(e===ae.LOSSY)return this.lossyDC;if(e===ae.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,r;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const s=this.pcManager.subscriber.getLocalDescription(),a=this.pcManager.subscriber.getRemoteDescription(),o=(r=(i=this.signalOpts)===null||i===void 0?void 0:i.autoSubscribe)!==null&&r!==void 0?r:!0,c=new Array,l=new Array;e.forEach(u=>{u.isDesired!==o&&c.push(u.trackSid),u.isEnabled||l.push(u.trackSid)}),this.client.sendSyncState(new lh({answer:s?Xs({sdp:s.sdp,type:s.type}):void 0,offer:a?Xs({sdp:a.sdp,type:a.type}):void 0,subscription:new Ms({trackSids:c,subscribe:!o,participantTracks:[]}),publishTracks:tC(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,r)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new uh({label:i.label,id:i.id,target:r}))};return t(this.dataChannelForKind(ae.LOSSY),Nt.PUBLISHER),t(this.dataChannelForKind(ae.RELIABLE),Nt.PUBLISHER),t(this.dataChannelForKind(ae.LOSSY,!0),Nt.SUBSCRIBER),t(this.dataChannelForKind(ae.RELIABLE,!0),Nt.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Je.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){pt()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){pt()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Ai extends Error{}function UC(n){return n!==void 0&&n>13}function BC(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}class xc{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 ec(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return y(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(i=>!this.attemptedRegions.find(r=>r.url===i.url));if(t.length>0){const i=t[0];return this.attemptedRegions.push(i),re.debug("next region: ".concat(i.region)),i.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return y(this,void 0,void 0,function*(){const t=yield fetch("".concat(FC(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const i=yield t.json();return this.lastUpdateAt=Date.now(),i}else throw new me("Could not fetch region settings: ".concat(t.statusText),t.status===401?se.NotAllowed:se.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function FC(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class Vf{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class jC extends Vf{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>y(this,void 0,void 0,function*(){try{const{done:t,value:i}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch{return{done:!0,value:void 0}}}),return(){return y(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return y(this,void 0,void 0,function*(){var e,t,i,r;let s=new Set;try{for(var a=!0,o=On(this),c;c=yield o.next(),e=c.done,!e;a=!0){r=c.value,a=!1;const l=r;s.add(l)}}catch(l){t={error:l}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return Array.from(s)})}}class VC extends Vf{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=$s(e.chunkIndex),r=this.receivedChunks.get(i);if(r&&r.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;const s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,s)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>y(this,void 0,void 0,function*(){try{const{done:i,value:r}=yield e.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(r),{done:!1,value:t.decode(r.content)})}catch{return{done:!0,value:void 0}}}),return(){return y(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return y(this,void 0,void 0,function*(){var e,t,i,r;let s="";try{for(var a=!0,o=On(this),c;c=yield o.next(),e=c.done,!e;a=!0)r=c.value,a=!1,s+=r}catch(l){t={error:l}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return s})}}class Gf{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return y(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 GC extends Gf{}class zC extends Gf{}class zf extends I{constructor(e,t,i,r,s){super(e,i,s),this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?D.Muted:D.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(D.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return y(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(),Tc)),nC()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:r,rtpTimestamp:s}=i;s&&this.rtpTimestamp!==s&&(this.emit(D.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}}class HC extends zf{constructor(e,t,i,r,s,a){super(e,t,I.Kind.Audio,i,a),this.monitorReceiver=()=>y(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=Js(o,this.prevStats)),this.prevStats=o}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Xt()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Xt())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return y(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Zo(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Zo(e)&&e.setSinkId(this.sinkId).catch(i=>{this.log.error("Failed to set sink id on remote audio track",i,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{i.connect(r),i=r}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(D.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(D.AudioPlaybackFailed,r)})}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 y(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(i=>{i.type==="inbound-rtp"&&(t={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}}const _c=100;class WC extends zf{constructor(e,t,i,r,s){super(e,t,I.Kind.Video,i,s),this.elementInfos=[],this.monitorReceiver=()=>y(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=Js(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=gc(()=>{this.updateDimensions()},_c),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Ei(this._mediaStreamTrack,t):_i(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 qC(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return y(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(i=s.codecId,t={type:"video",streamId:s.id,framesDecoded:s.framesDecoded,framesDropped:s.framesDropped,framesReceived:s.framesReceived,packetsReceived:s.packetsReceived,packetsLost:s.packetsLost,frameWidth:s.frameWidth,frameHeight:s.frameHeight,pliCount:s.pliCount,firCount:s.firCount,nackCount:s.nackCount,jitter:s.jitter,timestamp:s.timestamp,bytesReceived:s.bytesReceived,decoderImplementation:s.decoderImplementation}):s.type==="codec"&&r.set(s.id,s)}),t&&i!==""&&r.get(i)&&(t.mimeType=r.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return y(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const i=this.elementInfos.reduce((o,c)=>Math.max(o,c.visibilityChangedAt||0),0),r=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,s=this.elementInfos.some(o=>o.pictureInPicture),a=this.elementInfos.some(o=>o.visible)&&!r||s;if(this.lastVisible!==a){if(!a&&Date.now()-i<_c){Je.setTimeout(()=>{this.updateVisibility()},_c);return}this.lastVisible=a,this.emit(D.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let i=0,r=0;const s=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*s,c=a.height()*s;o+c>i+r&&(i=o,r=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===r||(this.lastDimensions={width:i,height:r},this.emit(D.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?uf():t||(uf()>2?2:1)}}class qC{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var r;const{target:s,isIntersecting:a}=i;s===this.element&&(this.isIntersecting=a,this.isPiP=pr(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var i,r,s;(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),this.isPiP=pr(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=pr(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??Ec(e),this.isPiP=pt()&&pr(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Ec(this.element),this.isPiP=pr(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,hf().observe(this.element),df().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,r,s;(e=hf())===null||e===void 0||e.unobserve(this.element),(t=df())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(s=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||s===void 0||s.removeEventListener("pagehide",this.onLeavePiP)}}function pr(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Ec(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Ec(n,e){const t=e||window;let i=n.offsetTop,r=n.offsetLeft;const s=n.offsetWidth,a=n.offsetHeight,{hidden:o}=n,{display:c}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,r+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&r<t.pageXOffset+t.innerWidth&&i+a>t.pageYOffset&&r+s>t.pageXOffset&&!o&&c!=="none"}class on extends Yt.EventEmitter{constructor(e,t,i,r){var s;super(),this.metadataMuted=!1,this.encryption=vt.NONE,this.log=re,this.handleMuted=()=>{this.emit(D.Muted)},this.handleUnmuted=()=>{this.emit(D.Unmuted)},this.log=rn((s=r==null?void 0:r.loggerName)!==null&&s!==void 0?s:Mt.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=I.Source.Unknown}setTrack(e){this.track&&(this.track.off(D.Muted,this.handleMuted),this.track.off(D.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(D.Muted,this.handleMuted),e.on(D.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),ue(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==vt.NONE}get audioTrack(){if(an(this.track))return this.track}get videoTrack(){if(Ii(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=I.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===I.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={}))})(on||(on={}));class Rc extends on{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(D.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(D.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(D.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 y(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return y(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return y(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return y(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(an(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(At.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(At.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(At.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(At.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(At.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(At.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function ta(n,e){return y(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:r,optionsWithoutProcessor:s}=yf(n);let a=s.audio,o=s.video;if(i&&typeof s.audio=="object"&&(s.audio.processor=i),r&&typeof s.video=="object"&&(s.video.processor=r),n.audio&&typeof s.audio=="object"&&typeof s.audio.deviceId=="string"){const d=s.audio.deviceId;s.audio.deviceId={exact:d},t=!0,a=Object.assign(Object.assign({},s.audio),{deviceId:{ideal:d}})}if(s.video&&typeof s.video=="object"&&typeof s.video.deviceId=="string"){const d=s.video.deviceId;s.video.deviceId={exact:d},t=!0,o=Object.assign(Object.assign({},s.video),{deviceId:{ideal:d}})}(s.audio===!0||typeof s.audio=="object"&&!s.audio.deviceId)&&(s.audio={deviceId:"default"}),s.video===!0?s.video={deviceId:"default"}:typeof s.video=="object"&&!s.video.deviceId&&(s.video.deviceId="default");const c=mf(s,Pf,If),l=lc(c),u=navigator.mediaDevices.getUserMedia(l);s.audio&&(He.userMediaPromiseMap.set("audioinput",u),u.catch(()=>He.userMediaPromiseMap.delete("audioinput"))),s.video&&(He.userMediaPromiseMap.set("videoinput",u),u.catch(()=>He.userMediaPromiseMap.delete("videoinput")));try{const d=yield u;return yield Promise.all(d.getTracks().map(h=>y(this,void 0,void 0,function*(){const f=h.kind==="audio";let m=f?c.audio:c.video;(typeof m=="boolean"||!m)&&(m={});let p;const v=f?l.audio:l.video;typeof v!="boolean"&&(p=v);const b=h.getSettings().deviceId;p!=null&&p.deviceId&&Dn(p.deviceId)!==b?p.deviceId=b:p||(p={deviceId:b});const C=CC(h,p,e);return C.kind===I.Kind.Video?C.source=I.Source.Camera:C.kind===I.Kind.Audio&&(C.source=I.Source.Microphone),C.mediaStream=d,an(C)&&i?yield C.setProcessor(i):Ii(C)&&r&&(yield C.setProcessor(r)),C})))}catch(d){if(!t)throw d;return ta(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function KC(n){return y(this,void 0,void 0,function*(){return(yield ta({audio:!1,video:n??!0}))[0]})}function $C(n){return y(this,void 0,void 0,function*(){return(yield ta({audio:n??!0,video:!1}))[0]})}var Fn;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(Fn||(Fn={}));function YC(n){switch(n){case ar.EXCELLENT:return Fn.Excellent;case ar.GOOD:return Fn.Good;case ar.POOR:return Fn.Poor;case ar.LOST:return Fn.Lost;default:return Fn.Unknown}}class Hf extends Yt.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===Ns.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Si.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,r,s,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Ns.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Fn.Unknown,this.log=re,this.log=rn((c=a==null?void 0:a.loggerName)!==null&&c!==void 0?c:Mt.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=s??{}}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 rc,this.once(j.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(I.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(I.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(I.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===Si.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Si.ACTIVE&&this.emit(j.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(j.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(j.ParticipantNameChanged,e)}_setAttributes(e){const t=iC(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(j.AttributesChanged,t)}setPermissions(e){var t,i,r,s,a,o;const c=this.permissions,l=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,d)=>{var h;return u!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[d])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,l&&this.emit(j.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(j.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=YC(e),t!==this._connectionQuality&&this.emit(j.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=>an(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(D.Muted,()=>{this.emit(j.TrackMuted,e)}),e.on(D.Unmuted,()=>{this.emit(j.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case I.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case I.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function XC(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new oh({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}const Wf=15e3;class JC extends Hf{constructor(e,t,i,r,s){super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=vt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new rc)},this.handleReconnected=()=>{var a,o;(o=(a=this.reconnectFuture)===null||a===void 0?void 0:a.resolve)===null||o===void 0||o.call(a),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var a,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(c=>this.log.warn(c.message,this.logContext)),(o=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||o===void 0||o.call(a,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=a=>{const{requestId:o,reason:c,message:l}=a,u=this.pendingSignalRequests.get(o);u&&(c!==Ao.OK&&u.reject(new nf(l,c)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let o=a.value.value,c=null,l=null;o.value.case==="payload"?c=o.value.value:o.value.case==="error"&&(l=Pe.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,c,l);break;case"rpcAck":let u=a.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(a=>XC(a)))},this.onTrackUnmuted=a=>{this.onTrackMuted(a,a.isUpstreamPaused)},this.onTrackMuted=(a,o)=>{if(o===void 0&&(o=!0),!a.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),ue(a)));return}this.engine.updateMuteStatus(a.sid,o)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),ue(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),ue(a))),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{const o=this.audioTrackPublications.get(a.sid);if(!o){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(a.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.handleSubscribedQualityUpdate=a=>y(this,void 0,void 0,function*(){var o,c,l,u,d,h;if(!(!((d=this.roomOptions)===null||d===void 0)&&d.dynacast))return;const f=this.videoTrackPublications.get(a.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}if(a.subscribedCodecs.length>0){if(!f.videoTrack)return;const b=yield f.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var m=!0,p=On(b),v;v=yield p.next(),o=v.done,!o;m=!0){u=v.value,m=!1;const C=u;LS(C)&&(this.log.debug("publish ".concat(C," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),ue(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,C,f.options))}}catch(C){c={error:C}}finally{try{!m&&!o&&(l=p.return)&&(yield l.call(p))}finally{if(c)throw c.error}}}else a.subscribedQualities.length>0&&(yield(h=f.videoTrack)===null||h===void 0?void 0:h.setPublishingLayers(a.subscribedQualities))}),this.handleLocalTrackUnpublished=a=>{const o=this.trackPublications.get(a.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=a=>y(this,void 0,void 0,function*(){if(a.source===I.Source.ScreenShare||a.source===I.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),ue(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(Zn(a)||Un(a))try{if(pt())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:a.source===I.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),Object.assign(Object.assign({},this.logContext),ue(a))),o.onchange=()=>{o.state!=="denied"&&(a.isMuted||a.restartTrack(),o.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}a.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),ue(a))),Zn(a)?yield a.restartTrack({deviceId:"default"}):yield a.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),ue(a))),yield a.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=r,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==vt.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(U.RemoteMute,(t,i)=>{const r=this.trackPublications.get(t);!r||!r.track||(i?r.mute():r.unmute())}),this.engine.on(U.Connected,this.handleReconnected).on(U.SignalRestarted,this.handleReconnected).on(U.SignalResumed,this.handleReconnected).on(U.Restarting,this.handleReconnecting).on(U.Resuming,this.handleReconnecting).on(U.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(U.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(U.Disconnected,this.handleDisconnected).on(U.SignalRequestResponse,this.handleSignalRequestResponse).on(U.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return y(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return y(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return y(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return y(this,arguments,void 0,function(t){var i=this;let{metadata:r,name:s,attributes:a}=t;return function*(){return new Promise((o,c)=>y(i,void 0,void 0,function*(){var l,u;try{let d=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((l=r??this.metadata)!==null&&l!==void 0?l:"",(u=s??this.name)!==null&&u!==void 0?u:"",a),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:m=>{c(m),d=!0},values:{name:s,metadata:r,attributes:a}});performance.now()-f<5e3&&!d;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!a||Object.entries(a).every(m=>{let[p,v]=m;return this.attributes[p]===v||v===""&&!this.attributes[p]}))){this.pendingSignalRequests.delete(h),o();return}yield ft(50)}c(new nf("Request to update local metadata timed out","TimeoutError"))}catch(d){d instanceof Error&&c(d)}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(I.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(I.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(I.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(j.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return y(this,void 0,void 0,function*(){this.encryptionType=e?vt.GCM:vt.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,r){return y(this,void 0,void 0,function*(){var s,a;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let c;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case I.Source.Camera:c=yield this.createTracks({video:(s=i)!==null&&s!==void 0?s:!0});break;case I.Source.Microphone:c=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case I.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new sn(e)}}catch(l){throw c==null||c.forEach(u=>{u.stop()}),l instanceof Error&&this.emit(j.MediaDevicesError,l),this.pendingPublishing.delete(e),l}try{const l=[];for(const d of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),ue(d))),l.push(this.publishTrack(d,r));[o]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(u=>{u.stop()}),l}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===I.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(I.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return y(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(I.Source.Camera)||this.pendingPublishing.has(I.Source.Microphone))){this.pendingPublishing.add(I.Source.Camera),this.pendingPublishing.add(I.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(I.Source.Camera),this.pendingPublishing.delete(I.Source.Microphone)}}})}createTracks(e){return y(this,void 0,void 0,function*(){var t,i;e??(e={});const r=mf(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield ta(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(an(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=I.Source.Microphone,this.emit(j.AudioStreamAcquired)),Ii(o)&&(this.cameraError=void 0,o.source=I.Source.Camera),o))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return y(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new zo("getDisplayMedia not supported");e.resolution===void 0&&!VS()&&(e.resolution=Xo.h1080fps30.resolution);const t=eC(e),i=yield navigator.mediaDevices.getDisplayMedia(t),r=i.getVideoTracks();if(r.length===0)throw new sn("no video track found");const s=new ea(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=I.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);const a=[s];if(i.getAudioTracks().length>0){this.emit(j.AudioStreamAcquired);const o=new Qs(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=I.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return y(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return y(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,c,l,u;Zn(i)&&i.setAudioContext(s.audioContext),yield(o=s.reconnectFuture)===null||o===void 0?void 0:o.promise,s.republishPromise&&!a&&(yield s.republishPromise),Pi(i)&&s.pendingPublishPromises.has(i)&&(yield s.pendingPublishPromises.get(i));let d;if(i instanceof MediaStreamTrack)d=i.getConstraints();else{d=i.constraints;let b;switch(i.source){case I.Source.Microphone:b="audioinput";break;case I.Source.Camera:b="videoinput"}b&&s.activeDeviceMap.has(b)&&(d=Object.assign(Object.assign({},d),{deviceId:s.activeDeviceMap.get(b)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new Qs(i,d,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":i=new ea(i,d,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new sn("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let h;if(s.trackPublications.forEach(b=>{b.track&&b.track===i&&(h=b)}),h)return s.log.warn("track has already been published, skipping",Object.assign(Object.assign({},s.logContext),ue(h))),h;const f="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.mediaStreamTrack.getConstraints().channelCount===2,m=(c=r==null?void 0:r.forceStereo)!==null&&c!==void 0?c:f;m&&(r||(r={}),r.dtx===void 0&&s.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},s.logContext),ue(i))),r.red===void 0&&s.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=r.dtx)!==null&&l!==void 0||(r.dtx=!1),(u=r.red)!==null&&u!==void 0||(r.red=!1));const p=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r);!GS()&&s.roomOptions.e2ee&&(s.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({},s.logContext)),p.simulcast=!1),p.source&&(i.source=p.source);const v=new Promise((b,C)=>y(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==be.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:ue(i)}));const x=()=>y(this,void 0,void 0,function*(){try{const k=yield this.publish(i,p,m);b(k)}catch(k){C(k)}});setTimeout(()=>{this.engine.off(U.SignalConnected,x),C(new Wo("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(U.SignalConnected,x),this.engine.on(U.Closing,()=>{this.engine.off(U.SignalConnected,x),C(new Wo("publishing rejected as engine closed",499))})}else try{const x=yield this.publish(i,p,m);b(x)}catch(x){C(x)}}catch(x){C(x)}}));s.pendingPublishPromises.set(i,v);try{return yield v}catch(b){throw b}finally{s.pendingPublishPromises.delete(i)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),ue(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(r=>rC(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),ue(e))),!1)}publish(e,t,i){return y(this,void 0,void 0,function*(){var r,s,a,o,c,l,u,d,h,f;if(!this.hasPermissionsToPublish(e))throw new Wo("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(S=>Pi(e)&&S.source===e.source)&&e.source!==I.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),ue(e))),t.stopMicTrackOnMute&&an(e)&&(e.stopOnMute=!0),e.source===I.Source.ScreenShare&&Ri()&&(t.simulcast=!1),t.videoCodec==="av1"&&!BS()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!FS()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=vc),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(S=>t.videoCodec===Ys(S.mime))||(t.videoCodec=Ys(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(D.Muted,this.onTrackMuted),e.on(D.Unmuted,this.onTrackUnmuted),e.on(D.Ended,this.handleTrackEnded),e.on(D.UpstreamPaused,this.onTrackUpstreamPaused),e.on(D.UpstreamResumed,this.onTrackUpstreamResumed),e.on(D.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=new Eo({cid:e.mediaStreamTrack.id,name:t.name,type:I.kindToProto(e.kind),muted:e.isMuted,source:I.sourceToProto(e.source),disableDtx:!(!((r=t.dtx)!==null&&r!==void 0)||r),encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(!((s=t.red)!==null&&s!==void 0)||s),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy});let b;if(e.kind===I.Kind.Video){let S={width:0,height:0};try{S=yield e.waitForDimensions()}catch{const E=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:ur.h720.resolution;S={width:E.width,height:E.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),ue(e)),{dims:S}))}v.width=S.width,v.height=S.height,Un(e)&&(dr(p)&&(e.source===I.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),ue(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),v.simulcastCodecs=[new _o({codec:p,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:vc}),t.backupCodec&&p!==t.backupCodec.codec&&v.encryption===vt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new _o({codec:t.backupCodec.codec,cid:""})))),b=Sc(e.source===I.Source.ScreenShare,v.width,v.height,t),v.layers=Bf(v.width,v.height,b,dr(t.videoCodec))}else e.kind===I.Kind.Audio&&(b=[{maxBitrate:(l=t.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(d=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&d!==void 0?d:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new Ge("cannot publish track when not connected");const C=()=>y(this,void 0,void 0,function*(){var S,w,E;if(!this.engine.pcManager)throw new Ge("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),Un(e)&&((S=t.degradationPreference)!==null&&S!==void 0||(t.degradationPreference=NC(e)),e.setDegradationPreference(t.degradationPreference)),b)if(Ri()&&e.kind===I.Kind.Audio){let A;for(const O of this.engine.pcManager.publisher.getTransceivers())if(O.sender===e.sender){A=O;break}A&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:A,codec:"opus",maxbr:!((w=b[0])===null||w===void 0)&&w.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&dr(e.codec)&&(!((E=b[0])===null||E===void 0)&&E.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let x;if(this.enabledPublishVideoCodecs.length>0)x=(yield Promise.all([this.engine.addTrack(v),C()]))[0];else{x=yield this.engine.addTrack(v);let S;if(x.codecs.forEach(w=>{S===void 0&&(S=w.mimeType)}),S&&e.kind===I.Kind.Video){const w=Ys(S);w!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),ue(e)),{codec:w})),t.videoCodec=w,b=Sc(e.source===I.Source.ScreenShare,v.width,v.height,t))}yield C()}const k=new Rc(e.kind,x,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return k.options=t,e.sid=x.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:x})),Un(e)?e.startMonitor(this.engine.client):Zn(e)&&e.startMonitor(),this.addTrackPublication(k),this.emit(j.LocalTrackPublished,k),k})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return y(this,void 0,void 0,function*(){var r;if(this.encryptionType!==vt.NONE)return;let s;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(s=f)}),!s)throw new sn("track is not published");if(!Un(e))throw new sn("track is not a video track");const a=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),i),o=IC(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),ue(e)));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const l=new Eo({cid:c.mediaStreamTrack.id,type:I.kindToProto(e.kind),muted:e.isMuted,source:I.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=Bf(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new Ge("cannot publish track when not connected");const u=()=>y(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:h}))})}unpublishTrack(e,t){return y(this,void 0,void 0,function*(){var i,r;if(Pi(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),ue(e))),yield l)}const s=this.getPublicationForTrack(e),a=s?ue(s):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!s||!s.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));return}e=s.track,e.off(D.Muted,this.onTrackMuted),e.off(D.Unmuted,this.onTrackUnmuted),e.off(D.Ended,this.handleTrackEnded),e.off(D.UpstreamPaused,this.onTrackUpstreamPaused),e.off(D.UpstreamResumed,this.onTrackUpstreamResumed),e.off(D.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(r=(i=this.roomOptions)===null||i===void 0?void 0:i.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),t?e.stop():e.stopMonitor();let o=!1;const c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Re.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),Un(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(o=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:l}))}switch(this.trackPublications.delete(s.trackSid),s.kind){case I.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case I.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(j.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return y(this,void 0,void 0,function*(){return(yield Promise.all(e.map(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Promise((s,a)=>y(i,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),o.push(c))}),yield Promise.all(o.map(c=>y(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),r&&!l.isMuted&&l.source!==I.Source.ScreenShare&&l.source!==I.Source.ScreenShareAudio&&(Zn(l)||Un(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),s()}catch(o){a(o)}finally{this.republishPromise=void 0}})),yield i.republishPromise}()})}publishData(e){return y(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const s=r.reliable?ae.RELIABLE:ae.LOSSY,a=r.destinationIdentities,o=r.topic,c=new ht({kind:s,value:{case:"user",value:new Vd({participantIdentity:i.identity,payload:t,destinationIdentities:a,topic:o})}});yield i.engine.sendDataPacket(c,s)}()})}publishDtmf(e,t){return y(this,void 0,void 0,function*(){const i=new ht({kind:ae.RELIABLE,value:{case:"sipDtmf",value:new Gd({code:e,digit:t})}});yield this.engine.sendDataPacket(i,ae.RELIABLE)})}sendChatMessage(e,t){return y(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},r=new ht({value:{case:"chatMessage",value:new To(Object.assign(Object.assign({},i),{timestamp:we.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(r,ae.RELIABLE),this.emit(j.ChatMessage,i),i})}editChatMessage(e,t){return y(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new ht({value:{case:"chatMessage",value:new To(Object.assign(Object.assign({},i),{timestamp:we.parse(i.timestamp),editTimestamp:we.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,ae.RELIABLE),this.emit(j.ChatMessage,i),i})}sendText(e,t){return y(this,void 0,void 0,function*(){var i;const r=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(i=t==null?void 0:t.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(o?o.length+1:1).fill(0),l=(d,h)=>{var f;c[h]=d;const m=c.reduce((p,v)=>p+v,0);(f=t==null?void 0:t.onProgress)===null||f===void 0||f.call(t,m)},u=yield this.streamText({streamId:r,totalSize:a,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),l(1,0),yield u.close(),t!=null&&t.attachments&&o&&(yield Promise.all(t.attachments.map((d,h)=>y(this,void 0,void 0,function*(){return this._sendFile(o[h],d,{topic:t.topic,mimeType:d.type,onProgress:f=>{l(f,h+1)}})})))),u.info})}streamText(e){return y(this,void 0,void 0,function*(){var t,i;const r=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),s={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},a=new So({streamId:r,mimeType:s.mimeType,topic:s.topic,timestamp:Qn(s.timestamp),totalLength:Qn(e==null?void 0:e.totalSize),attributes:s.attributes,contentHeader:{case:"textHeader",value:new Zd({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"?ko.UPDATE:ko.CREATE})}}),o=e==null?void 0:e.destinationIdentities,c=new ht({destinationIdentities:o,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(c,ae.RELIABLE);let l=0;const u=this,d=new WritableStream({write(m){return y(this,void 0,void 0,function*(){for(const p of QS(m,Wf)){yield u.engine.waitForBufferStatusLow(ae.RELIABLE);const v=new Co({content:p,streamId:r,chunkIndex:Qn(l)}),b=new ht({destinationIdentities:o,value:{case:"streamChunk",value:v}});yield u.engine.sendDataPacket(b,ae.RELIABLE),l+=1}})},close(){return y(this,void 0,void 0,function*(){const m=new wo({streamId:r}),p=new ht({destinationIdentities:o,value:{case:"streamTrailer",value:m}});yield u.engine.sendDataPacket(p,ae.RELIABLE)})},abort(m){console.log("Sink error:",m)}});let h=()=>y(this,void 0,void 0,function*(){yield f.close()});u.engine.once(U.Closing,h);const f=new GC(d,s,()=>this.engine.off(U.Closing,h));return f})}sendFile(e,t){return y(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return y(this,void 0,void 0,function*(){var r;const s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(r=i==null?void 0:i.mimeType)!==null&&r!==void 0?r:t.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.destinationIdentities}),a=t.stream().getReader();for(;;){const{done:o,value:c}=yield a.read();if(o)break;yield s.write(c)}return yield s.close(),s.info})}streamBytes(e){return y(this,void 0,void 0,function*(){var t,i,r,s,a;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),c=e==null?void 0:e.destinationIdentities,l={id:o,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"application/octet-stream",topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(s=e==null?void 0:e.name)!==null&&s!==void 0?s:"unknown"},u=new So({totalLength:Qn((a=l.size)!==null&&a!==void 0?a:0),mimeType:l.mimeType,streamId:o,topic:l.topic,timestamp:Qn(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new eh({name:l.name})}}),d=new ht({destinationIdentities:c,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(d,ae.RELIABLE);let h=0;const f=new ut,m=this.engine,p=this.log,v=new WritableStream({write(C){return y(this,void 0,void 0,function*(){const x=yield f.lock();let k=0;try{for(;k<C.byteLength;){const S=C.slice(k,k+Wf);yield m.waitForBufferStatusLow(ae.RELIABLE);const w=new ht({destinationIdentities:c,value:{case:"streamChunk",value:new Co({content:S,streamId:o,chunkIndex:Qn(h)})}});yield m.sendDataPacket(w,ae.RELIABLE),h+=1,k+=S.byteLength}}finally{x()}})},close(){return y(this,void 0,void 0,function*(){const C=new wo({streamId:o}),x=new ht({destinationIdentities:c,value:{case:"streamTrailer",value:C}});yield m.sendDataPacket(x,ae.RELIABLE)})},abort(C){p.error("Sink error:",C)}});return new zC(v,l)})}performRpc(e){return y(this,arguments,void 0,function(t){var i=this;let{destinationIdentity:r,method:s,payload:a,responseTimeout:o=1e4}=t;return function*(){return new Promise((l,u)=>y(i,void 0,void 0,function*(){var d,h,f,m;if(yc(a)>Of){u(Pe.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((h=(d=this.engine.latestJoinResponse)===null||d===void 0?void 0:d.serverInfo)===null||h===void 0)&&h.version&&Jn((m=(f=this.engine.latestJoinResponse)===null||f===void 0?void 0:f.serverInfo)===null||m===void 0?void 0:m.version,"1.8.0")<0){u(Pe.builtIn("UNSUPPORTED_SERVER"));return}const p=crypto.randomUUID();yield this.publishRpcRequest(r,p,s,a,o-2e3);const v=setTimeout(()=>{this.pendingAcks.delete(p),u(Pe.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(p),clearTimeout(b)},2e3);this.pendingAcks.set(p,{resolve:()=>{clearTimeout(v)},participantIdentity:r});const b=setTimeout(()=>{this.pendingResponses.delete(p),u(Pe.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(p,{resolve:(C,x)=>{clearTimeout(b),this.pendingAcks.has(p)&&(console.warn("RPC response received before ack",p),this.pendingAcks.delete(p),clearTimeout(v)),x?u(x):l(C??"")},participantIdentity:r})}))}()})}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,i){const r=this.pendingResponses.get(e);r?(r.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,r,s){return y(this,void 0,void 0,function*(){const a=new ht({destinationIdentities:[e],kind:ae.RELIABLE,value:{case:"rpcRequest",value:new zd({id:t,method:i,payload:r,responseTimeoutMs:s,version:1})}});yield this.engine.sendDataPacket(a,ae.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:r}]of this.pendingResponses)i===e&&(r(null,Pe.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var i,r;const s=this.trackPublications.get(t.sid);if(s){const a=s.isMuted||((r=(i=s.track)===null||i===void 0?void 0:i.isUpstreamPaused)!==null&&r!==void 0?r:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),ue(s)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const r=i.track;r&&(e instanceof MediaStreamTrack?(Zn(r)||Un(r))&&r.mediaStreamTrack===e&&(t=i):e===r&&(t=i))}),t}waitForPendingPublicationOfSource(e){return y(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const r=Array.from(this.pendingPublishPromises.entries()).find(s=>{let[a]=s;return a.source===e});if(r)return r[1];yield ft(20)}})}}class QC extends on{constructor(e,t,i,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Ct.HIGH,this.handleEnded=s=>{this.setTrack(void 0),this.emit(D.Ended,s)},this.handleVisibilityChange=s=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(s),this.logContext),this.disabled=!s,this.emitTrackUpdate()},this.handleVideoDimensionsChange=s=>{this.log.debug("adaptivestream video dimensions ".concat(s.width,"x").concat(s.height),this.logContext),this.videoDimensions=s,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const r=new Ms({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Kd({participantSid:"",trackSids:[this.trackSid]})]});this.emit(D.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?on.SubscriptionStatus.Unsubscribed:super.isSubscribed?on.SubscriptionStatus.Subscribed:on.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?on.PermissionStatus.Allowed:on.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,i;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.videoDimensions)===null||i===void 0?void 0:i.height)===e.height||(oc(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&oc(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(D.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(D.VisibilityChanged,this.handleVisibilityChange),r.off(D.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(D.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(D.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(D.VisibilityChanged,this.handleVisibilityChange),e.on(D.Ended,this.handleEnded),this.emit(D.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(D.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?D.Muted:D.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(D.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(D.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===I.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 oc(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new nh({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=Ct.HIGH,this.emit(D.UpdateSettings,e)}}class na extends Hf{static fromParticipantInfo(e,t,i){return new na(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,r,s,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ns.STANDARD;super(t,i||"",r,s,a,o,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(D.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),ue(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(D.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(D.SubscriptionPermissionChanged,t=>{this.emit(j.TrackSubscriptionPermissionChanged,e,t)}),e.on(D.SubscriptionStatusChanged,t=>{this.emit(j.TrackSubscriptionStatusChanged,e,t)}),e.on(D.Subscribed,t=>{this.emit(j.TrackSubscribed,t,e)}),e.on(D.Unsubscribed,t=>{this.emit(j.TrackUnsubscribed,t,e)}),e.on(D.SubscriptionFailed,t=>{this.emit(j.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]:I.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:I.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,r,s,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(u=>{!o&&e.kind===u.kind.toString()&&(o=u)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(j.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,r,s,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),ue(o))),this.emit(j.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let l;return c?l=new WC(e,t,r,s):l=new HC(e,t,r,this.audioContext,this.audioOutput),l.source=o.source,l.isMuted=o.isMuted,l.setMediaStream(i),l.start(),o.setTrack(l),this.volumeMap.has(o.source)&&ac(l)&&an(l)&&l.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach(r=>{var s,a;let o=this.getTrackPublicationBySid(r.sid);if(o)o.updateInfo(r);else{const c=I.kindFromProto(r.type);if(!c)return;o=new QC(c,r,(s=this.signalClient.connectOptions)===null||s===void 0?void 0:s.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(r),i.set(r.sid,o);const l=Array.from(this.trackPublications.values()).find(u=>u.source===(o==null?void 0:o.source));l&&o.source!==I.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:ue(l),newTrack:ue(o)})),this.addTrackPublication(o)}t.set(r.sid,o)}),this.trackPublications.forEach(r=>{t.has(r.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),ue(r))),this.unpublishTrack(r.trackSid,!0))}),i.forEach(r=>{this.emit(j.TrackPublished,r)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:r}=i;switch(r&&(r.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case I.Kind.Audio:this.audioTrackPublications.delete(e);break;case I.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(j.TrackUnpublished,i)}setAudioOutput(e){return y(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var r;an(i.track)&&ac(i.track)&&t.push(i.track.setSinkId((r=e.deviceId)!==null&&r!==void 0?r:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var ce;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(ce||(ce={}));const ZC=4*1e3;class Ni extends Yt.EventEmitter{constructor(e){var t,i,r,s;if(super(),t=this,this.state=ce.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=re,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=(a,o,c)=>y(this,void 0,void 0,function*(){var l;if(!jS())throw Xt()?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===ce.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(ce.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==a&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ec(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new xc(a,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(f=>{var m;(m=this.regionUrlProvider)===null||m===void 0||m.setServerReportedRegions(f)}).catch(f=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:f}))}));const d=(f,m,p)=>y(this,void 0,void 0,function*(){var v,b;this.abortController&&this.abortController.abort();const C=new AbortController;this.abortController=C,u==null||u();try{yield this.attemptConnection(p??a,o,c,C),this.abortController=void 0,f()}catch(x){if(this.regionUrlProvider&&x instanceof me&&x.reason!==se.Cancelled&&x.reason!==se.NotAllowed){let k=null;try{k=yield this.regionUrlProvider.getNextBestRegionUrl((v=this.abortController)===null||v===void 0?void 0:v.signal)}catch(S){if(S instanceof me&&(S.status===401||S.reason===se.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),m(S);return}}k&&!(!((b=this.abortController)===null||b===void 0)&&b.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(x.message,". Retrying with another region: ").concat(k),this.logContext),this.recreateEngine(),yield d(f,m,k)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,pf(x)),m(x))}else{let k=Ot.UNKNOWN_REASON;x instanceof me&&(k=pf(x)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,k),m(x)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new rc((f,m)=>{d(f,m,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,o,c,l,u,d)=>y(this,void 0,void 0,function*(){var h,f,m;const p=yield c.join(a,o,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},d.signal);let v=p.serverInfo;if(v||(v={version:p.serverVersion,region:p.serverRegion}),this.serverInfo=v,this.log.debug("connected to Livekit Server ".concat(Object.entries(v).map(b=>{let[C,x]=b;return"".concat(C,": ").concat(x)}).join(", ")),{room:(h=p.room)===null||h===void 0?void 0:h.name,roomSid:(f=p.room)===null||f===void 0?void 0:f.sid,identity:(m=p.participant)===null||m===void 0?void 0:m.identity}),!v.version)throw new xS("unknown server version");return v.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),p}),this.applyJoinResponse=a=>{const o=a.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(a.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(a.sifTrailer)}catch(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([o,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,o,c,l)=>y(this,void 0,void 0,function*(){var u,d;this.state===ce.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(),!((d=this.regionUrlProvider)===null||d===void 0)&&d.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},bc),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(a,o,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(M.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new me("could not establish signal connection",se.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof me&&(f.reason=h.reason,f.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),f}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new me("Connection attempt aborted",se.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}pt()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),pt()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ce.Connected),this.emit(M.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var a=arguments.length,o=new Array(a),c=0;c<a;c++)o[c]=arguments[c];return y(t,[...o],void 0,function(){var l=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var d,h,f,m;const p=yield l.disconnectLock.lock();try{if(l.state===ce.Disconnected){l.log.debug("already disconnected",l.logContext);return}l.log.info("disconnect from room",Object.assign({},l.logContext)),(l.state===ce.Connecting||l.state===ce.Reconnecting||l.isResuming)&&(l.log.warn("abort connection attempt",l.logContext),(d=l.abortController)===null||d===void 0||d.abort(),(f=(h=l.connectFuture)===null||h===void 0?void 0:h.reject)===null||f===void 0||f.call(h,new me("Client initiated disconnect",se.Cancelled)),l.connectFuture=void 0),!((m=l.engine)===null||m===void 0)&&m.client.isDisconnected||(yield l.engine.client.sendLeave()),l.engine&&(yield l.engine.close()),l.handleDisconnect(u,Ot.CLIENT_INITIATED),l.engine=void 0}finally{p()}}()})},this.onPageLeave=()=>y(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>y(this,void 0,void 0,function*(){const a=[],o=Lt();if(o&&o.os==="iOS"){const c="livekit-dummy-audio-el";let l=document.getElementById(c);if(!l){l=document.createElement("audio"),l.id=c,l.autoplay=!0,l.hidden=!0;const u=ic();u.enabled=!0;const d=new MediaStream([u]);l.srcObject=d,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:d,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(M.Disconnected,()=>{l==null||l.remove(),l=null})}a.push(l)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(u=>{a.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>y(this,void 0,void 0,function*(){const a=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(c=>{var l;(l=c.track)===null||l===void 0||l.attachedElements.forEach(u=>{a.includes(u)||a.push(u)})});yield Promise.all(a.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 a of this.remoteParticipants.values())this.handleParticipantDisconnected(a.identity,a);this.setAndEmitConnectionState(ce.Reconnecting)&&this.emit(M.Reconnecting)},this.handleSignalRestarted=a=>y(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(a.serverRegion),Object.assign(Object.assign({},this.logContext),{region:a.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(a);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:a.serverRegion}))}catch{return}this.setAndEmitConnectionState(ce.Connected),this.emit(M.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(o=>{var c;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(c=this.sidToIdentity.get(o.sid))!==null&&c!==void 0?c:"");let l=this.remoteParticipants.get(o.identity);o.state===Si.DISCONNECTED?this.handleParticipantDisconnected(o.identity,l):l=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=a=>{const o=[],c={};a.forEach(l=>{if(c[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(l.sid);u&&(u.audioLevel=l.level,u.setIsSpeaking(!0),o.push(u))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{c[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(M.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=a=>{const o=new Map;this.activeSpeakers.forEach(l=>{const u=this.remoteParticipants.get(l.identity);u&&u.sid!==l.sid||o.set(l.sid,l)}),a.forEach(l=>{let u=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=l.level,u.setIsSpeaking(l.active),l.active?o.set(l.sid,u):o.delete(l.sid))});const c=Array.from(o.values());c.sort((l,u)=>u.audioLevel-l.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(M.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(o=>{const c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(o.trackSid);if(!l||!l.track)return;const u=I.streamStateFromProto(o.state);u!==l.track.streamState&&(l.track.streamState=u,c.emit(j.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(M.TrackStreamStateChanged,l,l.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=a=>{const o=this.getRemoteParticipantBySid(a.participantSid);if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const o=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(a.trackSid));if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.setSubscriptionError(a.err)},this.handleDataPacket=a=>{const o=this.remoteParticipants.get(a.participantIdentity);if(a.value.case==="user")this.handleUserPacket(o,a.value.value,a.kind);else if(a.value.case==="transcription")this.handleTranscription(o,a.value.value);else if(a.value.case==="sipDtmf")this.handleSipDtmf(o,a.value.value);else if(a.value.case==="chatMessage")this.handleChatMessage(o,a.value.value);else if(a.value.case==="metrics")this.handleMetrics(a.value.value,o);else if(a.value.case==="streamHeader")this.handleStreamHeader(a.value.value,a.participantIdentity);else if(a.value.case==="streamChunk")this.handleStreamChunk(a.value.value);else if(a.value.case==="streamTrailer")this.handleStreamTrailer(a.value.value);else if(a.value.case==="rpcRequest"){const c=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(a,o,c)=>{this.emit(M.DataReceived,o.payload,a,c,o.topic),a==null||a.emit(j.DataReceived,o.payload,c)},this.handleSipDtmf=(a,o)=>{this.emit(M.SipDTMFReceived,o,a),a==null||a.emit(j.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(a,o)=>{const c=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),l=c==null?void 0:c.trackPublications.get(o.trackId),u=$S(o,this.transcriptionReceivedTimes);l==null||l.emit(D.TranscriptionReceived,u),c==null||c.emit(j.TranscriptionReceived,u,l),this.emit(M.TranscriptionReceived,u,c,l)},this.handleChatMessage=(a,o)=>{const c=YS(o);this.emit(M.ChatMessage,c,a)},this.handleMetrics=(a,o)=>{this.emit(M.MetricsReceived,a,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(M.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=a=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:a})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(M.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(M.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(M.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>y(this,void 0,void 0,function*(){var a,o,c;const l=He.getInstance().previousDevices,u=yield He.getInstance().getDevices(void 0,!1),d=Lt();if((d==null?void 0:d.name)==="Chrome"&&d.os!=="iOS")for(let f of u){const m=l.find(p=>p.deviceId===f.deviceId);m&&m.label!==""&&m.kind===f.kind&&m.label!==f.label&&this.getActiveDevice(f.kind)==="default"&&this.emit(M.ActiveDeviceChanged,f.kind,f.deviceId)}const h=["audiooutput","audioinput","videoinput"];for(let f of h){const m=ZS(f),p=this.localParticipant.getTrackPublication(m);if(p&&(!((a=p.track)===null||a===void 0)&&a.isUserProvided))continue;const v=u.filter(C=>C.kind===f),b=this.getActiveDevice(f);if(b===((o=l.filter(C=>C.kind===f)[0])===null||o===void 0?void 0:o.deviceId)&&v.length>0&&((c=v[0])===null||c===void 0?void 0:c.deviceId)!==b){yield this.switchActiveDevice(f,v[0].deviceId);continue}f==="audioinput"&&!Ln()||f==="videoinput"||v.length>0&&!v.find(C=>C.deviceId===this.getActiveDevice(f))&&(yield this.switchActiveDevice(f,v[0].deviceId))}this.emit(M.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const o=this.roomInfo;this.roomInfo=a,o&&o.metadata!==a.metadata&&this.emitWhenConnected(M.RoomMetadataChanged,a.metadata),(o==null?void 0:o.activeRecording)!==a.activeRecording&&this.emitWhenConnected(M.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>{a.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const c=this.getRemoteParticipantBySid(o.participantSid);c&&c.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=a=>{this.emit(M.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(M.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(M.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(M.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(M.TrackUnmuted,a,this.localParticipant)},this.onTrackProcessorUpdate=a=>{var o;(o=a==null?void 0:a.onPublish)===null||o===void 0||o.call(a,this)},this.onLocalTrackPublished=a=>y(this,void 0,void 0,function*(){var o,c,l,u,d,h;(o=a.track)===null||o===void 0||o.on(D.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.on(D.Restarted,this.onLocalTrackRestarted),(d=(u=(l=a.track)===null||l===void 0?void 0:l.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||d===void 0||d.call(u,this),this.emit(M.LocalTrackPublished,a,this.localParticipant),Zn(a.track)&&(yield a.track.checkForSilence())&&this.emit(M.LocalAudioSilenceDetected,a);const f=yield(h=a.track)===null||h===void 0?void 0:h.getDeviceId(!1),m=bf(a.source);m&&f&&f!==this.localParticipant.activeDeviceMap.get(m)&&(this.localParticipant.activeDeviceMap.set(m,f),this.emit(M.ActiveDeviceChanged,m,f))}),this.onLocalTrackUnpublished=a=>{var o,c;(o=a.track)===null||o===void 0||o.off(D.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.off(D.Restarted,this.onLocalTrackRestarted),this.emit(M.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>y(this,void 0,void 0,function*(){const o=yield a.getDeviceId(!1),c=bf(a.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,o),this.emit(M.ActiveDeviceChanged,c,o))}),this.onLocalConnectionQualityChanged=a=>{this.emit(M.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=a=>{this.emit(M.MediaDevicesError,a)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(M.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(M.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},TC),e),this.log=rn((i=this.options.loggerName)!==null&&i!==void 0?i:Mt.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Pf),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},If),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},yC),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new ut,this.localParticipant=new JC("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Dn(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Dn(this.options.audioCaptureDefaults.deviceId)),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&this.switchActiveDevice("audiooutput",Dn(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),pt()){const a=new AbortController;(s=navigator.mediaDevices)===null||s===void 0||s.addEventListener("devicechange",this.handleDeviceChange,{signal:a.signal}),Ni.cleanupRegistry&&Ni.cleanupRegistry.register(this,()=>{a.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,i,r,s,a){return y(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,Pe.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,Pe.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const u=yield o({requestId:t,callerIdentity:e,payload:r,responseTimeout:s});yc(u)>Of?(c=Pe.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):l=u}catch(u){u instanceof Pe?c=u:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),u),c=Pe.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,l,c)})}setE2EEEnabled(e){return y(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 sC(this.options.e2ee),this.e2eeManager.on(Nn.ParticipantEncryptionStatusChanged,(t,i)=>{JS(i)&&(this.isE2EEEnabled=t),this.emit(M.ParticipantEncryptionStatusChanged,t,i)}),this.e2eeManager.on(Nn.EncryptionError,t=>this.emit(M.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 y(this,void 0,void 0,function*(){return this.state===ce.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const i=r=>{r.sid!==""&&(this.engine.off(U.RoomUpdate,i),e(r.sid))};this.engine.on(U.RoomUpdate,i),this.once(M.Disconnected,()=>{this.engine.off(U.RoomUpdate,i),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 DC(this.options),this.engine.on(U.ParticipantUpdate,this.handleParticipantUpdates).on(U.RoomUpdate,this.handleRoomUpdate).on(U.SpeakersChanged,this.handleSpeakersChanged).on(U.StreamStateChanged,this.handleStreamStateUpdate).on(U.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(U.SubscriptionError,this.handleSubscriptionError).on(U.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(U.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(U.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(U.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(U.DataPacketReceived,this.handleDataPacket).on(U.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ce.SignalReconnecting)&&this.emit(M.SignalReconnecting)}).on(U.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ce.Connected)&&this.emit(M.Reconnected)}).on(U.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ce.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(U.Restarting,this.handleRestarting).on(U.SignalRestarted,this.handleSignalRestarted).on(U.Offline,()=>{this.setAndEmitConnectionState(ce.Reconnecting)&&this.emit(M.Reconnecting)}).on(U.DCBufferStatusChanged,(e,t)=>{this.emit(M.DCBufferStatusChanged,e,t)}).on(U.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:r}=i;return r===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(j.LocalTrackSubscribed,t),this.emitWhenConnected(M.LocalTrackSubscribed,t,this.localParticipant)}).on(U.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,i)=>{this.handleParticipantDisconnected(i,t)}),this.emit(M.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 He.getInstance().getDevices(e,t)}prepareConnection(e,t){return y(this,void 0,void 0,function*(){if(this.state===ce.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(ec(new URL(e))&&t){this.regionUrlProvider=new xc(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===ce.Disconnected&&(this.regionUrl=i,yield fetch(sc(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(sc(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return y(this,void 0,void 0,function*(){let i=()=>{},r;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":r=new $t({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new $t({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new $t({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new $t({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>y(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new $t({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>y(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new $t({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":r=new $t({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>y(this,void 0,void 0,function*(){const s=this.engine.client.onLeave;s&&s(new Ls({reason:Ot.CLIENT_INITIATED,action:wi.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new $t({scenario:{case:"subscriberBandwidth",value:Qn(t)}});break;case"leave-full-reconnect":r=new $t({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield i())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return y(this,arguments,void 0,function(i,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,c,l,u,d,h,f,m;let p=!0,v=!1;const b=a?{exact:r}:r;if(i==="audioinput"){v=s.localParticipant.audioTrackPublications.size===0;const C=(o=s.getActiveDevice(i))!==null&&o!==void 0?o:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=b;const x=Array.from(s.localParticipant.audioTrackPublications.values()).filter(k=>k.source===I.Source.Microphone);try{p=(yield Promise.all(x.map(k=>{var S;return(S=k.audioTrack)===null||S===void 0?void 0:S.setDeviceId(b)}))).every(k=>k===!0)}catch(k){throw s.options.audioCaptureDefaults.deviceId=C,k}}else if(i==="videoinput"){v=s.localParticipant.videoTrackPublications.size===0;const C=(c=s.getActiveDevice(i))!==null&&c!==void 0?c:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=b;const x=Array.from(s.localParticipant.videoTrackPublications.values()).filter(k=>k.source===I.Source.Camera);try{p=(yield Promise.all(x.map(k=>{var S;return(S=k.videoTrack)===null||S===void 0?void 0:S.setDeviceId(b)}))).every(k=>k===!0)}catch(k){throw s.options.videoCaptureDefaults.deviceId=C,k}}else if(i==="audiooutput"){if(!Zo()&&!s.options.webAudioMix||s.options.webAudioMix&&s.audioContext&&!("setSinkId"in s.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");s.options.webAudioMix&&(r=(l=yield He.getInstance().normalizeDeviceId("audiooutput",r))!==null&&l!==void 0?l:""),(u=(m=s.options).audioOutput)!==null&&u!==void 0||(m.audioOutput={});const C=(d=s.getActiveDevice(i))!==null&&d!==void 0?d:s.options.audioOutput.deviceId;s.options.audioOutput.deviceId=r;try{s.options.webAudioMix&&((h=s.audioContext)===null||h===void 0||h.setSinkId(r)),yield Promise.all(Array.from(s.remoteParticipants.values()).map(x=>x.setAudioOutput({deviceId:r})))}catch(x){throw s.options.audioOutput.deviceId=C,x}}return(v||i==="audiooutput")&&(s.localParticipant.activeDeviceMap.set(i,i==="audiooutput"&&((f=s.options.audioOutput)===null||f===void 0?void 0:f.deviceId)||r),s.emit(M.ActiveDeviceChanged,i,r)),p}()})}setupLocalParticipantEvents(){this.localParticipant.on(j.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(j.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(j.AttributesChanged,this.onLocalAttributesChanged).on(j.TrackMuted,this.onLocalTrackMuted).on(j.TrackUnmuted,this.onLocalTrackUnmuted).on(j.LocalTrackPublished,this.onLocalTrackPublished).on(j.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(j.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(j.MediaDevicesError,this.onMediaDevicesError).on(j.AudioStreamAcquired,this.startAudio).on(j.ChatMessage,this.onLocalChatMessageSent).on(j.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){if(this.state===ce.Connecting||this.state===ce.Reconnecting){const u=()=>{this.onTrackAdded(e,t,i),d()},d=()=>{this.off(M.Reconnected,u),this.off(M.Connected,u),this.off(M.Disconnected,d)};this.once(M.Reconnected,u),this.once(M.Connected,u),this.once(M.Disconnected,d);return}if(this.state===ce.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 r=US(t.id),s=r[0];let a=r[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===s);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={}),c.addSubscribedMediaTrack(e,o,t,i,l)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==ce.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{r.unpublishTrack(s.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var s,a,o;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((s=r.track)===null||s===void 0||s.detach(),(a=r.track)===null||a===void 0||a.stop()):(o=r.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(j.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(j.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(j.AttributesChanged,this.onLocalAttributesChanged).off(j.TrackMuted,this.onLocalTrackMuted).off(j.TrackUnmuted,this.onLocalTrackUnmuted).off(j.LocalTrackPublished,this.onLocalTrackPublished).off(j.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(j.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(j.MediaDevicesError,this.onMediaDevicesError).off(j.AudioStreamAcquired,this.startAudio).off(j.ChatMessage,this.onLocalChatMessageSent).off(j.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),pt()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(i=navigator.mediaDevices)===null||i===void 0||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ce.Disconnected),this.emit(M.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(r=>{t.unpublishTrack(r.trackSid,!0)}),this.emit(M.ParticipantDisconnected,t),t.setDisconnected(),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return y(this,void 0,void 0,function*(){var i;if(e.contentHeader.case==="byteHeader"){const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let s;const a={id:e.streamId,name:(i=e.contentHeader.value.name)!==null&&i!==void 0?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:$s(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:c=>{s=c,this.byteStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now()})}});r(new jC(a,o,$s(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let s;const a={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:c=>{s=c,this.textStreamControllers.set(e.streamId,{info:a,controller:s,startTime:Date.now()})}});r(new VC(a,o,$s(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.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 i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return y(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=vf())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),ft(200)])}catch(r){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:r}))}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(M.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let r;return t?r=na.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):r=new na(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&r.setAudioOutput(this.options.audioOutput).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),r}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const r=this.remoteParticipants.get(e);return t&&r.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),r}const i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(M.ParticipantConnected,i),i.on(j.TrackPublished,r=>{this.emitWhenConnected(M.TrackPublished,r,i)}).on(j.TrackSubscribed,(r,s)=>{r.kind===I.Kind.Audio?(r.on(D.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(D.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===I.Kind.Video&&(r.on(D.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(D.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(M.TrackSubscribed,r,s,i)}).on(j.TrackUnpublished,r=>{this.emit(M.TrackUnpublished,r,i)}).on(j.TrackUnsubscribed,(r,s)=>{this.emit(M.TrackUnsubscribed,r,s,i)}).on(j.TrackMuted,r=>{this.emitWhenConnected(M.TrackMuted,r,i)}).on(j.TrackUnmuted,r=>{this.emitWhenConnected(M.TrackUnmuted,r,i)}).on(j.ParticipantMetadataChanged,r=>{this.emitWhenConnected(M.ParticipantMetadataChanged,r,i)}).on(j.ParticipantNameChanged,r=>{this.emitWhenConnected(M.ParticipantNameChanged,r,i)}).on(j.AttributesChanged,r=>{this.emitWhenConnected(M.ParticipantAttributesChanged,r,i)}).on(j.ConnectionQualityChanged,r=>{this.emitWhenConnected(M.ConnectionQualityChanged,r,i)}).on(j.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(M.ParticipantPermissionsChanged,r,i)}).on(j.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(M.TrackSubscriptionStatusChanged,r,s,i)}).on(j.TrackSubscriptionFailed,(r,s)=>{this.emit(M.TrackSubscriptionFailed,r,i,s)}).on(j.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(M.TrackSubscriptionPermissionChanged,r,s,i)}).on(j.Active,()=>{this.emitWhenConnected(M.ParticipantActive,i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,r)=>(i.push(...r.getTrackPublications()),i),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&XS(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=Je.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,Ot.STATE_MISMATCH))):e=0},ZC)}clearConnectionReconcile(){this.connectionReconcileInterval&&Je.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(M.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(this.state===ce.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===ce.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return y(this,void 0,void 0,function*(){var t,i;const r=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),s=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Os({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:we.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Kn({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(M.SignalConnected),this.emit(M.Connected),this.setAndEmitConnectionState(ce.Connected),r.video){const a=new Rc(I.Kind.Video,new Ci({source:Ue.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:It.AUDIO,name:"video-dummy"}),new ea(r.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:ff(160*((t=s.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(a),this.localParticipant.emit(j.LocalTrackPublished,a)}if(r.audio){const a=new Rc(I.Kind.Audio,new Ci({source:Ue.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:It.AUDIO}),new Qs(r.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:ic(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit(j.LocalTrackPublished,a)}for(let a=0;a<s.count-1;a+=1){let o=new Kn({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:Si.ACTIVE,tracks:[],joinedAt:we.parse(Date.now())});const c=this.getOrCreateParticipant(o.identity,o);if(s.video){const l=ff(160*((i=s.aspectRatios[a%s.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),u=new Ci({source:Ue.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:It.AUDIO});c.addSubscribedMediaTrack(l,u.sid,new MediaStream([l]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}if(s.audio){const l=ic(),u=new Ci({source:Ue.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:It.AUDIO});c.addSubscribedMediaTrack(l,u.sid,new MediaStream([l]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}c.updateInfo(o)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];if(e!==M.ActiveSpeakersChanged&&e!==M.TranscriptionReceived){const s=qf(i).filter(a=>a!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:s}))}return super.emit(e,...i)}}Ni.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function qf(n){return n.map(e=>{if(e)return Array.isArray(e)?qf(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Bt;(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"})(Bt||(Bt={}));class jn extends Yt.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Bt.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Ni(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return y(this,void 0,void 0,function*(){if(this.status!==Bt.IDLE)throw Error("check is running already");this.setStatus(Bt.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!==Bt.SKIPPED&&this.setStatus(this.isSuccess()?Bt.SUCCESS:Bt.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return y(this,void 0,void 0,function*(){return this.room.state===ce.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return y(this,void 0,void 0,function*(){this.room&&this.room.state!==ce.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Bt.SKIPPED)}switchProtocol(e){return y(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(M.Reconnecting,()=>{t=!0}),this.room.once(M.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!t)return;const r=Date.now()+1e4;for(;Date.now()<r;){if(i)return;yield ft(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 e1 extends jn{get description(){return"Cloud regions"}perform(){return y(this,void 0,void 0,function*(){const e=new xc(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let s=0;s<3;s++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((s,a)=>(s.duration-a.duration)*.5+(s.rtt-a.rtt)*.5);const r=t[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return y(this,void 0,void 0,function*(){var t,i;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const r=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!r)throw new Error("Region not found");const s=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,c=1e6/a,l="A".repeat(a),u=Date.now();for(let m=0;m<c;m++)yield s.write(l);yield s.close();const d=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:r,rtt:1e4,duration:d-u};return h==null||h.forEach(m=>{m.type==="candidate-pair"&&m.nominated&&(f.rtt=m.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const Pc=1e4;class t1 extends jn{get description(){return"Connection via UDP vs TCP"}perform(){return y(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(Pc/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Pc/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return y(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let r=0;const s=()=>{r=(r+1)%360,i.fillStyle="hsl(".concat(r,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(s)};s();const o=t.captureStream(30).getVideoTracks()[0],l=(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},d=setInterval(()=>y(this,void 0,void 0,function*(){const h=yield l.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(u.packetsSent=f.packetsSent,u.qualityLimitationDurations=f.qualityLimitationDurations,u.bitrateTotal+=f.targetBitrate,u.count++):f.type==="remote-inbound-rtp"&&(u.packetsLost=f.packetsLost,u.rttTotal+=f.roundTripTime,u.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Pc)),clearInterval(d),o.stop(),t.remove(),yield this.disconnect(),u})}}class n1 extends jn{get description(){return"Can publish audio"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield $C();if(yield gf(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));const s=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let a=0;if(s.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class i1 extends jn{get description(){return"Can publish video"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield KC();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));const r=yield(e=i.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(s+=a.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," video packets"))})}checkForVideo(e){return y(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const i=document.createElement("video");i.srcObject=t,i.muted=!0,yield new Promise(r=>{i.onplay=()=>{setTimeout(()=>{var s,a,o,c;const l=document.createElement("canvas"),u=e.getSettings(),d=(a=(s=u.width)!==null&&s!==void 0?s:i.videoWidth)!==null&&a!==void 0?a:1280,h=(c=(o=u.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&c!==void 0?c:720;l.width=d,l.height=h;const f=l.getContext("2d");f.drawImage(i,0,0);const p=f.getImageData(0,0,l.width,l.height).data;let v=!0;for(let b=0;b<p.length;b+=4)if(p[b]!==0||p[b+1]!==0||p[b+2]!==0){v=!1;break}v?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},i.play()}),i.remove()})}}class r1 extends jn{get description(){return"Resuming connection after interruption"}perform(){return y(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,r=!1,s;const a=new Promise(l=>{setTimeout(l,5e3),s=l}),o=()=>{i=!0};t.on(M.SignalReconnecting,o).on(M.Reconnecting,o).on(M.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield a,i){if(!r||t.state!==ce.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 s1 extends jn{get description(){return"Can connect via TURN"}perform(){return y(this,void 0,void 0,function*(){var e,t;const i=new dc,r=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let s=!1,a=!1,o=!1;for(let c of r.iceServers)for(let l of c.urls)l.startsWith("turn:")?(a=!0,o=!0):l.startsWith("turns:")&&(a=!0,o=!0,s=!0),l.startsWith("stun:")&&(o=!0);o?a&&!s&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield i.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||a?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(c=>setTimeout(c,0)))})}}class a1 extends jn{get description(){return"Establishing WebRTC connection"}perform(){return y(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(M.SignalConnected,()=>{const i=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,s)=>{if(r.candidate){const a=new RTCIceCandidate(r);let o="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(o1(a.address)?o+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,o+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(o)}i&&i(r,s)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),re.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function o1(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 c1 extends jn{get description(){return"Connecting to signal connection via WebSocket"}perform(){return y(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new dc;const s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(s.serverVersion,".")),((e=s.serverInfo)===null||e===void 0?void 0:e.edition)===$d.Cloud&&(!((t=s.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=s.serverInfo)===null||i===void 0?void 0:i.region)),yield r.close()})}}class S_ extends Yt.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Bt.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!==Bt.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return y(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),r=a=>{this.updateCheck(t,a)};i.on("update",r);const s=yield i.run();return i.off("update",r),s})}checkWebsocket(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(c1)})}checkWebRTC(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(a1)})}checkTURN(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(s1)})}checkReconnect(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(r1)})}checkPublishAudio(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(n1)})}checkPublishVideo(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(i1)})}checkConnectionProtocol(){return y(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(t1);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return y(this,void 0,void 0,function*(){return this.createAndRunCheck(e1)})}}const l1=/\{[^{}]+\}/g;function u1(){return Math.random().toString(36).slice(2,11)}function d1(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:i=globalThis.fetch,querySerializer:r,bodySerializer:s,headers:a,...o}={...n};e=Xf(e);const c=[];async function l(u,d){const{baseUrl:h,fetch:f=i,Request:m=t,headers:p,params:v={},parseAs:b="json",querySerializer:C,bodySerializer:x=s??f1,body:k,...S}=d||{};h&&(e=Xf(h));let w=typeof r=="function"?r:Yf(r);C&&(w=typeof C=="function"?C:Yf({...typeof r=="object"?r:{},...C}));const E=k===void 0?void 0:x(k),A=E===void 0||E instanceof FormData?{}:{"Content-Type":"application/json"},O={redirect:"follow",...o,...S,body:E,headers:m1(A,a,p,v.header)};let B,L,R=new t(p1(u,{baseUrl:e,params:v,querySerializer:w}),O);for(const X in S)X in R||(R[X]=S[X]);if(c.length){B=u1(),L=Object.freeze({baseUrl:e,fetch:f,parseAs:b,querySerializer:w,bodySerializer:x});for(const X of c)if(X&&typeof X=="object"&&typeof X.onRequest=="function"){const K=await X.onRequest({request:R,schemaPath:u,params:v,options:L,id:B});if(K){if(!(K instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");R=K}}}let H=await f(R);if(c.length)for(let X=c.length-1;X>=0;X--){const K=c[X];if(K&&typeof K=="object"&&typeof K.onResponse=="function"){const ye=await K.onResponse({request:R,response:H,schemaPath:u,params:v,options:L,id:B});if(ye){if(!(ye instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");H=ye}}}if(H.status===204||H.headers.get("Content-Length")==="0")return H.ok?{data:{},response:H}:{error:{},response:H};if(H.ok)return b==="stream"?{data:H.body,response:H}:{data:await H[b](),response:H};let Q=await H.text();try{Q=JSON.parse(Q)}catch{}return{error:Q,response:H}}return{GET(u,d){return l(u,{...d,method:"GET"})},PUT(u,d){return l(u,{...d,method:"PUT"})},POST(u,d){return l(u,{...d,method:"POST"})},DELETE(u,d){return l(u,{...d,method:"DELETE"})},OPTIONS(u,d){return l(u,{...d,method:"OPTIONS"})},HEAD(u,d){return l(u,{...d,method:"HEAD"})},PATCH(u,d){return l(u,{...d,method:"PATCH"})},TRACE(u,d){return l(u,{...d,method:"TRACE"})},use(...u){for(const d of u)if(d){if(typeof d!="object"||!("onRequest"in d||"onResponse"in d))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");c.push(d)}},eject(...u){for(const d of u){const h=c.indexOf(d);h!==-1&&c.splice(h,1)}}}}function ia(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 Kf(n,e,t){if(!e||typeof e!="object")return"";const i=[],r={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(const o in e)i.push(o,t.allowReserved===!0?e[o]:encodeURIComponent(e[o]));const a=i.join(",");switch(t.style){case"form":return`${n}=${a}`;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return a}}for(const a in e){const o=t.style==="deepObject"?`${n}[${a}]`:a;i.push(ia(o,e[a],t))}const s=i.join(r);return t.style==="label"||t.style==="matrix"?`${r}${s}`:s}function $f(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){const s={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",a=(t.allowReserved===!0?e:e.map(o=>encodeURIComponent(o))).join(s);switch(t.style){case"simple":return a;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return`${n}=${a}`}}const i={simple:",",label:".",matrix:";"}[t.style]||"&",r=[];for(const s of e)t.style==="simple"||t.style==="label"?r.push(t.allowReserved===!0?s:encodeURIComponent(s)):r.push(ia(n,s,t));return t.style==="label"||t.style==="matrix"?`${i}${r.join(i)}`:r.join(i)}function Yf(n){return function(t){const i=[];if(t&&typeof t=="object")for(const r in t){const s=t[r];if(s!=null){if(Array.isArray(s)){if(s.length===0)continue;i.push($f(r,s,{style:"form",explode:!0,...n==null?void 0:n.array,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}if(typeof s=="object"){i.push(Kf(r,s,{style:"deepObject",explode:!0,...n==null?void 0:n.object,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}i.push(ia(r,s,n))}}return i.join("&")}}function h1(n,e){let t=n;for(const i of n.match(l1)??[]){let r=i.substring(1,i.length-1),s=!1,a="simple";if(r.endsWith("*")&&(s=!0,r=r.substring(0,r.length-1)),r.startsWith(".")?(a="label",r=r.substring(1)):r.startsWith(";")&&(a="matrix",r=r.substring(1)),!e||e[r]===void 0||e[r]===null)continue;const o=e[r];if(Array.isArray(o)){t=t.replace(i,$f(r,o,{style:a,explode:s}));continue}if(typeof o=="object"){t=t.replace(i,Kf(r,o,{style:a,explode:s}));continue}if(a==="matrix"){t=t.replace(i,`;${ia(r,o)}`);continue}t=t.replace(i,a==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function f1(n){return n instanceof FormData?n:JSON.stringify(n)}function p1(n,e){var r;let t=`${e.baseUrl}${n}`;(r=e.params)!=null&&r.path&&(t=h1(t,e.params.path));let i=e.querySerializer(e.params.query??{});return i.startsWith("?")&&(i=i.substring(1)),i&&(t+=`?${i}`),t}function m1(...n){const e=new Headers;for(const t of n){if(!t||typeof t!="object")continue;const i=t instanceof Headers?t.entries():Object.entries(t);for(const[r,s]of i)if(s===null)e.delete(r);else if(Array.isArray(s))for(const a of s)e.append(r,a);else s!==void 0&&e.set(r,s)}return e}function Xf(n){return n.endsWith("/")?n.substring(0,n.length-1):n}const Jf="Onboardee-Session-Token",Qf="OnboardeeSessionToken";class Zf{constructor(e){this.client=d1({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch}),this.client.use({onRequest({request:t}){if(window.localStorage){const i=window.localStorage.getItem(Qf);i&&t.headers.set(Jf,i)}return t},onResponse({response:t}){const i=t.headers.get(Jf);return i&&window.localStorage&&window.localStorage.setItem(Qf,i),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 listUsers(){return await this.client.GET("/api/users")}async createUser(e){return await this.client.POST("/api/users",{body:e})}async updateUser(e,t){return await this.client.PATCH("/api/users/{id}",{params:{path:{id:e}},body:t})}async deleteUser(e){return await this.client.DELETE("/api/users/{id}",{params:{path:{id:e}}})}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,i,r){return await this.client.GET("/api/products/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...i&&{end_date:i},...r&&{course_id:r}}}})}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 getProductAppToken(e){return await this.client.GET("/api/products/{id}/app-token",{params:{path:{id:e}}})}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:{content:t.content||""}})}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,i){return await this.client.GET("/api/products/{id}/knowledge-blocks/search",{params:{path:{id:e},query:{q:t,...i&&{limit:i.toString()}}}})}async listAudiences(e){return await this.client.GET("/api/products/{id}/audiences",{params:{path:{id:String(e)}}})}async createAudience(e,t){return await this.client.POST("/api/products/{id}/audiences",{params:{path:{id:String(e)}},body:t})}async getAudience(e,t){return await this.client.GET("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:t}}})}async updateAudience(e,t,i){return await this.client.PATCH("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:t}},body:i})}async deleteAudience(e,t){return await this.client.DELETE("/api/products/{id}/audiences/{audienceId}",{params:{path:{id:String(e),audienceId:t}}})}async replaceAudiencePlans(e,t,i){return await this.client.PUT("/api/products/{id}/audiences/{audienceId}/plans",{params:{path:{id:String(e),audienceId:t}},body:{plans:i}})}async updateProductKnowledgeBlock(e,t,i){return await this.client.PATCH("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:i})}async deleteProductKnowledgeBlock(e,t){return await this.client.DELETE("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async listProductPronunciationRules(e){return await this.client.GET("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}}})}async bulkCreateProductPronunciationRules(e,t){return await this.client.POST("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}},body:t})}async bulkUpdateProductPronunciationRules(e,t){return await this.client.PATCH("/api/products/{id}/pronunciation-dictionary",{params:{path:{id:e}},body:t})}async deleteProductPronunciationRule(e,t){return await this.client.DELETE("/api/products/{id}/pronunciation-dictionary/{ruleId}",{params:{path:{id:e,ruleId:t}}})}async listProductExternalKnowledge(e){return await this.client.GET("/api/products/{id}/external-knowledge",{params:{path:{id:e}}})}async createProductExternalKnowledge(e,t){return await this.client.POST("/api/products/{id}/external-knowledge",{params:{path:{id:e}},body:t})}async updateProductExternalKnowledge(e,t,i){return await this.client.PATCH("/api/products/{id}/external-knowledge/{entryId}",{params:{path:{id:e,entryId:t}},body:i})}async deleteProductExternalKnowledge(e,t){return await this.client.DELETE("/api/products/{id}/external-knowledge/{entryId}",{params:{path:{id:e,entryId:t}}})}async refreshProductExternalKnowledge(e,t){return await this.client.POST("/api/products/{id}/external-knowledge/{entryId}/refresh",{params:{path:{id:e,entryId:t}}})}async listExternalKnowledgePages(e,t){return await this.client.GET("/api/products/{id}/external-knowledge/{entryId}/pages",{params:{path:{id:e,entryId: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,i){return await this.client.GET("/api/plans/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...i&&{end_date:i}}}})}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 duplicatePlan(e){return await this.client.POST("/api/plans/{id}/duplicate",{params:{path:{id:e}}})}async listAdminUsers(e){const t={};return e!=null&&e.search&&(t.search=e.search),e!=null&&e.page&&(t.page=e.page),e!=null&&e.limit&&(t.limit=e.limit),await this.client.GET("/api/admin/users",{params:Object.keys(t).length>0?{query:t}:void 0})}async createAdminUser(e){return await this.client.POST("/api/users",{body:e})}async publishPlanRevision(e,t){return await this.client.POST("/api/plans/{id}/publish",{params:{path:{id:e}},body:t})}async getPlanAutosave(e){return await this.client.GET("/api/plans/{id}/autosave",{params:{path:{id:e}}})}async upsertPlanAutosave(e,t,i){return await this.client.PUT("/api/plans/{id}/autosave",{params:{path:{id:e}},body:t,signal:i})}async deletePlanAutosave(e){return await this.client.DELETE("/api/plans/{id}/autosave",{params:{path:{id:e}}})}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,i){return await this.client.PUT("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:i})}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:{content:t.content||""}})}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 listPlanFAQs(e,t=!1){return await this.client.GET("/api/plans/{id}/faqs",{params:{path:{id:e},query:{include_drafts:String(t)}}})}async listPlanDraftFAQs(e){return await this.client.GET("/api/plans/{id}/draft-faqs",{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 listRevisionFAQs(e,t){return await this.client.GET("/api/revisions/{id}/faqs",{params:{path:{id:e},query:{...t!==void 0&&{include_drafts:t.toString()}}}})}async createRevisionFAQ(e,t){return await this.client.POST("/api/revisions/{id}/faqs",{params:{path:{id:e}},body:t})}async updateFAQ(e,t){return await this.client.PUT("/api/faqs/{id}",{params:{path:{id:e}},body:t})}async deleteFAQ(e){return await this.client.DELETE("/api/faqs/{id}",{params:{path:{id:e}}})}async promoteFAQ(e){return await this.client.POST("/api/faqs/{id}/promote",{params:{path:{id:e}}})}async promoteFAQs(e){return await this.client.POST("/api/faqs/promote",{body:{faq_ids:e}})}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,i){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:i})}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 i={token:e};return t!=null&&t.productId&&(i.product_id=t.productId),t!=null&&t.startDate&&(i.start_date=t.startDate),t!=null&&t.endDate&&(i.end_date=t.endDate),await this.client.GET("/api/sessions",{params:{query:i}})}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:i}={}){return await this.client.GET("/api/join-token",{params:{query:{token:e,...t&&{client_type:t},...i&&{user:encodeURIComponent(i)}}}})}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}}})}async getGraphemes(){return await this.client.GET("/api/graphemes")}async listVoices(){return await this.client.GET("/api/voices")}async generateVoiceSample(e,t){return await this.client.POST("/api/voices/generate-sample",{body:{product_id:t,voice_id:e},parseAs:"stream"})}async getFeatureFlags(e){return await this.client.GET("/api/features",{params:e?{query:e}:void 0})}getClient(){return this.client}}const ep="https://app.coragents.ai";class ra extends Pa{constructor(e,t,i,r){super(),this.state=null,this.isPaused=!1,this.isAudioTrackPublished=!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.agentAudioContext=null,this.userAudioContext=null,this.frequencyDataBuffer=null,this.publishedAudioStream=null,this.publishedAudioTrack=null,this.appToken=e,this.planId=t,this.clientType=i,this.api=r.api||new Zf({baseUrl:ep}),this.identity=r.identity||null,this.roomFactory=r.roomFactory||(s=>new Ni(s)),this.captureScreen=r.captureScreen||null}async start(e){this.planId,e==null||e.roomId,this.setState("connecting"),this.speakingStateChanged("thinking");try{const i=(await this.api.clientStartSession(this.appToken,{client_type:this.clientType,onboarding_plan:this.planId,...(e==null?void 0:e.roomId)&&{room_id:e.roomId}})).data;if(!(i!=null&&i.url)||!(i!=null&&i.token)||!(i!=null&&i.room)||!(i!=null&&i.session_uuid))throw new Error("Invalid room info");this.sessionUuid=i==null?void 0:i.session_uuid,this.roomId=i==null?void 0:i.room,this.joinToken=i==null?void 0:i.token,this.roomUrl=i==null?void 0:i.url,this.startedAt=Date.now(),await this.joinRoom(),this.setState("volume-check"),this.planId,this.sessionUuid}catch(t){console.error("[obi] error starting session",{error:t}),this.setState("error")}}async joinRoom({withMicrophone:e=!1,withStateRecovery:t=!1}={}){if(this.room=this.roomFactory({adaptiveStream:!0,dynacast:!0}),this.room.on(M.Disconnected,i=>{if(!this.room)return;let r=null;switch(i){case 12:r="invalid-room";break}this.shutdown(r)}),this.room.on(M.TrackSubscribed,i=>{if(console.info("[obi] track subscribed kind=",i.kind,"source=",i.source),i.kind==="audio"&&(i.attach(),i.source===I.Source.Microphone)){this.agentAnalyser&&(this.agentAnalyser.disconnect(),this.agentAnalyser=null),this.agentAudioContext&&(this.agentAudioContext.close(),this.agentAudioContext=null);const{analyser:r,context:s}=this.createFFT(i.mediaStream);this.agentAnalyser=r,this.agentAudioContext=s}}),this.room.on(M.LocalTrackPublished,i=>{if(console.info("[obi] local track published kind=",i.kind,"source=",i.source),i.kind==="audio"){this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null);const{analyser:r,context:s}=this.createFFT(i.audioTrack.mediaStream);this.userAnalyser=r,this.userAudioContext=s}}),this.room.on(M.ParticipantAttributesChanged,i=>{if(!i["lk.agent.state"])return;const r=i["lk.agent.state"];switch(r){case"speaking":this.speakingStateChanged("speaking");break;case"listening":this.speakingStateChanged("listening");break;case"thinking":this.speakingStateChanged("thinking");break;default:console.warn("[obi] unknown speaking state",r)}}),this.room.on(M.DataReceived,async i=>{try{const r=new TextDecoder().decode(i),s=JSON.parse(r);switch(s.status||s.request||s.type){case"course_progress":typeof s.current_step=="number"&&typeof s.total_steps=="number"&&Array.isArray(s.step_names)&&this.emit("courseProgress",{currentStep:Math.max(1,s.current_step),totalSteps:Math.max(1,s.total_steps),stepNames:s.step_names});break;case"open_text_input":this.emit("textInputRequested");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"in_progress":this.setState("in-progress");break;case"shutdown":this.shutdown("server-sent");break;case"mute_microphone":this.muteMicrophone();break;case"unmute_microphone":this.unmuteMicrophone();break;case"transcript":this.emit("transcript",s.transcript,s.role);break;default:console.warn("[obi] unknown data received",s)}}catch(r){console.error("[obi] error parsing data",r)}}),this.room.localParticipant.registerRpcMethod("mic_check",async i=>(this.sessionUuid,await this.checkMicrophone()?"ok":"error")),this.room.localParticipant.registerRpcMethod("screen_capture",async i=>{if(!this.captureScreen)return console.error("[obi] no captureScreen function provided"),"error";let r=null,s=null;try{r=await this.captureScreen()}catch(a){r=null,a=a}if(!r||s)return console.error("[obi] error capturing screen",{error:s}),"error";try{return await this.room.localParticipant.sendFile(new File([r],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),"ok"}catch(a){return console.error("[obi] error sending screen capture",{error:a}),"error"}}),await this.room.connect(this.roomUrl,this.joinToken),e&&await this.room.localParticipant.setMicrophoneEnabled(!0),t){let i=!1;for(const r of this.room.remoteParticipants.values())r.isSpeaking&&(i=!0);i?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(i){i=i,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 publishAudioTrack(){if(this.sessionUuid,!this.room)return console.error("[obi] cannot publish audio track: room not connected"),!1;let e=!1;try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia){const l=!!navigator.mediaDevices;return console.error("[obi] getUserMedia not available in this environment",l),!1}console.log("[obi] requesting audio track via getUserMedia"),this.publishedAudioStream=await navigator.mediaDevices.getUserMedia({audio:!0});const t=this.publishedAudioStream.getAudioTracks().map(l=>{var u,d;return{id:l.id,label:l.label,enabled:l.enabled,muted:l.muted,readyState:l.readyState,constraints:(u=l.getConstraints)==null?void 0:u.call(l),settings:(d=l.getSettings)==null?void 0:d.call(l)}});console.log("[obi] getUserMedia resolved",t);const i=this.publishedAudioStream.getAudioTracks()[0];if(!i){const l=this.publishedAudioStream.getAudioTracks().length;return console.warn("[obi] no audio track found from getUserMedia stream",l),!1}this.publishedAudioTrack=i;const r={id:i.id,label:i.label,kind:i.kind,readyState:i.readyState},s=this.room.localParticipant.identity;console.log("[obi] publishing audio track to LiveKit",r,s);const a=await this.room.localParticipant.publishTrack(i,{name:"microphone",source:I.Source.Microphone});console.log("[obi] published audio track to LiveKit",i.id,s,a.isEnabled),this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null);const{analyser:o,context:c}=this.createFFT(this.publishedAudioStream);this.userAnalyser=o,this.userAudioContext=c,this.isAudioTrackPublished=!0,e=!0}catch(t){if(console.error("[obi] failed to publish audio track",t),this.isAudioTrackPublished=!1,this.publishedAudioStream){try{this.publishedAudioStream.getTracks().forEach(i=>i.stop())}catch(i){console.warn("[obi] error stopping tracks during cleanup",i)}this.publishedAudioStream=null}this.publishedAudioTrack=null}return e}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,i;e.handleMuted(),(i=(t=e.track)==null?void 0:t.mediaStream)==null||i.getTracks().forEach(r=>r.enabled=!1)})}unmuteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var t,i;e.handleUnmuted(),(i=(t=e.track)==null?void 0:t.mediaStream)==null||i.getTracks().forEach(r=>r.enabled=!0)})}async stop(){this.emit("stopped"),await this.shutdown()}async shutdown(e=null){if(this.room){if(this.sessionUuid,this.publishedAudioTrack&&this.isAudioTrackPublished)try{console.log("[obi] unpublishing audio track",this.publishedAudioTrack.id,this.room.localParticipant.identity),this.room.localParticipant.unpublishTrack(this.publishedAudioTrack)}catch(i){console.warn("[obi] failed to unpublish audio track",i)}if(this.publishedAudioStream)try{const i=this.publishedAudioStream.getAudioTracks().length;console.log("[obi] stopping published audio stream tracks",i),this.publishedAudioStream.getTracks().forEach(r=>r.stop())}catch(i){console.warn("[obi] error stopping published audio tracks",i)}e!=="server-sent"&&await this.sendData({request:"shutdown"});const t=this.room;this.room=null,await t.disconnect(),this.sessionUuid}this.agentAnalyser&&(this.agentAnalyser.disconnect(),this.agentAnalyser=null),this.agentAudioContext&&(this.agentAudioContext.close(),this.agentAudioContext=null),this.userAnalyser&&(this.userAnalyser.disconnect(),this.userAnalyser=null),this.userAudioContext&&(this.userAudioContext.close(),this.userAudioContext=null),this.isAudioTrackPublished=!1,this.publishedAudioStream=null,this.publishedAudioTrack=null,this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.frequencyDataBuffer=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}agentAudioSpectrum(){return this.agentAnalyser?this.normaliseSpectrum(this.agentAnalyser):null}normaliseSpectrum(e){const i=e.context.sampleRate/2/e.frequencyBinCount;(!this.frequencyDataBuffer||this.frequencyDataBuffer.length!==e.frequencyBinCount)&&(this.frequencyDataBuffer=new Uint8Array(new ArrayBuffer(e.frequencyBinCount))),e.getByteFrequencyData(this.frequencyDataBuffer);const r=[],s=50,a=5e3,o=8,c=Math.pow(a/s,1/o);for(let l=0;l<o;l++){const u=s*Math.pow(c,l),d=s*Math.pow(c,l+1),h=Math.floor(u/i),f=Math.floor(d/i),m=Math.min(f,this.frequencyDataBuffer.length),p=Math.min(h,m);if(p<m){let v=0;for(let C=p;C<m;C++)v+=this.frequencyDataBuffer[C];const b=v/(m-p)/255;r.push(b)}else r.push(0)}return r}setState(e){this.state;const t=this.state;this.state=e,this.emit("stateChanged",e,t)}static deserialise(e,t,i,r={}){const s=JSON.parse(e),a=new ra(t,s.planId,i,r);return a.state=s.state,a.speakingState=s.speakingState,a.identity=s.identity||null,a.isPaused=s.isPaused||!1,a.sessionUuid=s.sessionUuid||null,a.roomId=s.roomId||null,a.joinToken=s.joinToken||null,a.roomUrl=s.roomUrl||null,a.startedAt=s.startedAt||null,a}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,i=t.createAnalyser();return t.createMediaStreamSource(e).connect(i),i.fftSize=2048,i.smoothingTimeConstant=.6,{analyser:i,context:t}}}class sa extends Pa{constructor(e,t,i={}){super(),this.state="loading",this.error=null,this.identity=null,this.product=null,this.engagement=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=i.api||new Zf({baseUrl:i.apiBaseUrl||ep}),this.sessionFactory=i.sessionFactory||((r,s,a,o)=>new ra(r,s,a,o)),this.captureScreen=i.captureScreen||null}async initialise(e={}){var t,i,r,s,a,o;if(!this.appToken)throw new Error("App token is required");this.setState("loading");try{const c=await this.api.clientInitialise(this.appToken,{identity:e.identity,client_type:this.clientType});if(this.identity=e.identity||null,this.product=((t=c.data)==null?void 0:t.product)||null,this.plans=((i=c.data)==null?void 0:i.onboarding_plans)||[],this.selectedPlan=((r=c.data)==null?void 0:r.selected_plan)||null,this.planIsCompleted=((s=c.data)==null?void 0:s.plan_is_completed)||[],this.showWidget=((a=c.data)==null?void 0:a.show_widget)||!1,this.engagement=((o=c.data)==null?void 0:o.engagement)||null,e.planUuid){let l=null;try{const u=await this.api.getPlanSDK(e.planUuid);if(u.error)throw new Error(`Plan not found: ${u.error}`);u.data&&(l=u.data)}catch(u){try{const d=await this.api.getSessionPlan(e.planUuid);if(d.error)throw new Error(`Session plan not found: ${d.error}`);d.data&&(l=d.data)}catch(d){console.error("[obi] error getting plan via both endpoints",{planErr:u,sessionErr:d})}}l?(this.selectedPlan=l,this.selectedPlanUuid=e.planUuid):console.warn("[obi] plan not found",{planUuid:e.planUuid})}this.identity,this.product,this.plans,this.selectedPlan,this.showWidget}catch(c){throw this.error=c instanceof Error?c:new Error(String(c)),this.setState("error"),c}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,i){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(i).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,i;return this.state,(t=this.session)==null||t.state,(i=this.session)==null||i.speakingState,this.session.captureScreen=this.captureScreen,this.prepareSession(e),this.session.joinRoom({withMicrophone:!0,withStateRecovery:!0}).then(()=>{this.emit("sessionResumed",this.session)}).catch(r=>{console.error("[obi] error joining room",{error:r}),r instanceof Error&&r.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 i,r,s;if((i=this.session)!=null&&i.startedAt&&this.session.startedAt+5*60*1e3<Date.now()){const a=this.plans.findIndex(o=>{var c;return o.uuid===((c=this.selectedPlan)==null?void 0:c.uuid)});a!==-1&&(this.planIsCompleted[a]=!0)}(s=(r=this.session)==null?void 0:r.removeAllListeners)==null||s.call(r),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,engagement:this.engagement,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,i,r={}){const s=JSON.parse(e),a=new sa(t,i,r);return a.state=s.state,a.identity=s.identity||null,a.product=s.product||null,a.engagement=s.engagement||null,a.plans=s.plans||[],a.selectedPlan=s.selectedPlan||null,a.selectedPlanUuid=s.selectedPlanUuid||null,a.showWidget=s.showWidget||!1,s.session&&(a.session=ra.deserialise(s.session,t,i,{api:a.api})),a}setState(e){const t=this.state;this.state=e,this.emit("stateChanged",e,t)}trackEvent(e,t={}){var i,r,s;this.emit("trackEvent",e,{...t,clientType:this.clientType,planId:(i=this.selectedPlan)==null?void 0:i.uuid,productId:(r=this.product)==null?void 0:r.uuid,sessionId:(s=this.session)==null?void 0:s.sessionUuid})}}var aa,J,tp,ei,np,ip,rp,sp,Ic,Oc,Ac,ap,mr={},op=[],g1=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,gr=Array.isArray;function cn(n,e){for(var t in e)n[t]=e[t];return n}function Nc(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function Mc(n,e,t){var i,r,s,a={};for(s in e)s=="key"?i=e[s]:s=="ref"?r=e[s]:a[s]=e[s];if(arguments.length>2&&(a.children=arguments.length>3?aa.call(arguments,2):t),typeof n=="function"&&n.defaultProps!=null)for(s in n.defaultProps)a[s]==null&&(a[s]=n.defaultProps[s]);return oa(n,a,i,r,null)}function oa(n,e,t,i,r){var s={type:n,props:e,key:t,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:r??++tp,__i:-1,__u:0};return r==null&&J.vnode!=null&&J.vnode(s),s}function nt(n){return n.children}function ln(n,e){this.props=n,this.context=e}function Mi(n,e){if(e==null)return n.__?Mi(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"?Mi(n):null}function cp(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 cp(n)}}function Lc(n){(!n.__d&&(n.__d=!0)&&ei.push(n)&&!ca.__r++||np!=J.debounceRendering)&&((np=J.debounceRendering)||ip)(ca)}function ca(){for(var n,e,t,i,r,s,a,o=1;ei.length;)ei.length>o&&ei.sort(rp),n=ei.shift(),o=ei.length,n.__d&&(t=void 0,r=(i=(e=n).__v).__e,s=[],a=[],e.__P&&((t=cn({},i)).__v=i.__v+1,J.vnode&&J.vnode(t),Dc(e.__P,t,i,e.__n,e.__P.namespaceURI,32&i.__u?[r]:null,s,r??Mi(i),!!(32&i.__u),a),t.__v=i.__v,t.__.__k[t.__i]=t,fp(s,t,a),t.__e!=r&&cp(t)));ca.__r=0}function lp(n,e,t,i,r,s,a,o,c,l,u){var d,h,f,m,p,v,b=i&&i.__k||op,C=e.length;for(c=v1(t,e,b,c,C),d=0;d<C;d++)(f=t.__k[d])!=null&&(h=f.__i==-1?mr:b[f.__i]||mr,f.__i=d,v=Dc(n,f,h,r,s,a,o,c,l,u),m=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&Uc(h.ref,null,f),u.push(f.ref,f.__c||m,f)),p==null&&m!=null&&(p=m),4&f.__u||h.__k===f.__k?c=up(f,c,n):typeof f.type=="function"&&v!==void 0?c=v:m&&(c=m.nextSibling),f.__u&=-7);return t.__e=p,c}function v1(n,e,t,i,r){var s,a,o,c,l,u=t.length,d=u,h=0;for(n.__k=new Array(r),s=0;s<r;s++)(a=e[s])!=null&&typeof a!="boolean"&&typeof a!="function"?(c=s+h,(a=n.__k[s]=typeof a=="string"||typeof a=="number"||typeof a=="bigint"||a.constructor==String?oa(null,a,null,null,null):gr(a)?oa(nt,{children:a},null,null,null):a.constructor==null&&a.__b>0?oa(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):a).__=n,a.__b=n.__b+1,o=null,(l=a.__i=b1(a,t,c,d))!=-1&&(d--,(o=t[l])&&(o.__u|=2)),o==null||o.__v==null?(l==-1&&(r>u?h--:r<u&&h++),typeof a.type!="function"&&(a.__u|=4)):l!=c&&(l==c-1?h--:l==c+1?h++:(l>c?h--:h++,a.__u|=4))):n.__k[s]=null;if(d)for(s=0;s<u;s++)(o=t[s])!=null&&!(2&o.__u)&&(o.__e==i&&(i=Mi(o)),mp(o,o));return i}function up(n,e,t){var i,r;if(typeof n.type=="function"){for(i=n.__k,r=0;i&&r<i.length;r++)i[r]&&(i[r].__=n,e=up(i[r],e,t));return e}n.__e!=e&&(e&&n.type&&!t.contains(e)&&(e=Mi(n)),t.insertBefore(n.__e,e||null),e=n.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function la(n,e){return e=e||[],n==null||typeof n=="boolean"||(gr(n)?n.some(function(t){la(t,e)}):e.push(n)),e}function b1(n,e,t,i){var r,s,a=n.key,o=n.type,c=e[t];if(c===null&&n.key==null||c&&a==c.key&&o==c.type&&!(2&c.__u))return t;if(i>(c!=null&&!(2&c.__u)?1:0))for(r=t-1,s=t+1;r>=0||s<e.length;){if(r>=0){if((c=e[r])&&!(2&c.__u)&&a==c.key&&o==c.type)return r;r--}if(s<e.length){if((c=e[s])&&!(2&c.__u)&&a==c.key&&o==c.type)return s;s++}}return-1}function dp(n,e,t){e[0]=="-"?n.setProperty(e,t??""):n[e]=t==null?"":typeof t!="number"||g1.test(e)?t:t+"px"}function ua(n,e,t,i,r){var s;e:if(e=="style")if(typeof t=="string")n.style.cssText=t;else{if(typeof i=="string"&&(n.style.cssText=i=""),i)for(e in i)t&&e in t||dp(n.style,e,"");if(t)for(e in t)i&&t[e]==i[e]||dp(n.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(sp,"$1")),e=e.toLowerCase()in n||e=="onFocusOut"||e=="onFocusIn"?e.toLowerCase().slice(2):e.slice(2),n.l||(n.l={}),n.l[e+s]=t,t?i?t.u=i.u:(t.u=Ic,n.addEventListener(e,s?Ac:Oc,s)):n.removeEventListener(e,s?Ac:Oc,s);else{if(r=="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 hp(n){return function(e){if(this.l){var t=this.l[e.type+n];if(e.t==null)e.t=Ic++;else if(e.t<t.u)return;return t(J.event?J.event(e):e)}}}function Dc(n,e,t,i,r,s,a,o,c,l){var u,d,h,f,m,p,v,b,C,x,k,S,w,E,A,O,B,L=e.type;if(e.constructor!=null)return null;128&t.__u&&(c=!!(32&t.__u),s=[o=e.__e=t.__e]),(u=J.__b)&&u(e);e:if(typeof L=="function")try{if(b=e.props,C="prototype"in L&&L.prototype.render,x=(u=L.contextType)&&i[u.__c],k=u?x?x.props.value:u.__:i,t.__c?v=(d=e.__c=t.__c).__=d.__E:(C?e.__c=d=new L(b,k):(e.__c=d=new ln(b,k),d.constructor=L,d.render=T1),x&&x.sub(d),d.props=b,d.state||(d.state={}),d.context=k,d.__n=i,h=d.__d=!0,d.__h=[],d._sb=[]),C&&d.__s==null&&(d.__s=d.state),C&&L.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=cn({},d.__s)),cn(d.__s,L.getDerivedStateFromProps(b,d.__s))),f=d.props,m=d.state,d.__v=e,h)C&&L.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),C&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(C&&L.getDerivedStateFromProps==null&&b!==f&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(b,k),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(b,d.__s,k)===!1||e.__v==t.__v){for(e.__v!=t.__v&&(d.props=b,d.state=d.__s,d.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.some(function(R){R&&(R.__=e)}),S=0;S<d._sb.length;S++)d.__h.push(d._sb[S]);d._sb=[],d.__h.length&&a.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(b,d.__s,k),C&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(f,m,p)})}if(d.context=k,d.props=b,d.__P=n,d.__e=!1,w=J.__r,E=0,C){for(d.state=d.__s,d.__d=!1,w&&w(e),u=d.render(d.props,d.state,d.context),A=0;A<d._sb.length;A++)d.__h.push(d._sb[A]);d._sb=[]}else do d.__d=!1,w&&w(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++E<25);d.state=d.__s,d.getChildContext!=null&&(i=cn(cn({},i),d.getChildContext())),C&&!h&&d.getSnapshotBeforeUpdate!=null&&(p=d.getSnapshotBeforeUpdate(f,m)),O=u,u!=null&&u.type===nt&&u.key==null&&(O=pp(u.props.children)),o=lp(n,gr(O)?O:[O],e,t,i,r,s,a,o,c,l),d.base=e.__e,e.__u&=-161,d.__h.length&&a.push(d),v&&(d.__E=d.__=null)}catch(R){if(e.__v=null,c||s!=null)if(R.then){for(e.__u|=c?160:128;o&&o.nodeType==8&&o.nextSibling;)o=o.nextSibling;s[s.indexOf(o)]=null,e.__e=o}else for(B=s.length;B--;)Nc(s[B]);else e.__e=t.__e,e.__k=t.__k;J.__e(R,e,t)}else s==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):o=e.__e=y1(t.__e,e,t,i,r,s,a,c,l);return(u=J.diffed)&&u(e),128&e.__u?void 0:o}function fp(n,e,t){for(var i=0;i<t.length;i++)Uc(t[i],t[++i],t[++i]);J.__c&&J.__c(e,n),n.some(function(r){try{n=r.__h,r.__h=[],n.some(function(s){s.call(r)})}catch(s){J.__e(s,r.__v)}})}function pp(n){return typeof n!="object"||n==null||n.__b&&n.__b>0?n:gr(n)?n.map(pp):cn({},n)}function y1(n,e,t,i,r,s,a,o,c){var l,u,d,h,f,m,p,v=t.props,b=e.props,C=e.type;if(C=="svg"?r="http://www.w3.org/2000/svg":C=="math"?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),s!=null){for(l=0;l<s.length;l++)if((f=s[l])&&"setAttribute"in f==!!C&&(C?f.localName==C:f.nodeType==3)){n=f,s[l]=null;break}}if(n==null){if(C==null)return document.createTextNode(b);n=document.createElementNS(r,C,b.is&&b),o&&(J.__m&&J.__m(e,s),o=!1),s=null}if(C==null)v===b||o&&n.data==b||(n.data=b);else{if(s=s&&aa.call(n.childNodes),v=t.props||mr,!o&&s!=null)for(v={},l=0;l<n.attributes.length;l++)v[(f=n.attributes[l]).name]=f.value;for(l in v)if(f=v[l],l!="children"){if(l=="dangerouslySetInnerHTML")d=f;else if(!(l in b)){if(l=="value"&&"defaultValue"in b||l=="checked"&&"defaultChecked"in b)continue;ua(n,l,null,f,r)}}for(l in b)f=b[l],l=="children"?h=f:l=="dangerouslySetInnerHTML"?u=f:l=="value"?m=f:l=="checked"?p=f:o&&typeof f!="function"||v[l]===f||ua(n,l,f,v[l],r);if(u)o||d&&(u.__html==d.__html||u.__html==n.innerHTML)||(n.innerHTML=u.__html),e.__k=[];else if(d&&(n.innerHTML=""),lp(e.type=="template"?n.content:n,gr(h)?h:[h],e,t,i,C=="foreignObject"?"http://www.w3.org/1999/xhtml":r,s,a,s?s[0]:t.__k&&Mi(t,0),o,c),s!=null)for(l=s.length;l--;)Nc(s[l]);o||(l="value",C=="progress"&&m==null?n.removeAttribute("value"):m!=null&&(m!==n[l]||C=="progress"&&!m||C=="option"&&m!=v[l])&&ua(n,l,m,v[l],r),l="checked",p!=null&&p!=n[l]&&ua(n,l,p,v[l],r))}return n}function Uc(n,e,t){try{if(typeof n=="function"){var i=typeof n.__u=="function";i&&n.__u(),i&&e==null||(n.__u=n(e))}else n.current=e}catch(r){J.__e(r,t)}}function mp(n,e,t){var i,r;if(J.unmount&&J.unmount(n),(i=n.ref)&&(i.current&&i.current!=n.__e||Uc(i,null,e)),(i=n.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(s){J.__e(s,e)}i.base=i.__P=null}if(i=n.__k)for(r=0;r<i.length;r++)i[r]&&mp(i[r],e,t||typeof n.type!="function");t||Nc(n.__e),n.__c=n.__=n.__e=void 0}function T1(n,e,t){return this.constructor(n,t)}function k1(n,e,t){var i,r,s,a;e==document&&(e=document.documentElement),J.__&&J.__(n,e),r=(i=typeof t=="function")?null:t&&t.__k||e.__k,s=[],a=[],Dc(e,n=(!i&&t||e).__k=Mc(nt,null,[n]),r||mr,mr,e.namespaceURI,!i&&t?[t]:r?null:e.firstChild?aa.call(e.childNodes):null,s,!i&&t?t:r?r.__e:e.firstChild,i,a),fp(s,n,a)}function S1(n){function e(t){var i,r;return this.getChildContext||(i=new Set,(r={})[e.__c]=this,this.getChildContext=function(){return r},this.componentWillUnmount=function(){i=null},this.shouldComponentUpdate=function(s){this.props.value!=s.value&&i.forEach(function(a){a.__e=!0,Lc(a)})},this.sub=function(s){i.add(s);var a=s.componentWillUnmount;s.componentWillUnmount=function(){i&&i.delete(s),a&&a.call(s)}}),t.children}return e.__c="__cC"+ap++,e.__=n,e.Provider=e.__l=(e.Consumer=function(t,i){return t.children(i)}).contextType=e,e}aa=op.slice,J={__e:function(n,e,t,i){for(var r,s,a;e=e.__;)if((r=e.__c)&&!r.__)try{if((s=r.constructor)&&s.getDerivedStateFromError!=null&&(r.setState(s.getDerivedStateFromError(n)),a=r.__d),r.componentDidCatch!=null&&(r.componentDidCatch(n,i||{}),a=r.__d),a)return r.__E=r}catch(o){n=o}throw n}},tp=0,ln.prototype.setState=function(n,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=cn({},this.state),typeof n=="function"&&(n=n(cn({},t),this.props)),n&&cn(t,n),n!=null&&this.__v&&(e&&this._sb.push(e),Lc(this))},ln.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),Lc(this))},ln.prototype.render=nt,ei=[],ip=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,rp=function(n,e){return n.__v.__b-e.__v.__b},ca.__r=0,sp=/(PointerCapture)$|Capture$/i,Ic=0,Oc=hp(!1),Ac=hp(!0),ap=0;var C1=0;function g(n,e,t,i,r,s){e||(e={});var a,o,c=e;if("ref"in c)for(o in c={},e)o=="ref"?a=e[o]:c[o]=e[o];var l={type:n,props:c,key:t,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--C1,__i:-1,__u:0,__source:r,__self:s};if(typeof n=="function"&&(a=n.defaultProps))for(o in a)c[o]===void 0&&(c[o]=a[o]);return J.vnode&&J.vnode(l),l}var ti,xe,Bc,gp,vr=0,vp=[],Me=J,bp=Me.__b,yp=Me.__r,Tp=Me.diffed,kp=Me.__c,Sp=Me.unmount,Cp=Me.__;function br(n,e){Me.__h&&Me.__h(xe,n,vr||e),vr=0;var t=xe.__H||(xe.__H={__:[],__h:[]});return n>=t.__.length&&t.__.push({}),t.__[n]}function Y(n){return vr=1,w1(_p,n)}function w1(n,e,t){var i=br(ti++,2);if(i.t=n,!i.__c&&(i.__=[t?t(e):_p(void 0,e),function(o){var c=i.__N?i.__N[0]:i.__[0],l=i.t(c,o);c!==l&&(i.__N=[l,i.__[1]],i.__c.setState({}))}],i.__c=xe,!xe.__f)){var r=function(o,c,l){if(!i.__c.__H)return!0;var u=i.__c.__H.__.filter(function(h){return!!h.__c});if(u.every(function(h){return!h.__N}))return!s||s.call(this,o,c,l);var d=i.__c.props!==o;return u.forEach(function(h){if(h.__N){var f=h.__[0];h.__=h.__N,h.__N=void 0,f!==h.__[0]&&(d=!0)}}),s&&s.call(this,o,c,l)||d};xe.__f=!0;var s=xe.shouldComponentUpdate,a=xe.componentWillUpdate;xe.componentWillUpdate=function(o,c,l){if(this.__e){var u=s;s=void 0,r(o,c,l),s=u}a&&a.call(this,o,c,l)},xe.shouldComponentUpdate=r}return i.__N||i.__}function Qe(n,e){var t=br(ti++,3);!Me.__s&&jc(t.__H,e)&&(t.__=n,t.u=e,xe.__H.__h.push(t))}function da(n,e){var t=br(ti++,4);!Me.__s&&jc(t.__H,e)&&(t.__=n,t.u=e,xe.__h.push(t))}function Be(n){return vr=5,ha(function(){return{current:n}},[])}function ha(n,e){var t=br(ti++,7);return jc(t.__H,e)&&(t.__=n(),t.__H=e,t.__h=n),t.__}function x1(n,e){return vr=8,ha(function(){return n},e)}function wp(n){var e=xe.context[n.__c],t=br(ti++,9);return t.c=n,e?(t.__==null&&(t.__=!0,e.sub(xe)),e.props.value):n.__}function _1(){for(var n;n=vp.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(fa),n.__H.__h.forEach(Fc),n.__H.__h=[]}catch(e){n.__H.__h=[],Me.__e(e,n.__v)}}Me.__b=function(n){xe=null,bp&&bp(n)},Me.__=function(n,e){n&&e.__k&&e.__k.__m&&(n.__m=e.__k.__m),Cp&&Cp(n,e)},Me.__r=function(n){yp&&yp(n),ti=0;var e=(xe=n.__c).__H;e&&(Bc===xe?(e.__h=[],xe.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.forEach(fa),e.__h.forEach(Fc),e.__h=[],ti=0)),Bc=xe},Me.diffed=function(n){Tp&&Tp(n);var e=n.__c;e&&e.__H&&(e.__H.__h.length&&(vp.push(e)!==1&&gp===Me.requestAnimationFrame||((gp=Me.requestAnimationFrame)||E1)(_1)),e.__H.__.forEach(function(t){t.u&&(t.__H=t.u),t.u=void 0})),Bc=xe=null},Me.__c=function(n,e){e.some(function(t){try{t.__h.forEach(fa),t.__h=t.__h.filter(function(i){return!i.__||Fc(i)})}catch(i){e.some(function(r){r.__h&&(r.__h=[])}),e=[],Me.__e(i,t.__v)}}),kp&&kp(n,e)},Me.unmount=function(n){Sp&&Sp(n);var e,t=n.__c;t&&t.__H&&(t.__H.__.forEach(function(i){try{fa(i)}catch(r){e=r}}),t.__H=void 0,e&&Me.__e(e,t.__v))};var xp=typeof requestAnimationFrame=="function";function E1(n){var e,t=function(){clearTimeout(i),xp&&cancelAnimationFrame(e),setTimeout(n)},i=setTimeout(t,100);xp&&(e=requestAnimationFrame(t))}function fa(n){var e=xe,t=n.__c;typeof t=="function"&&(n.__c=void 0,t()),xe=e}function Fc(n){var e=xe;n.__c=n.__(),xe=e}function jc(n,e){return!n||n.length!==e.length||e.some(function(t,i){return t!==n[i]})}function _p(n,e){return typeof e=="function"?e(n):e}function R1({size:n=24,color:e="#000"}){return g("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:[g("path",{d:"M18 6 6 18"}),g("path",{d:"m6 6 12 12"})]})}function Ep({onClose:n}){return g("button",{class:"obi-button obi-close-button",onClick:n,"aria-label":"Close",type:"button",children:g(R1,{})})}function Rp({open:n=!1,children:e,onClose:t,size:i="medium",preventOutsideClick:r=!1}){const s=Be(null),a=Be(null);Qe(()=>{const u=s.current;u&&(n&&!u.open?u.showModal():!n&&u.open&&(a.current="programmatic",u.close()))},[n]);const o=u=>{const d=s.current;u.target===d&&!r&&(a.current="user-initiated",d==null||d.close())},c=u=>{u.preventDefault(),a.current||(a.current="user-initiated");const d=a.current;a.current=null,t==null||t(d)},l=()=>{var u;a.current="user-initiated",(u=s.current)==null||u.close()};return Qe(()=>{const u=s.current;if(u)return u.addEventListener("click",o),u.addEventListener("close",c),()=>{u.removeEventListener("click",o),u.removeEventListener("close",c)}},[t]),g("dialog",{ref:s,className:`modal-${i}`,children:[g(Ep,{onClose:l}),g("div",{class:"modal-content",children:n?typeof e=="function"?e():e:null})]})}function Vc({className:n="",isActive:e=!1,speakingStatus:t,onClick:i,onMouseEnter:r,onMouseLeave:s,children:a}){let o=`obi-pill container ${e&&"active"}`;return t==="user-speaking"&&(o+=" user-speaking"),t==="busy"&&(o+=" busy"),g("div",{className:o,onMouseEnter:r,onMouseLeave:s,children:g("div",{className:`obi-pill pill ${n}`,onClick:i,children:a})})}function P1({className:n="",active:e,speakingStatus:t,onClick:i,onMouseEnter:r,onMouseLeave:s,children:a,...o}){const c=`obi-pill2 container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return g("div",{className:c,...o,children:g("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:s,children:a})})}function I1({className:n="",active:e,speakingStatus:t,onClick:i,onMouseEnter:r,onMouseLeave:s,children:a,...o}){const c=`obi-pill-up container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return g("div",{className:c,...o,children:g("div",{className:"pill",onClick:i,onMouseEnter:r,onMouseLeave:s,children:a})})}const Pp=8,pa=8,O1=100,A1=.7,Li=3;function Ip({getBands:n,color:e="white"}){const t=Be(null);return Qe(()=>{if(!n)return;let i=0,r;const s=a=>{try{if(a-i>=O1){const o=n();if(t.current){const c=t.current.querySelectorAll(".bar"),l=o&&o.length>0?o.slice(0,pa).map(u=>{const d=Math.abs(u);return Math.min(d/A1*Pp,Pp)||Li}):Array(pa).fill(Li);for(;l.length<pa;)l.push(Li);l.forEach((u,d)=>{if(u<Li&&(u=Li),c[d]){const h=u*2;c[d].style.height=`${h}px`,c[d].style.display=u>0?"block":"none"}})}i=a}r=requestAnimationFrame(s)}catch(o){console.warn("Error updating equaliser:",o),r=requestAnimationFrame(s)}};return r=requestAnimationFrame(s),()=>{cancelAnimationFrame(r)}},[n]),g("div",{className:"obi-equaliser",ref:t,children:Array.from({length:pa},(i,r)=>g("div",{className:"column",children:g("div",{className:"bar",style:{height:`${Li}px`,backgroundColor:e,display:"block"}})},r))})}function N1(n){const{spectrum:e}=n;return g(Vc,{isActive:!0,children:g(Ip,{getBands:e})})}function Gc(n){const{children:e,className:t="",...i}=n;return g("div",{className:`${t} obi-panel`,...i,children:e})}function ni({type:n,size:e=24}){return g("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:M1(n)})}function M1(n){switch(n){case"pause":return g(nt,{children:[g("rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}),g("rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"})]});case"play":return g(nt,{children:g("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 g(nt,{children:[g("path",{d:"M18 6 6 18"}),g("path",{d:"m6 6 12 12"})]});case"message":return g(nt,{children:g("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 g(nt,{children:[g("path",{d:"m14 10 7-7"}),g("path",{d:"M20 10h-6V4"}),g("path",{d:"m3 21 7-7"}),g("path",{d:"M4 14h6v6"})]});case"voice":return g(nt,{children:[g("path",{d:"M2 10v3"}),g("path",{d:"M6 6v11"}),g("path",{d:"M10 3v18"}),g("path",{d:"M14 8v7"}),g("path",{d:"M18 5v13"}),g("path",{d:"M22 10v3"})]});case"open":return g(nt,{children:[g("path",{d:"M12 7v14"}),g("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 zc=S1(null);function L1({children:n}){const e=wp(zc);if(!e)throw new Error("PopoutTarget must be used within a Popout component");const{controlledOpen:t,isOpen:i,setIsOpen:r,setAnimating:s,targetRef:a,trigger:o,onChange:c,delayMs:l}=e,u=Be(null),d=Op(a,s),[h,f]=Y(!1);Qe(()=>{t!==void 0&&t!==h&&(t?p():v()),f(t)},[t]),Qe(()=>()=>{u.current&&clearTimeout(u.current)},[]);function m(){u.current&&(clearTimeout(u.current),u.current=null)}function p(){m(),l>0?u.current=setTimeout(()=>{c==null||c(!0),r(!0),u.current=null},l):(c==null||c(!0),r(!0))}function v(){m(),c==null||c(!1),r(!1)}const b=()=>{o==="click"&&(i?v():p())};function C(){o==="hover"&&p()}function x(){o==="hover"&&v()}return g("div",{ref:d,class:"target",onClick:b,onMouseEnter:C,onMouseLeave:x,children:n})}function D1({children:n}){const e=wp(zc);if(!e)throw new Error("PopoutContent must be used within a Popout component");const{isOpen:t,animating:i,setAnimating:r,targetRef:s,contentRef:a}=e,o=Op(a,r);return da(()=>{if(t&&!i&&s.current&&a.current){const c=a.current;if(!c)return;const l=s.current;if(!l)return;const u=c.getBoundingClientRect(),d=l.getBoundingClientRect(),h=d.right-d.left;c.style.top=`${u.top-u.bottom-(8+e.offset)}px`,c.style.left=`${-(u.right-u.left-h)/2}px`}},[t,i]),t?g("div",{ref:o,class:"content",style:{opacity:i?0:1},children:n}):null}function mt({trigger:n="click",open:e,onChange:t,children:i,delayMs:r=0,offset:s=0,className:a=""}){const[o,c]=Y(!1),[l,u]=Y(!1),d=Be(null),h=Be(null),f={controlledOpen:e,isOpen:o,setIsOpen:c,animating:l,setAnimating:u,targetRef:d,contentRef:h,trigger:n,onChange:t,delayMs:r,offset:s};return g(zc.Provider,{value:f,children:g("div",{class:`obi-popout ${a}`,children:i})})}mt.Target=L1,mt.Content=D1;function Op(n,e){const t=Be(null),i=Be(null),r=Be(!0),s=x1(a=>{if(n.current=a,!a){i.current&&(i.current.disconnect(),i.current=null),r.current=!0;return}function o(){if(r.current){r.current=!1;return}t.current?clearTimeout(t.current):e(!0),t.current=setTimeout(()=>{e(!1),t.current=null},200)}i.current=new ResizeObserver(o),i.current.observe(a,{box:"border-box"})},[]);return Qe(()=>()=>{i.current&&(i.current.disconnect(),i.current=null)},[]),s}function Ft({className:n,onClick:e,type:t,disabled:i,title:r}){const s={cancel:g(ni,{type:"close",size:16}),pause:g(ni,{type:"pause",size:16}),play:g(ni,{type:"play",size:16}),message:g(ni,{type:"message",size:16}),minimize:g(ni,{type:"minimize",size:16}),voice:g(ni,{type:"voice",size:16}),open:g(ni,{type:"open",size:16})}[t],a={cancel:"",pause:"",play:"",message:"",minimize:"",voice:"",open:""}[t],o=g("button",{class:`obi-button obi-round-button ${a} ${n}`,onClick:i?void 0:e,disabled:i,children:s});return r?g(mt,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[g(mt.Target,{children:o}),g(mt.Content,{children:g("div",{className:"obi-round-button-title",children:r})})]}):o}function un({className:n,children:e,onClick:t}){return t?g("button",{class:`obi-button obi-message ${n} clickable`,onClick:t,children:e}):g("div",{class:`obi-message ${n}`,children:e})}const U1=8;function B1({color:n="white"}){return g("div",{className:"obi-loading-dots",children:Array.from({length:U1},(e,t)=>g("div",{className:"column",children:[g("div",{className:"bar",style:{backgroundColor:n,animationDelay:`${t*.15}s`}}),g("div",{className:"dot",style:{backgroundColor:n}})]},t))})}function F1({onContinue:n,onWrapUp:e}){return g(Gc,{className:"obi-exit-survey",children:g(V1,{onContinue:n,onWrapUp:()=>{e()}})})}function j1({onOtherSelect:n,onReasonSelect:e,onClose:t}){const[i,r]=Y("reason"),s=a=>{a==="other"?(n(),r("other-reason")):e(a)};return g(Gc,{className:`obi-exit-survey ${i==="reason"?"obi-exit-survey-reason":""}`,children:i==="reason"?g(G1,{onReasonSelect:s}):g(z1,{onReasonSelect:s,onClose:t})})}function V1({onContinue:n,onWrapUp:e}){return g("div",{className:"obi-exit-survey-container",children:[g("h2",{className:"obi-exit-survey-title",children:"Wrapping up early?"}),g("div",{className:"obi-exit-survey-options",children:[g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-continue",onClick:n,type:"button",children:"No, let's continue"}),g("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 G1({onReasonSelect:n}){return g("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[g("div",{className:"obi-exit-survey-header",children:g("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Quick feedback?"})}),g("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("do-later"),type:"button",children:"Will do later"}),g("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"}),g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("prefer-written"),type:"button",children:"Prefer written instructions"}),g("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("technical-issues"),type:"button",children:"Experienced technical issues"})]})]})}function z1({onReasonSelect:n,onClose:e}){const[t,i]=Y("");return g("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[g("div",{className:"obi-exit-survey-header",children:[g(Ep,{onClose:e}),g("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Tell us more"})]}),g("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[g("textarea",{className:"obi-exit-survey-button obi-exit-survey-reason-button",placeholder:"What's on your mind?",value:t,onChange:r=>i(r.target.value)}),g("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 H1(n,e){for(var t in e)n[t]=e[t];return n}function Ap(n,e){for(var t in n)if(t!=="__source"&&!(t in e))return!0;for(var i in e)if(i!=="__source"&&n[i]!==e[i])return!0;return!1}function Np(n,e){this.props=n,this.context=e}(Np.prototype=new ln).isPureReactComponent=!0,Np.prototype.shouldComponentUpdate=function(n,e){return Ap(this.props,n)||Ap(this.state,e)};var Mp=J.__b;J.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),Mp&&Mp(n)};var W1=J.__e;J.__e=function(n,e,t,i){if(n.then){for(var r,s=e;s=s.__;)if((r=s.__c)&&r.__c)return e.__e==null&&(e.__e=t.__e,e.__k=t.__k),r.__c(n,e)}W1(n,e,t,i)};var Lp=J.unmount;function Dp(n,e,t){return n&&(n.__c&&n.__c.__H&&(n.__c.__H.__.forEach(function(i){typeof i.__c=="function"&&i.__c()}),n.__c.__H=null),(n=H1({},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(i){return Dp(i,e,t)})),n}function Up(n,e,t){return n&&t&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(i){return Up(i,e,t)}),n.__c&&n.__c.__P===e&&(n.__e&&t.appendChild(n.__e),n.__c.__e=!0,n.__c.__P=t)),n}function Hc(){this.__u=0,this.o=null,this.__b=null}function Bp(n){var e=n.__.__c;return e&&e.__a&&e.__a(n)}function ma(){this.i=null,this.l=null}J.unmount=function(n){var e=n.__c;e&&e.__R&&e.__R(),e&&32&n.__u&&(n.type=null),Lp&&Lp(n)},(Hc.prototype=new ln).__c=function(n,e){var t=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(t);var r=Bp(i.__v),s=!1,a=function(){s||(s=!0,t.__R=null,r?r(o):o())};t.__R=a;var o=function(){if(!--i.__u){if(i.state.__a){var c=i.state.__a;i.__v.__k[0]=Up(c,c.__c.__P,c.__c.__O)}var l;for(i.setState({__a:i.__b=null});l=i.o.pop();)l.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),n.then(a,a)},Hc.prototype.componentWillUnmount=function(){this.o=[]},Hc.prototype.render=function(n,e){if(this.__b){if(this.__v.__k){var t=document.createElement("div"),i=this.__v.__k[0].__c;this.__v.__k[0]=Dp(this.__b,t,i.__O=i.__P)}this.__b=null}var r=e.__a&&Mc(nt,null,n.fallback);return r&&(r.__u&=-33),[Mc(nt,null,e.__a?null:n.children),r]};var Fp=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]}};(ma.prototype=new ln).__a=function(n){var e=this,t=Bp(e.__v),i=e.l.get(n);return i[0]++,function(r){var s=function(){e.props.revealOrder?(i.push(r),Fp(e,n,i)):r()};t?t(s):s()}},ma.prototype.render=function(n){this.i=null,this.l=new Map;var e=la(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},ma.prototype.componentDidUpdate=ma.prototype.componentDidMount=function(){var n=this;this.l.forEach(function(e,t){Fp(n,t,e)})};var q1=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,K1=/^(?: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]/,$1=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Y1=/[A-Z0-9]/g,X1=typeof document<"u",J1=function(n){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(n)};ln.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(n){Object.defineProperty(ln.prototype,n,{configurable:!0,get:function(){return this["UNSAFE_"+n]},set:function(e){Object.defineProperty(this,n,{configurable:!0,writable:!0,value:e})}})});var jp=J.event;function Q1(){}function Z1(){return this.cancelBubble}function ew(){return this.defaultPrevented}J.event=function(n){return jp&&(n=jp(n)),n.persist=Q1,n.isPropagationStopped=Z1,n.isDefaultPrevented=ew,n.nativeEvent=n};var tw={enumerable:!1,configurable:!0,get:function(){return this.class}},Vp=J.vnode;J.vnode=function(n){typeof n.type=="string"&&function(e){var t=e.props,i=e.type,r={},s=i.indexOf("-")===-1;for(var a in t){var o=t[a];if(!(a==="value"&&"defaultValue"in t&&o==null||X1&&a==="children"&&i==="noscript"||a==="class"||a==="className")){var c=a.toLowerCase();a==="defaultValue"&&"value"in t&&t.value==null?a="value":a==="download"&&o===!0?o="":c==="translate"&&o==="no"?o=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?a="ondblclick":c!=="onchange"||i!=="input"&&i!=="textarea"||J1(t.type)?c==="onfocus"?a="onfocusin":c==="onblur"?a="onfocusout":$1.test(a)&&(a=c):c=a="oninput":s&&K1.test(a)?a=a.replace(Y1,"-$&").toLowerCase():o===null&&(o=void 0),c==="oninput"&&r[a=c]&&(a="oninputCapture"),r[a]=o}}i=="select"&&r.multiple&&Array.isArray(r.value)&&(r.value=la(t.children).forEach(function(l){l.props.selected=r.value.indexOf(l.props.value)!=-1})),i=="select"&&r.defaultValue!=null&&(r.value=la(t.children).forEach(function(l){l.props.selected=r.multiple?r.defaultValue.indexOf(l.props.value)!=-1:r.defaultValue==l.props.value})),t.class&&!t.className?(r.class=t.class,Object.defineProperty(r,"className",tw)):(t.className&&!t.class||t.class&&t.className)&&(r.class=r.className=t.className),e.props=r}(n),n.$$typeof=q1,Vp&&Vp(n)};var Gp=J.__r;J.__r=function(n){Gp&&Gp(n),n.__c};var zp=J.diffed;J.diffed=function(n){zp&&zp(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 nw(n){const{placeholder:e="Type your message...",value:t,defaultValue:i,onChange:r,onSend:s,onCancel:a,onExpand:o,isLoading:c=!1,disabled:l=!1,maxLength:u=500,children:d}=n,[h,f]=Y(t||i||""),[m,p]=Y((t||i||"").length>24),v=Be(null);da(()=>{m&&(o==null||o(!0))},[]);const b=t!==void 0?t:h,C=S=>{const w=S.currentTarget.value;t===void 0&&f(w),r==null||r(w)},x=S=>{S.key==="Escape"&&(f(t||i||""),p(!1),a==null||a()),S.key==="Enter"&&!S.shiftKey&&b.trim()&&(S.preventDefault(),f(t||i||""),p(!1),k()),(b||"").length>=24&&!m&&(p(!0),o==null||o(!0))};Qe(()=>{v.current&&v.current.focus()},[v.current]);const k=()=>{!b.trim()||c||l||(s==null||s(b.trim()),t===void 0&&f(""))};return g("div",{className:`obi-message-input ${m?"expanded":""}`,children:[g("div",{className:"container",children:g("textarea",{ref:v,className:"field",placeholder:e,value:b,onInput:C,onKeyDown:x,disabled:l||c,maxLength:u,rows:1})}),g("div",{className:"button-container",children:[m&&g("div",{children:d}),g("button",{className:"obi-button send",onClick:k,disabled:!b.trim()||c||l,type:"button",children:g("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:g("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 iw(n){const{currentStep:e,totalSteps:t,stepNames:i,className:r,onStepClick:s}=n,[a,o]=Y(null),c=Array.from({length:t},(d,h)=>({isCompleted:h<e,isFuture:h>=e,stepNumber:h+1})),l=i[e-1]&&i[e-1].trim().length>0?i[e-1]:`Step ${e}`,u=(()=>{if(a!==null){const d=i[a]&&i[a].trim().length>0?i[a]:`Step ${a+1}`;return`${a+1}/${t} \u2022 ${d}`}return`${e}/${t} \u2022 ${l}`})();return g("div",{class:`obi-course-progress ${r||""}`,children:[g("div",{class:"obi-course-progress-steps",children:c.map((d,h)=>{const f=i[h]&&i[h].trim().length>0?i[h]:`Step ${h+1}`,m=d.isCompleted?"completed":"future";function p(){s&&s(h,f)}function v(b){s&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),p())}return g("div",{class:"obi-course-progress-container","data-testid":`course-progress-step-${h}`,onMouseEnter:()=>o(h),onMouseLeave:()=>o(null),onClick:s?p:void 0,onKeyDown:s?v:void 0,role:s?"button":void 0,tabIndex:s?0:void 0,children:g("div",{class:`obi-course-progress-step ${m}`,"aria-label":f})},h)})}),g("div",{class:"obi-course-progress-description",children:u})]})}function Hp({className:n="",size:e=64}){return g("svg",{width:e,height:e,viewBox:"0 0 256 256",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:n,children:g("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 rw(n){const{disabled:e,inPlan:t,isPaused:i}=n,[r,s]=Y(null),[a,o]=Y(n.isActive??n.defaultIsActive??!1),[c,l]=Y(!1),[u,d]=Y(n.cancelling??!1),[h,f]=Y(n.messaging??!1),[m,p]=Y(!1),[v,b]=Y(h),[C,x]=Y(!1);function k(){o(!0),l(!1),x(!0)}function S(){}function w(){r&&(clearTimeout(r),s(null))}function E(){s(setTimeout(()=>{o(n.defaultIsActive??!1),x(!1)},400))}function A(ne){var je;p(!1),(je=n.onMessage)==null||je.call(n,ne)}function O(){var ne;f(!1),p(!1),o(!1),l(!0),(ne=n.onMinimize)==null||ne.call(n)}function B(){var ne;f(!1),d(!0),p(!1),(ne=n.onCancelClick)==null||ne.call(n)}function L(){var ne;t||((ne=n.onOpen)==null||ne.call(n))}function R(ne){var je,We,xt,hn,_t,Jt;switch(ne){case"need-help":(je=n.onMessage)==null||je.call(n,"I'm struggling, can you look at my screen and help me out."),(We=n.onOneClickAction)==null||We.call(n,"need-help");break;case"continue":(xt=n.onMessage)==null||xt.call(n,"Okay, let's continue."),(hn=n.onOneClickAction)==null||hn.call(n,"continue");break;case"say-again":(_t=n.onMessage)==null||_t.call(n,"Please say that again."),(Jt=n.onOneClickAction)==null||Jt.call(n,"say-again");break}}function H(ne){var je,We;n.messaging===void 0?((je=n.onMessagingChange)==null||je.call(n,ne),f(ne)):((We=n.onMessagingChange)==null||We.call(n,!n.messaging),f(!n.messaging)),ne||p(!1)}const Q=n.isActive??((a||t)&&!c&&!e),X=Q&&t,K=Q&&t&&!m,ye=n.speakingStatus==="user-speaking",Te=n.speakingStatus==="thinking",W=n.speakingStatus==="busy",de=Q&&!t&&!u&&C,te=Q&&t&&i&&!ye&&!u,ge=Q&&t&&!te&&!ye&&h!==v&&!u,oe=Q&&t&&i&&ye&&!u,Fe=Q&&t&&!i&&ye&&!u,$=Q&&t&&!i&&W&&!u,ke=n.messaging!==void 0?n.messaging:h,Le=ke&&ye,gt=de||te||oe||Fe||ge||u,bt=400,Fi=!!n.courseProgress&&!c,ai=de?5:10;return da(()=>{b(h)},[ye]),!t&&!u?g(sw,{...n}):!t&&u?g(aw,{onOtherSelect:()=>{var ne;(ne=n.onCancelReasonOther)==null||ne.call(n)},onCancelReason:ne=>{var je;o(n.defaultIsActive??!1),d(!1),(je=n.onCancelReason)==null||je.call(n,ne)},onClose:()=>{o(n.defaultIsActive??!1),d(!1)}}):g(Gc,{className:`obi-widget-panel ${X?"expanded":""} ${m?"maximized":""} ${ke?"messaging":""} ${W?"tool-usage":""}`,children:[g("div",{className:`obi-widget ${Q?"active":""} ${t?"in-plan":""}`,onMouseEnter:w,onMouseLeave:E,children:[K&&g(Ft,{type:"cancel",onClick:B,disabled:u,title:"Cancel session"}),K&&!i&&g(Ft,{type:"pause",onClick:n.onPause,title:"Pause session"}),K&&i&&g(Ft,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),g(mt,{className:"obi-widget-popout",open:gt,trigger:null,delayMs:bt,offset:ai,children:[g(mt.Target,{children:[Le&&g(nw,{value:n.message,onCancel:()=>H(!1),onSend:A,onExpand:p,onChange:n.onMessageChange,children:g("div",{className:"obi-widget-buttons",children:[g(Ft,{type:"cancel",onClick:B,disabled:u,title:"Cancel session"}),!i&&g(Ft,{type:"pause",onClick:n.onPause,title:"Pause session"}),i&&g(Ft,{type:"play",onClick:n.onUnpause,title:"Unpause session"}),g(Ft,{type:ke?"voice":"message",onClick:()=>H(!ke),title:ke?"Voice input":"Text input"}),g(Ft,{type:"minimize",onClick:O,title:"Minimize widget"})]})}),!Le&&g(Vc,{className:Q&&!t?"button":"",isActive:Q,speakingStatus:n.speakingStatus,onClick:L,onMouseEnter:k,onMouseLeave:S,children:[Q&&!t&&!$&&g("span",{className:"obi-widget-pill-text",children:"Tutorials"}),Q&&t&&$&&g("span",{className:"obi-widget-pill-text",children:"Searching knowledge ..."}),Q&&t&&!Te&&!$&&g(Ip,{getBands:n.spectrum}),Q&&Te&&!$&&g(B1,{})]})]}),g(mt.Content,{children:g("div",{onMouseLeave:E,children:[de&&g(un,{onClick:L,children:"Click to see all"}),te&&g(un,{children:"Session will pause shortly"}),ge&&g(un,{children:["Switched to ",ke?"chat":"voice"]}),oe&&g(un,{children:"Paused"}),Fe&&g("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},children:[g(un,{onClick:()=>R("need-help"),children:"Need help"}),g(un,{onClick:()=>R("continue"),children:"Continue"}),g(un,{onClick:()=>R("say-again"),children:"Say again"})]}),u&&g(F1,{onContinue:()=>{var ne;(ne=n.onCancelAbort)==null||ne.call(n),d(!1),n.messaging!==void 0&&f(n.messaging)},onWrapUp:()=>{var ne;(ne=n.onCancel)==null||ne.call(n)}})]})})]}),K&&g(Ft,{type:ke?"voice":"message",onClick:()=>H(!ke),title:ke?"Voice input":"Text input"}),K&&g(Ft,{type:"minimize",onClick:O,title:"Minimize widget"})]}),Fi&&n.courseProgress&&g("div",{className:`obi-widget-course-progress ${ke?"expanded":""}`,children:g(iw,{currentStep:n.courseProgress.currentStep,totalSteps:n.courseProgress.totalSteps,stepNames:n.courseProgress.stepNames,onStepClick:(ne,je)=>{var xt;const We=`Can we please jump to the steps related to: ${je}`;(xt=n.onMessage)==null||xt.call(n,We)}})})]})}function sw(n){const{disabled:e,completedTutorials:t,totalTutorials:i,agentName:r}=n,[s,a]=Y(null),[o,c]=Y(n.isActive??n.defaultIsActive??!1),[l,u]=Y(!1),[d,h]=Y(n.hovered??!1),[f,m]=Y(null),[p,v]=Y(null);function b(){p&&(clearTimeout(p),v(null)),f&&m(null)}function C(){var H;c(!0),u(!1),h(!0),(H=n.onHover)==null||H.call(n,!0)}function x(){}function k(){s&&(clearTimeout(s),a(null))}function S(){o&&a(setTimeout(()=>{var H;c(n.defaultIsActive??!1),h(!1),(H=n.onHover)==null||H.call(n,!1)},400))}function w(){b(),c(!1),u(!0)}function E(){var H;b(),(H=n.onOpen)==null||H.call(n)}const A=n.hovered??(d&&!l),O=n.isActive??(o&&!e&&!l),B=O&&A||!!f,L=`round-button ${O?"active":""}`;let R=`${r||"Obi"}`;return t!==void 0&&i!==void 0&&t>=0&&i>0&&(R=`${t}/${i} completed`),da(()=>{if(n.toastMessage&&n.toastMessage.text){p&&clearTimeout(p);const H=n.toastMessage.autoCloseMs??3e3;m({text:n.toastMessage.text,autoCloseMs:H});const Q=setTimeout(()=>{m(null)},H);v(Q)}else n.toastMessage===null&&(p&&clearTimeout(p),m(null))},[n.toastMessage]),g("div",{className:"obi-widget-out-of-plan-container",children:g("div",{className:`obi-widget-out-of-plan ${A?"hover":""} ${O?"active":""}`,onMouseEnter:k,onMouseLeave:S,onClickCapture:b,children:[g("div",{className:L,style:{width:"30px",height:"30px"}}),g(mt,{className:"obi-widget-popout",open:B,trigger:null,delayMs:400,offset:5,children:[g(mt.Target,{children:g(I1,{className:O?"button":"",active:O,onClick:E,onMouseEnter:C,onMouseLeave:x,children:g("span",{className:"text",children:[g(Hp,{size:16}),R]})})}),g(mt.Content,{children:[!!f&&g(un,{onClick:()=>{b(),E()},children:f.text}),!f&&g("div",{onMouseLeave:S,children:g(un,{className:"message",onClick:E,children:"Click to see all"})})]})]}),g(Ft,{className:L,type:"minimize",onClick:w,title:"Minimize widget"})]})})}function aw(n){return g("div",{className:"obi-widget-out-of-plan-container",children:g("div",{className:"obi-widget-out-of-plan",children:g(mt,{className:"obi-widget-popout",open:!0,trigger:null,delayMs:100,offset:5,children:[g(mt.Target,{children:g(P1,{active:!1})}),g(mt.Content,{children:g(j1,{onOtherSelect:()=>{var e;(e=n.onOtherSelect)==null||e.call(n)},onReasonSelect:(e,t)=>{var i;(i=n.onCancelReason)==null||i.call(n,e,t)},onClose:()=>{var e;(e=n.onClose)==null||e.call(n)}})})]})})})}function ow({open:n=!1,children:e,onClose:t,preventOutsideClick:i=!1}){return g(Rp,{open:n,onClose:t,preventOutsideClick:i,size:"medium",children:g("div",{className:"tour content-area",children:n?typeof e=="function"?e():e:null})})}function cw(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Wp={exports:{}};(function(n){(function(){var e={}.hasOwnProperty;function t(){for(var s="",a=0;a<arguments.length;a++){var o=arguments[a];o&&(s=r(s,i(o)))}return s}function i(s){if(typeof s=="string"||typeof s=="number")return s;if(typeof s!="object")return"";if(Array.isArray(s))return t.apply(null,s);if(s.toString!==Object.prototype.toString&&!s.toString.toString().includes("[native code]"))return s.toString();var a="";for(var o in s)e.call(s,o)&&s[o]&&(a=r(a,o));return a}function r(s,a){return a?s?s+" "+a:s+a:s}n.exports?(t.default=t,n.exports=t):window.classNames=t})()})(Wp);var lw=Wp.exports;const uw=cw(lw);function Di({className:n,title:e="",agentName:t="Obi",buttonText:i="Continue",speakingState:r=null,actionDisabled:s=!1,footer:a,href:o=null,glow:c=!1,centerVisual:l,description:u,button:d,onAction:h}){const[f,m]=Y(s),[p,v]=Y(!1),[b,C]=Y(r);Qe(()=>{p||(r==="listening"&&b!=="listening"&&f&&m(!1),r!=="listening"&&!f&&m(!0)),C(r)},[r,f]),Qe(()=>{m(s)},[s]);const x=()=>{f||(m(!0),v(!0),h==null||h())},k=()=>{switch(r){case"thinking":return"Loading...";case"speaking":return`${t} is speaking`;default:return i}},S=o?"a":"button",w=o?{href:o,target:"_blank",rel:"noopener noreferrer"}:{type:"button"};return g("div",{className:uw("tour-content",n),children:g("div",{className:"container",children:[g("div",{className:`visual ${c?"glow":""}`,children:l}),g("div",{className:"header",children:[g("h1",{className:"title",children:e}),g("div",{className:"description",children:u})]}),g("div",{className:"button-container",children:d||g(S,{className:`action-button ${f?"disabled":""}`,onClick:x,disabled:f,...w,children:g("span",{className:"button-text",children:k()})})}),a&&g("div",{className:"tour-footer",children:a})]})})}function dw({logoUrl:n="",appName:e="App"}){const[t,i]=Y(!1),[r,s]=Y(!1),a=()=>{i(!0)},o=()=>{s(!0),i(!1)},c={container:{display:"block"},logoContainer:{width:"480px",height:"240px",borderRadius:"12px",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",overflow:"hidden"},backgroundPattern:{position:"absolute",inset:0,zIndex:0,background:"#F5F5F5",backgroundImage:`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='277' height='195' viewBox='0 0 277 195' fill='none'%3E%3Cpath opacity='0.4' d='M341.308 0.75C380.279 0.750001 411.872 24.3772 411.872 53.5229C411.872 82.6685 380.279 106.296 341.308 106.296H215.792C176.964 108.335 145.691 130.837 141.128 159.475V256.616C145.912 286.659 180.089 309.954 221.548 309.954H330.872C375.607 309.954 411.872 282.833 411.872 249.377V159.069C411.872 129.923 443.465 106.296 482.436 106.296C521.407 106.296 553 129.923 553 159.069V257.181C553 285.058 524.099 307.88 487.483 309.815C489.264 309.902 491.061 309.954 492.871 309.954C448.137 309.954 411.872 337.076 411.872 370.532C411.872 369.177 411.803 367.834 411.686 366.502C409.098 393.885 378.582 415.5 341.308 415.5H210.118C171.147 415.5 139.554 391.873 139.554 362.727C139.554 362.204 139.565 361.683 139.585 361.163C133.564 332.156 100.023 309.954 59.5488 309.954C61.4544 309.954 63.3441 309.9 65.2169 309.803C28.7434 307.76 -8.57239e-07 284.982 0 257.181V159.069C1.64632e-06 130.901 29.5078 107.89 66.6662 106.377C64.3207 106.224 61.9472 106.141 59.5488 106.141C100.012 106.141 133.54 83.951 139.575 54.9552C139.558 54.4793 139.554 54.0018 139.554 53.5229C139.554 24.3772 171.147 0.75 210.118 0.75H341.308Z' fill='white'/%3E%3C/svg%3E")`,backgroundRepeat:"no-repeat",backgroundPosition:"190px 60px",backgroundSize:"300px 225px"},logoWrapper:{background:"#888888",width:"120px",height:"120px",display:"flex",alignItems:"center",justifyContent:"center",borderRadius:"4px",boxShadow:"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",zIndex:10,overflow:"hidden"},appLogo:{width:"120px",height:"120px",objectFit:"cover",display:n&&!t&&r?"block":"none"},placeholderLogo:{width:"60px",height:"60px",background:"rgba(255, 255, 255, 0.2)",borderRadius:"4px",display:!n||t||!r?"flex":"none",alignItems:"center",justifyContent:"center",color:"rgba(255, 255, 255, 0.8)",fontSize:"24px",fontWeight:"bold"}};return g("div",{style:c.container,children:g("div",{style:c.logoContainer,children:[g("div",{style:c.backgroundPattern}),g("div",{style:c.logoWrapper,children:[n&&g("img",{style:c.appLogo,src:n,alt:`${e} logo`,onError:a,onLoad:o}),g("div",{style:c.placeholderLogo,children:e.charAt(0).toUpperCase()})]})]})})}function hw({session:n,speakingState:e,onAction:t}){const i=n.appName?`Navigate to ${n.appName}`:"Navigate to app",r=n.appName?`Open ${n.appName}`:"Open app",s=n.appName?`Enjoy the tutorial in ${n.appName}`:"Enjoy the tutorial";return g(Di,{title:i,subtitle:"Click the button below to open the app",agentName:n.agentName||"Obi",buttonText:r,speakingState:e,actionDisabled:!0,href:n.url,description:s,centerVisual:g(dw,{logoUrl:n.appLogoUrl,appName:n.appName}),onAction:t})}const{entries:qp,setPrototypeOf:Kp,isFrozen:fw,getPrototypeOf:pw,getOwnPropertyDescriptor:mw}=Object;let{freeze:st,seal:wt,create:$p}=Object,{apply:Wc,construct:qc}=typeof Reflect<"u"&&Reflect;st||(st=function(n){return n}),wt||(wt=function(n){return n}),Wc||(Wc=function(n,e,t){return n.apply(e,t)}),qc||(qc=function(n,e){return new n(...e)});const ga=ot(Array.prototype.forEach),gw=ot(Array.prototype.lastIndexOf),Yp=ot(Array.prototype.pop),yr=ot(Array.prototype.push),vw=ot(Array.prototype.splice),va=ot(String.prototype.toLowerCase),Kc=ot(String.prototype.toString),Xp=ot(String.prototype.match),Tr=ot(String.prototype.replace),bw=ot(String.prototype.indexOf),yw=ot(String.prototype.trim),jt=ot(Object.prototype.hasOwnProperty),at=ot(RegExp.prototype.test),kr=Tw(TypeError);function ot(n){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,i=new Array(t>1?t-1:0),r=1;r<t;r++)i[r-1]=arguments[r];return Wc(n,e,i)}}function Tw(n){return function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return qc(n,t)}}function ee(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:va;Kp&&Kp(n,null);let i=e.length;for(;i--;){let r=e[i];if(typeof r=="string"){const s=t(r);s!==r&&(fw(e)||(e[i]=s),r=s)}n[r]=!0}return n}function kw(n){for(let e=0;e<n.length;e++)jt(n,e)||(n[e]=null);return n}function dn(n){const e=$p(null);for(const[t,i]of qp(n))jt(n,t)&&(Array.isArray(i)?e[t]=kw(i):i&&typeof i=="object"&&i.constructor===Object?e[t]=dn(i):e[t]=i);return e}function Sr(n,e){for(;n!==null;){const i=mw(n,e);if(i){if(i.get)return ot(i.get);if(typeof i.value=="function")return ot(i.value)}n=pw(n)}function t(){return null}return t}const Jp=st(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),$c=st(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Yc=st(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Sw=st(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Xc=st(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Cw=st(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Qp=st(["#text"]),Zp=st(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Jc=st(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),em=st(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),ba=st(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),ww=wt(/\{\{[\w\W]*|[\w\W]*\}\}/gm),xw=wt(/<%[\w\W]*|[\w\W]*%>/gm),_w=wt(/\$\{[\w\W]*/gm),Ew=wt(/^data-[\-\w.\u00B7-\uFFFF]+$/),Rw=wt(/^aria-[\-\w]+$/),tm=wt(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Pw=wt(/^(?:\w+script|data):/i),Iw=wt(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),nm=wt(/^html$/i),Ow=wt(/^[a-z][.\w]*(-[.\w]+)+$/i);var im=Object.freeze({__proto__:null,ARIA_ATTR:Rw,ATTR_WHITESPACE:Iw,CUSTOM_ELEMENT:Ow,DATA_ATTR:Ew,DOCTYPE_NAME:nm,ERB_EXPR:xw,IS_ALLOWED_URI:tm,IS_SCRIPT_OR_DATA:Pw,MUSTACHE_EXPR:ww,TMPLIT_EXPR:_w});const Cr={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Aw=function(){return typeof window>"u"?null:window},Nw=function(n,e){if(typeof n!="object"||typeof n.createPolicy!="function")return null;let t=null;const i="data-tt-policy-suffix";e&&e.hasAttribute(i)&&(t=e.getAttribute(i));const r="dompurify"+(t?"#"+t:"");try{return n.createPolicy(r,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+r+" could not be created."),null}},rm=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function sm(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Aw();const e=T=>sm(T);if(e.version="3.2.6",e.removed=[],!n||!n.document||n.document.nodeType!==Cr.document||!n.Element)return e.isSupported=!1,e;let{document:t}=n;const i=t,r=i.currentScript,{DocumentFragment:s,HTMLTemplateElement:a,Node:o,Element:c,NodeFilter:l,NamedNodeMap:u=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:d,DOMParser:h,trustedTypes:f}=n,m=c.prototype,p=Sr(m,"cloneNode"),v=Sr(m,"remove"),b=Sr(m,"nextSibling"),C=Sr(m,"childNodes"),x=Sr(m,"parentNode");if(typeof a=="function"){const T=t.createElement("template");T.content&&T.content.ownerDocument&&(t=T.content.ownerDocument)}let k,S="";const{implementation:w,createNodeIterator:E,createDocumentFragment:A,getElementsByTagName:O}=t,{importNode:B}=i;let L=rm();e.isSupported=typeof qp=="function"&&typeof x=="function"&&w&&w.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:R,ERB_EXPR:H,TMPLIT_EXPR:Q,DATA_ATTR:X,ARIA_ATTR:K,IS_SCRIPT_OR_DATA:ye,ATTR_WHITESPACE:Te,CUSTOM_ELEMENT:W}=im;let{IS_ALLOWED_URI:de}=im,te=null;const ge=ee({},[...Jp,...$c,...Yc,...Xc,...Qp]);let oe=null;const Fe=ee({},[...Zp,...Jc,...em,...ba]);let $=Object.seal($p(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ke=null,Le=null,gt=!0,bt=!0,Fi=!1,ai=!0,ne=!1,je=!0,We=!1,xt=!1,hn=!1,_t=!1,Jt=!1,oi=!1,_r=!0,Er=!1;const _a="user-content-";let ji=!0,Vn=!1,fn={},N=null;const q=ee({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Z=null;const Se=ee({},["audio","video","img","source","image","track"]);let qe=null;const Qt=ee({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),pn="http://www.w3.org/1998/Math/MathML",Vi="http://www.w3.org/2000/svg",Et="http://www.w3.org/1999/xhtml";let mn=Et,Gi=!1,gn=null;const h_=ee({},[pn,Vi,Et],Kc);let Ea=ee({},["mi","mo","mn","ms","mtext"]),Ra=ee({},["annotation-xml"]);const f_=ee({},["title","style","font","a","script"]);let Rr=null;const p_=["application/xhtml+xml","text/html"],m_="text/html";let Ke=null,zi=null;const g_=t.createElement("form"),Am=function(T){return T instanceof RegExp||T instanceof Function},sl=function(){let T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(zi&&zi===T)){if((!T||typeof T!="object")&&(T={}),T=dn(T),Rr=p_.indexOf(T.PARSER_MEDIA_TYPE)===-1?m_:T.PARSER_MEDIA_TYPE,Ke=Rr==="application/xhtml+xml"?Kc:va,te=jt(T,"ALLOWED_TAGS")?ee({},T.ALLOWED_TAGS,Ke):ge,oe=jt(T,"ALLOWED_ATTR")?ee({},T.ALLOWED_ATTR,Ke):Fe,gn=jt(T,"ALLOWED_NAMESPACES")?ee({},T.ALLOWED_NAMESPACES,Kc):h_,qe=jt(T,"ADD_URI_SAFE_ATTR")?ee(dn(Qt),T.ADD_URI_SAFE_ATTR,Ke):Qt,Z=jt(T,"ADD_DATA_URI_TAGS")?ee(dn(Se),T.ADD_DATA_URI_TAGS,Ke):Se,N=jt(T,"FORBID_CONTENTS")?ee({},T.FORBID_CONTENTS,Ke):q,ke=jt(T,"FORBID_TAGS")?ee({},T.FORBID_TAGS,Ke):dn({}),Le=jt(T,"FORBID_ATTR")?ee({},T.FORBID_ATTR,Ke):dn({}),fn=jt(T,"USE_PROFILES")?T.USE_PROFILES:!1,gt=T.ALLOW_ARIA_ATTR!==!1,bt=T.ALLOW_DATA_ATTR!==!1,Fi=T.ALLOW_UNKNOWN_PROTOCOLS||!1,ai=T.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ne=T.SAFE_FOR_TEMPLATES||!1,je=T.SAFE_FOR_XML!==!1,We=T.WHOLE_DOCUMENT||!1,_t=T.RETURN_DOM||!1,Jt=T.RETURN_DOM_FRAGMENT||!1,oi=T.RETURN_TRUSTED_TYPE||!1,hn=T.FORCE_BODY||!1,_r=T.SANITIZE_DOM!==!1,Er=T.SANITIZE_NAMED_PROPS||!1,ji=T.KEEP_CONTENT!==!1,Vn=T.IN_PLACE||!1,de=T.ALLOWED_URI_REGEXP||tm,mn=T.NAMESPACE||Et,Ea=T.MATHML_TEXT_INTEGRATION_POINTS||Ea,Ra=T.HTML_INTEGRATION_POINTS||Ra,$=T.CUSTOM_ELEMENT_HANDLING||{},T.CUSTOM_ELEMENT_HANDLING&&Am(T.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&($.tagNameCheck=T.CUSTOM_ELEMENT_HANDLING.tagNameCheck),T.CUSTOM_ELEMENT_HANDLING&&Am(T.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&($.attributeNameCheck=T.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),T.CUSTOM_ELEMENT_HANDLING&&typeof T.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&($.allowCustomizedBuiltInElements=T.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ne&&(bt=!1),Jt&&(_t=!0),fn&&(te=ee({},Qp),oe=[],fn.html===!0&&(ee(te,Jp),ee(oe,Zp)),fn.svg===!0&&(ee(te,$c),ee(oe,Jc),ee(oe,ba)),fn.svgFilters===!0&&(ee(te,Yc),ee(oe,Jc),ee(oe,ba)),fn.mathMl===!0&&(ee(te,Xc),ee(oe,em),ee(oe,ba))),T.ADD_TAGS&&(te===ge&&(te=dn(te)),ee(te,T.ADD_TAGS,Ke)),T.ADD_ATTR&&(oe===Fe&&(oe=dn(oe)),ee(oe,T.ADD_ATTR,Ke)),T.ADD_URI_SAFE_ATTR&&ee(qe,T.ADD_URI_SAFE_ATTR,Ke),T.FORBID_CONTENTS&&(N===q&&(N=dn(N)),ee(N,T.FORBID_CONTENTS,Ke)),ji&&(te["#text"]=!0),We&&ee(te,["html","head","body"]),te.table&&(ee(te,["tbody"]),delete ke.tbody),T.TRUSTED_TYPES_POLICY){if(typeof T.TRUSTED_TYPES_POLICY.createHTML!="function")throw kr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof T.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw kr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');k=T.TRUSTED_TYPES_POLICY,S=k.createHTML("")}else k===void 0&&(k=Nw(f,r)),k!==null&&typeof S=="string"&&(S=k.createHTML(""));st&&st(T),zi=T}},Nm=ee({},[...$c,...Yc,...Sw]),Mm=ee({},[...Xc,...Cw]),v_=function(T){let z=x(T);(!z||!z.tagName)&&(z={namespaceURI:mn,tagName:"template"});const F=va(T.tagName),fe=va(z.tagName);return gn[T.namespaceURI]?T.namespaceURI===Vi?z.namespaceURI===Et?F==="svg":z.namespaceURI===pn?F==="svg"&&(fe==="annotation-xml"||Ea[fe]):!!Nm[F]:T.namespaceURI===pn?z.namespaceURI===Et?F==="math":z.namespaceURI===Vi?F==="math"&&Ra[fe]:!!Mm[F]:T.namespaceURI===Et?z.namespaceURI===Vi&&!Ra[fe]||z.namespaceURI===pn&&!Ea[fe]?!1:!Mm[F]&&(f_[F]||!Nm[F]):!!(Rr==="application/xhtml+xml"&&gn[T.namespaceURI]):!1},ci=function(T){yr(e.removed,{element:T});try{x(T).removeChild(T)}catch{v(T)}},Hi=function(T,z){try{yr(e.removed,{attribute:z.getAttributeNode(T),from:z})}catch{yr(e.removed,{attribute:null,from:z})}if(z.removeAttribute(T),T==="is")if(_t||Jt)try{ci(z)}catch{}else try{z.setAttribute(T,"")}catch{}},Lm=function(T){let z=null,F=null;if(hn)T="<remove></remove>"+T;else{const Ie=Xp(T,/^[\r\n\t ]+/);F=Ie&&Ie[0]}Rr==="application/xhtml+xml"&&mn===Et&&(T='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+T+"</body></html>");const fe=k?k.createHTML(T):T;if(mn===Et)try{z=new h().parseFromString(fe,Rr)}catch{}if(!z||!z.documentElement){z=w.createDocument(mn,"template",null);try{z.documentElement.innerHTML=Gi?S:fe}catch{}}const Ze=z.body||z.documentElement;return T&&F&&Ze.insertBefore(t.createTextNode(F),Ze.childNodes[0]||null),mn===Et?O.call(z,We?"html":"body")[0]:We?z.documentElement:Ze},Dm=function(T){return E.call(T.ownerDocument||T,T,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},al=function(T){return T instanceof d&&(typeof T.nodeName!="string"||typeof T.textContent!="string"||typeof T.removeChild!="function"||!(T.attributes instanceof u)||typeof T.removeAttribute!="function"||typeof T.setAttribute!="function"||typeof T.namespaceURI!="string"||typeof T.insertBefore!="function"||typeof T.hasChildNodes!="function")},Um=function(T){return typeof o=="function"&&T instanceof o};function vn(T,z,F){ga(T,fe=>{fe.call(e,z,F,zi)})}const Bm=function(T){let z=null;if(vn(L.beforeSanitizeElements,T,null),al(T))return ci(T),!0;const F=Ke(T.nodeName);if(vn(L.uponSanitizeElement,T,{tagName:F,allowedTags:te}),je&&T.hasChildNodes()&&!Um(T.firstElementChild)&&at(/<[/\w!]/g,T.innerHTML)&&at(/<[/\w!]/g,T.textContent)||T.nodeType===Cr.progressingInstruction||je&&T.nodeType===Cr.comment&&at(/<[/\w]/g,T.data))return ci(T),!0;if(!te[F]||ke[F]){if(!ke[F]&&jm(F)&&($.tagNameCheck instanceof RegExp&&at($.tagNameCheck,F)||$.tagNameCheck instanceof Function&&$.tagNameCheck(F)))return!1;if(ji&&!N[F]){const fe=x(T)||T.parentNode,Ze=C(T)||T.childNodes;if(Ze&&fe){const Ie=Ze.length;for(let bn=Ie-1;bn>=0;--bn){const Vt=p(Ze[bn],!0);Vt.__removalCount=(T.__removalCount||0)+1,fe.insertBefore(Vt,b(T))}}}return ci(T),!0}return T instanceof c&&!v_(T)||(F==="noscript"||F==="noembed"||F==="noframes")&&at(/<\/no(script|embed|frames)/i,T.innerHTML)?(ci(T),!0):(ne&&T.nodeType===Cr.text&&(z=T.textContent,ga([R,H,Q],fe=>{z=Tr(z,fe," ")}),T.textContent!==z&&(yr(e.removed,{element:T.cloneNode()}),T.textContent=z)),vn(L.afterSanitizeElements,T,null),!1)},Fm=function(T,z,F){if(_r&&(z==="id"||z==="name")&&(F in t||F in g_))return!1;if(!(bt&&!Le[z]&&at(X,z))&&!(gt&&at(K,z))){if(!oe[z]||Le[z]){if(!(jm(T)&&($.tagNameCheck instanceof RegExp&&at($.tagNameCheck,T)||$.tagNameCheck instanceof Function&&$.tagNameCheck(T))&&($.attributeNameCheck instanceof RegExp&&at($.attributeNameCheck,z)||$.attributeNameCheck instanceof Function&&$.attributeNameCheck(z))||z==="is"&&$.allowCustomizedBuiltInElements&&($.tagNameCheck instanceof RegExp&&at($.tagNameCheck,F)||$.tagNameCheck instanceof Function&&$.tagNameCheck(F))))return!1}else if(!qe[z]&&!at(de,Tr(F,Te,""))&&!((z==="src"||z==="xlink:href"||z==="href")&&T!=="script"&&bw(F,"data:")===0&&Z[T])&&!(Fi&&!at(ye,Tr(F,Te,"")))&&F)return!1}return!0},jm=function(T){return T!=="annotation-xml"&&Xp(T,W)},Vm=function(T){vn(L.beforeSanitizeAttributes,T,null);const{attributes:z}=T;if(!z||al(T))return;const F={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:oe,forceKeepAttr:void 0};let fe=z.length;for(;fe--;){const Ze=z[fe],{name:Ie,namespaceURI:bn,value:Vt}=Ze,Zt=Ke(Ie),ol=Vt;let it=Ie==="value"?ol:yw(ol);if(F.attrName=Zt,F.attrValue=it,F.keepAttr=!0,F.forceKeepAttr=void 0,vn(L.uponSanitizeAttribute,T,F),it=F.attrValue,Er&&(Zt==="id"||Zt==="name")&&(Hi(Ie,T),it=_a+it),je&&at(/((--!?|])>)|<\/(style|title)/i,it)){Hi(Ie,T);continue}if(F.forceKeepAttr)continue;if(!F.keepAttr){Hi(Ie,T);continue}if(!ai&&at(/\/>/i,it)){Hi(Ie,T);continue}ne&&ga([R,H,Q],y_=>{it=Tr(it,y_," ")});const Gm=Ke(T.nodeName);if(!Fm(Gm,Zt,it)){Hi(Ie,T);continue}if(k&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!bn)switch(f.getAttributeType(Gm,Zt)){case"TrustedHTML":{it=k.createHTML(it);break}case"TrustedScriptURL":{it=k.createScriptURL(it);break}}if(it!==ol)try{bn?T.setAttributeNS(bn,Ie,it):T.setAttribute(Ie,it),al(T)?ci(T):Yp(e.removed)}catch{Hi(Ie,T)}}vn(L.afterSanitizeAttributes,T,null)},b_=function T(z){let F=null;const fe=Dm(z);for(vn(L.beforeSanitizeShadowDOM,z,null);F=fe.nextNode();)vn(L.uponSanitizeShadowNode,F,null),Bm(F),Vm(F),F.content instanceof s&&T(F.content);vn(L.afterSanitizeShadowDOM,z,null)};return e.sanitize=function(T){let z=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},F=null,fe=null,Ze=null,Ie=null;if(Gi=!T,Gi&&(T="<!-->"),typeof T!="string"&&!Um(T))if(typeof T.toString=="function"){if(T=T.toString(),typeof T!="string")throw kr("dirty is not a string, aborting")}else throw kr("toString is not a function");if(!e.isSupported)return T;if(xt||sl(z),e.removed=[],typeof T=="string"&&(Vn=!1),Vn){if(T.nodeName){const Zt=Ke(T.nodeName);if(!te[Zt]||ke[Zt])throw kr("root node is forbidden and cannot be sanitized in-place")}}else if(T instanceof o)F=Lm("<!---->"),fe=F.ownerDocument.importNode(T,!0),fe.nodeType===Cr.element&&fe.nodeName==="BODY"||fe.nodeName==="HTML"?F=fe:F.appendChild(fe);else{if(!_t&&!ne&&!We&&T.indexOf("<")===-1)return k&&oi?k.createHTML(T):T;if(F=Lm(T),!F)return _t?null:oi?S:""}F&&hn&&ci(F.firstChild);const bn=Dm(Vn?T:F);for(;Ze=bn.nextNode();)Bm(Ze),Vm(Ze),Ze.content instanceof s&&b_(Ze.content);if(Vn)return T;if(_t){if(Jt)for(Ie=A.call(F.ownerDocument);F.firstChild;)Ie.appendChild(F.firstChild);else Ie=F;return(oe.shadowroot||oe.shadowrootmode)&&(Ie=B.call(i,Ie,!0)),Ie}let Vt=We?F.outerHTML:F.innerHTML;return We&&te["!doctype"]&&F.ownerDocument&&F.ownerDocument.doctype&&F.ownerDocument.doctype.name&&at(nm,F.ownerDocument.doctype.name)&&(Vt="<!DOCTYPE "+F.ownerDocument.doctype.name+`>
|
|
43
43
|
`+Vt),ne&&ga([R,H,Q],Zt=>{Vt=Tr(Vt,Zt," ")}),k&&oi?k.createHTML(Vt):Vt},e.setConfig=function(){let T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};sl(T),xt=!0},e.clearConfig=function(){zi=null,xt=!1},e.isValidAttribute=function(T,z,F){zi||sl({});const fe=Ke(T),Ze=Ke(z);return Fm(fe,Ze,F)},e.addHook=function(T,z){typeof z=="function"&&yr(L[T],z)},e.removeHook=function(T,z){if(z!==void 0){const F=gw(L[T],z);return F===-1?void 0:vw(L[T],F,1)[0]}return Yp(L[T])},e.removeHooks=function(T){L[T]=[]},e.removeAllHooks=function(){L=rm()},e}var Mw=sm();function Lw({}){return g("div",{className:"obi-static-voice",children:[g("div",{className:"obi-static-voice-visual-title",children:"AI Guided Tutorial"}),g("div",{style:{transform:"scale(1.25) translateY(-4px)"},children:g(Vc,{isActive:!0,children:g("div",{className:"obi-static-voice-visual",children:[g("div",{className:"column",children:g("div",{className:"bar bar-1"})}),g("div",{className:"column",children:g("div",{className:"bar bar-2"})}),g("div",{className:"column",children:g("div",{className:"bar bar-3"})}),g("div",{className:"column",children:g("div",{className:"bar bar-4"})}),g("div",{className:"column",children:g("div",{className:"bar bar-5"})}),g("div",{className:"column",children:g("div",{className:"bar bar-6"})}),g("div",{className:"column",children:g("div",{className:"bar bar-7"})}),g("div",{className:"column",children:g("div",{className:"bar bar-8"})})]})})})]})}function Dw({session:n,speakingState:e,onAction:t}){const i="Sessions are securely recorded for quality improvement purposes.",r=ha(()=>{var c;const o=(c=n.legalFooter)==null?void 0:c.trim();return o?Mw.sanitize(o):null},[n.legalFooter]),s=Be(null);Qe(()=>{if(!r)return;const o=s.current;o&&o.querySelectorAll("a").forEach(c=>{c.setAttribute("target","_blank");const l=(c.getAttribute("rel")||"").split(/\s+/);l.includes("noopener")||l.push("noopener"),l.includes("noreferrer")||l.push("noreferrer"),c.setAttribute("rel",l.filter(Boolean).join(" ")),c.style.color="black"})},[r]);const a=r?g("span",{ref:s,dangerouslySetInnerHTML:{__html:r}}):i;return g(Di,{className:"session-start-content",title:n.name,subtitle:"AI voice-guided tutorial",description:n.description,footer:a,buttonText:"Get started",agentName:n.agentName||"Obi",speakingState:e,centerVisual:g(Lw,{}),onAction:t})}function Uw(){const n={host:{display:"block",position:"relative",width:"100%",height:"161px"},container:{position:"relative",width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},permissionDialog:{boxSizing:"border-box",display:"flex",flexDirection:"row",justifyContent:"flex-start",alignItems:"center",padding:"16px 20px",gap:"16px",position:"absolute",width:"344px",height:"125px",left:"calc(50% - 344px/2)",top:"calc(50% - 125px/2)",background:"#FFFFFF",border:"1px solid #E5E7EB",boxShadow:"0px 10px 15px -3px rgba(0, 0, 0, 0.1), 0px 4px 6px -2px rgba(0, 0, 0, 0.05)",borderRadius:"8px"},permissionContent:{width:"100%",display:"flex",flexDirection:"column",gap:"16px"},permissionContentTop:{display:"flex",flexDirection:"row",alignItems:"center",padding:"0px",gap:"16px"},micIconContainer:{color:"var(--obi-color-text)",boxSizing:"border-box",display:"flex",flexDirection:"row",justifyContent:"center",alignItems:"center",padding:"12px",gap:"8px",width:"48px",height:"48px",background:"#F9FAFB",border:"1px solid #D1D5DB",borderRadius:"6px",flex:"none",order:0,flexGrow:0},micIcon:{width:"24px",height:"24px",flex:"none",order:0,flexGrow:0},permissionText:{flex:1,height:"24px",fontFamily:"'Inter', sans-serif",fontStyle:"normal",fontWeight:500,fontSize:"16px",lineHeight:"24px",display:"flex",alignItems:"center",color:"#111827",flexGrow:1,order:1},allowButton:{alignSelf:"flex-end",boxSizing:"border-box",display:"flex",flexDirection:"row",justifyContent:"center",alignItems:"center",padding:"10px 20px",gap:"8px",minWidth:"80px",height:"40px",background:"#F9FAFB",border:"1px solid #D1D5DB",borderRadius:"6px",flex:"none",order:2,flexGrow:0,cursor:"pointer",fontFamily:"'Inter', sans-serif",fontStyle:"normal",fontWeight:500,fontSize:"14px",lineHeight:"20px",color:"#374151"},cursorPointer:{position:"absolute",width:"24px",height:"24px",right:"80px",bottom:"60px",zIndex:3,animation:"pointToAllow 2s ease-in-out infinite"},cursorSvg:{width:"100%",height:"100%",filter:"drop-shadow(0px 1px 1.8px rgba(0, 0, 0, 0.65))"}};return g("div",{style:n.host,children:[g("style",{children:`
|
|
44
44
|
@keyframes pointToAllow {
|
|
45
45
|
0%, 100% { transform: translate(0, 0); }
|
|
@@ -53,4 +53,4 @@ a=extmap-allow-mixed`)!==-1){const s=r.sdp.split(`
|
|
|
53
53
|
}
|
|
54
54
|
`}),g("article",{style:n.skeletonContainer,role:"status","aria-label":"Loading content",children:[g("section",{style:n.headerSection,children:[g("div",{style:n.avatar,role:"img","aria-label":"Loading avatar",children:g("div",{style:n.shimmer})}),g("div",{style:n.textLines,children:[g("div",{style:n.textLine,role:"presentation","aria-label":"Loading text line 1",children:g("div",{style:n.shimmer})}),g("div",{style:n.textLine,role:"presentation","aria-label":"Loading text line 2",children:g("div",{style:n.shimmer})})]})]}),g("section",{style:n.contentSection,children:g("div",{style:n.contentBlock,role:"presentation","aria-label":"Loading card content",children:g("div",{style:n.shimmer})})})]})]})}function Vw({}){const n={host:{display:"block",height:"161px"},shareContainer:{width:"480px",height:"240px",borderRadius:"12px",display:"grid",placeItems:"center",overflow:"hidden",position:"relative",backgroundColor:"var(--obi-color-tint)"},controlsRow:{zIndex:10,gridRowStart:1,gridColumnStart:1,display:"flex",alignSelf:"flex-start",marginTop:"36px",alignItems:"center",gap:"8px"},monitorIconContainer:{display:"flex",height:"40px",width:"40px",aspectRatio:"1",alignItems:"center",justifyContent:"center",gap:"8px",borderRadius:"2px",border:"1px solid #E4E4E7",background:"#F8FAFC",padding:"8px"},monitorIcon:{width:"24px",height:"24px",color:"#111827"},tabSelector:{display:"flex",width:"260px",height:"40px",padding:"4px",alignItems:"center",borderRadius:"2px",background:"#E4E4E7"},tabButton:e=>({display:"flex",flex:1,alignSelf:"stretch",alignItems:"center",justifyContent:"center",gap:"10px",borderRadius:"2px",padding:"6px 12px",border:"none",cursor:"pointer",fontFamily:"'Inter', sans-serif",fontSize:"14px",fontWeight:500,opacity:e?1:.4,background:e?"white":"#F8FAFC",boxShadow:e?"0 1px 2px 0 rgba(0, 0, 0, 0.05)":"none"}),skeletonContainer:{marginTop:"104px",gridColumnStart:1,gridRowStart:1,alignSelf:"center"}};return g("div",{style:n.host,children:g("div",{style:n.shareContainer,children:[g("div",{style:n.controlsRow,children:[g("div",{style:n.monitorIconContainer,children:g("svg",{style:n.monitorIcon,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[g("rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",ry:"2"}),g("line",{x1:"8",x2:"16",y1:"21",y2:"21"}),g("line",{x1:"12",x2:"12",y1:"17",y2:"21"})]})}),g("div",{style:n.tabSelector,children:[g("button",{style:n.tabButton(!1),children:"Tab"}),g("button",{style:n.tabButton(!0),children:"Window"})]})]}),g("div",{style:n.skeletonContainer,children:g(jw,{})})]})})}function Gw({session:n,speakingState:e,onAction:t}){return g(Di,{title:"Connect your screen",subtitle:"Watch for the prompt in your browser",agentName:n.agentName||"Obi",buttonText:"Share screen",speakingState:e,description:`${n.agentName||"Obi"} will guide you through ${n.appName||"the app"} by watching your screen.`,centerVisual:g(Vw,{}),actionDisabled:!0,onAction:t})}function zw({session:n,speakingState:e,spectrum:t,onAction:i}){return g(Di,{title:"Overview",subtitle:`${n.agentName||"Obi"} will start your tutorial in a moment`,agentName:n.agentName||"Obi",speakingState:e,description:`Get ready to explore ${n.appName||"the app"} with ${n.agentName||"Obi"}.`,centerVisual:g(am,{spectrum:t}),actionDisabled:!0,onAction:i})}function Hw({id:n,name:e,description:t,duration:i=10,order:r=0,selected:s=!1,completed:a=!1,onClick:o}){return g("div",{className:`course-container ${s?"selected":""}`,onClick:()=>{o==null||o({id:n,name:e,description:t,duration:i,order:r})},children:[g("div",{className:"header-row",children:[g("h2",{className:"course-title",children:e}),a&&g("span",{className:"duration",children:"Completed"})]}),t&&g("p",{className:"course-description",children:t})]})}function Ww({courses:n=[],selectedCourseId:e=null,loading:t=!1,error:i="",onCourseSelect:r}){const[s,a]=Y(""),o=u=>{const d=u.currentTarget;a(d.value)},c=u=>{r==null||r(u)};if(t)return g("div",{className:"loading",children:"Loading..."});if(i)return g("div",{className:"error",children:i});if(!n||n.length===0)return g("div",{className:"empty",children:"No courses available"});const l=n.filter(u=>u.name.toLowerCase().includes(s.toLowerCase())||(u.description||"").toLowerCase().includes(s.toLowerCase()));return g("div",{className:"tour-select",children:[g("div",{className:"controls",children:[g("div",{className:"tabs",children:g("button",{className:"tab active",children:"All"})}),g("div",{className:"filter",children:[g("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:g("path",{d:"M10.0417 8.75002H9.42087L9.20004 8.53502C9.96921 7.63585 10.4417 6.47502 10.4417 5.20835C10.4417 2.56085 8.32254 0.441681 5.67504 0.441681C3.02754 0.441681 0.908374 2.56085 0.908374 5.20835C0.908374 7.85585 3.02754 9.97502 5.67504 9.97502C6.94171 9.97502 8.10254 9.50252 9.00171 8.73335L9.22671 8.95418V9.57502L13.2167 13.5592L14.375 12.4008L10.0417 8.75002ZM5.67504 8.75002C3.72754 8.75002 2.15837 7.18085 2.15837 5.20835C2.15837 3.23585 3.72754 1.66668 5.67504 1.66668C7.62254 1.66668 9.19171 3.23585 9.19171 5.20835C9.19171 7.18085 7.62254 8.75002 5.67504 8.75002Z",fill:"#6B7280"})}),g("input",{type:"text",placeholder:"Search...",value:s,onInput:o})]})]}),g("div",{className:"course-grid",children:l.sort((u,d)=>(u.order||0)-(d.order||0)).map(u=>{const d=u.id===e;return g(Hw,{id:u.id,name:u.name,description:u.description||"",duration:u.duration,order:u.order||0,completed:u.completed,selected:d,onClick:c},u.id)})})]})}function qw({open:n,courses:e=[],loading:t=!1,error:i="",title:r="AI Coach",productName:s,onClose:a,onCourseSelect:o,onCourseHighlight:c}){const[l,u]=Y(null),d=f=>{u(f),c==null||c(f)},h=()=>{l&&o&&o(l)};return g(Rp,{open:n,onClose:a,size:"large",preventOutsideClick:!0,children:g("div",{className:"tour-select-modal-container",children:[g("div",{className:"header",children:[g("div",{className:"icon",style:{color:"white"},children:g(Hp,{})}),g("div",{className:"title-section",children:t?g(nt,{children:[g("div",{className:"skeleton skeleton-title"}),g("div",{className:"skeleton skeleton-subtitle"})]}):g(nt,{children:[g("h1",{children:r}),g("p",{className:"subtitle",children:["Start a tutorial and learn how to use ",s," through an interactive conversation."]})]})})]}),g("div",{className:"course-list-wrapper",children:g(Ww,{courses:e,selectedCourseId:(l==null?void 0:l.id)||"",loading:t,error:i,onCourseSelect:d})}),g("div",{className:"footer",children:[g("button",{className:"obi-button footer-button",onClick:h,disabled:!l,children:[g("span",{children:"Get started"}),g("svg",{xmlns:"http://www.w3.org/2000/svg",width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",children:g("path",{d:"M3.83325 8.00065H13.1666M13.1666 8.00065L8.49992 3.33398M13.1666 8.00065L8.49992 12.6673",stroke:l?"#FAFAFA":"#999","stroke-width":"1.33","stroke-linecap":"round","stroke-linejoin":"round"})})]}),g("p",{className:"footer-text",children:"Sessions are securely recorded for quality improvement purposes."})]})]})})}function Kw({session:n,sessionState:e,speakingState:t,spectrum:i,onStart:r,onContinue:s,onShareMicrophone:a,onShareScreen:o,onModalChange:c}){const[l,u]=Y(null);function d(f){l!==f&&(c==null||c(f),u(f))}function h(){e==="connecting"||e==="connected"||!e?r==null||r():e==="volume-check"||e==="mic-check"?s==null||s():e==="mic-share"?a==null||a():e==="screen-share"&&(o==null||o())}return ha(()=>{switch(e){case null:case"connecting":case"connected":return d("session-start"),g(Dw,{session:n,speakingState:t,onAction:h});case"volume-check":return d("voice-guidance"),g(Fw,{session:n,speakingState:t,spectrum:i,onAction:h});case"mic-check":return d("overview"),g(zw,{session:n,speakingState:t,spectrum:i,onAction:h});case"mic-share":return d("share-mic"),g(Bw,{session:n,speakingState:t,onAction:h});case"screen-share":return d("share-screen"),g(Gw,{session:n,speakingState:t,onAction:h});case"navigate":return d("navigate"),g(hw,{session:n,speakingState:t,onAction:h});default:return null}},[e,t,r,s,a,o])}function $w(n){const{session:e,sessionState:t,speakingState:i,spectrum:r,onClose:s,onStart:a,onContinue:o,onShareMicrophone:c,onShareScreen:l,onModalChange:u}=n,[d,h]=Y(null);function f(v){u==null||u(v),h(v)}function m(v){s(v,d),h(null)}const p=(n.open??!0)&&(!t||t==="connecting"||t==="connected"||t==="volume-check"||t==="mic-check"||t==="mic-share"||t==="screen-share"||t==="navigate");return g(ow,{open:p,onClose:m,preventOutsideClick:!0,children:()=>g(Kw,{session:e,sessionState:t,speakingState:i,spectrum:r,onStart:a,onContinue:o,onShareMicrophone:c,onShareScreen:l,onModalChange:f})})}const Yw={identify:()=>{},track:()=>{},page:()=>{},reset:()=>{}};function ii(){return Yw}const Xw=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,om="9.23.0",Ui=globalThis;function Jw(n,e,t=Ui){const i=t.__SENTRY__=t.__SENTRY__||{},r=i[om]=i[om]||{};return r[n]||(r[n]=e())}const Qw="Sentry Logger ",cm=["debug","info","warn","error","log","assert","trace"],lm={};function Zw(n){if(!("console"in Ui))return n();const e=Ui.console,t={},i=Object.keys(lm);i.forEach(r=>{const s=lm[r];t[r]=e[r],e[r]=s});try{return n()}finally{i.forEach(r=>{e[r]=t[r]})}}function ex(){let n=!1;const e={enable:()=>{n=!0},disable:()=>{n=!1},isEnabled:()=>n};return Xw?cm.forEach(t=>{e[t]=(...i)=>{n&&Zw(()=>{Ui.console[t](`${Qw}[${t}]:`,...i)})}}):cm.forEach(t=>{e[t]=()=>{}}),e}Jw("logger",ex);const um=1e3;function tx(){return Date.now()/um}function nx(){const{performance:n}=Ui;if(!(n!=null&&n.now))return tx;const e=Date.now()-n.now(),t=n.timeOrigin==null?e:n.timeOrigin;return()=>(t+n.now())/um}nx();const dm=50,Bi="?",hm=/\(error: (.*)\)/,fm=/captureMessage|captureException/;function ix(...n){const e=n.sort((t,i)=>t[0]-i[0]).map(t=>t[1]);return(t,i=0,r=0)=>{const s=[],a=t.split(`
|
|
55
55
|
`);for(let o=i;o<a.length;o++){const c=a[o];if(c.length>1024)continue;const l=hm.test(c)?c.replace(hm,"$1"):c;if(!l.match(/\S*Error: /)){for(const u of e){const d=u(l);if(d){s.push(d);break}}if(s.length>=dm+r)break}}return rx(s.slice(r))}}function rx(n){if(!n.length)return[];const e=Array.from(n);return/sentryWrapped/.test(ya(e).function||"")&&e.pop(),e.reverse(),fm.test(ya(e).function||"")&&(e.pop(),fm.test(ya(e).function||"")&&e.pop()),e.slice(0,dm).map(t=>({...t,filename:t.filename||ya(e).filename,function:t.function||Bi}))}function ya(n){return n[n.length-1]||{}}var pm;(function(n){n[n.PENDING=0]="PENDING";const e=1;n[n.RESOLVED=e]="RESOLVED";const t=2;n[n.REJECTED=t]="REJECTED"})(pm||(pm={})),Ui._sentryClientToLogBufferMap=new WeakMap,typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const sx=30,ax=50;function Qc(n,e,t,i){const r={filename:n,function:e==="<anonymous>"?Bi:e,in_app:!0};return t!==void 0&&(r.lineno=t),i!==void 0&&(r.colno=i),r}const ox=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,cx=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,lx=/\((\S*)(?::(\d+))(?::(\d+))\)/,ux=n=>{const e=ox.exec(n);if(e){const[,i,r,s]=e;return Qc(i,Bi,+r,+s)}const t=cx.exec(n);if(t){if(t[2]&&t[2].indexOf("eval")===0){const s=lx.exec(t[2]);s&&(t[2]=s[1],t[3]=s[2],t[4]=s[3])}const[i,r]=mm(t[1]||Bi,t[2]);return Qc(r,i,t[3]?+t[3]:void 0,t[4]?+t[4]:void 0)}},dx=[sx,ux],hx=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,fx=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;ix(...[dx,[ax,n=>{const e=hx.exec(n);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const r=fx.exec(e[3]);r&&(e[1]=e[1]||"eval",e[3]=r[1],e[4]=r[2],e[5]="")}let t=e[3],i=e[1]||Bi;return[i,t]=mm(i,t),Qc(t,i,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}]]);const mm=(n,e)=>{const t=n.indexOf("safari-extension")!==-1,i=n.indexOf("safari-web-extension")!==-1;return t||i?[n.indexOf("@")!==-1?n.split("@")[0]:Bi,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[n,e]};typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;function px(n){let e=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"__DOUBLE_STAR__").replace(/\*/g,"[^/]*").replace(/__DOUBLE_STAR__/g,".*").replace(/\?/g,"[^/]");return new RegExp(`^${e}$`,"i")}function mx(n,e){if(!e||e.length===0)return!1;const t=n.replace(/^https?:\/\//,"").replace(/\/$/,"");return e.some(i=>{try{const r=px(i);return r.test(t)||r.test(n)}catch(r){return console.warn(`Invalid URL pattern: ${i}`,r),!1}})}function Ta(n){if(!n||n.length===0)return!1;const e=window.location.origin+window.location.pathname;return mx(e,n)}function gx(n,e,t,i){function r(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(u){try{l(i.next(u))}catch(d){a(d)}}function c(u){try{l(i.throw(u))}catch(d){a(d)}}function l(u){u.done?s(u.value):r(u.value).then(o,c)}l((i=i.apply(n,e||[])).next())})}function vx(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,r,s,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function o(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(t=0)),t;)try{if(i=1,r&&(s=l[0]&2?r.return:l[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,l[1])).done)return s;switch(r=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,r=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(n,t)}catch(u){l=[6,u],r=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}typeof SuppressedError=="function"&&SuppressedError;for(var gm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",wr=typeof Uint8Array>"u"?[]:new Uint8Array(256),ka=0;ka<gm.length;ka++)wr[gm.charCodeAt(ka)]=ka;for(var bx=function(n){var e=n.length*.75,t=n.length,i,r=0,s,a,o,c;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);var l=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u"&&typeof Uint8Array.prototype.slice<"u"?new ArrayBuffer(e):new Array(e),u=Array.isArray(l)?l:new Uint8Array(l);for(i=0;i<t;i+=4)s=wr[n.charCodeAt(i)],a=wr[n.charCodeAt(i+1)],o=wr[n.charCodeAt(i+2)],c=wr[n.charCodeAt(i+3)],u[r++]=s<<2|a>>4,u[r++]=(a&15)<<4|o>>2,u[r++]=(o&3)<<6|c&63;return l},yx=function(n){for(var e=n.length,t=[],i=0;i<e;i+=2)t.push(n[i+1]<<8|n[i]);return t},Tx=function(n){for(var e=n.length,t=[],i=0;i<e;i+=4)t.push(n[i+3]<<24|n[i+2]<<16|n[i+1]<<8|n[i]);return t},ri=5,Zc=6+5,el=2,kx=Zc-ri,vm=65536>>ri,Sx=1<<ri,tl=Sx-1,Cx=1024>>ri,wx=vm+Cx,xx=wx,_x=32,Ex=xx+_x,Rx=65536>>Zc,Px=1<<kx,Ix=Px-1,bm=function(n,e,t){return n.slice?n.slice(e,t):new Uint16Array(Array.prototype.slice.call(n,e,t))},Ox=function(n,e,t){return n.slice?n.slice(e,t):new Uint32Array(Array.prototype.slice.call(n,e,t))},Ax=function(n,e){var t=bx(n),i=Array.isArray(t)?Tx(t):new Uint32Array(t),r=Array.isArray(t)?yx(t):new Uint16Array(t),s=24,a=bm(r,s/2,i[4]/2),o=i[5]===2?bm(r,(s+i[4])/2):Ox(i,Math.ceil((s+i[4])/4));return new Nx(i[0],i[1],i[2],i[3],a,o)},Nx=function(){function n(e,t,i,r,s,a){this.initialValue=e,this.errorValue=t,this.highStart=i,this.highValueIndex=r,this.index=s,this.data=a}return n.prototype.get=function(e){var t;if(e>=0){if(e<55296||e>56319&&e<=65535)return t=this.index[e>>ri],t=(t<<el)+(e&tl),this.data[t];if(e<=65535)return t=this.index[vm+(e-55296>>ri)],t=(t<<el)+(e&tl),this.data[t];if(e<this.highStart)return t=Ex-Rx+(e>>Zc),t=this.index[t],t+=e>>ri&Ix,t=this.index[t],t=(t<<el)+(e&tl),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},n}(),ym="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Mx=typeof Uint8Array>"u"?[]:new Uint8Array(256),Sa=0;Sa<ym.length;Sa++)Mx[ym.charCodeAt(Sa)]=Sa;var Tm=null;function Lx(n){return gx(this,void 0,void 0,function(){var e;return vx(this,function(t){switch(t.label){case 0:return Tm!==null?[3,2]:[4,n()];case 1:if(e=t.sent(),!e.base64||!e.byte_length)throw new Error("Invalid graphemes response");Tm=Ax(e.base64,e.byte_length),t.label=2;case 2:return[2]}})})}for(var km="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Dx=typeof Uint8Array>"u"?[]:new Uint8Array(256),Ca=0;Ca<km.length;Ca++)Dx[km.charCodeAt(Ca)]=Ca;function Ux(n,e,t,i){function r(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(u){try{l(i.next(u))}catch(d){a(d)}}function c(u){try{l(i.throw(u))}catch(d){a(d)}}function l(u){u.done?s(u.value):r(u.value).then(o,c)}l((i=i.apply(n,e||[])).next())})}function Bx(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,r,s,a=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),typeof Symbol=="function"&&(a[Symbol.iterator]=function(){return this}),a;function o(l){return function(u){return c([l,u])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;a&&(a=0,l[0]&&(t=0)),t;)try{if(i=1,r&&(s=l[0]&2?r.return:l[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,l[1])).done)return s;switch(r=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,r=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(n,t)}catch(u){l=[6,u],r=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}typeof SuppressedError=="function"&&SuppressedError;for(var Sm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",xr=typeof Uint8Array>"u"?[]:new Uint8Array(256),wa=0;wa<Sm.length;wa++)xr[Sm.charCodeAt(wa)]=wa;for(var Fx=function(n){var e=n.length*.75,t=n.length,i,r=0,s,a,o,c;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);var l=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u"&&typeof Uint8Array.prototype.slice<"u"?new ArrayBuffer(e):new Array(e),u=Array.isArray(l)?l:new Uint8Array(l);for(i=0;i<t;i+=4)s=xr[n.charCodeAt(i)],a=xr[n.charCodeAt(i+1)],o=xr[n.charCodeAt(i+2)],c=xr[n.charCodeAt(i+3)],u[r++]=s<<2|a>>4,u[r++]=(a&15)<<4|o>>2,u[r++]=(o&3)<<6|c&63;return l},jx=function(n){for(var e=n.length,t=[],i=0;i<e;i+=2)t.push(n[i+1]<<8|n[i]);return t},Vx=function(n){for(var e=n.length,t=[],i=0;i<e;i+=4)t.push(n[i+3]<<24|n[i+2]<<16|n[i+1]<<8|n[i]);return t},si=5,nl=6+5,il=2,Gx=nl-si,Cm=65536>>si,zx=1<<si,rl=zx-1,Hx=1024>>si,Wx=Cm+Hx,qx=Wx,Kx=32,$x=qx+Kx,Yx=65536>>nl,Xx=1<<Gx,Jx=Xx-1,wm=function(n,e,t){return n.slice?n.slice(e,t):new Uint16Array(Array.prototype.slice.call(n,e,t))},Qx=function(n,e,t){return n.slice?n.slice(e,t):new Uint32Array(Array.prototype.slice.call(n,e,t))},Zx=function(n,e){var t=Fx(n),i=Array.isArray(t)?Vx(t):new Uint32Array(t),r=Array.isArray(t)?jx(t):new Uint16Array(t),s=24,a=wm(r,s/2,i[4]/2),o=i[5]===2?wm(r,(s+i[4])/2):Qx(i,Math.ceil((s+i[4])/4));return new e_(i[0],i[1],i[2],i[3],a,o)},e_=function(){function n(e,t,i,r,s,a){this.initialValue=e,this.errorValue=t,this.highStart=i,this.highValueIndex=r,this.index=s,this.data=a}return n.prototype.get=function(e){var t;if(e>=0){if(e<55296||e>56319&&e<=65535)return t=this.index[e>>si],t=(t<<il)+(e&rl),this.data[t];if(e<=65535)return t=this.index[Cm+(e-55296>>si)],t=(t<<il)+(e&rl),this.data[t];if(e<this.highStart)return t=$x-Yx+(e>>nl),t=this.index[t],t+=e>>si&Jx,t=this.index[t],t=(t<<il)+(e&rl),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},n}(),xm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t_=typeof Uint8Array>"u"?[]:new Uint8Array(256),xa=0;xa<xm.length;xa++)t_[xm.charCodeAt(xa)]=xa;var _m=null;function n_(n){return Ux(this,void 0,void 0,function(){var e;return Bx(this,function(t){switch(t.label){case 0:return _m!==null?[3,2]:[4,n()];case 1:if(e=t.sent(),!e.base64||!e.byte_length)throw console.error("invalid graphemes response",e),new Error("Invalid graphemes response");_m=Zx(e.base64,e.byte_length),t.label=2;case 2:return[2]}})})}const i_=`:root,:host{--obi-modal-padding: 32px 48px;--obi-modal-background-color: #FFFFFF;--obi-modal-border-radius: 24px;--obi-modal-shadow: 0px 1px 2px rgba(0, 0, 0, .05);--obi-modal-xsmall-width: 320px;--obi-modal-xsmall-height: 240px;--obi-modal-small-width: 480px;--obi-modal-small-height: 400px;--obi-modal-medium-width: 640px;--obi-modal-medium-height: 372px;--obi-modal-large-width: 1200px;--obi-modal-large-height: 700px;--obi-font-family: "Satoshi", sans-serif;--obi-color-primary: #9500FF;--obi-color-primary-50: color-mix(in srgb, var(--obi-color-primary) 50%, white 50%);--obi-color-primary-30: color-mix(in srgb, var(--obi-color-primary) 30%, white 70%);--obi-color-tint: color-mix(in srgb, var(--obi-color-primary) 5%, white 95%);--obi-color-text: #18181B;--obi-course-color-selected: var(--obi-color-primary-50);--obi-course-color-tint: var(--obi-color-tint);--obi-course-progress-step-completed: #B3B3B3;--obi-course-progress-step-incomplete: #D9D9D9;--obi-course-progress-text-color: #757575;font-family:var(--obi-font-family);color:var(--obi-color-text)}.obi-button{font-family:var(--obi-font-family);color:var(--obi-color-text)}dialog{margin:auto;padding:0;border:none;border-radius:var(--obi-modal-border-radius);box-shadow:var(--obi-modal-shadow);background:var(--obi-modal-background-color);box-sizing:border-box}dialog>.modal-content{padding:var(--obi-modal-padding);box-sizing:border-box}dialog,dialog.modal-medium,dialog>.modal-content,dialog.modal-medium>.modal-content{width:var(--obi-modal-medium-width);min-height:var(--obi-modal-medium-height)}dialog.modal-xsmall,dialog.modal-xsmall>.modal-content{width:var(--obi-modal-xsmall-width);min-height:var(--obi-modal-xsmall-height)}dialog.modal-small,dialog.modal-small>.modal-content{width:var(--obi-modal-small-width);min-height:var(--obi-modal-small-height)}dialog.modal-large,dialog.modal-large>.modal-content{width:var(--obi-modal-large-width);min-height:var(--obi-modal-large-height)}dialog::backdrop{background:rgba(0,0,0,.5)}.tour-content{display:block;width:100%;height:100%}.tour-content .container{box-sizing:border-box;display:flex;flex-direction:column;align-items:center;padding:0;width:100%;height:100%}.tour-content .header{display:block;flex-grow:1;flex-direction:column;align-items:center;padding:0;width:100%;margin-bottom:16px}.tour-content .title{width:100%;font-family:Inter,sans-serif;font-style:normal;font-weight:700;font-size:24px;text-align:center;letter-spacing:-.03em;color:#18181b;margin:0 0 12px}.tour-content .subtitle{width:100%;font-family:Inter,sans-serif;font-style:normal;font-weight:400;font-size:16px;line-height:140%;text-align:center;letter-spacing:-.01em;color:#18181b;margin:0}.tour-content .visual{flex-grow:0;flex-shrink:0;display:flex;align-items:center;justify-content:center;position:relative;margin-bottom:24px}.tour-content .visual.glow{width:390px;border-radius:15px;background-color:var(--obi-color-tint)}.tour-content .description{height:45px;width:100%;font-family:Inter,sans-serif;font-style:normal;font-weight:400;font-size:16px;color:#757575!important;line-height:140%;text-align:center;letter-spacing:-.01em;color:#18181b;overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}.tour-content .button-container{flex-grow:0;display:flex;flex-direction:column;align-items:center;gap:16px;width:100%}.tour-content .action-button{box-sizing:border-box;display:flex;flex-direction:row;justify-content:center;align-items:center;padding:12px;gap:8px;height:40px;background:#303030;border:1px solid #303030;border-radius:4px;cursor:pointer;text-decoration:none}.tour-content .action-button.disabled{opacity:.6;cursor:not-allowed}.tour-content .button-text{height:16px;font-family:Inter,sans-serif;font-style:normal;font-weight:500;font-size:16px;line-height:100%;color:#fbf3ff}.tour.content-area{height:100%;flex:1;display:flex;flex-direction:column}.tour-footer{width:100%!important;text-align:center;display:flex;align-items:flex-end;justify-content:center;font-family:Inter,sans-serif;font-size:8px;font-weight:200;margin-top:20px}.session-start-content .description{height:48px}.obi-close-button{position:absolute;top:24px;right:24px;width:24px;height:24px;cursor:pointer;border:none;background:none;padding:0;display:flex;align-items:center;justify-content:center;z-index:1}.obi-pill.container{width:96px;height:30px;display:flex;align-items:center;justify-content:center}.obi-pill.container .pill{display:flex;align-items:center;justify-content:center;width:48px;height:6px;opacity:.7;border-radius:3px;background-color:var(--obi-color-primary);transition:width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out}.obi-pill.container .pill.button{cursor:pointer}.obi-pill.container.user-speaking .pill{background-color:var(--obi-color-primary-30)}.obi-pill.container.active .pill{width:96px;height:30px;border-radius:15px;opacity:1}.obi-pill.container.busy,.obi-pill.container.busy .pill{width:220px}.obi-pill2.container{display:flex;align-items:center;justify-content:center}.obi-pill2.container .pill{display:flex;align-items:center;justify-content:center;min-width:48px;max-width:48px;height:6px;opacity:.7;border-radius:3px;border:1px solid #FFFFFF1F;background-color:var(--obi-color-primary);transform:translateY(0);overflow:hidden;white-space:nowrap;flex:0 0 auto;box-sizing:border-box;padding-left:0;padding-right:0;transition:max-width .15s ease-in-out,min-width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out,padding-left .15s ease-in-out,padding-right .15s ease-in-out}.obi-pill2.container .pill.button{cursor:pointer}.obi-pill2.container:not(.active){transition:height 0s linear .15s;height:6px}.obi-pill2.container:not(.active) .pill{transform:translateY(12px);transition:transform 0s linear .15s,max-width .15s ease-in-out,min-width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out,padding-left .15s ease-in-out,padding-right .15s ease-in-out}.obi-pill2.container.active{transition:none;height:30px}.obi-pill2.container.active .pill{transition:transform 0s,max-width .15s ease-in-out,min-width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out,padding-left .15s ease-in-out,padding-right .15s ease-in-out;max-width:1000px;height:30px;border-radius:15px;opacity:1;padding-left:14px;padding-right:14px}.obi-pill2.container.user-speaking .pill{background-color:var(--obi-color-primary-30)}.obi-pill2.container:not(.active) .pill .text{opacity:0;animation:none}.obi-pill-up.container{display:flex;align-items:flex-end;justify-content:center}.obi-pill-up.container .pill{display:flex;align-items:center;justify-content:center;min-width:48px;max-width:48px;height:6px;opacity:.7;border-radius:3px;border:1px solid #FFFFFF1F;background-color:var(--obi-color-primary);overflow:hidden;white-space:nowrap;flex:0 0 auto;box-sizing:border-box;padding-left:0;padding-right:0;transition:max-width .15s ease-in-out,min-width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out,padding-left .15s ease-in-out,padding-right .15s ease-in-out}.obi-pill-up.container .pill.button{cursor:pointer}.obi-pill-up.container:not(.active){transition:height 0s linear .15s;height:6px}.obi-pill-up.container:not(.active) .pill{transition:max-width .15s ease-in-out,min-width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out,padding-left .15s ease-in-out,padding-right .15s ease-in-out}.obi-pill-up.container.active{transition:none;height:30px}.obi-pill-up.container.active .pill{transition:max-width .15s ease-in-out,min-width .15s ease-in-out,height .15s ease-in-out,border-radius .15s ease-in-out,padding-left .15s ease-in-out,padding-right .15s ease-in-out;max-width:1000px;height:30px;border-radius:15px;opacity:1;padding-left:14px;padding-right:14px}.obi-pill-up.container.user-speaking .pill{background-color:var(--obi-color-primary-30)}.obi-pill-up.container:not(.active) .pill .text{opacity:0;animation:none}.obi-equaliser{display:flex;align-items:center;gap:2px;height:32px}.obi-equaliser .column{position:relative;display:flex;align-items:center;justify-content:center;width:5px;height:100%}.obi-equaliser .bar{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:3px;border-radius:2px;z-index:1}.obi-panel{box-sizing:border-box;padding:24px;background-color:#fff;box-shadow:0 16px 32px -4px #0000001f,0 4px 8px -2px #00000014,inset 0 1px #fff9;border-radius:12px}.obi-popout{position:relative;display:inline-block}.obi-popout .obi-popout-target{cursor:pointer;display:inline-block}.obi-popout .content{position:absolute;background-color:#fff0;z-index:100;animation:popout-appear .15s ease-out}@keyframes popout-appear{0%{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}.obi-round-button-popout{z-index:600}.obi-round-button{flex:0 0 auto;display:flex;align-items:center;justify-content:center;width:30px;height:30px;border-radius:50%;padding:0;box-sizing:border-box;background-color:#fff;border:1px solid #D9D9D9;box-shadow:none}.obi-round-button:hover{cursor:pointer}.obi-round-button:disabled{box-shadow:none;background-color:#f0f0f0;color:#999;cursor:not-allowed!important;pointer-events:none}.obi-round-button-title{padding:8px 16px;border-radius:12px;background-color:#fff;color:#000;font-size:14px;font-weight:400;white-space:nowrap;box-shadow:0 4px 12px #00000026,0 2px 4px #0000001a;border:1px solid rgba(0,0,0,.08);z-index:5000;pointer-events:none;-webkit-user-select:none;user-select:none;position:relative}.obi-round-button-title:after{content:"";position:absolute;top:100%;left:50%;transform:translate(-50%);width:0;height:0;border-left:6px solid transparent;border-right:6px solid transparent;border-top:6px solid white;filter:drop-shadow(0 2px 2px rgba(0,0,0,.1))}.obi-message{display:inline-flex;align-items:center;justify-content:center;padding:0 15px;text-wrap:nowrap;font-size:16px;font-weight:400;height:30px;box-sizing:border-box;background-color:#fff;border-radius:15px;border:1px solid #D9D9D9}.obi-message.clickable{box-shadow:0 4px 6px #0000001a;cursor:pointer}.obi-loading-dots{display:flex;align-items:center;gap:2px;height:32px}.obi-loading-dots .column{position:relative;display:flex;align-items:center;justify-content:center;width:5px;height:100%}.obi-loading-dots .dot{width:3px;height:3px;border-radius:2px;position:relative;z-index:2}.obi-loading-dots .bar{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:3px;border-radius:2px;z-index:1;height:0px;animation:bounce .9s ease-in-out infinite}@keyframes bounce{0%,60%,to{height:0px}30%{height:16px}}.obi-exit-survey{position:relative;width:320px;margin:0 auto;-webkit-backdrop-filter:none;backdrop-filter:none;background:white;z-index:9999}.obi-exit-survey-container{display:flex;flex-direction:column;align-items:center;padding:0;gap:16px;width:272px;flex:none;align-self:stretch}.obi-exit-survey-header{display:flex;flex-direction:column;align-items:flex-start;padding:0;gap:4px;width:272px;flex:none;align-self:stretch}.obi-exit-survey-title{width:272px;height:22px;margin:0;font-family:Satoshi,sans-serif;font-size:16px;font-weight:600;line-height:140%;text-align:center;color:#1e1e1e;flex:none;align-self:stretch}.obi-exit-survey-subtitle{width:272px;height:20px;margin:0;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:14px;line-height:140%;text-align:center;color:#757575;flex:none;align-self:stretch}.obi-exit-survey-options{display:flex;flex-direction:column;align-items:flex-start;padding:0;gap:4px;width:272px;flex:none;align-self:stretch}.obi-exit-survey-options textarea{height:80px;resize:none;outline:none}.obi-exit-survey-button{box-sizing:border-box;display:flex;flex-direction:row;justify-content:center;align-items:center;padding:12px;gap:8px;width:272px;height:44px;border-radius:12px;cursor:pointer;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:14px;line-height:140%;flex:none;align-self:stretch;transition:all .2s ease}.obi-exit-survey-button:hover{transform:translateY(-1px);box-shadow:0 4px 8px #0000001a}.obi-exit-survey-button:active{transform:translateY(0)}.obi-exit-survey-button-continue{background:rgba(255,255,255);border:1px solid rgba(217,217,217);color:#1e1e1e}.obi-exit-survey-button-continue:hover{background:rgba(255,255,255);border-color:#d9d9d9}.obi-exit-survey-button-wrap-up{background:#303030;border:1px solid rgba(217,217,217);color:#fff;font-weight:500}.obi-exit-survey-button-wrap-up:hover{background:#404040;border-color:#d9d9d9}.obi-exit-survey-reason-button{background:rgba(255,255,255);border:1px solid rgba(217,217,217);color:#1e1e1e}.obi-exit-survey-reason-button:hover{background:rgba(255,255,255);border-color:#d9d9d9}.obi-exit-survey-reason-button-secondary{display:flex;flex-direction:row;justify-content:center;align-items:center;padding:4px 6px;gap:8px;width:272px;height:28px;border-radius:4px;cursor:pointer;border:none;background:transparent;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:14px;line-height:140%;color:#5a5a5a;flex:none;align-self:stretch;transition:all .2s ease}.obi-exit-survey-reason-button-secondary:hover{background:rgba(0,0,0,.05);color:#3a3a3a}.obi-message-input{display:inline-block;position:relative}.obi-message-input .container{width:212px;height:30px;box-sizing:border-box;background:#FFFFFF;border:1px solid var(--obi-color-primary-30);border-radius:15px;display:flex;align-items:center;flex:none;order:2;flex-grow:0;transition:height .3s ease,border-radius .3s ease;animation:expandMessageInput .2s cubic-bezier(.4,0,.2,1) 0s 1 normal both}.obi-message-input.expanded .container{height:auto;min-height:140px;border-radius:15px;align-items:flex-start;padding:8px 0;animation:expandMessageInputWide .2s cubic-bezier(.4,0,.2,1) 0s 1 normal both}.obi-message-input .field{flex:1 1 0;border:none;background:transparent;outline:none;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:14px;line-height:18px;color:#000;padding:4px 3px 0 16px;height:100%;box-sizing:border-box;min-width:0;resize:none;overflow:hidden;scrollbar-width:none;transition:padding .3s ease;animation:fadeInInputField .2s cubic-bezier(.4,0,.2,1) 0s 1 normal both}.obi-message-input.expanded .field{height:auto;min-height:120px;padding:4px 16px;overflow-y:auto;line-height:18px}.obi-message-input .field::placeholder{color:#999}.obi-message-input .field:disabled{cursor:not-allowed;opacity:.6}.obi-message-input .send{position:absolute;bottom:3px;right:4px;flex-shrink:0;width:24px;height:24px;background:var(--obi-color-primary);border:none;border-radius:9999px;display:flex;justify-content:center;align-items:center;cursor:pointer;transition:all .3s ease;color:#fff}.obi-message-input.expanded .send{width:28px;height:28px;position:relative;top:0;bottom:0;margin-right:0}.obi-message-input.expanded .button-container{display:flex;justify-content:space-between;align-items:center;width:100%;margin-top:8px}.obi-message-input .send:disabled{background:#CCCCCC;cursor:not-allowed;transform:none}.obi-message-input .container:focus-within{border-color:var(--obi-color-primary);box-shadow:0 0 0 2px #9008ff1a}@keyframes expandMessageInput{0%{width:32px}to{width:212px}}@keyframes expandMessageInputWide{0%{width:212px}to{width:340px}}@keyframes fadeInInputField{0%{opacity:0}60%{opacity:0}to{opacity:1}}.obi-course-progress{display:flex;flex-direction:column;justify-content:center;align-items:flex-start;gap:6px;width:100%;min-width:0;height:24px;flex:none;order:1;align-self:stretch;flex-grow:0}.obi-course-progress-steps{display:flex;flex-direction:row;align-items:center;justify-content:space-between;padding:0;gap:2px;width:100%;height:14px;flex:none;order:0;align-self:stretch;flex-grow:0}.obi-course-progress-container{display:flex;flex-direction:column;justify-content:center;align-items:stretch;padding:6px 0;height:100%;flex:1;min-width:0;cursor:pointer}.obi-course-progress-step{width:100%;height:2px;background:var(--obi-course-progress-step-incomplete);border-radius:24px;flex:none;order:0;align-self:stretch;flex-grow:0;cursor:pointer}.obi-course-progress-step.completed{background:var(--obi-course-progress-step-completed)}.obi-course-progress-description{width:100%;height:14px;font-family:var(--obi-font-family);font-style:normal;font-weight:500;font-size:14px;line-height:100%;color:var(--obi-course-progress-text-color);flex:none;order:1;flex-grow:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.obi-course-progress .obi-widget-popout,.obi-course-progress .obi-widget-popout .content{z-index:800}.obi-widget-popout{z-index:400}.obi-widget-panel{display:flex;flex-direction:column;gap:8px;align-items:center;justify-content:center;min-width:222px;width:min-content;padding:12px;box-sizing:border-box;border-radius:27px;background:white;transition:background .1s ease-out .1s,box-shadow .1s ease-out .1s}.obi-widget-panel:not(.messaging){width:256px}.obi-widget-panel.tool-usage{width:384px}.obi-widget-panel:not(.expanded){background:transparent;border:none;box-shadow:none;transition:background .1s ease-out .1s,border .1s ease-out .1s,box-shadow .1s ease-out .1s}.obi-widget-panel.maximized{transform:translateY(-110px)}.obi-widget-panel .obi-widget{display:flex;align-items:center;min-width:192px;padding-left:58px;box-sizing:border-box;gap:4px}.obi-widget-panel .obi-widget.active.in-plan{padding-left:0}.obi-widget-panel .obi-widget.active.in-plan .obi-round-button{animation:fade-in-button .2s ease-out .15s both}.obi-widget-panel .obi-widget.active .obi-equaliser{animation:fade-in-equaliser .2s ease-out .15s both}@keyframes fade-in-button{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes fade-in-equaliser{0%{opacity:0}to{opacity:1}}.obi-widget-panel .obi-widget-course-progress{display:block;width:100%;max-width:220px;max-height:40px;opacity:1;transform:translateY(0);overflow:visible;position:relative;z-index:800;transition:max-height .3s ease-in-out,opacity .3s ease-in-out,transform .3s ease-in-out}.obi-widget-panel .obi-widget-course-progress.expanded{max-width:330px}@keyframes expand-course-progress{0%{max-height:0;opacity:0;transform:translateY(-10px)}to{max-height:40px;opacity:1;transform:translateY(0)}}.obi-widget-pill-text{font-size:16px;font-weight:400;color:#fff;opacity:0;animation:fade-in-pill-text .3s ease-in-out forwards}@keyframes fade-in-pill-text{0%{opacity:0}40%{opacity:0}to{opacity:1}}.obi-widget-buttons{display:flex;flex-direction:row;gap:4px}.obi-widget-out-of-plan{display:flex;align-items:center;gap:0}.obi-widget-out-of-plan .text{font-size:16px;color:#fff;display:inline-flex;align-items:center;gap:8px;animation:fade-in-pill-text .3s ease-in-out forwards}.obi-widget-out-of-plan .round-button{display:none;animation:fade-in-button .2s ease-out .15s both}.obi-widget-out-of-plan .message{display:none}.obi-widget-out-of-plan.active{gap:0}.obi-widget-out-of-plan.active:hover,.obi-widget-out-of-plan.active.hover{gap:4px}.obi-widget-out-of-plan.active:hover .round-button,.obi-widget-out-of-plan.active:hover .message,.obi-widget-out-of-plan.active.hover .round-button,.obi-widget-out-of-plan.active.hover .message{display:flex}.obi-widget-draggable .obi-widget-panel{cursor:grab}.obi-widget-draggable.dragging .obi-widget-panel{cursor:grabbing;-webkit-user-select:none;user-select:none}.obi-static-voice{height:96px;display:flex;flex-direction:column;align-items:center;justify-content:center}.obi-static-voice-visual-title{font-family:Inter,sans-serif;font-style:normal;font-weight:600;font-size:14px;color:var(--obi-color-primary);background-color:var(--obi-color-tint);padding:8px 12px;border-radius:20px;margin-bottom:24px}.obi-static-voice-visual{display:flex;align-items:center;gap:2px;height:32px}.obi-static-voice-visual .column{position:relative;display:flex;align-items:center;justify-content:center;width:5px;height:100%}.obi-static-voice-visual .bar{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:3px;background-color:#fff;border-radius:2px;z-index:1}.obi-static-voice-visual .bar-1{height:2px}.obi-static-voice-visual .bar-2{height:6px}.obi-static-voice-visual .bar-3{height:10px}.obi-static-voice-visual .bar-4,.obi-static-voice-visual .bar-5{height:16px}.obi-static-voice-visual .bar-6{height:10px}.obi-static-voice-visual .bar-7{height:6px}.obi-static-voice-visual .bar-8{height:2px}.tour-select{display:block;font-family:Inter,sans-serif}.course-container{display:flex;padding:20px;align-items:flex-start;gap:8px;height:180px;border-radius:6px;border:1px solid rgba(0,0,0,.6);background:#fff;cursor:pointer;transition:all .2s;flex-direction:column;box-sizing:border-box;overflow:hidden}.course-container:hover{background-color:#f9fafb;border-color:#d1d5db;box-shadow:0 1px 2px #0000000d}.course-container:active{transform:scale(.98)}.course-container.selected{border-radius:6px;border:1px solid var(--obi-course-color-selected);background:var(--obi-course-color-tint)}.course-container.selected:hover{background:var(--obi-course-color-tint)}.header-row{display:flex;justify-content:space-between;align-items:flex-start;align-self:stretch;flex-shrink:0;text-align:left}.course-title{color:#000;font-family:Inter,sans-serif;font-size:20px;font-style:normal;font-weight:500;line-height:100%;letter-spacing:-.2px;margin:0}.duration{display:flex;padding:4px 12px;justify-content:center;align-items:center;gap:8px;border-radius:9999px;background:var(--obi-course-color-tint);color:#000;font-family:Inter,sans-serif;font-size:14px;font-style:normal;font-weight:500;line-height:100%;letter-spacing:-.14px;flex-shrink:0}.course-container.selected .duration{background:#fff}.course-description{flex:1 0 0;color:#0009;font-family:Inter,sans-serif;font-size:16px;font-style:normal;font-weight:400;line-height:140%;letter-spacing:-.16px;margin:0;overflow:hidden;display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;text-align:left}.course-grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:4px;padding:0;flex:1 0 0;align-self:stretch;min-height:364px}.controls{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}.tabs{display:flex;gap:10px}.tab{display:flex;padding:6px 12px;justify-content:center;align-items:center;align-self:stretch;border:none;background:none;cursor:pointer;font-family:Inter,sans-serif;font-size:16px;font-weight:500;color:#0006;border-bottom:2px solid transparent;transition:all .2s}.tab.active{color:#000;border-bottom:2px solid var(--obi-color-primary)}.tab:hover{color:#000}.filter{position:relative;display:flex;align-items:center;width:336px;height:40px}.filter input{color:var(--obi-color-text);caret-color:var(--obi-color-text);padding:8px 12px 8px 36px;border-radius:6px;border:1px solid rgba(0,0,0,.1);background:#fff;font-family:Inter,sans-serif;font-size:14px;line-height:20px;width:100%;height:100%;box-sizing:border-box;outline:none}.filter input:focus{outline:1px solid var(--obi-color-primary);outline-offset:-1px}.filter input::placeholder{color:#0006}.filter svg{position:absolute;left:12px;pointer-events:none}@media (max-width: 767px){.course-grid{grid-template-columns:1fr}}.loading,.error,.empty{display:flex;justify-content:center;align-items:center;margin-top:16px}.error{color:#ef4444}.tour-select-modal-container{display:flex;flex-direction:column;align-items:center;gap:24px;flex:1 0 0;align-self:stretch;font-family:Satoshi,sans-serif;color:#000;text-align:center;max-width:1200px;width:100%;min-height:600px;box-sizing:border-box}.course-list-wrapper{flex:1;overflow-y:auto;width:100%;min-height:0;max-height:424px;padding-right:3px;box-sizing:border-box}.course-list-wrapper::-webkit-scrollbar{width:3px}.course-list-wrapper::-webkit-scrollbar-track{background:transparent}.course-list-wrapper::-webkit-scrollbar-thumb{background-color:#000;border-radius:2px;min-height:20px}.course-list-wrapper::-webkit-scrollbar-thumb:hover{background-color:#333}.header{display:flex;align-items:flex-start;gap:16px;width:100%;text-align:left}.icon{display:flex;width:56px;height:56px;padding:12px;justify-content:center;align-items:center;border-radius:12px;border:1px solid var(--obi-color-primary);background:var(--obi-color-primary);box-sizing:border-box}.icon img{width:32px;height:32px;color:#fff;fill:#fff}.title-section{align-self:stretch;flex:1}.tour-select-modal-container h1{color:#18181b;font-family:Satoshi;font-size:32px;font-style:normal;font-weight:700;line-height:90%;letter-spacing:-.96px;margin:0 0 8px}.subtitle{color:#18181b;font-family:Satoshi;font-size:20px;font-style:normal;font-weight:500;line-height:90%;letter-spacing:-.6px;margin:0}.footer{display:flex;width:360px;flex-direction:column;align-items:center;gap:12px}.footer-button{display:flex;height:48px;padding:16px;justify-content:center;align-items:center;gap:8px;align-self:stretch;border-radius:6px;background:#18181b;border:none;cursor:pointer;color:#fafafa;font-family:Satoshi;font-weight:500;transition:opacity .2s ease}.footer-button:disabled{opacity:.5;cursor:not-allowed}.footer-button:not(:disabled){opacity:1}.footer-button:not(:disabled):hover{background:#27272a}.footer-text{color:#18181b;font-family:Satoshi;font-size:12px;font-style:normal;font-weight:400;line-height:100%;letter-spacing:-.12px;margin:0;text-align:center}.skeleton{background:linear-gradient(90deg,#e5e7eb 25%,#f3f4f6 50%,#e5e7eb 75%);background-size:200% 100%;animation:loading 1.5s infinite;border-radius:4px}@keyframes loading{0%{background-position:200% 0}to{background-position:-200% 0}}.skeleton-title{height:32px;width:60%;margin-bottom:12px}.skeleton-subtitle{height:20px;width:80%}
|
|
56
|
-
`;function r_(n){var xt,hn,_t,Jt,oi,_r,Er,_a,ji,Vn,fn;const[e,t]=Y(!1),[i,r]=Y(!1),[s,a]=Y(!1),[o,c]=Y(null),[l,u]=Y(!1),[d,h]=Y(null),[f,m]=Y(null),[p,v]=Y(null),[b,C]=Y(!1),x=Be(null),k=Be(0),S=Be(0),w=Be(0),E=Be(0),A=Be({width:0,height:0}),O=Be(null),B=Be(!1),L=6,R=s_(n.sdk,H,n.shadowHost,m,a,N=>{if(!N){c(null);return}if(Fe&&(c(N),!de&&K==="minimized")){u(!0);const q=Math.max(0,N.autoCloseMs??3e3);d&&window.clearTimeout(d);const Z=window.setTimeout(()=>u(!1),q);h(Z)}});function H(N){var q;(q=R.client)!=null&&q.session||(N?We():t(!1))}if(!R.client)return null;const Q=R.client.planIsCompleted.filter(Boolean).length===R.client.plans.length,X=a_((xt=R.client.product)==null?void 0:xt.widget_url_blacklist),K=Q?R.completedWidgetDisplay||((hn=R.client.product)==null?void 0:hn.completed_widget_display):R.widgetDisplay||((_t=R.client.product)==null?void 0:_t.widget_display),ye=R.widgetPosition||((Jt=R.client.product)==null?void 0:Jt.widget_position);let Te=R.isActive;((_r=(oi=R.client)==null?void 0:oi.product)==null?void 0:_r.name)==="Canibuild"&&(Te=!0);const W=R.client.session,de=!!W,te=de&&!e;let ge;switch(W==null?void 0:W.speakingState){case"listening":ge="user-speaking";break;case"speaking":ge="agent-speaking";break;case"thinking":ge="thinking";break;case"busy":ge="busy";break}const oe=W==null?void 0:W.isPaused,Fe=de||R.client.state==="ready"&&Te&&!X&&(K!=="invisible"||R.client.selectedPlan),$=()=>{var N,q,Z,Se,qe,Qt,pn;return{name:(N=R.client.selectedPlan)==null?void 0:N.name,description:(q=R.client.selectedPlan)==null?void 0:q.description,appName:(Z=R.client.product)==null?void 0:Z.name,appLogoUrl:((Se=R.client.product)==null?void 0:Se.logo_url)||"",url:(qe=R.client.product)==null?void 0:qe.url,agentName:((Qt=R.client.product)==null?void 0:Qt.agent_name)||"Obi",legalFooter:((pn=R.client.product)==null?void 0:pn.legal_footer_text)||void 0}};function ke(){const N=ye==="bottom-right"?{position:"fixed",right:"250px",width:"max-content",transform:"translateX(50%)"}:{position:"fixed",left:"50%",transform:"translateX(-50%)",width:"max-content"};return te?N.top="calc(100vh - 100px)":N.bottom="20px",N}const Le=(()=>{if(de&&p)return{position:"fixed",left:`${Math.round(p.left)}px`,top:`${Math.round(p.top)}px`,width:"max-content",right:void 0,bottom:void 0,transform:void 0,touchAction:"none"};const N=ke();return de&&(N.touchAction="none"),N})();Qe(()=>{de||(v(null),C(!1),x.current=null,B.current=!1,O.current&&(cancelAnimationFrame(O.current),O.current=null))},[de]);function gt(N,q,Z){return Math.max(q,Math.min(Z,N))}function bt(N){var Qt;if(!de)return;const q=N.currentTarget;if(!q)return;const Z=N.target;if((Qt=Z==null?void 0:Z.closest)==null?void 0:Qt.call(Z,'button, a[href], input, textarea, select, [role="button"], [contenteditable="true"], [data-no-drag]'))return;x.current=N.pointerId;const qe=q.getBoundingClientRect();k.current=N.clientX,S.current=N.clientY,w.current=qe.left,E.current=qe.top,A.current={width:qe.width,height:qe.height},B.current=!1,v({left:qe.left,top:qe.top})}function Fi(N){var mn;if(!de||x.current!==N.pointerId)return;const q=N.clientX-k.current,Z=N.clientY-S.current;if(!b){if(Math.hypot(q,Z)<L)return;const gn=N.currentTarget;try{(mn=gn==null?void 0:gn.setPointerCapture)==null||mn.call(gn,N.pointerId)}catch{}C(!0),B.current=!0,p||v({left:w.current,top:E.current})}const Se=8,qe=Se,Qt=Se,pn=Math.max(Se,window.innerWidth-A.current.width-Se),Vi=Math.max(Se,window.innerHeight-A.current.height-Se),Et={left:gt(w.current+q,qe,pn),top:gt(E.current+Z,Qt,Vi)};if(O.current==null){const Gi=Et;O.current=requestAnimationFrame(()=>{v(Gi),O.current=null})}else v(Et)}function ai(N){var q,Z;if(x.current!==null)try{(Z=(q=N.currentTarget)==null?void 0:q.releasePointerCapture)==null||Z.call(q,x.current)}catch{}x.current=null,C(!1)}function ne(N){de&&x.current===N.pointerId&&ai(N)}function je(N){de&&x.current===N.pointerId&&ai(N)}const We=()=>{const N=R.client;if(!N)return;const q=N.plans||[];if(q.length===1){const[Z]=q;N.selectedPlanUuid!==Z.uuid&&(N.selectPlan(Z),ii().track("course-get-started",{courseName:Z.name,courseUuid:Z.uuid})),t(!1),r(!0);return}t(!0)};return g("div",{children:[e&&g(qw,{open:e,courses:R.client.plans.map((N,q)=>{var Z,Se;return{id:N.uuid,name:N.name,description:N.description||"",duration:N.duration||0,completed:((Se=(Z=R.client)==null?void 0:Z.planIsCompleted)==null?void 0:Se[q])||!1}}),loading:!1,title:((Er=R.client.product)==null?void 0:Er.assistant_subtitle)||void 0,productName:((_a=R.client.product)==null?void 0:_a.name)||"",onCourseHighlight:N=>{N&&ii().track("course-selected",{courseName:N.name,courseUuid:N.id})},onCourseSelect:N=>{const q=R.client.plans.find(Z=>Z.uuid===N.id)||null;q&&(q==null?void 0:q.uuid)!==R.client.selectedPlanUuid&&(R.client.selectPlan(q),t(!1),r(!0),ii().track("course-get-started",{courseName:N.name,courseUuid:N.id}))},onClose:N=>{N==="user-initiated"&&R.client.selectPlan(null),t(!1)}}),Fe&&g(nt,{children:[g("div",{className:de?`obi-widget-draggable${b?" dragging":""}`:void 0,style:Le,onPointerDown:bt,onPointerMove:Fi,onPointerUp:ne,onPointerCancel:je,onClickCapture:N=>{var q,Z;B.current&&((q=N.preventDefault)==null||q.call(N),(Z=N.stopPropagation)==null||Z.call(N),B.current=!1)},children:g(rw,{inPlan:de,isActive:i?!1:l?!0:void 0,defaultIsActive:K!=="minimized",isPaused:oe,toastMessage:o,messaging:(W==null?void 0:W.isMicShared)===!1||s?!0:void 0,speakingStatus:ge,spectrum:()=>(W==null?void 0:W.audioSpectrum())||null,courseProgress:f,onOpen:We,onCancelClick:()=>{},onCancelAbort:()=>{},onCancel:()=>{var N;(N=R.client.session)==null||N.stop()},onCancelReason:(N,q)=>{},onPause:()=>{var N,q;(q=(N=R.client.session)==null?void 0:N.pause)==null||q.call(N)},onUnpause:()=>{var N,q;(q=(N=R.client.session)==null?void 0:N.unpause)==null||q.call(N)},onMessagingChange:N=>{var q,Z,Se,qe;a(!1),N?(Z=(q=R.client.session)==null?void 0:q.muteMicrophone)==null||Z.call(q):(qe=(Se=R.client.session)==null?void 0:Se.unmuteMicrophone)==null||qe.call(Se)},onMessageChange:N=>{ii().track("chat-input-provided",{message:N,length:N.length})},onMessage:N=>{R.say(N),a(!1),ii().track("chat-message-sent",{message:N,length:N.length})},onHover:N=>{},onOneClickAction:N=>{a(!1)},onMinimize:()=>{},agentName:((ji=R.client.product)==null?void 0:ji.agent_name)||"Obi",completedTutorials:((Vn=R.client.product)==null?void 0:Vn.widget_show_progress)===!1?void 0:R.client.planIsCompleted.filter(Boolean).length,totalTutorials:((fn=R.client.product)==null?void 0:fn.widget_show_progress)===!1?void 0:R.client.plans.length})}),!!R.client.selectedPlan&&g($w,{open:!0,session:$(),sessionState:(W==null?void 0:W.state)||null,speakingState:(W==null?void 0:W.speakingState)||null,spectrum:()=>(W==null?void 0:W.audioSpectrum())||null,onModalChange:N=>{},onClose:(N,q)=>{var Z,Se;N==="user-initiated"&&(((Z=R.client.session)==null?void 0:Z.state)==="mic-share"?(Se=R.client.session)==null||Se.shareMicrophoneFailed():R.client.stopSession()),r(!1)},onStart:()=>{R.client.selectedPlanUuid&&R.startSession()},onContinue:()=>{W==null||W.continue()},onShareMicrophone:()=>{W==null||W.shareMicrophone()}})]})]})}function s_(n,e,t,i,r,s){const[a,o]=Y(0),[c,l]=Y(null),u=Be(s);Qe(()=>{u.current=s},[s]);const d=h=>{var f;(f=u.current)==null||f.call(u,h)};return Qe(()=>{const h=m=>{e(m)};n.on("showMenu",h);const f=()=>{o(m=>m+1)};return n.on("configUpdated",f),n.on("showMessage",d),()=>{var m,p,v;(m=n.off)==null||m.call(n,"showMenu",h),(p=n.off)==null||p.call(n,"configUpdated",f),(v=n.off)==null||v.call(n,"showMessage",d)}},[n]),Qe(()=>{n.client&&(n.client.session&&l(n.client.session),n.client.on("sessionStarted",h=>{l(h),r==null||r(!1),o(f=>f+1)}),n.client.on("sessionStopped",()=>{l(null),r==null||r(!1),o(h=>h+1)}),n.client.on("sessionShutdown",()=>{o(h=>h+1)}),n.client.on("sessionResumed",()=>{o(h=>h+1)}),n.client.on("stateChanged",()=>{var h;n.client.state==="ready"&&t.style.setProperty("--obi-color-primary",((h=n.client.product)==null?void 0:h.primary_color)||"#9500FF"),o(f=>f+1)}),n.client.on("planSelected",()=>{o(h=>h+1)}))},[n,n.client]),Qe(()=>{if(!c)return;c.on("stateChanged",()=>{o(f=>f+1)}),c.on("speakingStateChanged",()=>{o(f=>f+1)}),c.on("paused",()=>{o(f=>f+1)}),c.on("unpaused",()=>{o(f=>f+1)}),c.on("micCheckComplete",f=>{}),c.on("transcript",(f,m)=>{}),c.on&&c.on("textInputRequested",()=>{r==null||r(!0),o(f=>f+1)});const h=f=>{i(f)};return c.on&&c.on("courseProgress",h),()=>{c.off&&c.off("courseProgress",h),c.off&&c.off("textInputRequested")}},[c]),n}function a_(n){const[e,t]=Y(()=>Ta(n));return Qe(()=>{t(Ta(n))},[n]),Qe(()=>{o_();const i=()=>{t(Ta(n))};return window.addEventListener("locationchange",i),window.addEventListener("popstate",i),window.addEventListener("hashchange",i),()=>{window.removeEventListener("locationchange",i),window.removeEventListener("popstate",i),window.removeEventListener("hashchange",i)}},[n]),e}function o_(){const n=window;if(n.__obi_history_patched)return;const{pushState:e,replaceState:t}=window.history,i=r=>function(...s){const a=r.apply(this,s);return window.dispatchEvent(new Event("locationchange")),a};window.history.pushState=i(e),window.history.replaceState=i(t),n.__obi_history_patched=!0}function c_(n){if(document.querySelector("obi-widget"))return;l_();const e=document.createElement("div");e.id="obi-host",e.style.position="fixed",e.style.zIndex="9999",document.body.appendChild(e);const t=e.attachShadow({mode:"open"}),i=document.createElement("div");i.id="obi-container",t.appendChild(i);const r=new CSSStyleSheet;r.replaceSync(i_),t.adoptedStyleSheets=[r],k1(g(r_,{sdk:n,shadowHost:e}),i),console.log("[obi-sdk] widget mounted")}function l_(){Em("https://fonts.cdnfonts.com/css/satoshi"),Em("https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap")}function Em(n){const e=document.createElement("link");e.href=n,e.rel="stylesheet",document.head.appendChild(e)}const Rm="49206C6F7665204F6269_session",Pm="obi-url-params";class u_ extends Pa{constructor(e){super(),this.client=null,this.isActive=!1,this.primaryColour="#9500FF",this.passivePlanUuid=null,this.commandLog=[],this.commandQueue=[],this._resumed=!1,this.dispatchCommand=(t,i)=>{var r,s,a,o,c;switch(this.commandLog.push({commandType:t,args:i}),t){case"update":this.updateConfig(i);break;case"startSession":if(!(i!=null&&i.planUuid)){console.warn("[obi] startSession command requires a planUuid",i);return}const l=(((r=this.client)==null?void 0:r.plans)||[]).find(u=>u.uuid===i.planUuid)||null;if(!l){console.warn("[obi] startSession command requires a valid planUuid",i);return}this.updateActive(!0),(a=(s=this.client)==null?void 0:s.selectPlan)==null||a.call(s,l);break;case"stopSession":(c=(o=this.client)==null?void 0:o.stopSession)==null||c.call(o);break;case"say":this.say(i);break;default:console.warn("[obi] unknown command",{commandType:t,args:i})}},e&&this.createClient(e),this.parsePassiveParams()}async createClient(e){if(this.client){this.client.appToken!==e&&console.warn("[obi] client already exists with different app token");return}let t=null;const i=this.load();if(i)try{t=sa.deserialise(i,e,"sdk",{apiBaseUrl:"https://staging.coragents.ai",captureScreen:this.captureScreen.bind(this)}),t?this._resumed=!0:localStorage.removeItem("obi-client")}catch(r){console.error("[obi] error loading cached client",r)}t||(t=new sa(e,"sdk",{apiBaseUrl:"https://staging.coragents.ai",captureScreen:this.captureScreen.bind(this)})),this.client=t,this.client.on("stateChanged",r=>{var s,a,o,c,l,u,d,h,f,m;r==="ready"&&this.updateConfig({isActive:((s=window==null?void 0:window.obiWidgetConfig)==null?void 0:s.isActive)??((a=this.client)==null?void 0:a.showWidget),primaryColour:((c=(o=this.client)==null?void 0:o.product)==null?void 0:c.primary_color)||"#9500FF",widgetDisplay:((l=window==null?void 0:window.obiWidgetConfig)==null?void 0:l.widgetDisplay)||((d=(u=this.client)==null?void 0:u.product)==null?void 0:d.widget_display)||"regular",completedWidgetDisplay:((h=window==null?void 0:window.obiWidgetConfig)==null?void 0:h.completedWidgetDisplay)||((m=(f=this.client)==null?void 0:f.product)==null?void 0:m.completed_widget_display)||"regular"})}),this.client.on("sessionStarted",()=>{this.save(),this.passivePlanUuid=null}),this.client.on("sessionStopped",()=>{localStorage.removeItem("obi-client"),this.passivePlanUuid=null}),this.client.on("sessionShutdown",()=>{localStorage.removeItem("obi-client")}),this.client.on("trackEvent",(r,s)=>{}),this.client.session&&this.client.resumeSession(r=>{r.on("stateChanged",s=>{s!=="disconnecting"&&s!=="disconnected"&&s!=="error"&&s!=="connecting"&&this.save()}),r.on("paused",()=>{this.save()}),r.on("unpaused",()=>{this.save()})})}_maybeActOnServerEngagement(){var o;const e=this.client;if(!e||e.state!=="ready")return;const t=e.product,i=(o=e.engagement)==null?void 0:o.style;if(!i||t&&Ta(t.widget_url_blacklist||[])||!e.showWidget)return;const r=e.plans||[],s=e.planIsCompleted||[],a=r.length>0&&s.filter(Boolean).length===r.length;if(!(r.length===0||a)){if(i==="modal"){const c=s.findIndex(u=>!u),l=c>=0?r[c]:null;l&&e.selectPlan(l)}else i==="popover"&&setTimeout(()=>{this.showMessage("Don't forget to complete your onboarding",{autoCloseMs:1e4})},1e3);try{ii().track("engagement-prompt-shown",{style:i})}catch{}}}async initialise(e={}){var t;this.commandQueue=e.queuedCommands||[],this._resumed?(this._resumed=!1,this.dispatchCommandQueue()):this.client?this.client.initialise({planUuid:this.passivePlanUuid||void 0,identity:((t=window==null?void 0:window.obiWidgetConfig)==null?void 0:t.user)||void 0}).then(()=>{this.emit("initialised");try{this._maybeActOnServerEngagement()}catch{}this.dispatchCommandQueue()}).catch(i=>{console.error("[obi] error initialising client",i),this.emit("error",i)}):this.dispatchCommandQueue()}async updateConfig(e){await this.updateAppToken(e.apiKey),this.updateActive(e.isActive),this.updatePrimaryColour(e.primaryColour),this.updateWidgetDisplay(e.widgetDisplay),this.updateCompletedWidgetDisplay(e.completedWidgetDisplay),this.updateWidgetPosition(e.widgetPosition),await this.updateIdentity(e.user),this.updateShowMenu(e.showMenu),this.emit("configUpdated")}async updateAppToken(e){var t;e===void 0||e==((t=this.client)==null?void 0:t.appToken)||(this.passivePlanUuid,await this.createClient(e),this.client&&await this.client.initialise({planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised");try{this._maybeActOnServerEngagement()}catch{}}).catch(i=>{console.error("[obi] error initialising client",i),this.emit("error",i)}))}updateActive(e){e===void 0||e==this.isActive||(this.isActive=e)}updatePrimaryColour(e){e===void 0||e==this.primaryColour||(this.primaryColour=e)}updateWidgetDisplay(e){e===void 0||e==this.widgetDisplay||(this.widgetDisplay=e)}updateCompletedWidgetDisplay(e){e===void 0||e==this.completedWidgetDisplay||(this.completedWidgetDisplay=e)}updateWidgetPosition(e){e===void 0||e==this.widgetPosition||(this.widgetPosition=e)}async updateIdentity(e){var i,r;if(e===void 0||e==((i=this.client)==null?void 0:i.identity))return;(r=this.client)==null||r.identity;let t=e?{...e,extra:{...e,...(e==null?void 0:e.extra)||{}}}:void 0;await this.client.initialise({identity:t,planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised");try{this._maybeActOnServerEngagement()}catch{}}).catch(s=>{console.error("[obi] error initialising client",s),this.emit("error",s)}),e!=null&&e.email&&ii().identify((e==null?void 0:e.email)||"",t)}updateShowMenu(e){e!==void 0&&this.emit("showMenu",e)}async say(e){var t,i,r;await((r=(i=(t=this.client)==null?void 0:t.session)==null?void 0:i.say)==null?void 0:r.call(i,e))}async startSession(){await this.client.startSession(this.client.selectedPlanUuid,e=>{e.on("stateChanged",t=>{t!=="disconnecting"&&t!=="disconnected"&&t!=="error"&&t!=="connecting"&&this.save()})})}dispatchCommandQueue(){const e=this.commandQueue;this.commandQueue=[],e.forEach(t=>{try{this.dispatchCommand(t[0],t[1]||[])}catch(i){console.error("[obi] error dispatching command",i)}})}parsePassiveParams(){if(this.passivePlanUuid){this.passivePlanUuid;return}let e={};e=JSON.parse(localStorage.getItem(Pm)||"{}"),Object.keys(e).length===0&&new URLSearchParams(window.location.search).forEach((s,a)=>{e[a]=s});const t=e[Rm];if(!t)return null;const i=new URL(window.location.href);i.searchParams.delete(Rm),window.history.replaceState({},"",i.toString()),i.toString(),localStorage.removeItem(Pm),this.passivePlanUuid=t}mountWidget(){c_(this)}showMessage(e,t){try{this.emit("showMessage",{text:e,autoCloseMs:t==null?void 0:t.autoCloseMs})}catch{}}async captureScreen(){try{await Lx(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.text_segmentation)),await n_(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.css_line_breaks))}catch(e){throw console.error("[obi] error initialising unicode trie",e),e}try{return(await ET(document.documentElement,{useCORS:!0,allowTaint:!0,foreignObjectRendering:!0})).toDataURL("image/png")}catch(e){throw console.error("[obi] error capturing screen",e),e}}save(){var t;const e=((t=this.client)==null?void 0:t.serialise())||"";localStorage.setItem("obi-client",e)}load(){return localStorage.getItem("obi-client")}}async function Im(n,e){let t;try{t=window}catch{console.warn("[obi] no window object found"),t={}}return d_({appToken:n,window:t,init:e})}async function d_({appToken:n,window:e,init:t}){var s,a;if(e.obi){console.warn("[obi] obi object already found on window, skipping");return}t&&t(),n||(n=(s=e==null?void 0:e.obiWidgetConfig)==null?void 0:s.apiKey);let i;try{i=((a=e.ObiSDK)==null?void 0:a.q)||[]}catch{i=[]}const r=new u_(n);return e.ObiSDK=r.dispatchCommand,await r.initialise({queuedCommands:i}),e.obi=r,r.mountWidget(),r}function Om(){}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{Im(void 0,Om)}):Im(void 0,Om)})();
|
|
56
|
+
`;function r_(n){var xt,hn,_t,Jt,oi,_r,Er,_a,ji,Vn,fn;const[e,t]=Y(!1),[i,r]=Y(!1),[s,a]=Y(!1),[o,c]=Y(null),[l,u]=Y(!1),[d,h]=Y(null),[f,m]=Y(null),[p,v]=Y(null),[b,C]=Y(!1),x=Be(null),k=Be(0),S=Be(0),w=Be(0),E=Be(0),A=Be({width:0,height:0}),O=Be(null),B=Be(!1),L=6,R=s_(n.sdk,H,n.shadowHost,m,a,N=>{if(!N){c(null);return}if(Fe&&(c(N),!de&&K==="minimized")){u(!0);const q=Math.max(0,N.autoCloseMs??3e3);d&&window.clearTimeout(d);const Z=window.setTimeout(()=>u(!1),q);h(Z)}});function H(N){var q;(q=R.client)!=null&&q.session||(N?We():t(!1))}if(!R.client)return null;const Q=R.client.planIsCompleted.filter(Boolean).length===R.client.plans.length,X=a_((xt=R.client.product)==null?void 0:xt.widget_url_blacklist),K=Q?R.completedWidgetDisplay||((hn=R.client.product)==null?void 0:hn.completed_widget_display):R.widgetDisplay||((_t=R.client.product)==null?void 0:_t.widget_display),ye=R.widgetPosition||((Jt=R.client.product)==null?void 0:Jt.widget_position);let Te=R.isActive;((_r=(oi=R.client)==null?void 0:oi.product)==null?void 0:_r.name)==="Canibuild"&&(Te=!0);const W=R.client.session,de=!!W,te=de&&!e;let ge;switch(W==null?void 0:W.speakingState){case"listening":ge="user-speaking";break;case"speaking":ge="agent-speaking";break;case"thinking":ge="thinking";break;case"busy":ge="busy";break}const oe=W==null?void 0:W.isPaused,Fe=de||R.client.state==="ready"&&Te&&!X&&(K!=="invisible"||R.client.selectedPlan),$=()=>{var N,q,Z,Se,qe,Qt,pn;return{name:(N=R.client.selectedPlan)==null?void 0:N.name,description:(q=R.client.selectedPlan)==null?void 0:q.description,appName:(Z=R.client.product)==null?void 0:Z.name,appLogoUrl:((Se=R.client.product)==null?void 0:Se.logo_url)||"",url:(qe=R.client.product)==null?void 0:qe.url,agentName:((Qt=R.client.product)==null?void 0:Qt.agent_name)||"Obi",legalFooter:((pn=R.client.product)==null?void 0:pn.legal_footer_text)||void 0}};function ke(){const N=ye==="bottom-right"?{position:"fixed",right:"250px",width:"max-content",transform:"translateX(50%)"}:{position:"fixed",left:"50%",transform:"translateX(-50%)",width:"max-content"};return te?N.top="calc(100vh - 100px)":N.bottom="20px",N}const Le=(()=>{if(de&&p)return{position:"fixed",left:`${Math.round(p.left)}px`,top:`${Math.round(p.top)}px`,width:"max-content",right:void 0,bottom:void 0,transform:void 0,touchAction:"none"};const N=ke();return de&&(N.touchAction="none"),N})();Qe(()=>{de||(v(null),C(!1),x.current=null,B.current=!1,O.current&&(cancelAnimationFrame(O.current),O.current=null))},[de]);function gt(N,q,Z){return Math.max(q,Math.min(Z,N))}function bt(N){var Qt;if(!de)return;const q=N.currentTarget;if(!q)return;const Z=N.target;if((Qt=Z==null?void 0:Z.closest)==null?void 0:Qt.call(Z,'button, a[href], input, textarea, select, [role="button"], [contenteditable="true"], [data-no-drag]'))return;x.current=N.pointerId;const qe=q.getBoundingClientRect();k.current=N.clientX,S.current=N.clientY,w.current=qe.left,E.current=qe.top,A.current={width:qe.width,height:qe.height},B.current=!1,v({left:qe.left,top:qe.top})}function Fi(N){var mn;if(!de||x.current!==N.pointerId)return;const q=N.clientX-k.current,Z=N.clientY-S.current;if(!b){if(Math.hypot(q,Z)<L)return;const gn=N.currentTarget;try{(mn=gn==null?void 0:gn.setPointerCapture)==null||mn.call(gn,N.pointerId)}catch{}C(!0),B.current=!0,p||v({left:w.current,top:E.current})}const Se=8,qe=Se,Qt=Se,pn=Math.max(Se,window.innerWidth-A.current.width-Se),Vi=Math.max(Se,window.innerHeight-A.current.height-Se),Et={left:gt(w.current+q,qe,pn),top:gt(E.current+Z,Qt,Vi)};if(O.current==null){const Gi=Et;O.current=requestAnimationFrame(()=>{v(Gi),O.current=null})}else v(Et)}function ai(N){var q,Z;if(x.current!==null)try{(Z=(q=N.currentTarget)==null?void 0:q.releasePointerCapture)==null||Z.call(q,x.current)}catch{}x.current=null,C(!1)}function ne(N){de&&x.current===N.pointerId&&ai(N)}function je(N){de&&x.current===N.pointerId&&ai(N)}const We=()=>{const N=R.client;if(!N)return;const q=N.plans||[];if(q.length===1){const[Z]=q;N.selectedPlanUuid!==Z.uuid&&(N.selectPlan(Z),ii().track("course-get-started",{courseName:Z.name,courseUuid:Z.uuid})),t(!1),r(!0);return}t(!0)};return g("div",{children:[e&&g(qw,{open:e,courses:R.client.plans.map((N,q)=>{var Z,Se;return{id:N.uuid,name:N.name,description:N.description||"",duration:N.duration||0,completed:((Se=(Z=R.client)==null?void 0:Z.planIsCompleted)==null?void 0:Se[q])||!1}}),loading:!1,title:((Er=R.client.product)==null?void 0:Er.assistant_subtitle)||void 0,productName:((_a=R.client.product)==null?void 0:_a.name)||"",onCourseHighlight:N=>{N&&ii().track("course-selected",{courseName:N.name,courseUuid:N.id})},onCourseSelect:N=>{const q=R.client.plans.find(Z=>Z.uuid===N.id)||null;q&&(q==null?void 0:q.uuid)!==R.client.selectedPlanUuid&&(R.client.selectPlan(q),t(!1),r(!0),ii().track("course-get-started",{courseName:N.name,courseUuid:N.id}))},onClose:N=>{N==="user-initiated"&&R.client.selectPlan(null),t(!1)}}),Fe&&g(nt,{children:[g("div",{className:de?`obi-widget-draggable${b?" dragging":""}`:void 0,style:Le,onPointerDown:bt,onPointerMove:Fi,onPointerUp:ne,onPointerCancel:je,onClickCapture:N=>{var q,Z;B.current&&((q=N.preventDefault)==null||q.call(N),(Z=N.stopPropagation)==null||Z.call(N),B.current=!1)},children:g(rw,{inPlan:de,isActive:i?!1:l?!0:void 0,defaultIsActive:K!=="minimized",isPaused:oe,toastMessage:o,messaging:(W==null?void 0:W.isMicShared)===!1||s?!0:void 0,speakingStatus:ge,spectrum:()=>(W==null?void 0:W.audioSpectrum())||null,courseProgress:f,onOpen:We,onCancelClick:()=>{},onCancelAbort:()=>{},onCancel:()=>{var N;(N=R.client.session)==null||N.stop()},onCancelReason:(N,q)=>{},onPause:()=>{var N,q;(q=(N=R.client.session)==null?void 0:N.pause)==null||q.call(N)},onUnpause:()=>{var N,q;(q=(N=R.client.session)==null?void 0:N.unpause)==null||q.call(N)},onMessagingChange:N=>{var q,Z,Se,qe;a(!1),N?(Z=(q=R.client.session)==null?void 0:q.muteMicrophone)==null||Z.call(q):(qe=(Se=R.client.session)==null?void 0:Se.unmuteMicrophone)==null||qe.call(Se)},onMessageChange:N=>{ii().track("chat-input-provided",{message:N,length:N.length})},onMessage:N=>{R.say(N),a(!1),ii().track("chat-message-sent",{message:N,length:N.length})},onHover:N=>{},onOneClickAction:N=>{a(!1)},onMinimize:()=>{},agentName:((ji=R.client.product)==null?void 0:ji.agent_name)||"Obi",completedTutorials:((Vn=R.client.product)==null?void 0:Vn.widget_show_progress)===!1?void 0:R.client.planIsCompleted.filter(Boolean).length,totalTutorials:((fn=R.client.product)==null?void 0:fn.widget_show_progress)===!1?void 0:R.client.plans.length})}),!!R.client.selectedPlan&&g($w,{open:!0,session:$(),sessionState:(W==null?void 0:W.state)||null,speakingState:(W==null?void 0:W.speakingState)||null,spectrum:()=>(W==null?void 0:W.audioSpectrum())||null,onModalChange:N=>{},onClose:(N,q)=>{var Z,Se;N==="user-initiated"&&(((Z=R.client.session)==null?void 0:Z.state)==="mic-share"?(Se=R.client.session)==null||Se.shareMicrophoneFailed():R.client.stopSession()),r(!1)},onStart:()=>{R.client.selectedPlanUuid&&R.startSession()},onContinue:()=>{W==null||W.continue()},onShareMicrophone:()=>{W==null||W.shareMicrophone()}})]})]})}function s_(n,e,t,i,r,s){const[a,o]=Y(0),[c,l]=Y(null),u=Be(s);Qe(()=>{u.current=s},[s]);const d=h=>{var f;(f=u.current)==null||f.call(u,h)};return Qe(()=>{const h=m=>{e(m)};n.on("showMenu",h);const f=()=>{o(m=>m+1)};return n.on("configUpdated",f),n.on("showMessage",d),()=>{var m,p,v;(m=n.off)==null||m.call(n,"showMenu",h),(p=n.off)==null||p.call(n,"configUpdated",f),(v=n.off)==null||v.call(n,"showMessage",d)}},[n]),Qe(()=>{n.client&&(n.client.session&&l(n.client.session),n.client.on("sessionStarted",h=>{l(h),r==null||r(!1),o(f=>f+1)}),n.client.on("sessionStopped",()=>{l(null),r==null||r(!1),o(h=>h+1)}),n.client.on("sessionShutdown",()=>{o(h=>h+1)}),n.client.on("sessionResumed",()=>{o(h=>h+1)}),n.client.on("stateChanged",()=>{var h;n.client.state==="ready"&&t.style.setProperty("--obi-color-primary",((h=n.client.product)==null?void 0:h.primary_color)||"#9500FF"),o(f=>f+1)}),n.client.on("planSelected",()=>{o(h=>h+1)}))},[n,n.client]),Qe(()=>{if(!c)return;c.on("stateChanged",()=>{o(f=>f+1)}),c.on("speakingStateChanged",()=>{o(f=>f+1)}),c.on("paused",()=>{o(f=>f+1)}),c.on("unpaused",()=>{o(f=>f+1)}),c.on("micCheckComplete",f=>{}),c.on("transcript",(f,m)=>{}),c.on&&c.on("textInputRequested",()=>{r==null||r(!0),o(f=>f+1)});const h=f=>{i(f)};return c.on&&c.on("courseProgress",h),()=>{c.off&&c.off("courseProgress",h),c.off&&c.off("textInputRequested")}},[c]),n}function a_(n){const[e,t]=Y(()=>Ta(n));return Qe(()=>{t(Ta(n))},[n]),Qe(()=>{o_();const i=()=>{t(Ta(n))};return window.addEventListener("locationchange",i),window.addEventListener("popstate",i),window.addEventListener("hashchange",i),()=>{window.removeEventListener("locationchange",i),window.removeEventListener("popstate",i),window.removeEventListener("hashchange",i)}},[n]),e}function o_(){const n=window;if(n.__obi_history_patched)return;const{pushState:e,replaceState:t}=window.history,i=r=>function(...s){const a=r.apply(this,s);return window.dispatchEvent(new Event("locationchange")),a};window.history.pushState=i(e),window.history.replaceState=i(t),n.__obi_history_patched=!0}function c_(n){if(document.querySelector("obi-widget"))return;l_();const e=document.createElement("div");e.id="obi-host",e.style.position="fixed",e.style.zIndex="9999",document.body.appendChild(e);const t=e.attachShadow({mode:"open"}),i=document.createElement("div");i.id="obi-container",t.appendChild(i);const r=new CSSStyleSheet;r.replaceSync(i_),t.adoptedStyleSheets=[r],k1(g(r_,{sdk:n,shadowHost:e}),i),console.log("[obi-sdk] widget mounted")}function l_(){Em("https://fonts.cdnfonts.com/css/satoshi"),Em("https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap")}function Em(n){const e=document.createElement("link");e.href=n,e.rel="stylesheet",document.head.appendChild(e)}const Rm="49206C6F7665204F6269_session",Pm="obi-url-params";class u_ extends Pa{constructor(e){super(),this.client=null,this.isActive=!1,this.primaryColour="#9500FF",this.passivePlanUuid=null,this.commandLog=[],this.commandQueue=[],this._resumed=!1,this.dispatchCommand=(t,i)=>{var r,s,a,o,c;switch(this.commandLog.push({commandType:t,args:i}),t){case"update":this.updateConfig(i);break;case"startSession":if(!(i!=null&&i.planUuid)){console.warn("[obi] startSession command requires a planUuid",i);return}const l=(((r=this.client)==null?void 0:r.plans)||[]).find(u=>u.uuid===i.planUuid)||null;if(!l){console.warn("[obi] startSession command requires a valid planUuid",i);return}this.updateActive(!0),(a=(s=this.client)==null?void 0:s.selectPlan)==null||a.call(s,l);break;case"stopSession":(c=(o=this.client)==null?void 0:o.stopSession)==null||c.call(o);break;case"say":this.say(i);break;default:console.warn("[obi] unknown command",{commandType:t,args:i})}},e&&this.createClient(e),this.parsePassiveParams()}async createClient(e){if(this.client){this.client.appToken!==e&&console.warn("[obi] client already exists with different app token");return}let t=null;const i=this.load();if(i)try{t=sa.deserialise(i,e,"sdk",{apiBaseUrl:"https://app.coragents.ai",captureScreen:this.captureScreen.bind(this)}),t?this._resumed=!0:localStorage.removeItem("obi-client")}catch(r){console.error("[obi] error loading cached client",r)}t||(t=new sa(e,"sdk",{apiBaseUrl:"https://app.coragents.ai",captureScreen:this.captureScreen.bind(this)})),this.client=t,this.client.on("stateChanged",r=>{var s,a,o,c,l,u,d,h,f,m;r==="ready"&&this.updateConfig({isActive:((s=window==null?void 0:window.obiWidgetConfig)==null?void 0:s.isActive)??((a=this.client)==null?void 0:a.showWidget),primaryColour:((c=(o=this.client)==null?void 0:o.product)==null?void 0:c.primary_color)||"#9500FF",widgetDisplay:((l=window==null?void 0:window.obiWidgetConfig)==null?void 0:l.widgetDisplay)||((d=(u=this.client)==null?void 0:u.product)==null?void 0:d.widget_display)||"regular",completedWidgetDisplay:((h=window==null?void 0:window.obiWidgetConfig)==null?void 0:h.completedWidgetDisplay)||((m=(f=this.client)==null?void 0:f.product)==null?void 0:m.completed_widget_display)||"regular"})}),this.client.on("sessionStarted",()=>{this.save(),this.passivePlanUuid=null}),this.client.on("sessionStopped",()=>{localStorage.removeItem("obi-client"),this.passivePlanUuid=null}),this.client.on("sessionShutdown",()=>{localStorage.removeItem("obi-client")}),this.client.on("trackEvent",(r,s)=>{}),this.client.session&&this.client.resumeSession(r=>{r.on("stateChanged",s=>{s!=="disconnecting"&&s!=="disconnected"&&s!=="error"&&s!=="connecting"&&this.save()}),r.on("paused",()=>{this.save()}),r.on("unpaused",()=>{this.save()})})}_maybeActOnServerEngagement(){var o;const e=this.client;if(!e||e.state!=="ready")return;const t=e.product,i=(o=e.engagement)==null?void 0:o.style;if(!i||t&&Ta(t.widget_url_blacklist||[])||!e.showWidget)return;const r=e.plans||[],s=e.planIsCompleted||[],a=r.length>0&&s.filter(Boolean).length===r.length;if(!(r.length===0||a)){if(i==="modal"){const c=s.findIndex(u=>!u),l=c>=0?r[c]:null;l&&e.selectPlan(l)}else i==="popover"&&setTimeout(()=>{this.showMessage("Don't forget to complete your onboarding",{autoCloseMs:1e4})},1e3);try{ii().track("engagement-prompt-shown",{style:i})}catch{}}}async initialise(e={}){var t;this.commandQueue=e.queuedCommands||[],this._resumed?(this._resumed=!1,this.dispatchCommandQueue()):this.client?this.client.initialise({planUuid:this.passivePlanUuid||void 0,identity:((t=window==null?void 0:window.obiWidgetConfig)==null?void 0:t.user)||void 0}).then(()=>{this.emit("initialised");try{this._maybeActOnServerEngagement()}catch{}this.dispatchCommandQueue()}).catch(i=>{console.error("[obi] error initialising client",i),this.emit("error",i)}):this.dispatchCommandQueue()}async updateConfig(e){await this.updateAppToken(e.apiKey),this.updateActive(e.isActive),this.updatePrimaryColour(e.primaryColour),this.updateWidgetDisplay(e.widgetDisplay),this.updateCompletedWidgetDisplay(e.completedWidgetDisplay),this.updateWidgetPosition(e.widgetPosition),await this.updateIdentity(e.user),this.updateShowMenu(e.showMenu),this.emit("configUpdated")}async updateAppToken(e){var t;e===void 0||e==((t=this.client)==null?void 0:t.appToken)||(this.passivePlanUuid,await this.createClient(e),this.client&&await this.client.initialise({planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised");try{this._maybeActOnServerEngagement()}catch{}}).catch(i=>{console.error("[obi] error initialising client",i),this.emit("error",i)}))}updateActive(e){e===void 0||e==this.isActive||(this.isActive=e)}updatePrimaryColour(e){e===void 0||e==this.primaryColour||(this.primaryColour=e)}updateWidgetDisplay(e){e===void 0||e==this.widgetDisplay||(this.widgetDisplay=e)}updateCompletedWidgetDisplay(e){e===void 0||e==this.completedWidgetDisplay||(this.completedWidgetDisplay=e)}updateWidgetPosition(e){e===void 0||e==this.widgetPosition||(this.widgetPosition=e)}async updateIdentity(e){var i,r;if(e===void 0||e==((i=this.client)==null?void 0:i.identity))return;(r=this.client)==null||r.identity;let t=e?{...e,extra:{...e,...(e==null?void 0:e.extra)||{}}}:void 0;await this.client.initialise({identity:t,planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised");try{this._maybeActOnServerEngagement()}catch{}}).catch(s=>{console.error("[obi] error initialising client",s),this.emit("error",s)}),e!=null&&e.email&&ii().identify((e==null?void 0:e.email)||"",t)}updateShowMenu(e){e!==void 0&&this.emit("showMenu",e)}async say(e){var t,i,r;await((r=(i=(t=this.client)==null?void 0:t.session)==null?void 0:i.say)==null?void 0:r.call(i,e))}async startSession(){await this.client.startSession(this.client.selectedPlanUuid,e=>{e.on("stateChanged",t=>{t!=="disconnecting"&&t!=="disconnected"&&t!=="error"&&t!=="connecting"&&this.save()})})}dispatchCommandQueue(){const e=this.commandQueue;this.commandQueue=[],e.forEach(t=>{try{this.dispatchCommand(t[0],t[1]||[])}catch(i){console.error("[obi] error dispatching command",i)}})}parsePassiveParams(){if(this.passivePlanUuid){this.passivePlanUuid;return}let e={};e=JSON.parse(localStorage.getItem(Pm)||"{}"),Object.keys(e).length===0&&new URLSearchParams(window.location.search).forEach((s,a)=>{e[a]=s});const t=e[Rm];if(!t)return null;const i=new URL(window.location.href);i.searchParams.delete(Rm),window.history.replaceState({},"",i.toString()),i.toString(),localStorage.removeItem(Pm),this.passivePlanUuid=t}mountWidget(){c_(this)}showMessage(e,t){try{this.emit("showMessage",{text:e,autoCloseMs:t==null?void 0:t.autoCloseMs})}catch{}}async captureScreen(){try{await Lx(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.text_segmentation)),await n_(async()=>(this.graphemes||(this.graphemes=await this.client.api.getGraphemes()),this.graphemes.data.css_line_breaks))}catch(e){throw console.error("[obi] error initialising unicode trie",e),e}try{return(await ET(document.documentElement,{useCORS:!0,allowTaint:!0,foreignObjectRendering:!0})).toDataURL("image/png")}catch(e){throw console.error("[obi] error capturing screen",e),e}}save(){var t;const e=((t=this.client)==null?void 0:t.serialise())||"";localStorage.setItem("obi-client",e)}load(){return localStorage.getItem("obi-client")}}async function Im(n,e){let t;try{t=window}catch{console.warn("[obi] no window object found"),t={}}return d_({appToken:n,window:t,init:e})}async function d_({appToken:n,window:e,init:t}){var s,a;if(e.obi){console.warn("[obi] obi object already found on window, skipping");return}t&&t(),n||(n=(s=e==null?void 0:e.obiWidgetConfig)==null?void 0:s.apiKey);let i;try{i=((a=e.ObiSDK)==null?void 0:a.q)||[]}catch{i=[]}const r=new u_(n);return e.ObiSDK=r.dispatchCommand,await r.initialise({queuedCommands:i}),e.obi=r,r.mountWidget(),r}function Om(){}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{Im(void 0,Om)}):Im(void 0,Om)})();
|