obi-sdk 0.18.34-beta.1 → 0.18.34-beta.2

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.
@@ -39,7 +39,7 @@ a=extmap-allow-mixed`)!==-1){const A=i.sdp.split(`
39
39
  `).filter(s=>s.trim()!=="a=extmap-allow-mixed").join(`
40
40
  `);n.RTCSessionDescription&&i instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:i.type,sdp:A}):i.sdp=A}return t.apply(this,arguments)}}function $o(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(n.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function ea(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return t.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?t.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(s=>t.apply(this,[s]))})}var fF=Object.freeze({__proto__:null,removeExtmapAllowMixed:bl,shimAddIceCandidateNullOrEmpty:$o,shimConnectionState:wl,shimMaxMessageSize:Yo,shimParameterlessSetLocalDescription:ea,shimRTCIceCandidate:Xo,shimRTCIceCandidateRelayProtocol:yl,shimSendThrowTypeError:Zo});function gF(){let{window:n}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=ov,r=lF(n),i={browserDetails:r,commonShim:fF,extractVersion:zo,disableLog:cF,disableWarnings:uF,sdp:pF};switch(r.browser){case"chrome":if(!wv||!gl||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),i;if(r.version===null)return t("Chrome shim can not determine version, not shimming."),i;t("adapter.js shimming chrome."),i.browserShim=wv,$o(n,r),ea(n),dv(n,r),hv(n),gl(n,r),pv(n),vv(n,r),fv(n),gv(n),yv(n,r),Xo(n),yl(n),wl(n),Yo(n,r),Zo(n),bl(n,r);break;case"firefox":if(!Fv||!ml||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),i;t("adapter.js shimming firefox."),i.browserShim=Fv,$o(n,r),ea(n),bv(n,r),ml(n,r),Bv(n),Sv(n),Cv(n),_v(n),kv(n),Ev(n),Uv(n),Tv(n),Iv(n),Xo(n),wl(n),Yo(n,r),Zo(n);break;case"safari":if(!Hv||!e.shimSafari)return t("Safari shim is not included in this adapter release."),i;t("adapter.js shimming safari."),i.browserShim=Hv,$o(n,r),ea(n),Mv(n),Dv(n),Rv(n),xv(n),Qv(n),Lv(n),Pv(n),Nv(n),Xo(n),yl(n),Yo(n,r),Zo(n),bl(n,r);break;default:t("Unsupported browser!");break}return i}gF({window:typeof window>"u"?void 0:window});const mF=10,ta="lk_e2ee",vF={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:mF,keyringSize:16};var lr;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(lr||(lr={}));var Gv;(function(n){n.KeyRatcheted="keyRatcheted"})(Gv||(Gv={}));var dr;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(dr||(dr={}));var jv;(function(n){n.Error="cryptorError"})(jv||(jv={}));function yF(){return wF()||Bl()}function Bl(){return typeof window.RTCRtpScriptTransform<"u"}function wF(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class x4 extends Sn.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,r,i)=>{ue.debug("key ratcheted event received",{ratchetResult:t,participantId:r,keyIndex:i})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},vF),e),this.on(lr.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,r){const i={key:e,participantIdentity:t,keyIndex:r};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(r??0),i),this.emit(lr.SetKey,i)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(lr.RatchetRequest,e,t)}}class hr extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var de;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.ServerUnreachable=1]="ServerUnreachable",n[n.InternalError=2]="InternalError",n[n.Cancelled=3]="Cancelled",n[n.LeaveRequest=4]="LeaveRequest"})(de||(de={}));class Fe extends hr{constructor(e,t,r,i){super(1,e),this.name="ConnectionError",this.status=r,this.reason=t,this.context=i,this.reasonName=de[t]}}class Cl extends hr{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class Dn extends hr{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class bF extends hr{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class lt extends hr{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class _l extends hr{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Sl extends hr{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class Wv extends hr{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:dl[t]}}var na;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(na||(na={})),function(n){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?n.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?n.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?n.DeviceInUse:n.Other}n.getFailure=e}(na||(na={}));var qv;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(qv||(qv={}));var O;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",n.Moved="moved",n.MediaDevicesChanged="mediaDevicesChanged",n.ParticipantConnected="participantConnected",n.ParticipantDisconnected="participantDisconnected",n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalAudioSilenceDetected="localAudioSilenceDetected",n.ActiveSpeakersChanged="activeSpeakersChanged",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.ParticipantAttributesChanged="participantAttributesChanged",n.ParticipantActive="participantActive",n.RoomMetadataChanged="roomMetadataChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.AudioPlaybackStatusChanged="audioPlaybackChanged",n.VideoPlaybackStatusChanged="videoPlaybackChanged",n.MediaDevicesError="mediaDevicesError",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.SignalConnected="signalConnected",n.RecordingStatusChanged="recordingStatusChanged",n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ActiveDeviceChanged="activeDeviceChanged",n.ChatMessage="chatMessage",n.LocalTrackSubscribed="localTrackSubscribed",n.MetricsReceived="metricsReceived"})(O||(O={}));var K;(function(n){n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.IsSpeakingChanged="isSpeakingChanged",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded",n.AttributesChanged="attributesChanged",n.LocalTrackSubscribed="localTrackSubscribed",n.ChatMessage="chatMessage",n.Active="active"})(K||(K={}));var D;(function(n){n.TransportsCreated="transportsCreated",n.Connected="connected",n.Disconnected="disconnected",n.Resuming="resuming",n.Resumed="resumed",n.Restarting="restarting",n.Restarted="restarted",n.SignalResumed="signalResumed",n.SignalRestarted="signalRestarted",n.Closing="closing",n.MediaTrackAdded="mediaTrackAdded",n.ActiveSpeakersUpdate="activeSpeakersUpdate",n.DataPacketReceived="dataPacketReceived",n.RTPVideoMapUpdate="rtpVideoMapUpdate",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ParticipantUpdate="participantUpdate",n.RoomUpdate="roomUpdate",n.SpeakersChanged="speakersChanged",n.StreamStateChanged="streamStateChanged",n.ConnectionQualityUpdate="connectionQualityUpdate",n.SubscriptionError="subscriptionError",n.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",n.RemoteMute="remoteMute",n.SubscribedQualityUpdate="subscribedQualityUpdate",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackSubscribed="localTrackSubscribed",n.Offline="offline",n.SignalRequestResponse="signalRequestResponse",n.SignalConnected="signalConnected",n.RoomMoved="roomMoved"})(D||(D={}));var L;(function(n){n.Message="message",n.Muted="muted",n.Unmuted="unmuted",n.Restarted="restarted",n.Ended="ended",n.Subscribed="subscribed",n.Unsubscribed="unsubscribed",n.UpdateSettings="updateSettings",n.UpdateSubscription="updateSubscription",n.AudioPlaybackStarted="audioPlaybackStarted",n.AudioPlaybackFailed="audioPlaybackFailed",n.AudioSilenceDetected="audioSilenceDetected",n.VisibilityChanged="visibilityChanged",n.VideoDimensionsChanged="videoDimensionsChanged",n.VideoPlaybackStarted="videoPlaybackStarted",n.VideoPlaybackFailed="videoPlaybackFailed",n.ElementAttached="elementAttached",n.ElementDetached="elementDetached",n.UpstreamPaused="upstreamPaused",n.UpstreamResumed="upstreamResumed",n.SubscriptionPermissionChanged="subscriptionPermissionChanged",n.SubscriptionStatusChanged="subscriptionStatusChanged",n.SubscriptionFailed="subscriptionFailed",n.TrackProcessorUpdate="trackProcessorUpdate",n.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",n.TranscriptionReceived="transcriptionReceived",n.TimeSyncUpdate="timeSyncUpdate"})(L||(L={}));function BF(n){return typeof n>"u"?n:typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}const CF=/version\/(\d+(\.?_?\d+)+)/i;let kl;function un(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof n>"u"&&typeof navigator>"u")return;const t=(n??navigator.userAgent).toLowerCase();if(kl===void 0||e){const r=_F.find(i=>{let{test:A}=i;return A.test(t)});kl=r==null?void 0:r.describe(t)}return kl}const _F=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:ra(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:El(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:ra(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:El(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:ra(CF,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:El(n)}}}];function ra(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const r=e.match(n);return r&&r.length>=t&&r[t]||""}function El(n){return n.includes("mac os")?ra(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var SF="2.13.0";const kF=SF,EF=16;class wt{}wt.setTimeout=function(){return setTimeout(...arguments)},wt.setInterval=function(){return setInterval(...arguments)},wt.clearTimeout=function(){return clearTimeout(...arguments)},wt.clearInterval=function(){return clearInterval(...arguments)};const UF=5e3,NA=[];var Yt;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Yt||(Yt={}));class R extends Sn.EventEmitter{constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var i;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=R.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=ue,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),UF):this.handleAppVisibilityChanged()},this.log=Ln((i=r.loggerName)!==null&&i!==void 0?i:cn.Track),this.loggerContextCb=r.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=R.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),_e(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===R.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===R.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(NA.forEach(A=>{A.parentElement===null&&!e&&(e=A)}),e&&NA.splice(NA.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Fi(this.mediaStreamTrack,e);const r=e.srcObject.getTracks(),i=r.some(A=>A.kind==="audio");return e.play().then(()=>{this.emit(i?L.AudioPlaybackStarted:L.VideoPlaybackStarted)}).catch(A=>{A.name==="NotAllowedError"?this.emit(i?L.AudioPlaybackFailed:L.VideoPlaybackFailed,A):A.name==="AbortError"?ue.debug("".concat(i?"audio":"video"," playback aborted, likely due to new play request")):ue.warn("could not playback ".concat(i?"audio":"video"),A),i&&e&&r.some(s=>s.kind==="video")&&A.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(L.ElementAttached,e),e}detach(e){try{if(e){xi(this.mediaStreamTrack,e);const r=this.attachedElements.indexOf(e);return r>=0&&(this.attachedElements.splice(r,1),this.recycleElement(e),this.emit(L.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(r=>{xi(this.mediaStreamTrack,r),t.push(r),this.recycleElement(r),this.emit(L.ElementDetached,r)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=Ln(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),NA.forEach(r=>{r.parentElement||(t=!1)}),t&&NA.push(e)}}handleAppVisibilityChanged(){return S(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===R.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Ht()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Ht()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Fi(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let r;n.kind==="audio"?r=t.getAudioTracks():r=t.getVideoTracks(),r.includes(n)||(r.forEach(i=>{t.removeTrack(i)}),t.addTrack(n)),(!pr()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(pr()||Qi())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function xi(n,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(n),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(n){let e;(function(c){c.Audio="audio",c.Video="video",c.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(c){c.Camera="camera",c.Microphone="microphone",c.ScreenShare="screen_share",c.ScreenShareAudio="screen_share_audio",c.Unknown="unknown"})(t=n.Source||(n.Source={}));let r;(function(c){c.Active="active",c.Paused="paused",c.Unknown="unknown"})(r=n.StreamState||(n.StreamState={}));function i(c){switch(c){case e.Audio:return An.AUDIO;case e.Video:return An.VIDEO;default:return An.DATA}}n.kindToProto=i;function A(c){switch(c){case An.AUDIO:return e.Audio;case An.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=A;function s(c){switch(c){case t.Camera:return at.CAMERA;case t.Microphone:return at.MICROPHONE;case t.ScreenShare:return at.SCREEN_SHARE;case t.ScreenShareAudio:return at.SCREEN_SHARE_AUDIO;default:return at.UNKNOWN}}n.sourceToProto=s;function o(c){switch(c){case at.CAMERA:return t.Camera;case at.MICROPHONE:return t.Microphone;case at.SCREEN_SHARE:return t.ScreenShare;case at.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function a(c){switch(c){case Al.ACTIVE:return r.Active;case Al.PAUSED:return r.Paused;default:return r.Unknown}}n.streamStateFromProto=a})(R||(R={}));class Te{constructor(e,t,r,i,A){if(typeof e=="object")this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&r!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:r,maxFramerate:i,priority:A};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const TF=["vp8","h264"],IF=["vp8","h264","vp9","av1"];function FF(n){return!!TF.find(e=>e===n)}var Jv;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(Jv||(Jv={}));var Ul;(function(n){n.telephone={maxBitrate:12e3},n.speech={maxBitrate:24e3},n.music={maxBitrate:48e3},n.musicStereo={maxBitrate:64e3},n.musicHighQuality={maxBitrate:96e3},n.musicHighQualityStereo={maxBitrate:128e3}})(Ul||(Ul={}));const HA={h90:new Te(160,90,9e4,20),h180:new Te(320,180,16e4,20),h216:new Te(384,216,18e4,20),h360:new Te(640,360,45e4,20),h540:new Te(960,540,8e5,25),h720:new Te(1280,720,17e5,30),h1080:new Te(1920,1080,3e6,30),h1440:new Te(2560,1440,5e6,30),h2160:new Te(3840,2160,8e6,30)},Tl={h120:new Te(160,120,7e4,20),h180:new Te(240,180,125e3,20),h240:new Te(320,240,14e4,20),h360:new Te(480,360,33e4,20),h480:new Te(640,480,5e5,20),h540:new Te(720,540,6e5,25),h720:new Te(960,720,13e5,30),h1080:new Te(1440,1080,23e5,30),h1440:new Te(1920,1440,38e5,30)},Il={h360fps3:new Te(640,360,2e5,3,"medium"),h360fps15:new Te(640,360,4e5,15,"medium"),h720fps5:new Te(1280,720,8e5,5,"medium"),h720fps15:new Te(1280,720,15e5,15,"medium"),h720fps30:new Te(1280,720,2e6,30,"medium"),h1080fps15:new Te(1920,1080,25e5,15,"medium"),h1080fps30:new Te(1920,1080,5e6,30,"medium"),original:new Te(0,0,7e6,30,"medium")},xF="|",zv="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function QF(n){const e=n.split(xF);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function Nt(n){return S(this,void 0,void 0,function*(){return new Promise(e=>wt.setTimeout(e,n))})}function Fl(){return"addTransceiver"in RTCPeerConnection.prototype}function xl(){return"addTrack"in RTCPeerConnection.prototype}function RF(){if(!("getCapabilities"in RTCRtpSender)||pr())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType==="video/AV1"){e=!0;break}}return e}function PF(){if(!("getCapabilities"in RTCRtpSender)||Qi())return!1;if(pr()){const t=un();if(t!=null&&t.version&&Wr(t.version,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType==="video/VP9"){e=!0;break}}return e}function KA(n){return n==="av1"||n==="vp9"}function Ql(n){return document?(n||(n=document.createElement("audio")),"setSinkId"in n):!1}function OF(){return typeof RTCPeerConnection>"u"?!1:Fl()||xl()}function Qi(){var n;return((n=un())===null||n===void 0?void 0:n.name)==="Firefox"}function pr(){var n;return((n=un())===null||n===void 0?void 0:n.name)==="Safari"}function MF(){const n=un();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")}function Xv(){var n,e;return Ht()?(e=(n=navigator.userAgentData)===null||n===void 0?void 0:n.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function LF(){const n=un(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&Wr(e,n.osVersion)>=0?!0:n.name==="Safari"&&Wr(e,n.version)>=0}function Ht(){return typeof document<"u"}function kn(){return navigator.product=="ReactNative"}function Rl(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function Yv(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Zv(){if(!kn())return;let n=Yv();if(n)return n.platform}function $v(){if(Ht())return window.devicePixelRatio;if(kn()){let n=Yv();if(n)return n.devicePixelRatio}return 1}function Wr(n,e){const t=n.split("."),r=e.split("."),i=Math.min(t.length,r.length);for(let A=0;A<i;++A){const s=parseInt(t[A],10),o=parseInt(r[A],10);if(s>o)return 1;if(s<o)return-1;if(A===i-1&&s===o)return 0}return n===""&&e!==""?-1:e===""?1:t.length==r.length?0:t.length<r.length?-1:1}function DF(n){for(const e of n)e.target.handleResize(e)}function NF(n){for(const e of n)e.target.handleVisibilityChanged(e)}let Pl=null;const e0=()=>(Pl||(Pl=new ResizeObserver(DF)),Pl);let Ol=null;const t0=()=>(Ol||(Ol=new IntersectionObserver(NF,{root:null,rootMargin:"0px"})),Ol);function HF(){var n;const e=new II({sdk:Dm.JS,protocol:EF,version:kF});return kn()&&(e.os=(n=Zv())!==null&&n!==void 0?n:""),e}function n0(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const i=document.createElement("canvas");i.width=n,i.height=e;const A=i.getContext("2d");A==null||A.fillRect(0,0,i.width,i.height),r&&A&&(A.beginPath(),A.arc(n/2,e/2,50,0,Math.PI*2,!0),A.closePath(),A.fillStyle="grey",A.fill());const s=i.captureStream(),[o]=s.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let VA;function Ml(){if(!VA){const n=new AudioContext,e=n.createOscillator(),t=n.createGain();t.gain.setValueAtTime(0,0);const r=n.createMediaStreamDestination();if(e.connect(t),t.connect(r),e.start(),[VA]=r.stream.getAudioTracks(),!VA)throw Error("Could not get empty media stream audio track");VA.enabled=!1}return VA.clone()}class Ll{constructor(e,t){this.onFinally=t,this.promise=new Promise((r,i)=>S(this,void 0,void 0,function*(){this.resolve=r,this.reject=i,e&&(yield e(r,i))})).finally(()=>{var r;return(r=this.onFinally)===null||r===void 0?void 0:r.call(this)})}}function KF(n){return IF.includes(n)}function fr(n){if(typeof n=="string"||typeof n=="number")return n;if(Array.isArray(n))return n[0];if(n.exact)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function VF(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function Dl(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function GF(n,e){return n.segments.map(t=>{let{id:r,text:i,language:A,startTime:s,endTime:o,final:a}=t;var c;const u=(c=e.get(r))!==null&&c!==void 0?c:Date.now(),l=Date.now();return a?e.delete(r):e.set(r,u),{id:r,text:i,startTime:Number.parseInt(s.toString()),endTime:Number.parseInt(o.toString()),final:a,language:A,firstReceivedTime:u,lastReceivedTime:l}})}function jF(n){const{id:e,timestamp:t,message:r,editTimestamp:i}=n;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:r}}function r0(n){switch(n.reason){case de.LeaveRequest:return n.context;case de.Cancelled:return sn.CLIENT_INITIATED;case de.NotAllowed:return sn.USER_REJECTED;case de.ServerUnreachable:return sn.JOIN_FAILURE;default:return sn.UNKNOWN_REASON}}function ia(n){return n!==void 0?Number(n):void 0}function qr(n){return n!==void 0?BigInt(n):void 0}function Ri(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function Nn(n){return!!n&&n.kind==R.Kind.Audio}function Pi(n){return!!n&&n.kind==R.Kind.Video}function gr(n){return Ri(n)&&Pi(n)}function Jr(n){return Ri(n)&&Nn(n)}function Nl(n){return!!n&&!n.isLocal}function WF(n){return!!n&&!n.isLocal}function Hl(n){return Nl(n)&&Pi(n)}function qF(n){return n.isLocal}function JF(n,e){const t=[];let r=new TextEncoder().encode(n);for(;r.length>e;){let i=e;for(;i>0;){const A=r[i];if(A!==void 0&&(A&192)!==128)break;i--}t.push(r.slice(0,i)),r=r.slice(i)}return r.length>0&&t.push(r),t}function i0(n,e,t){var r,i,A,s;const{optionsWithoutProcessor:o,audioProcessor:a,videoProcessor:c}=a0(n??{}),u=e==null?void 0:e.processor,l=t==null?void 0:t.processor,d=o??{};return d.audio===!0&&(d.audio={}),d.video===!0&&(d.video={}),d.audio&&(Kl(d.audio,e),(r=(A=d.audio).deviceId)!==null&&r!==void 0||(A.deviceId={ideal:"default"}),(a||u)&&(d.audio.processor=a??u)),d.video&&(Kl(d.video,t),(i=(s=d.video).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||l)&&(d.video.processor=c??l)),d}function Kl(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function Vl(n){var e,t,r,i;const A={};if(n.video)if(typeof n.video=="object"){const s={},o=s,a=n.video;Object.keys(a).forEach(c=>{switch(c){case"resolution":Kl(o,a.resolution);break;default:o[c]=a[c]}}),A.video=s,(e=(r=A.video).deviceId)!==null&&e!==void 0||(r.deviceId={ideal:"default"})}else A.video=n.video?{deviceId:{ideal:"default"}}:!1;else A.video=!1;return n.audio?typeof n.audio=="object"?(A.audio=n.audio,(t=(i=A.audio).deviceId)!==null&&t!==void 0||(i.deviceId={ideal:"default"})):A.audio={deviceId:{ideal:"default"}}:A.audio=!1,A}function A0(n){return S(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const r=s0();if(r){const i=r.createAnalyser();i.fftSize=2048;const A=i.frequencyBinCount,s=new Uint8Array(A);r.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(i),yield Nt(t),i.getByteTimeDomainData(s);const a=s.some(c=>c!==128&&c!==0);return r.close(),!a}return!1}()})}function s0(){var n;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((n=window.document)===null||n===void 0)&&n.body)){const r=()=>S(this,void 0,void 0,function*(){var i;try{t.state==="suspended"&&(yield t.resume())}catch(A){console.warn("Error trying to auto-resume audio context",A)}(i=window.document.body)===null||i===void 0||i.removeEventListener("click",r)});window.document.body.addEventListener("click",r)}return t}}function zF(n){return n==="audioinput"?R.Source.Microphone:n==="videoinput"?R.Source.Camera:R.Source.Unknown}function o0(n){return n===R.Source.Microphone?"audioinput":n===R.Source.Camera?"videoinput":void 0}function XF(n){var e,t;let r=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(r=typeof r=="boolean"?{}:r,pr()?r=Object.assign(Object.assign({},r),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):r=Object.assign(Object.assign({},r),{width:{ideal:n.resolution.width},height:{ideal:n.resolution.height},frameRate:n.resolution.frameRate})),{audio:(t=n.audio)!==null&&t!==void 0?t:!1,video:r,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function Aa(n){return n.split("/")[1].toLowerCase()}function YF(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new ul({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function _e(n){return"mediaStreamTrack"in n?{trackID:n.sid,source:n.source,muted:n.isMuted,enabled:n.mediaStreamTrack.enabled,kind:n.kind,streamID:n.mediaStreamID,streamTrackID:n.mediaStreamTrack.id}:{trackID:n.trackSid,enabled:n.isEnabled,muted:n.isMuted,trackInfo:Object.assign({mimeType:n.mimeType,name:n.trackName,encrypted:n.isEncrypted,kind:n.kind,source:n.source},n.track?_e(n.track):{})}}function ZF(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function $F(n,e){var t;n===void 0&&(n={}),e===void 0&&(e={});const r=[...Object.keys(e),...Object.keys(n)],i={};for(const A of r)n[A]!==e[A]&&(i[A]=(t=e[A])!==null&&t!==void 0?t:"");return i}function a0(n){const e=Object.assign({},n);let t,r;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(r=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:r,optionsWithoutProcessor:BF(e)}}function ex(n){switch(n){case at.CAMERA:return R.Source.Camera;case at.MICROPHONE:return R.Source.Microphone;case at.SCREEN_SHARE:return R.Source.ScreenShare;case at.SCREEN_SHARE_AUDIO:return R.Source.ScreenShareAudio;default:return R.Source.Unknown}}class tx extends Sn.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var r,i;const{kind:A,data:s}=t.data;switch(A){case"error":ue.error(s.error.message),this.emit(dr.EncryptionError,s.error);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)}),this.encryptionEnabled!==s.enabled&&s.participantIdentity===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity))this.emit(dr.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const o=(i=this.room)===null||i===void 0?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(dr.ParticipantEncryptionStatusChanged,s.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(lr.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break}},this.onWorkerError=t=>{ue.error("e2ee worker encountered an error:",{error:t.error}),this.emit(dr.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!yF())throw new Cl("tried to setup end-to-end encryption on an unsupported browser");if(ue.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:iF.getLevel()}};this.worker&&(ue.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){ue.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?ue.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(D.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(O.TrackPublished,(r,i)=>this.setParticipantCryptorEnabled(r.trackInfo.encryption!==Wt.NONE,i.identity)),e.on(O.ConnectionStateChanged,r=>{r===fe.Connected&&e.remoteParticipants.forEach(i=>{i.trackPublications.forEach(A=>{this.setParticipantCryptorEnabled(A.trackInfo.encryption!==Wt.NONE,i.identity)})})}).on(O.TrackUnsubscribed,(r,i,A)=>{var s;const o={kind:"removeTransform",data:{participantIdentity:A.identity,trackId:r.mediaStreamID}};(s=this.worker)===null||s===void 0||s.postMessage(o)}).on(O.TrackSubscribed,(r,i,A)=>{this.setupE2EEReceiver(r,A.identity,i.trackInfo)}).on(O.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(r=>{this.postKey(r)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(K.LocalTrackPublished,r=>S(this,void 0,void 0,function*(){this.setupE2EESender(r.track,r.track.sender)})),t.on(lr.SetKey,r=>this.postKey(r)).on(lr.RatchetRequest,(r,i)=>this.postRatchetRequest(r,i))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const r={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(r)}postKey(e){let{key:t,participantIdentity:r,keyIndex:i}=e;var A;if(!this.worker)throw Error("could not set key, worker is missing");const s={kind:"setKey",data:{participantIdentity:r,isPublisher:r===((A=this.room)===null||A===void 0?void 0:A.localParticipant.identity),key:t,keyIndex:i}};this.worker.postMessage(s)}postEnable(e,t){if(this.worker){const r={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(r)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const r={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(r)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,r){if(e.receiver){if(!(r!=null&&r.mimeType)||r.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?Aa(r.mimeType):void 0)}}setupE2EESender(e,t){if(!Ri(e)||!t){t||ue.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,r,i){return S(this,void 0,void 0,function*(){if(this.worker){if(Bl()){const A={kind:"decode",participantIdentity:r,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,A)}else{if(ta in e&&i){const a={kind:"updateCodec",data:{trackId:t,codec:i,participantIdentity:r}};this.worker.postMessage(a);return}let A=e.writableStream,s=e.readableStream;if(!A||!s){const a=e.createEncodedStreams();e.writableStream=a.writable,A=a.writable,e.readableStream=a.readable,s=a.readable}const o={kind:"decode",data:{readableStream:s,writableStream:A,trackId:t,codec:i,participantIdentity:r}};this.worker.postMessage(o,[s,A])}e[ta]=!0}})}handleSender(e,t,r){var i;if(!(ta in e||!this.worker)){if(!(!((i=this.room)===null||i===void 0)&&i.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Bl()){ue.info("initialize script transform");const A={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:r};e.transform=new RTCRtpScriptTransform(this.worker,A)}else{ue.info("initialize encoded streams");const A=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:A.readable,writableStream:A.writable,codec:r,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s,[A.readable,A.writable])}e[ta]=!0}}}const Gl="default";class ft{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new ft),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var A;if(((A=ft.userMediaPromiseMap)===null||A===void 0?void 0:A.size)>0){ue.debug("awaiting getUserMedia promise");try{t?yield ft.userMediaPromiseMap.get(t):yield Promise.all(ft.userMediaPromiseMap.values())}catch{ue.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&!(pr()&&r.hasDeviceInUse(t))&&(s.filter(a=>a.kind===t).length===0||s.some(a=>{const c=a.label==="",u=t?a.kind===t:!0;return c&&u}))){const a={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},c=yield navigator.mediaDevices.getUserMedia(a);s=yield navigator.mediaDevices.enumerateDevices(),c.getTracks().forEach(u=>{u.stop()})}return r._previousDevices=s,t&&(s=s.filter(o=>o.kind===t)),s}()})}normalizeDeviceId(e,t,r){return S(this,void 0,void 0,function*(){if(t!==Gl)return t;const i=yield this.getDevices(e),A=i.find(o=>o.deviceId===Gl);if(!A){ue.warn("could not reliably determine default device");return}const s=i.find(o=>o.deviceId!==Gl&&o.groupId===(r??A.groupId));if(!s){ue.warn("could not reliably determine default device");return}return s==null?void 0:s.deviceId})}hasDeviceInUse(e){return e?ft.userMediaPromiseMap.has(e):ft.userMediaPromiseMap.size>0}}ft.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],ft.userMediaPromiseMap=new Map;var GA;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(GA||(GA={}));class nx{constructor(){this.pendingTasks=new Map,this.taskMutex=new Mt,this.nextTaskIndex=0}run(e){return S(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:GA.WAITING};this.pendingTasks.set(t.id,t);const r=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=GA.RUNNING,yield e()}finally{t.status=GA.COMPLETED,this.pendingTasks.delete(t.id),r()}})}flush(){return S(this,void 0,void 0,function*(){return this.run(()=>S(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function rx(n,e){const t=new URL(VF(n));return e.forEach((r,i)=>{t.searchParams.set(i,r)}),c0(t,"rtc")}function ix(n){const e=new URL(Dl(n));return c0(e,"validate")}function Ax(n){return n.endsWith("/")?n:"".concat(n,"/")}function c0(n,e){return n.pathname="".concat(Ax(n.pathname)).concat(e),n.toString()}const sx=["syncState","trickle","offer","answer","simulate","leave"];function ox(n){const e=sx.indexOf(n.case)>=0;return ue.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var Oe;(function(n){n[n.CONNECTING=0]="CONNECTING",n[n.CONNECTED=1]="CONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.DISCONNECTING=3]="DISCONNECTING",n[n.DISCONNECTED=4]="DISCONNECTED"})(Oe||(Oe={}));class jl{get currentState(){return this.state}get isDisconnected(){return this.state===Oe.DISCONNECTING||this.state===Oe.DISCONNECTED}get isEstablishingConnection(){return this.state===Oe.CONNECTING||this.state===Oe.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var r;this.rtt=0,this.state=Oe.DISCONNECTED,this.log=ue,this._requestId=0,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0},this.log=Ln((r=t.loggerName)!==null&&r!==void 0?r:cn.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new nx,this.queuedRequests=[],this.closingLock=new Mt,this.connectionLock=new Mt,this.state=Oe.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,r,i){return S(this,void 0,void 0,function*(){return this.state=Oe.CONNECTING,this.options=r,yield this.connect(e,t,r,i)})}reconnect(e,t,r,i){return S(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=Oe.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:r,reconnectReason:i}))})}connect(e,t,r,i){this.connectOptions=r;const A=HF(),s=ax(t,A,r),o=rx(e,s),a=ix(o);return new Promise((c,u)=>S(this,void 0,void 0,function*(){const l=yield this.connectionLock.lock();try{const d=()=>S(this,void 0,void 0,function*(){this.close(),clearTimeout(h),u(new Fe("room connection has been cancelled (signal)",de.Cancelled))}),h=setTimeout(()=>{this.close(),u(new Fe("room connection has timed out (signal)",de.ServerUnreachable))},r.websocketTimeout);i!=null&&i.aborted&&d(),i==null||i.addEventListener("abort",d);const f=new URL(o);f.searchParams.has("access_token")&&f.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(f),Object.assign({reconnect:r.reconnect,reconnectReason:r.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(h)},this.ws.onerror=p=>S(this,void 0,void 0,function*(){if(this.state!==Oe.CONNECTED){this.state=Oe.DISCONNECTED,clearTimeout(h);try{const g=yield fetch(a);if(g.status.toFixed(0).startsWith("4")){const v=yield g.text();u(new Fe(v,de.NotAllowed,g.status))}else u(new Fe("Encountered unknown websocket error during connection: ".concat(p.toString()),de.InternalError,g.status))}catch(g){u(new Fe(g instanceof Error?g.message:"server was not reachable",de.ServerUnreachable))}return}this.handleWSError(p)}),this.ws.onmessage=p=>S(this,void 0,void 0,function*(){var g,v,y;let B;if(typeof p.data=="string"){const b=JSON.parse(p.data);B=jm.fromJson(b,{ignoreUnknownFields:!0})}else if(p.data instanceof ArrayBuffer)B=jm.fromBinary(new Uint8Array(p.data));else{this.log.error("could not decode websocket message: ".concat(typeof p.data),this.logContext);return}if(this.state!==Oe.CONNECTED){let b=!1;if(((g=B.message)===null||g===void 0?void 0:g.case)==="join"?(this.state=Oe.CONNECTED,i==null||i.removeEventListener("abort",d),this.pingTimeoutDuration=B.message.value.pingTimeout,this.pingIntervalDuration=B.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),c(B.message.value)):this.state===Oe.RECONNECTING&&B.message.case!=="leave"?(this.state=Oe.CONNECTED,i==null||i.removeEventListener("abort",d),this.startPingInterval(),((v=B.message)===null||v===void 0?void 0:v.case)==="reconnect"?c(B.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),c(void 0),b=!0)):this.isEstablishingConnection&&B.message.case==="leave"?u(new Fe("Received leave request while trying to (re)connect",de.LeaveRequest,void 0,B.message.value.reason)):r.reconnect||u(new Fe("did not receive join response, got ".concat((y=B.message)===null||y===void 0?void 0:y.case," instead"),de.InternalError)),!b)return}this.signalLatency&&(yield Nt(this.signalLatency)),this.handleSignalResponse(B)}),this.ws.onclose=p=>{this.isEstablishingConnection&&u(new Fe("Websocket got closed during a (re)connection attempt",de.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:p.reason,code:p.code,wasClean:p.wasClean,state:this.state})),this.handleOnClose(p.reason)}}finally{l()}}))}close(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const r=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Oe.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const i=new Promise(A=>{e.ws?e.ws.onclose=()=>{A()}:A()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([i,Nt(250)])),e.ws=void 0}}finally{t&&(e.state=Oe.DISCONNECTED),r()}}()})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:sa(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:sa(e)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new al({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new cl({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const o=A.getNextRequestId();return yield A.sendRequest({case:"updateMetadata",value:new zm({requestId:o,metadata:r,name:i,attributes:s})}),o}()})}sendUpdateTrackSettings(e){this.sendRequest({case:"trackSetting",value:e})}sendUpdateSubscription(e){return this.sendRequest({case:"subscription",value:e})}sendSyncState(e){return this.sendRequest({case:"syncState",value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:"updateLayers",value:new Jm({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new Zm({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Ke.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new tv({timestamp:Ke.parse(Date.now()),rtt:Ke.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new qm({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new jo({reason:sn.CLIENT_INITIATED,action:Ti.DISCONNECT})})}sendRequest(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!i&&!ox(t)&&r.state===Oe.RECONNECTING){r.queuedRequests.push(()=>S(r,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(i||(yield r.requestQueue.flush()),r.signalLatency&&(yield Nt(r.signalLatency)),!r.ws||r.ws.readyState!==r.ws.OPEN){r.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),r.logContext);return}const s=new QI({message:t});try{r.useJSON?r.ws.send(s.toJsonString()):r.ws.send(s.toBinary())}catch(o){r.log.error("error sending signal message",Object.assign(Object.assign({},r.logContext),{error:o}))}}()})}handleSignalResponse(e){var t,r;const i=e.message;if(i==null){this.log.debug("received unsupported message",this.logContext);return}let A=!1;if(i.case==="answer"){const s=u0(i.value);this.onAnswer&&this.onAnswer(s)}else if(i.case==="offer"){const s=u0(i.value);this.onOffer&&this.onOffer(s)}else if(i.case==="trickle"){const s=JSON.parse(i.value.candidateInit);this.onTrickle&&this.onTrickle(s,i.value.target)}else i.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=i.value.participants)!==null&&t!==void 0?t:[]):i.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(i.value):i.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((r=i.value.speakers)!==null&&r!==void 0?r:[]):i.case==="leave"?this.onLeave&&this.onLeave(i.value):i.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(i.value.sid,i.value.muted):i.case==="roomUpdate"?this.onRoomUpdate&&i.value.room&&this.onRoomUpdate(i.value.room):i.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(i.value):i.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(i.value):i.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(i.value):i.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(i.value):i.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(i.value):i.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(i.value):i.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(i.value):i.case==="pong"||(i.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(i.value.lastPingTimestamp.toString()),this.resetPingTimeout(),A=!0):i.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(i.value):i.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(i.value.trackSid):i.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(i.value.token),this.onRoomMoved&&this.onRoomMoved(i.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:i.case})));A||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return S(this,void 0,void 0,function*(){if(this.state===Oe.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=wt.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&wt.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=wt.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&wt.clearInterval(this.pingInterval)}}function u0(n){const e={type:"offer",sdp:n.sdp};switch(n.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=n.type;break}return e}function sa(n){return new Gr({sdp:n.sdp,type:n.type})}function ax(n,e,t){var r;const i=new URLSearchParams;return i.set("access_token",n),t.reconnect&&(i.set("reconnect","1"),t.sid&&i.set("sid",t.sid)),i.set("auto_subscribe",t.autoSubscribe?"1":"0"),i.set("sdk",kn()?"reactnative":"js"),i.set("version",e.version),i.set("protocol",e.protocol.toString()),e.deviceModel&&i.set("device_model",e.deviceModel),e.os&&i.set("os",e.os),e.osVersion&&i.set("os_version",e.osVersion),e.browser&&i.set("browser",e.browser),e.browserVersion&&i.set("browser_version",e.browserVersion),t.adaptiveStream&&i.set("adaptive_stream","1"),t.reconnectReason&&i.set("reconnect_reason",t.reconnectReason.toString()),!((r=navigator.connection)===null||r===void 0)&&r.type&&i.set("network",navigator.connection.type),i}var ln={},Wl={},ql={exports:{}},l0;function Jl(){if(l0)return ql.exports;l0=1;var n=ql.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(e){return e.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(e){return e.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return e.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=e.raddr!=null?" raddr %s rport %d":"%v%v",t+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(t+=" generation %d"),t+=e["network-id"]!=null?" network-id %d":"%v",t+=e["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(e){var t="ssrc:%d";return e.attribute!=null&&(t+=" %s",e.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(e){return e.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(e){return e.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(e){return"imageattr:%s %s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(e){return"simulcast:%s %s"+(e.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(e){return"ts-refclk:%s"+(e.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=e.id!=null?"id=%s %s":"%v%s",t+=e.mediaClockValue!=null?"=%s":"",t+=e.rateNumerator!=null?" rate=%s":"",t+=e.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(n).forEach(function(e){var t=n[e];t.forEach(function(r){r.reg||(r.reg=/(.*)/),r.format||(r.format="%s")})}),ql.exports}var d0;function cx(){return d0||(d0=1,function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,a,c,u){if(u&&!c)a[u]=e(o[1]);else for(var l=0;l<c.length;l+=1)o[l+1]!=null&&(a[c[l]]=e(o[l+1]))},r=function(o,a,c){var u=o.name&&o.names;o.push&&!a[o.push]?a[o.push]=[]:u&&!a[o.name]&&(a[o.name]={});var l=o.push?{}:u?a[o.name]:a;t(c.match(o.reg),l,o.names,o.name),o.push&&a[o.push].push(l)},i=Jl(),A=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var a={},c=[],u=a;return o.split(/(\r\n|\r|\n)/).filter(A).forEach(function(l){var d=l[0],h=l.slice(2);d==="m"&&(c.push({rtp:[],fmtp:[]}),u=c[c.length-1]);for(var f=0;f<(i[d]||[]).length;f+=1){var p=i[d][f];if(p.reg.test(h))return r(p,u,h)}}),a.media=c,a};var s=function(o,a){var c=a.split(/=(.+)/,2);return c.length===2?o[c[0]]=e(c[1]):c.length===1&&a.length>1&&(o[c[0]]=void 0),o};n.parseParams=function(o){return o.split(/;\s?/).reduce(s,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(o){return o.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(o){for(var a=[],c=o.split(" ").map(e),u=0;u<c.length;u+=3)a.push({component:c[u],ip:c[u+1],port:c[u+2]});return a},n.parseImageAttributes=function(o){return o.split(" ").map(function(a){return a.substring(1,a.length-1).split(",").reduce(s,{})})},n.parseSimulcastStreamList=function(o){return o.split(";").map(function(a){return a.split(",").map(function(c){var u,l=!1;return c[0]!=="~"?u=e(c):(u=e(c.substring(1,c.length)),l=!0),{scid:u,paused:l}})})}}(Wl)),Wl}var zl,h0;function ux(){if(h0)return zl;h0=1;var n=Jl(),e=/%[sdv%]/g,t=function(s){var o=1,a=arguments,c=a.length;return s.replace(e,function(u){if(o>=c)return u;var l=a[o];switch(o+=1,u){case"%%":return"%";case"%s":return String(l);case"%d":return Number(l);case"%v":return""}})},r=function(s,o,a){var c=o.format instanceof Function?o.format(o.push?a:a[o.name]):o.format,u=[s+"="+c];if(o.names)for(var l=0;l<o.names.length;l+=1){var d=o.names[l];o.name?u.push(a[o.name][d]):u.push(a[o.names[l]])}else u.push(a[o.name]);return t.apply(null,u)},i=["v","o","s","i","u","e","p","c","b","t","r","z","a"],A=["i","c","b","a"];return zl=function(s,o){o=o||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(l){l.payloads==null&&(l.payloads="")});var a=o.outerOrder||i,c=o.innerOrder||A,u=[];return a.forEach(function(l){n[l].forEach(function(d){d.name in s&&s[d.name]!=null?u.push(r(l,d,s)):d.push in s&&s[d.push]!=null&&s[d.push].forEach(function(h){u.push(r(l,d,h))})})}),s.media.forEach(function(l){u.push(r("m",n.m[0],l)),c.forEach(function(d){n[d].forEach(function(h){h.name in l&&l[h.name]!=null?u.push(r(d,h,l)):h.push in l&&l[h.push]!=null&&l[h.push].forEach(function(f){u.push(r(d,h,f))})})})}),u.join(`\r
41
41
  `)+`\r
42
- `},zl}var p0;function lx(){if(p0)return ln;p0=1;var n=cx(),e=ux(),t=Jl();return ln.grammar=t,ln.write=e,ln.parse=n.parse,ln.parseParams=n.parseParams,ln.parseFmtpConfig=n.parseFmtpConfig,ln.parsePayloads=n.parsePayloads,ln.parseRemoteCandidates=n.parseRemoteCandidates,ln.parseImageAttributes=n.parseImageAttributes,ln.parseSimulcastStreamList=n.parseSimulcastStreamList,ln}var mr=lx();function Xl(n,e,t){var r,i,A;e===void 0&&(e=50),t===void 0&&(t={});var s=(r=t.isImmediate)!=null&&r,o=(i=t.callback)!=null&&i,a=t.maxWait,c=Date.now(),u=[];function l(){if(a!==void 0){var h=Date.now()-c;if(h+e>=a)return a-h}return e}var d=function(){var h=[].slice.call(arguments),f=this;return new Promise(function(p,g){var v=s&&A===void 0;if(A!==void 0&&clearTimeout(A),A=setTimeout(function(){if(A=void 0,c=Date.now(),!s){var B=n.apply(f,h);o&&o(B),u.forEach(function(b){return(0,b.resolve)(B)}),u=[]}},l()),v){var y=n.apply(f,h);return o&&o(y),p(y)}u.push({resolve:p,reject:g})})};return d.cancel=function(h){A!==void 0&&clearTimeout(A),u.forEach(function(f){return(0,f.reject)(h)}),u=[]},d}const dx=.7,hx=20,Oi={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class f0 extends Sn.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var r;super(),this.log=ue,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Xl(i=>S(this,void 0,void 0,function*(){this.emit(Oi.NegotiationStarted);try{yield this.createAndSendOffer()}catch(A){if(i)i(A);else throw A}}),hx),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=Ln((r=t.loggerName)!==null&&r!==void 0?r:cn.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var r;t.candidate&&((r=this.onIceCandidate)===null||r===void 0||r.call(this,t.candidate))},e.onicecandidateerror=t=>{var r;(r=this.onIceCandidateError)===null||r===void 0||r.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var r;(r=this.onDataChannel)===null||r===void 0||r.call(this,t)},e.ontrack=t=>{var r;(r=this.onTrack)===null||r===void 0||r.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return S(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return S(this,void 0,void 0,function*(){var t;let r;if(e.type==="offer"){let{stereoMids:i,nackMids:A}=px(e);this.remoteStereoMids=i,this.remoteNackMids=A}else if(e.type==="answer"){const i=mr.parse((t=e.sdp)!==null&&t!==void 0?t:"");i.media.forEach(A=>{A.type==="audio"&&this.trackBitrates.some(s=>{if(!s.transceiver||A.mid!=s.transceiver.mid)return!1;let o=0;if(A.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0)return!0;let a=!1;for(const c of A.fmtp)if(c.payload===o){c.config=c.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),s.maxbr>0&&(c.config+=";maxaveragebitrate=".concat(s.maxbr*1e3)),a=!0;break}return a||s.maxbr>0&&A.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(s.maxbr*1e3)}),!0})}),r=mr.write(i)}yield this.setMungedSDP(e,r,!0),this.pendingCandidates.forEach(i=>{this.pc.addIceCandidate(i)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Oi.NegotiationComplete),e.sdp&&mr.parse(e.sdp).media.forEach(A=>{A.type==="video"&&this.emit(Oi.RTPVideoPayloadTypes,A.rtp)}))})}createAndSendOffer(e){return S(this,void 0,void 0,function*(){var t;if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const A=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&A)yield this._pc.setRemoteDescription(A);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const i=mr.parse((t=r.sdp)!==null&&t!==void 0?t:"");i.media.forEach(A=>{m0(A),A.type==="audio"?g0(A,[],[]):A.type==="video"&&this.trackBitrates.some(s=>{if(!A.msid||!s.cid||!A.msid.includes(s.cid))return!1;let o=0;if(A.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0||(KA(s.codec)&&this.ensureVideoDDExtensionForSVC(A,i),s.codec!=="av1"))return!0;const a=Math.round(s.maxbr*dx);for(const c of A.fmtp)if(c.payload===o){c.config.includes("x-google-start-bitrate")||(c.config+=";x-google-start-bitrate=".concat(a));break}return!0})}),yield this.setMungedSDP(r,mr.write(i)),this.onOffer(r)})}createAndSetAnswer(){return S(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),r=mr.parse((e=t.sdp)!==null&&e!==void 0?e:"");return r.media.forEach(i=>{m0(i),i.type==="audio"&&g0(i,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,mr.write(r)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new lt("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new lt("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return S(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const r=new Map,i=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),r.set(o.id,o);break;case"remote-candidate":i.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const s=(e=r.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(s!==void 0)return i.get(s)})}setMungedSDP(e,t,r){return S(this,void 0,void 0,function*(){if(t){const i=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(r?"remote":"local"," description"),this.logContext),r?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(A){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:A,sdp:t})),e.sdp=i}}try{r?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(i){let A="unknown error";i instanceof Error?A=i.message:typeof i=="string"&&(A=i);const s={error:A,sdp:e.sdp};throw!r&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new _l(A)}})}ensureVideoDDExtensionForSVC(e,t){var r,i;if(!((r=e.ext)===null||r===void 0?void 0:r.some(s=>s.uri===zv))){if(this.ddExtID===0){let s=0;t.media.forEach(o=>{var a;o.type==="video"&&((a=o.ext)===null||a===void 0||a.forEach(c=>{c.value>s&&(s=c.value)}))}),this.ddExtID=s+1}(i=e.ext)===null||i===void 0||i.push({value:this.ddExtID,uri:zv})}}}function g0(n,e,t){let r=0;n.rtp.some(i=>i.codec==="opus"?(r=i.payload,!0):!1),r>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(n.mid)&&!n.rtcpFb.some(i=>i.payload===r&&i.type==="nack")&&n.rtcpFb.push({payload:r,type:"nack"}),e.includes(n.mid)&&n.fmtp.some(i=>i.payload===r?(i.config.includes("stereo=1")||(i.config+=";stereo=1"),!0):!1))}function px(n){var e;const t=[],r=[],i=mr.parse((e=n.sdp)!==null&&e!==void 0?e:"");let A=0;return i.media.forEach(s=>{var o;s.type==="audio"&&(s.rtp.some(a=>a.codec==="opus"?(A=a.payload,!0):!1),!((o=s.rtcpFb)===null||o===void 0)&&o.some(a=>a.payload===A&&a.type==="nack")&&r.push(s.mid),s.fmtp.some(a=>a.payload===A?(a.config.includes("sprop-stereo=1")&&t.push(s.mid),!0):!1))}),{stereoMids:t,nackMids:r}}function m0(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}const Yl="vp8",fx={audioPreset:Ul.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Il.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Yl,backupCodec:!0},v0={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},y0={deviceId:{ideal:"default"},resolution:HA.h720.resolution},gx={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new sF,disconnectOnPageLeave:!0,webAudioMix:!1},Zl={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Ye;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(Ye||(Ye={}));class mx{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,r){var i;this.peerConnectionTimeout=Zl.peerConnectionTimeout,this.log=ue,this.updateState=()=>{var A;const s=this.state,o=this.requiredTransports.map(a=>a.getConnectionState());o.every(a=>a==="connected")?this.state=Ye.CONNECTED:o.some(a=>a==="failed")?this.state=Ye.FAILED:o.some(a=>a==="connecting")?this.state=Ye.CONNECTING:o.every(a=>a==="closed")?this.state=Ye.CLOSED:o.some(a=>a==="closed")?this.state=Ye.CLOSING:o.every(a=>a==="new")&&(this.state=Ye.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(Ye[s]," to ").concat(Ye[this.state]),this.logContext),(A=this.onStateChange)===null||A===void 0||A.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Ln((i=r.loggerName)!==null&&i!==void 0?i:cn.PCManager),this.loggerOptions=r,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new f0(e,r),this.subscriber=new f0(e,r),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=A=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,A,an.PUBLISHER)},this.subscriber.onIceCandidate=A=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,A,an.SUBSCRIBER)},this.subscriber.onDataChannel=A=>{var s;(s=this.onDataChannel)===null||s===void 0||s.call(this,A)},this.subscriber.onTrack=A=>{var s;(s=this.onTrack)===null||s===void 0||s.call(this,A)},this.publisher.onOffer=A=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,A)},this.state=Ye.NEW,this.connectionLock=new Mt,this.remoteOfferLock=new Mt}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return S(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(r){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:r}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return S(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return S(this,void 0,void 0,function*(){t===an.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return S(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return S(this,void 0,void 0,function*(){var r;const i=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((r=this.requiredTransports)===null||r===void 0?void 0:r.map(A=>this.ensureTransportConnected(A,e,t)))}finally{i()}})}negotiate(e){return S(this,void 0,void 0,function*(){return new Promise((t,r)=>S(this,void 0,void 0,function*(){const i=setTimeout(()=>{r("negotiation timed out")},this.peerConnectionTimeout),A=()=>{clearTimeout(i),r("negotiation aborted")};e.signal.addEventListener("abort",A),this.publisher.once(Oi.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Oi.NegotiationComplete,()=>{clearTimeout(i),t()})}),yield this.publisher.negotiate(s=>{clearTimeout(i),r(s)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===an.PUBLISHER?this.publisher.getConnectedAddress():e===an.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(r.getConnectionState()!=="connected")return new Promise((a,c)=>S(A,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),wt.clearTimeout(l),c(new Fe("room connection has been cancelled",de.Cancelled))};i!=null&&i.signal.aborted&&u(),i==null||i.signal.addEventListener("abort",u);const l=wt.setTimeout(()=>{i==null||i.signal.removeEventListener("abort",u),c(new Fe("could not establish pc connection",de.InternalError))},s);for(;this.state!==Ye.CONNECTED;)if(yield Nt(50),i!=null&&i.signal.aborted){c(new Fe("room connection has been cancelled",de.Cancelled));return}wt.clearTimeout(l),i==null||i.signal.removeEventListener("abort",u),a()}))}()})}}class Ze extends Error{constructor(e,t,r){super(t),this.code=e,this.message=b0(t,Ze.MAX_MESSAGE_BYTES),this.data=r?b0(r,Ze.MAX_DATA_BYTES):void 0}static fromProto(e){return new Ze(e.code,e.message,e.data)}toProto(){return new Om({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new Ze(Ze.ErrorCode[e],Ze.ErrorMessage[e],t)}}Ze.MAX_MESSAGE_BYTES=256,Ze.MAX_DATA_BYTES=15360,Ze.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},Ze.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const w0=15360;function $l(n){return new TextEncoder().encode(n).length}function b0(n,e){if($l(n)<=e)return n;let t=0,r=n.length;const i=new TextEncoder;for(;t<r;){const A=Math.floor((t+r+1)/2);i.encode(n.slice(0,A)).length<=e?t=A:r=A-1}return n.slice(0,t)}const ed=2e3;function oa(n,e){if(!e)return 0;let t,r;return"bytesReceived"in n?(t=n.bytesReceived,r=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,r=e.bytesSent),t===void 0||r===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-r)*8*1e3/(n.timestamp-e.timestamp)}const vx=1e3;class B0 extends R{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,r){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,A=arguments.length>4?arguments[4]:void 0;super(e,t,A),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=Xl(()=>S(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>S(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(L.Ended,this)},this.reacquireTrack=!1,this.providedByUser=i,this.muteLock=new Mt,this.pauseUpstreamLock=new Mt,this.processorLock=new Mt,this.restartLock=new Mt,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),r&&(this._constraints=r)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==R.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return S(this,void 0,void 0,function*(){var r;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(A=>{xi(this._mediaStreamTrack,A)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let i;if(this.processor&&e){const A=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Fi(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}finally{A()}}this.sender&&((r=this.sender.transport)===null||r===void 0?void 0:r.state)!=="closed"&&(yield this.sender.replaceTrack(i??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(A=>{Fi(i??e,A)}))})}waitForDimensions(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:vx;return function*(){var r;if(e.kind===R.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((r=un())===null||r===void 0?void 0:r.os)==="iOS"&&(yield Nt(10));const i=Date.now();for(;Date.now()-i<t;){const A=e.dimensions;if(A)return A;yield Nt(50)}throw new Dn("unable to get track dimensions after timeout")}()})}setDeviceId(e){return S(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===fr(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),fr(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===R.Source.ScreenShare)return;const{deviceId:r,groupId:i}=e._mediaStreamTrack.getSettings(),A=e.kind===R.Kind.Audio?"audioinput":"videoinput";return t?ft.getInstance().normalizeDeviceId(A,r,i):r}()})}mute(){return S(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return S(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return S(this,void 0,void 0,function*(){if(!this.sender)throw new Dn("unable to replace an unpublished track");let r,i;return typeof t=="boolean"?r=t:t!==void 0&&(r=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return S(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:r,facingMode:i}=e,A=oF(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===R.Kind.Video?s.video=r||i?{deviceId:r,facingMode:i}:!0:s.audio=r?{deviceId:r}:!0,this.attachedElements.forEach(c=>{xi(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const a=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return yield a.applyConstraints(A),a.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(a),this._constraints=e,this.emit(L.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?L.Muted:L.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Xv()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return S(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(L.UpstreamPaused,this);const r=un();if((r==null?void 0:r.name)==="Safari"&&Wr(r.version,"12.0")<0)throw new Cl("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return S(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(L.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return S(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var A;const s=yield r.processorLock.lock();try{r.log.debug("setting up processor",r.logContext);const o=document.createElement(r.kind),a={kind:r.kind,track:r._mediaStreamTrack,element:o,audioContext:r.audioContext};if(yield t.init(a),r.log.debug("processor initialized",r.logContext),r.processor&&(yield r.stopProcessor()),r.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Fi(r._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>r.log.error("failed to play processor element",Object.assign(Object.assign({},r.logContext),{error:c}))),r.processor=t,r.processorElement=o,r.processor.processedTrack){for(const c of r.attachedElements)c!==r.processorElement&&i&&(xi(r._mediaStreamTrack,c),Fi(r.processor.processedTrack,c));yield(A=r.sender)===null||A===void 0?void 0:A.replaceTrack(r.processor.processedTrack)}r.emit(L.TrackProcessorUpdate,r.processor)}finally{s()}}()})}getProcessor(){return this.processor}stopProcessor(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var r,i;e.processor&&(e.log.debug("stopping processor",e.logContext),(r=e.processor.processedTrack)===null||r===void 0||r.stop(),yield e.processor.destroy(),e.processor=void 0,t||((i=e.processorElement)===null||i===void 0||i.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(L.TrackProcessorUpdate))}()})}}class aa extends B0{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0,A=arguments.length>4?arguments[4]:void 0;super(e,R.Kind.Audio,t,r,A),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>S(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}s&&this.prevStats&&(this._currentBitrate=oa(s,this.prevStats)),this.prevStats=s}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(L.AudioTrackFeatureUpdate,this,on.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(L.AudioTrackFeatureUpdate,this,on.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===R.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const r=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==fr(this._constraints.deviceId);return this.source===R.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||r)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return S(this,void 0,void 0,function*(){let t;if(e){const r=Vl({audio:e});typeof r.audio!="boolean"&&(t=r.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return S(this,void 0,void 0,function*(){const r=yield t.restart.call(this,e);return this.checkForSilence(),r})}startMonitor(){Ht()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},ed)))}setProcessor(e){return S(this,void 0,void 0,function*(){var t;const r=yield this.processorLock.lock();try{if(!kn()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(L.TrackProcessorUpdate,this.processor)}finally{r()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return S(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let r;return t.forEach(i=>{i.type==="outbound-rtp"&&(r={type:"audio",streamId:i.id,packetsSent:i.packetsSent,packetsLost:i.packetsLost,bytesSent:i.bytesSent,timestamp:i.timestamp,roundTripTime:i.roundTripTime,jitter:i.jitter})}),r})}checkForSilence(){return S(this,void 0,void 0,function*(){const e=yield A0(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(L.AudioSilenceDetected)),e})}}function yx(n,e,t){switch(n.kind){case"audio":return new aa(n,e,!1,void 0,t);case"video":return new ua(n,e,!1,t);default:throw new Dn("unsupported track type: ".concat(n.kind))}}const wx=Object.values(HA),bx=Object.values(Tl),Bx=Object.values(Il),Cx=[HA.h180,HA.h360],_x=[Tl.h180,Tl.h360],Sx=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var r,i;return new Te(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((r=n.encoding.maxFramerate)!==null&&r!==void 0?r:30)/((i=t.fps)!==null&&i!==void 0?i:30))))),t.fps,n.encoding.priority)}),td=["q","h","f"];function nd(n,e,t,r){var i,A;let s=r==null?void 0:r.videoEncoding;n&&(s=r==null?void 0:r.screenShareEncoding);const o=r==null?void 0:r.simulcast,a=r==null?void 0:r.scalabilityMode,c=r==null?void 0:r.videoCodec;if(!s&&!o&&!a||!e||!t)return[{}];s||(s=Ex(n,e,t,c),ue.debug("using video encoding",s));const u=s.maxFramerate,l=new Te(e,t,s.maxBitrate,s.maxFramerate,s.priority);if(a&&KA(c)){const f=new ca(a),p=[];if(f.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(a));const g=un();if(pr()||kn()||(g==null?void 0:g.name)==="Chrome"&&Wr(g==null?void 0:g.version,"113")<0){const v=f.suffix=="h"?2:3;for(let y=0;y<f.spatial;y+=1)p.push({rid:td[2-y],maxBitrate:s.maxBitrate/Math.pow(v,y),maxFramerate:l.encoding.maxFramerate});p[0].scalabilityMode=a}else p.push({maxBitrate:s.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:a});return l.encoding.priority&&(p[0].priority=l.encoding.priority,p[0].networkPriority=l.encoding.priority),ue.debug("using svc encoding",{encodings:p}),p}if(!o)return[s];let d=[];n?d=(i=_0(r==null?void 0:r.screenShareSimulcastLayers))!==null&&i!==void 0?i:C0(n,l):d=(A=_0(r==null?void 0:r.videoSimulcastLayers))!==null&&A!==void 0?A:C0(n,l);let h;if(d.length>0){const f=d[0];d.length>1&&([,h]=d);const p=Math.max(e,t);if(p>=960&&h)return rd(e,t,[f,h,l],u);if(p>=480)return rd(e,t,[f,l],u)}return rd(e,t,[l])}function kx(n,e,t){var r,i,A,s;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&ue.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),a=(r=o.width)!==null&&r!==void 0?r:(i=n.dimensions)===null||i===void 0?void 0:i.width,c=(A=o.height)!==null&&A!==void 0?A:(s=n.dimensions)===null||s===void 0?void 0:s.height;return n.source===R.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),nd(n.source===R.Source.ScreenShare,a,c,t)}function Ex(n,e,t,r){const i=Ux(n,e,t);let{encoding:A}=i[0];const s=Math.max(e,t);for(let o=0;o<i.length;o+=1){const a=i[o];if(A=a.encoding,a.width>=s)break}if(r)switch(r){case"av1":A=Object.assign({},A),A.maxBitrate=A.maxBitrate*.7;break;case"vp9":A=Object.assign({},A),A.maxBitrate=A.maxBitrate*.85;break}return A}function Ux(n,e,t){if(n)return Bx;const r=e>t?e/t:t/e;return Math.abs(r-16/9)<Math.abs(r-4/3)?wx:bx}function C0(n,e){if(n)return Sx(e);const{width:t,height:r}=e,i=t>r?t/r:r/t;return Math.abs(i-16/9)<Math.abs(i-4/3)?Cx:_x}function rd(n,e,t,r){const i=[];if(t.forEach((A,s)=>{if(s>=td.length)return;const o=Math.min(n,e),c={rid:td[s],scaleResolutionDownBy:Math.max(1,o/Math.min(A.width,A.height)),maxBitrate:A.encoding.maxBitrate},u=r&&A.encoding.maxFramerate?Math.min(r,A.encoding.maxFramerate):A.encoding.maxFramerate;u&&(c.maxFramerate=u);const l=Qi()||s===0;A.encoding.priority&&l&&(c.priority=A.encoding.priority,c.networkPriority=A.encoding.priority),i.push(c)}),kn()&&Zv()==="ios"){let A;i.forEach(o=>{A?o.maxFramerate&&o.maxFramerate>A&&(A=o.maxFramerate):A=o.maxFramerate});let s=!0;i.forEach(o=>{var a;o.maxFramerate!=A&&(s&&(s=!1,ue.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ue.info('Setting framerate of encoding "'.concat((a=o.rid)!==null&&a!==void 0?a:"",'" to ').concat(A)),o.maxFramerate=A)})}return i}function _0(n){if(n)return n.sort((e,t)=>{const{encoding:r}=e,{encoding:i}=t;return r.maxBitrate>i.maxBitrate?1:r.maxBitrate<i.maxBitrate?-1:r.maxBitrate===i.maxBitrate&&r.maxFramerate&&i.maxFramerate?r.maxFramerate>i.maxFramerate?1:-1:0})}class ca{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function Tx(n){return n.source===R.Source.ScreenShare||n.constraints.height&&fr(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const Ix=5e3;class ua extends B0{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0;super(e,R.Kind.Video,t,r,i),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>S(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let A;try{A=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}const s=new Map(A.map(o=>[o.rid,o]));if(this.prevStats){let o=0;s.forEach((a,c)=>{var u;const l=(u=this.prevStats)===null||u===void 0?void 0:u.get(c);o+=oa(a,l)}),this._currentBitrate=o}this.prevStats=s}),this.senderLock=new Mt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Ht())return;const r=(t=this.sender)===null||t===void 0?void 0:t.getParameters();r&&(this.encodings=r.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},ed))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return S(this,void 0,void 0,function*(){var t,r,i,A,s;yield e.pauseUpstream.call(this);try{for(var o=!0,a=ur(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0)A=c.value,o=!1,yield(s=A.sender)===null||s===void 0?void 0:s.replaceTrack(null)}catch(u){r={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(r)throw r.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return S(this,void 0,void 0,function*(){var t,r,i,A,s;yield e.resumeUpstream.call(this);try{for(var o=!0,a=ur(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0){A=c.value,o=!1;const u=A;yield(s=u.sender)===null||s===void 0?void 0:s.replaceTrack(u.mediaStreamTrack)}}catch(u){r={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(r)throw r.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===R.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===R.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return S(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],r=yield this.sender.getStats();return r.forEach(i=>{var A;if(i.type==="outbound-rtp"){const s={type:"video",streamId:i.id,frameHeight:i.frameHeight,frameWidth:i.frameWidth,framesPerSecond:i.framesPerSecond,framesSent:i.framesSent,firCount:i.firCount,pliCount:i.pliCount,nackCount:i.nackCount,packetsSent:i.packetsSent,bytesSent:i.bytesSent,qualityLimitationReason:i.qualityLimitationReason,qualityLimitationDurations:i.qualityLimitationDurations,qualityLimitationResolutionChanges:i.qualityLimitationResolutionChanges,rid:(A=i.rid)!==null&&A!==void 0?A:i.id,retransmittedPacketsSent:i.retransmittedPacketsSent,targetBitrate:i.targetBitrate,timestamp:i.timestamp},o=r.get(i.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}}),t.sort((i,A)=>{var s,o;return((s=A.frameWidth)!==null&&s!==void 0?s:0)-((o=i.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let r=Yt.LOW;r<=Yt.HIGH;r+=1)t.push(new ll({quality:r,enabled:r<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return S(this,void 0,void 0,function*(){var t,r,i,A,s;let o;if(e){const l=Vl({video:e});typeof l.video!="boolean"&&(o=l.video)}yield this.restart(o);try{for(var a=!0,c=ur(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;a=!0){A=u.value,a=!1;const l=A;l.sender&&((s=l.sender.transport)===null||s===void 0?void 0:s.state)!=="closed"&&(l.mediaStreamTrack=this.mediaStreamTrack.clone(),yield l.sender.replaceTrack(l.mediaStreamTrack))}}catch(l){r={error:l}}finally{try{!a&&!t&&(i=c.return)&&(yield i.call(c))}finally{if(r)throw r.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return S(this,arguments,void 0,function(r){var i=this;let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s,o,a,c,u,l;if(yield t.setProcessor.call(i,r,A),!((u=i.processor)===null||u===void 0)&&u.processedTrack)try{for(var d=!0,h=ur(i.simulcastCodecs.values()),f;f=yield h.next(),s=f.done,!s;d=!0)c=f.value,d=!1,yield(l=c.sender)===null||l===void 0?void 0:l.replaceTrack(i.processor.processedTrack)}catch(p){o={error:p}}finally{try{!d&&!s&&(a=h.return)&&(yield a.call(h))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return S(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const r={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,r),r}setSimulcastTrackSender(e,t){const r=this.simulcastCodecs.get(e);r&&(r.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Ix))}setPublishingCodecs(e){return S(this,void 0,void 0,function*(){var t,r,i,A,s,o,a;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,r=ur(e);i=yield r.next(),A=i.done,!A;t=!0){a=i.value,t=!1;const u=a;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(u.qualities);else{const l=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:l})),!l||!l.sender){for(const d of u.qualities)if(d.enabled){c.push(u.codec);break}}else l.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield S0(l.sender,l.encodings,u.qualities,this.senderLock,this.log,this.logContext))}}}catch(u){s={error:u}}finally{try{!t&&!A&&(o=r.return)&&(yield o.call(r))}finally{if(s)throw s.error}}return c})}setPublishingLayers(e){return S(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield S0(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Xv()&&this.isInBackground&&this.source===R.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function S0(n,e,t,r,i,A){return S(this,void 0,void 0,function*(){const s=yield r.lock();i.debug("setPublishingLayersForSender",Object.assign(Object.assign({},A),{sender:n,qualities:t,senderEncodings:e}));try{const o=n.getParameters(),{encodings:a}=o;if(!a)return;if(a.length!==e.length){i.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},A),{encodings:a,senderEncodings:e}));return}let c=!1;const u=un();if((u==null?void 0:u.name)==="Chrome"&&Wr(u==null?void 0:u.version,"133")>0&&a[0].scalabilityMode){const d=a[0],h=new ca(d.scalabilityMode);let f=Si.OFF;if(t.forEach(p=>{p.enabled&&(f===Si.OFF||p.quality>f)&&(f=p.quality)}),f===Si.OFF)d.active&&(d.active=!1,c=!0);else if(!d.active||h.spatial!==f+1){c=!0,d.active=!0;const p=new ca(e[0].scalabilityMode);h.spatial=f+1,h.suffix=p.suffix,h.spatial===1&&(h.suffix=void 0),d.scalabilityMode=h.toString(),d.scaleResolutionDownBy=Math.pow(2,2-f),e[0].maxBitrate&&(d.maxBitrate=e[0].maxBitrate/(d.scaleResolutionDownBy*d.scaleResolutionDownBy))}}else a.forEach((d,h)=>{var f;let p=(f=d.rid)!==null&&f!==void 0?f:"";p===""&&(p="q");const g=k0(p),v=t.find(y=>y.quality===g);v&&d.active!==v.enabled&&(c=!0,d.active=v.enabled,i.debug("setting layer ".concat(v.quality," to ").concat(d.active?"enabled":"disabled"),A),Qi()&&(v.enabled?(d.scaleResolutionDownBy=e[h].scaleResolutionDownBy,d.maxBitrate=e[h].maxBitrate,d.maxFrameRate=e[h].maxFrameRate):(d.scaleResolutionDownBy=4,d.maxBitrate=10,d.maxFrameRate=2)))});c&&(o.encodings=a,i.debug("setting encodings",Object.assign(Object.assign({},A),{encodings:o.encodings})),yield n.setParameters(o))}finally{s()}})}function k0(n){switch(n){case"f":return Yt.HIGH;case"h":return Yt.MEDIUM;case"q":return Yt.LOW;default:return Yt.HIGH}}function E0(n,e,t,r){if(!t)return[new Vr({quality:Yt.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(r){const i=t[0].scalabilityMode,A=new ca(i),s=[],o=A.suffix=="h"?1.5:2,a=A.suffix=="h"?2:3;for(let c=0;c<A.spatial;c+=1)s.push(new Vr({quality:Math.min(Yt.HIGH,A.spatial-1)-c,width:Math.ceil(n/Math.pow(o,c)),height:Math.ceil(e/Math.pow(o,c)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(a,c)):0,ssrc:0}));return s}return t.map(i=>{var A,s,o;const a=(A=i.scaleResolutionDownBy)!==null&&A!==void 0?A:1;let c=k0((s=i.rid)!==null&&s!==void 0?s:"");return new Vr({quality:c,width:Math.ceil(n/a),height:Math.ceil(e/a),bitrate:(o=i.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const U0="_lossy",T0="_reliable",Fx=2*1e3,id="leave-reconnect";var dn;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(dn||(dn={}));class xx extends Sn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Zl.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=dn.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=ue,this.handleDataChannel=r=>S(this,[r],void 0,function(i){var A=this;let{channel:s}=i;return function*(){if(s){if(s.label===T0)A.reliableDCSub=s;else if(s.label===U0)A.lossyDCSub=s;else return;A.log.debug("on data channel ".concat(s.id,", ").concat(s.label),A.logContext),s.onmessage=A.handleDataMessage}}()}),this.handleDataMessage=r=>S(this,void 0,void 0,function*(){var i,A;const s=yield this.dataProcessLock.lock();try{let o;if(r.data instanceof ArrayBuffer)o=r.data;else if(r.data instanceof Blob)o=yield r.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:r.data}));return}const a=Dt.fromBinary(new Uint8Array(o));((i=a.value)===null||i===void 0?void 0:i.case)==="speaker"?this.emit(D.ActiveSpeakersUpdate,a.value.value.speakers):(((A=a.value)===null||A===void 0?void 0:A.case)==="user"&&Rx(a,a.value.value),this.emit(D.DataPacketReceived,a))}finally{s()}}),this.handleDataError=r=>{const A=r.currentTarget.maxRetransmits===0?"lossy":"reliable";if(r instanceof ErrorEvent&&r.error){const{error:s}=r.error;this.log.error("DataChannel error on ".concat(A,": ").concat(r.message),Object.assign(Object.assign({},this.logContext),{error:s}))}else this.log.error("Unknown DataChannel error on ".concat(A),Object.assign(Object.assign({},this.logContext),{event:r}))},this.handleBufferedAmountLow=r=>{const A=r.currentTarget.maxRetransmits===0?pe.LOSSY:pe.RELIABLE;this.updateAndEmitDCBufferStatus(A)},this.handleDisconnect=(r,i)=>{if(this._isClosed)return;this.log.warn("".concat(r," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const A=a=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(a,"ms. giving up"),this.logContext),this.emit(D.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});if(o===null){A(s);return}r===id&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=wt.setTimeout(()=>this.attemptReconnect(i).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((r,i)=>{this.pcState===dn.Connected&&r();const A=()=>{this.off(D.Disconnected,s),r()},s=()=>{this.off(D.Restarted,A),i()};this.once(D.Restarted,A),this.once(D.Disconnected,s)}),this.updateAndEmitDCBufferStatus=r=>{const i=this.isBufferStatusLow(r);typeof i<"u"&&i!==this.dcBufferStatus.get(r)&&(this.dcBufferStatus.set(r,i),this.emit(D.DCBufferStatusChanged,i,r))},this.isBufferStatusLow=r=>{const i=this.dataChannelForKind(r);if(i)return i.bufferedAmount<=i.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Oe.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ki.RR_SIGNAL_DISCONNECTED))},this.log=Ln((t=e.loggerName)!==null&&t!==void 0?t:cn.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new jl(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Mt,this.dataProcessLock=new Mt,this.dcBufferStatus=new Map([[pe.LOSSY,!0],[pe.RELIABLE,!0]]),this.client.onParticipantUpdate=r=>this.emit(D.ParticipantUpdate,r),this.client.onConnectionQuality=r=>this.emit(D.ConnectionQualityUpdate,r),this.client.onRoomUpdate=r=>this.emit(D.RoomUpdate,r),this.client.onSubscriptionError=r=>this.emit(D.SubscriptionError,r),this.client.onSubscriptionPermissionUpdate=r=>this.emit(D.SubscriptionPermissionUpdate,r),this.client.onSpeakersChanged=r=>this.emit(D.SpeakersChanged,r),this.client.onStreamStateUpdate=r=>this.emit(D.StreamStateChanged,r),this.client.onRequestResponse=r=>this.emit(D.SignalRequestResponse,r)}get logContext(){var e,t,r,i,A,s,o,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(i=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.room)===null||i===void 0?void 0:i.sid,participant:(s=(A=this.latestJoinResponse)===null||A===void 0?void 0:A.participant)===null||s===void 0?void 0:s.identity,pID:(a=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||a===void 0?void 0:a.sid}}join(e,t,r,i){return S(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=r,this.maxJoinAttempts=r.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const A=yield this.client.join(e,t,r,i);return this._isClosed=!1,this.latestJoinResponse=A,this.subscriberPrimary=A.subscriberPrimary,this.pcManager||(yield this.configure(A)),(!this.subscriberPrimary||A.fastPublish)&&this.negotiate(),this.clientConfiguration=A.clientConfiguration,setTimeout(()=>{this.emit(D.SignalConnected)},10),A}catch(A){if(A instanceof Fe&&A.reason===de.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,r,i);throw A}})}close(){return S(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(D.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return S(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=r=>{r&&(r.close(),r.onbufferedamountlow=null,r.onclose=null,r.onclosing=null,r.onerror=null,r.onmessage=null,r.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0})}cleanupClient(){return S(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Dn("a track with the same ID has already been published");return new Promise((t,r)=>{const i=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],r(new Fe("publication of local track timed out, no response from server",de.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:A=>{clearTimeout(i),t(A)},reject:()=>{clearTimeout(i),r(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return S(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return S(this,void 0,void 0,function*(){var t,r;if(this.pcManager&&this.pcManager.currentState!==Ye.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const i=this.makeRTCConfiguration(e);this.pcManager=new mx(i,e.subscriberPrimary,this.loggerOptions),this.emit(D.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(A,s)=>{this.client.sendIceCandidate(A,s)},this.pcManager.onPublisherOffer=A=>{this.client.sendOffer(A)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(A,s,o)=>S(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(A),this.logContext),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),A===Ye.CONNECTED){const u=this.pcState===dn.New;this.pcState=dn.Connected,u&&this.emit(D.Connected,e)}else A===Ye.FAILED&&this.pcState===dn.Connected&&(this.pcState=dn.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?ki.RR_SUBSCRIBER_FAILED:ki.RR_PUBLISHER_FAILED));const a=this.client.isDisconnected||this.client.currentState===Oe.RECONNECTING,c=[Ye.FAILED,Ye.CLOSING,Ye.CLOSED].includes(A);a&&c&&!this._isClosed&&this.emit(D.Offline)}),this.pcManager.onTrack=A=>{this.emit(D.MediaTrackAdded,A.track,A.streams[0],A.receiver)},Qx((r=e.serverInfo)===null||r===void 0?void 0:r.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>S(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>S(this,void 0,void 0,function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:r}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],r(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(D.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(D.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(D.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(D.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.emit(D.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",ki.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Ti.DISCONNECT:this.emit(D.Disconnected,e==null?void 0:e.reason),this.close();break;case Ti.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(id);break;case Ti.RESUME:this.handleDisconnect(id)}}}makeRTCConfiguration(e){var t;const r=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),r.encodedInsertableStreams=!0),e.iceServers&&!r.iceServers){const i=[];e.iceServers.forEach(A=>{const s={urls:A.urls};A.username&&(s.username=A.username),A.credential&&(s.credential=A.credential),i.push(s)}),r.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===LA.ENABLED&&(r.iceTransportPolicy="relay"),r.sdpSemantics="unified-plan",r.continualGatheringPolicy="gather_continually",r}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(U0,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(T0,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,r){return S(this,void 0,void 0,function*(){if(Fl())return yield this.createTransceiverRTCRtpSender(e,t,r);if(xl())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new lt("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,r,i){return S(this,void 0,void 0,function*(){if(Fl())return this.createSimulcastTransceiverSender(e,t,r,i);if(xl())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new lt("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,r){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new lt("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),Pi(e)&&(e.codec=t.videoCodec);const A={direction:"sendonly",streams:i};return r&&(A.sendEncodings=r),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,A)).sender})}createSimulcastTransceiverSender(e,t,r,i){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new lt("publisher is closed");const A={direction:"sendonly"};i&&(A.sendEncodings=i);const s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,A);if(r.videoCodec)return e.setSimulcastTrackSender(r.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new lt("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return S(this,void 0,void 0,function*(){var t,r,i;if(!this._isClosed){if(this.attemptingReconnect){ue.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===LA.DISABLED||((i=(r=this.pcManager)===null||r===void 0?void 0:r.currentState)!==null&&i!==void 0?i:Ye.NEW)===Ye.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(A){this.reconnectAttempts+=1;let s=!0;A instanceof lt?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:A})),s=!1):A instanceof Mi||(this.fullReconnectOnNext=!0),s?this.handleDisconnect("reconnect",ki.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(D.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return S(this,void 0,void 0,function*(){var t,r,i;try{if(!this.url||!this.token)throw new lt("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(D.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let A;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Mi;A=yield this.join(e??this.url,this.token,this.signalOpts)}catch(s){throw s instanceof Fe&&s.reason===de.NotAllowed?new lt("could not reconnect, token might be expired"):new Mi}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(D.SignalRestarted,A),yield this.waitForPCReconnected(),this.client.currentState!==Oe.CONNECTED)throw new Mi("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(D.Restarted)}catch(A){const s=yield(r=this.regionUrlProvider)===null||r===void 0?void 0:r.getNextBestRegionUrl();if(s){yield this.restartConnection(s);return}else throw(i=this.regionUrlProvider)===null||i===void 0||i.resetAttempts(),A}})}resumeConnection(e){return S(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new lt("could not reconnect, url or token not saved");if(!this.pcManager)throw new lt("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(D.Resuming);let r;try{this.setupSignalClientCallbacks(),r=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(i){let A="";throw i instanceof Error&&(A=i.message,this.log.error(i.message,Object.assign(Object.assign({},this.logContext),{error:i}))),i instanceof Fe&&i.reason===de.NotAllowed?new lt("could not reconnect, token might be expired"):i instanceof Fe&&i.reason===de.LeaveRequest?i:new Mi(A)}if(this.emit(D.SignalResumed),r){const i=this.makeRTCConfiguration(r);this.pcManager.updateConfiguration(i)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Oe.CONNECTED)throw new Mi("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),this.emit(D.Resumed)})}waitForPCInitialConnection(e,t){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new lt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return S(this,void 0,void 0,function*(){this.pcState=dn.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Nt(Fx),!this.pcManager)throw new lt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=dn.Connected}catch(e){throw this.pcState=dn.Disconnected,new Fe("could not establish PC connection, ".concat(e.message),de.InternalError)}})}publishRpcResponse(e,t,r,i){return S(this,void 0,void 0,function*(){const A=new Dt({destinationIdentities:[e],kind:pe.RELIABLE,value:{case:"rpcResponse",value:new Pm({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:r??""}})}});yield this.sendDataPacket(A,pe.RELIABLE)})}publishRpcAck(e,t){return S(this,void 0,void 0,function*(){const r=new Dt({destinationIdentities:[e],kind:pe.RELIABLE,value:{case:"rpcAck",value:new Rm({requestId:t})}});yield this.sendDataPacket(r,pe.RELIABLE)})}sendDataPacket(e,t){return S(this,void 0,void 0,function*(){const r=e.toBinary();yield this.ensurePublisherConnected(t);const i=this.dataChannelForKind(t);i&&i.send(r),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,r)=>S(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const i=()=>r("Engine closed");for(this.once(D.Closing,i);!this.dcBufferStatus.get(e);)yield Nt(10);this.off(D.Closing,i),t()}}))}ensureDataTransportConnected(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var A;if(!r.pcManager)throw new lt("PC manager is closed");const s=i?r.pcManager.subscriber:r.pcManager.publisher,o=i?"Subscriber":"Publisher";if(!s)throw new Fe("".concat(o," connection not set"),de.InternalError);let a=!1;!i&&!r.dataChannelForKind(t,i)&&(r.createDataChannels(),a=!0),!a&&!i&&!r.pcManager.publisher.isICEConnected&&r.pcManager.publisher.getICEConnectionState()!=="checking"&&(a=!0),a&&r.negotiate();const c=r.dataChannelForKind(t,i);if((c==null?void 0:c.readyState)==="open")return;const u=new Date().getTime()+r.peerConnectionTimeout;for(;new Date().getTime()<u;){if(s.isICEConnected&&((A=r.dataChannelForKind(t,i))===null||A===void 0?void 0:A.readyState)==="open")return;yield Nt(50)}throw new Fe("could not establish ".concat(o," connection, state: ").concat(s.getICEConnectionState()),de.InternalError)}()})}ensurePublisherConnected(e){return S(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Ye.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return S(this,void 0,void 0,function*(){return new Promise((e,t)=>S(this,void 0,void 0,function*(){if(!this.pcManager){t(new _l("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const r=new AbortController,i=()=>{r.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(D.Closing,i),this.pcManager.publisher.once(Oi.RTPVideoPayloadTypes,A=>{const s=new Map;A.forEach(o=>{const a=o.codec.toLowerCase();KF(a)&&s.set(o.payload,a)}),this.emit(D.RTPVideoMapUpdate,s)});try{yield this.pcManager.negotiate(r),e()}catch(A){A instanceof _l&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ki.RR_UNKNOWN),t(A)}finally{this.off(D.Closing,i)}}))})}dataChannelForKind(e,t){if(t){if(e===pe.LOSSY)return this.lossyDCSub;if(e===pe.RELIABLE)return this.reliableDCSub}else{if(e===pe.LOSSY)return this.lossyDC;if(e===pe.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var r,i;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const A=this.pcManager.subscriber.getLocalDescription(),s=this.pcManager.subscriber.getRemoteDescription(),o=(i=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&i!==void 0?i:!0,a=new Array,c=new Array;e.forEach(u=>{u.isDesired!==o&&a.push(u.trackSid),u.isEnabled||c.push(u.trackSid)}),this.client.sendSyncState(new $m({answer:A?sa({sdp:A.sdp,type:A.type}):void 0,offer:s?sa({sdp:s.sdp,type:s.type}):void 0,subscription:new Go({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:YF(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(r,i)=>{(r==null?void 0:r.id)!==void 0&&r.id!==null&&e.push(new ev({label:r.label,id:r.id,target:i}))};return t(this.dataChannelForKind(pe.LOSSY),an.PUBLISHER),t(this.dataChannelForKind(pe.RELIABLE),an.PUBLISHER),t(this.dataChannelForKind(pe.LOSSY,!0),an.SUBSCRIBER),t(this.dataChannelForKind(pe.RELIABLE,!0),an.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&wt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ht()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Ht()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Mi extends Error{}function Qx(n){return n!==void 0&&n>13}function Rx(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const r=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=r,e.destinationIdentities=r}class Ad{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Rl(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return S(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter(r=>!this.attemptedRegions.find(i=>i.url===r.url));if(t.length>0){const r=t[0];return this.attemptedRegions.push(r),ue.debug("next region: ".concat(r.region)),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return S(this,void 0,void 0,function*(){const t=yield fetch("".concat(Px(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const r=yield t.json();return this.lastUpdateAt=Date.now(),r}else throw new Fe("Could not fetch region settings: ".concat(t.statusText),t.status===401?de.NotAllowed:de.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function Px(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class I0{get info(){return this._info}constructor(e,t,r){this.reader=t,this.totalByteSize=r,this._info=e,this.bytesReceived=0}}class Ox extends I0{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>S(this,void 0,void 0,function*(){try{const{done:t,value:r}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(r),{done:!1,value:r.content})}catch{return{done:!0,value:void 0}}}),return(){return S(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return S(this,void 0,void 0,function*(){var e,t,r,i;let A=new Set;try{for(var s=!0,o=ur(this),a;a=yield o.next(),e=a.done,!e;s=!0){i=a.value,s=!1;const c=i;A.add(c)}}catch(c){t={error:c}}finally{try{!s&&!e&&(r=o.return)&&(yield r.call(o))}finally{if(t)throw t.error}}return Array.from(A)})}}class Mx extends I0{constructor(e,t,r){super(e,t,r),this.receivedChunks=new Map}handleChunkReceived(e){var t;const r=ia(e.chunkIndex),i=this.receivedChunks.get(r);if(i&&i.version>e.version)return;this.receivedChunks.set(r,e),this.bytesReceived+=e.content.byteLength;const A=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,A)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>S(this,void 0,void 0,function*(){try{const{done:r,value:i}=yield e.read();return r?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:t.decode(i.content)})}catch{return{done:!0,value:void 0}}}),return(){return S(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return S(this,void 0,void 0,function*(){var e,t,r,i;let A="";try{for(var s=!0,o=ur(this),a;a=yield o.next(),e=a.done,!e;s=!0)i=a.value,s=!1,A+=i}catch(c){t={error:c}}finally{try{!s&&!e&&(r=o.return)&&(yield r.call(o))}finally{if(t)throw t.error}}return A})}}class F0{constructor(e,t,r){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=r,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return S(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class Lx extends F0{}class Dx extends F0{}class x0 extends R{constructor(e,t,r,i,A){super(e,r,A),this.sid=t,this.receiver=i}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?L.Muted:L.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=r=>{r.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(L.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return S(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),ed)),ZF()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const r=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(r){const{timestamp:i,rtpTimestamp:A}=r;A&&this.rtpTimestamp!==A&&(this.emit(L.TimeSyncUpdate,{timestamp:i,rtpTimestamp:A}),this.rtpTimestamp=A)}};e()}}class Nx extends x0{constructor(e,t,r,i,A,s){super(e,t,R.Kind.Audio,r,s),this.monitorReceiver=()=>S(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=oa(o,this.prevStats)),this.prevStats=o}),this.audioContext=i,this.webAudioPluginNodes=[],A&&(this.sinkId=A.deviceId)}setVolume(e){var t;for(const r of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):r.volume=e;kn()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(kn())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return S(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Ql(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Ql(e)&&e.setSinkId(this.sinkId).catch(r=>{this.log.error("Failed to set sink id on remote audio track",r,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let r=this.sourceNode;this.webAudioPluginNodes.forEach(i=>{r.connect(i),r=i}),this.gainNode=e.createGain(),r.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(L.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(i=>{this.emit(L.AudioPlaybackFailed,i)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return S(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(r=>{r.type==="inbound-rtp"&&(t={type:"audio",streamId:r.id,timestamp:r.timestamp,jitter:r.jitter,bytesReceived:r.bytesReceived,concealedSamples:r.concealedSamples,concealmentEvents:r.concealmentEvents,silentConcealedSamples:r.silentConcealedSamples,silentConcealmentEvents:r.silentConcealmentEvents,totalAudioEnergy:r.totalAudioEnergy,totalSamplesDuration:r.totalSamplesDuration})}),t})}}const sd=100;class Hx extends x0{constructor(e,t,r,i,A){super(e,t,R.Kind.Video,r,A),this.elementInfos=[],this.monitorReceiver=()=>S(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const s=yield this.getReceiverStats();s&&this.prevStats&&this.receiver&&(this._currentBitrate=oa(s,this.prevStats)),this.prevStats=s}),this.debouncedHandleResize=Xl(()=>{this.updateDimensions()},sd),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?xi(this._mediaStreamTrack,t):Fi(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new Kx(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(r=>r===e);for(const r of t)r.stopObserving();this.elementInfos=this.elementInfos.filter(r=>r!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const r of t)this.stopObservingElement(r);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return S(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,r="",i=new Map;return e.forEach(A=>{A.type==="inbound-rtp"?(r=A.codecId,t={type:"video",streamId:A.id,framesDecoded:A.framesDecoded,framesDropped:A.framesDropped,framesReceived:A.framesReceived,packetsReceived:A.packetsReceived,packetsLost:A.packetsLost,frameWidth:A.frameWidth,frameHeight:A.frameHeight,pliCount:A.pliCount,firCount:A.firCount,nackCount:A.nackCount,jitter:A.jitter,timestamp:A.timestamp,bytesReceived:A.bytesReceived,decoderImplementation:A.decoderImplementation}):A.type==="codec"&&i.set(A.id,A)}),t&&r!==""&&i.get(r)&&(t.mimeType=i.get(r).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(r=>r.element===e);for(const r of t)this.stopObservingElementInfo(r)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const r=this.elementInfos.reduce((o,a)=>Math.max(o,a.visibilityChangedAt||0),0),i=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,A=this.elementInfos.some(o=>o.pictureInPicture),s=this.elementInfos.some(o=>o.visible)&&!i||A;if(this.lastVisible!==s){if(!s&&Date.now()-r<sd){wt.setTimeout(()=>{this.updateVisibility()},sd);return}this.lastVisible=s,this.emit(L.VisibilityChanged,s,this)}}updateDimensions(){var e,t;let r=0,i=0;const A=this.getPixelDensity();for(const s of this.elementInfos){const o=s.width()*A,a=s.height()*A;o+a>r+i&&(r=o,i=a)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===r&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===i||(this.lastDimensions={width:r,height:i},this.emit(L.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?$v():t||($v()>2?2:1)}}class Kx{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=r=>{var i;const{target:A,isIntersecting:s}=r;A===this.element&&(this.isIntersecting=s,this.isPiP=jA(this.element),this.visibilityChangedAt=Date.now(),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this))},this.onEnterPiP=()=>{var r,i,A;(i=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP),this.isPiP=jA(this.element),(A=this.handleVisibilityChanged)===null||A===void 0||A.call(this)},this.onLeavePiP=()=>{var r;this.isPiP=jA(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.element=e,this.isIntersecting=t??od(e),this.isPiP=Ht()&&jA(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,r;this.isIntersecting=od(this.element),this.isPiP=jA(this.element),this.element.handleResize=()=>{var i;(i=this.handleResize)===null||i===void 0||i.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,t0().observe(this.element),e0().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(r=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,r,i,A;(e=t0())===null||e===void 0||e.unobserve(this.element),(t=e0())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(r=window.documentPictureInPicture)===null||r===void 0||r.removeEventListener("enter",this.onEnterPiP),(A=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||A===void 0||A.removeEventListener("pagehide",this.onLeavePiP)}}function jA(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?od(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function od(n,e){const t=e||window;let r=n.offsetTop,i=n.offsetLeft;const A=n.offsetWidth,s=n.offsetHeight,{hidden:o}=n,{display:a}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,r+=n.offsetTop,i+=n.offsetLeft;return r<t.pageYOffset+t.innerHeight&&i<t.pageXOffset+t.innerWidth&&r+s>t.pageYOffset&&i+A>t.pageXOffset&&!o&&a!=="none"}class Hn extends Sn.EventEmitter{constructor(e,t,r,i){var A;super(),this.metadataMuted=!1,this.encryption=Wt.NONE,this.log=ue,this.handleMuted=()=>{this.emit(L.Muted)},this.handleUnmuted=()=>{this.emit(L.Unmuted)},this.log=Ln((A=i==null?void 0:i.loggerName)!==null&&A!==void 0?A:cn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=r,this.source=R.Source.Unknown}setTrack(e){this.track&&(this.track.off(L.Muted,this.handleMuted),this.track.off(L.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(L.Muted,this.handleMuted),e.on(L.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),_e(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Wt.NONE}get audioTrack(){if(Nn(this.track))return this.track}get videoTrack(){if(Pi(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=R.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===R.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(n.PermissionStatus||(n.PermissionStatus={}))})(Hn||(Hn={}));class ad extends Hn{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,r,i){super(e,t.sid,t.name,i),this.track=void 0,this.handleTrackEnded=()=>{this.emit(L.Ended)},this.updateInfo(t),this.setTrack(r)}setTrack(e){this.track&&this.track.off(L.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(L.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return S(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return S(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return S(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return S(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Nn(this.track)){const t=this.track.getSourceTrackSettings(),r=new Set;return t.autoGainControl&&r.add(on.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&r.add(on.TF_ECHO_CANCELLATION),t.noiseSuppression&&r.add(on.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&r.add(on.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||r.add(on.TF_NO_DTX),this.track.enhancedNoiseCancellation&&r.add(on.TF_ENHANCED_NOISE_CANCELLATION),Array.from(r.values())}else return[]}}function la(n,e){return S(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:r,videoProcessor:i,optionsWithoutProcessor:A}=a0(n);let s=A.audio,o=A.video;if(r&&typeof A.audio=="object"&&(A.audio.processor=r),i&&typeof A.video=="object"&&(A.video.processor=i),n.audio&&typeof A.audio=="object"&&typeof A.audio.deviceId=="string"){const l=A.audio.deviceId;A.audio.deviceId={exact:l},t=!0,s=Object.assign(Object.assign({},A.audio),{deviceId:{ideal:l}})}if(A.video&&typeof A.video=="object"&&typeof A.video.deviceId=="string"){const l=A.video.deviceId;A.video.deviceId={exact:l},t=!0,o=Object.assign(Object.assign({},A.video),{deviceId:{ideal:l}})}(A.audio===!0||typeof A.audio=="object"&&!A.audio.deviceId)&&(A.audio={deviceId:"default"}),A.video===!0?A.video={deviceId:"default"}:typeof A.video=="object"&&!A.video.deviceId&&(A.video.deviceId="default");const a=i0(A,v0,y0),c=Vl(a),u=navigator.mediaDevices.getUserMedia(c);A.audio&&(ft.userMediaPromiseMap.set("audioinput",u),u.catch(()=>ft.userMediaPromiseMap.delete("audioinput"))),A.video&&(ft.userMediaPromiseMap.set("videoinput",u),u.catch(()=>ft.userMediaPromiseMap.delete("videoinput")));try{const l=yield u;return yield Promise.all(l.getTracks().map(d=>S(this,void 0,void 0,function*(){const h=d.kind==="audio";let f=h?a.audio:a.video;(typeof f=="boolean"||!f)&&(f={});let p;const g=h?c.audio:c.video;typeof g!="boolean"&&(p=g);const v=d.getSettings().deviceId;p!=null&&p.deviceId&&fr(p.deviceId)!==v?p.deviceId=v:p||(p={deviceId:v});const y=yx(d,p,e);return y.kind===R.Kind.Video?y.source=R.Source.Camera:y.kind===R.Kind.Audio&&(y.source=R.Source.Microphone),y.mediaStream=l,Nn(y)&&r?yield y.setProcessor(r):Pi(y)&&i&&(yield y.setProcessor(i)),y})))}catch(l){if(!t)throw l;return la(Object.assign(Object.assign({},n),{audio:s,video:o}),e)}})}function Vx(n){return S(this,void 0,void 0,function*(){return(yield la({audio:!1,video:n??!0}))[0]})}function Gx(n){return S(this,void 0,void 0,function*(){return(yield la({audio:n??!0,video:!1}))[0]})}var vr;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(vr||(vr={}));function jx(n){switch(n){case MA.EXCELLENT:return vr.Excellent;case MA.GOOD:return vr.Good;case MA.POOR:return vr.Poor;case MA.LOST:return vr.Lost;default:return vr.Unknown}}class Q0 extends Sn.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Vo.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Ei.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,r,i,A,s){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Vo.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=vr.Unknown,this.log=ue,this.log=Ln((a=s==null?void 0:s.loggerName)!==null&&a!==void 0?a:cn.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=r,this.metadata=i,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=A??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Ll,this.once(K.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(R.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(R.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(R.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Ei.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Ei.ACTIVE&&this.emit(K.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,r=this.metadata;this.metadata=e,t&&this.emit(K.ParticipantMetadataChanged,r)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(K.ParticipantNameChanged,e)}_setAttributes(e){const t=$F(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(K.AttributesChanged,t)}setPermissions(e){var t,r,i,A,s,o;const a=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((r=this.permissions)===null||r===void 0?void 0:r.canSubscribe)||e.canPublishData!==((i=this.permissions)===null||i===void 0?void 0:i.canPublishData)||e.hidden!==((A=this.permissions)===null||A===void 0?void 0:A.hidden)||e.recorder!==((s=this.permissions)===null||s===void 0?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,l)=>{var d;return u!==((d=this.permissions)===null||d===void 0?void 0:d.canPublishSources[l])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(K.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(K.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=jx(e),t!==this._connectionQuality&&this.emit(K.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Nn(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(L.Muted,()=>{this.emit(K.TrackMuted,e)}),e.on(L.Unmuted,()=>{this.emit(K.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case R.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case R.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Wx(n){var e,t,r;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Ym({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(r=n.allowAll)!==null&&r!==void 0?r:!1,trackSids:n.allowedTrackSids||[]})}const R0=15e3;class qx extends Q0{constructor(e,t,r,i,A){super(e,t,void 0,void 0,void 0,{loggerName:i.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Wt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Ll)},this.handleReconnected=()=>{var s,o;(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.resolve)===null||o===void 0||o.call(s),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var s,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(a=>this.log.warn(a.message,this.logContext)),(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.reject)===null||o===void 0||o.call(s,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=s=>{const{requestId:o,reason:a,message:c}=s,u=this.pendingSignalRequests.get(o);u&&(a!==dl.OK&&u.reject(new Wv(c,a)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=s=>{switch(s.value.case){case"rpcResponse":let o=s.value.value,a=null,c=null;o.value.case==="payload"?a=o.value.value:o.value.case==="error"&&(c=Ze.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,a,c);break;case"rpcAck":let u=s.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(s=>Wx(s)))},this.onTrackUnmuted=s=>{this.onTrackMuted(s,s.isUpstreamPaused)},this.onTrackMuted=(s,o)=>{if(o===void 0&&(o=!0),!s.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),_e(s)));return}this.engine.updateMuteStatus(s.sid,o)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),_e(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),_e(s))),this.onTrackMuted(s,s.isMuted)},this.onTrackFeatureUpdate=s=>{const o=this.audioTrackPublications.get(s.sid);if(!o){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(s.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.handleSubscribedQualityUpdate=s=>S(this,void 0,void 0,function*(){var o,a,c,u,l,d;if(!(!((l=this.roomOptions)===null||l===void 0)&&l.dynacast))return;const h=this.videoTrackPublications.get(s.trackSid);if(!h){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}if(s.subscribedCodecs.length>0){if(!h.videoTrack)return;const v=yield h.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var f=!0,p=ur(v),g;g=yield p.next(),o=g.done,!o;f=!0){u=g.value,f=!1;const y=u;FF(y)&&(this.log.debug("publish ".concat(y," for ").concat(h.videoTrack.sid),Object.assign(Object.assign({},this.logContext),_e(h))),yield this.publishAdditionalCodecForTrack(h.videoTrack,y,h.options))}}catch(y){a={error:y}}finally{try{!f&&!o&&(c=p.return)&&(yield c.call(p))}finally{if(a)throw a.error}}}else s.subscribedQualities.length>0&&(yield(d=h.videoTrack)===null||d===void 0?void 0:d.setPublishingLayers(s.subscribedQualities))}),this.handleLocalTrackUnpublished=s=>{const o=this.trackPublications.get(s.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=s=>S(this,void 0,void 0,function*(){if(s.source===R.Source.ScreenShare||s.source===R.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),_e(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(Jr(s)||gr(s))try{if(Ht())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:s.source===R.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(s.source),Object.assign(Object.assign({},this.logContext),_e(s))),o.onchange=()=>{o.state!=="denied"&&(s.isMuted||s.restartTrack(),o.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}s.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),_e(s))),Jr(s)?yield s.restartTrack({deviceId:"default"}):yield s.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),_e(s))),yield s.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=r,this.roomOptions=i,this.setupEngine(r),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=A}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Wt.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(D.RemoteMute,(t,r)=>{const i=this.trackPublications.get(t);!i||!i.track||(r?i.mute():i.unmute())}),this.engine.on(D.Connected,this.handleReconnected).on(D.SignalRestarted,this.handleReconnected).on(D.SignalResumed,this.handleReconnected).on(D.Restarting,this.handleReconnecting).on(D.Resuming,this.handleReconnecting).on(D.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(D.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(D.Disconnected,this.handleDisconnected).on(D.SignalRequestResponse,this.handleSignalRequestResponse).on(D.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return S(this,arguments,void 0,function(t){var r=this;let{metadata:i,name:A,attributes:s}=t;return function*(){return new Promise((o,a)=>S(r,void 0,void 0,function*(){var c,u;try{let l=!1;const d=yield this.engine.client.sendUpdateLocalMetadata((c=i??this.metadata)!==null&&c!==void 0?c:"",(u=A??this.name)!==null&&u!==void 0?u:"",s),h=performance.now();for(this.pendingSignalRequests.set(d,{resolve:o,reject:f=>{a(f),l=!0},values:{name:A,metadata:i,attributes:s}});performance.now()-h<5e3&&!l;){if((!A||this.name===A)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every(f=>{let[p,g]=f;return this.attributes[p]===g||g===""&&!this.attributes[p]}))){this.pendingSignalRequests.delete(d),o();return}yield Nt(50)}a(new Wv("Request to update local metadata timed out","TimeoutError"))}catch(l){l instanceof Error&&a(l)}}))}()})}setCameraEnabled(e,t,r){return this.setTrackEnabled(R.Source.Camera,e,t,r)}setMicrophoneEnabled(e,t,r){return this.setTrackEnabled(R.Source.Microphone,e,t,r)}setScreenShareEnabled(e,t,r){return this.setTrackEnabled(R.Source.ScreenShare,e,t,r)}setPermissions(e){const t=this.permissions,r=super.setPermissions(e);return r&&t&&this.emit(K.ParticipantPermissionsChanged,t),r}setE2EEEnabled(e){return S(this,void 0,void 0,function*(){this.encryptionType=e?Wt.GCM:Wt.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,r,i){return S(this,void 0,void 0,function*(){var A,s;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let a;if(this.pendingPublishing.has(e)){const c=yield this.waitForPendingPublicationOfSource(e);return c||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield c==null?void 0:c.unmute(),c}this.pendingPublishing.add(e);try{switch(e){case R.Source.Camera:a=yield this.createTracks({video:(A=r)!==null&&A!==void 0?A:!0});break;case R.Source.Microphone:a=yield this.createTracks({audio:(s=r)!==null&&s!==void 0?s:!0});break;case R.Source.ScreenShare:a=yield this.createScreenTracks(Object.assign({},r));break;default:throw new Dn(e)}}catch(c){throw a==null||a.forEach(u=>{u.stop()}),c instanceof Error&&this.emit(K.MediaDevicesError,c),this.pendingPublishing.delete(e),c}try{const c=[];for(const l of a)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),_e(l))),c.push(this.publishTrack(l,i));[o]=yield Promise.all(c)}catch(c){throw a==null||a.forEach(u=>{u.stop()}),c}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===R.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const a=this.getTrackPublication(R.Source.ScreenShareAudio);a&&a.track&&this.unpublishTrack(a.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return S(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(R.Source.Camera)||this.pendingPublishing.has(R.Source.Microphone))){this.pendingPublishing.add(R.Source.Camera),this.pendingPublishing.add(R.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(R.Source.Camera),this.pendingPublishing.delete(R.Source.Microphone)}}})}createTracks(e){return S(this,void 0,void 0,function*(){var t,r;e??(e={});const i=i0(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(r=this.roomOptions)===null||r===void 0?void 0:r.videoCaptureDefaults);try{return(yield la(i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Nn(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=R.Source.Microphone,this.emit(K.AudioStreamAcquired)),Pi(o)&&(this.cameraError=void 0,o.source=R.Source.Camera),o))}catch(A){throw A instanceof Error&&(e.audio&&(this.microphoneError=A),e.video&&(this.cameraError=A)),A}})}createScreenTracks(e){return S(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Cl("getDisplayMedia not supported");e.resolution===void 0&&!MF()&&(e.resolution=Il.h1080fps30.resolution);const t=XF(e),r=yield navigator.mediaDevices.getDisplayMedia(t),i=r.getVideoTracks();if(i.length===0)throw new Dn("no video track found");const A=new ua(i[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});A.source=R.Source.ScreenShare,e.contentHint&&(A.mediaStreamTrack.contentHint=e.contentHint);const s=[A];if(r.getAudioTracks().length>0){this.emit(K.AudioStreamAcquired);const o=new aa(r.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=R.Source.ScreenShareAudio,s.push(o)}return s})}publishTrack(e,t){return S(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,a,c,u;Jr(r)&&r.setAudioContext(A.audioContext),yield(o=A.reconnectFuture)===null||o===void 0?void 0:o.promise,A.republishPromise&&!s&&(yield A.republishPromise),Ri(r)&&A.pendingPublishPromises.has(r)&&(yield A.pendingPublishPromises.get(r));let l;if(r instanceof MediaStreamTrack)l=r.getConstraints();else{l=r.constraints;let v;switch(r.source){case R.Source.Microphone:v="audioinput";break;case R.Source.Camera:v="videoinput"}v&&A.activeDeviceMap.has(v)&&(l=Object.assign(Object.assign({},l),{deviceId:A.activeDeviceMap.get(v)}))}if(r instanceof MediaStreamTrack)switch(r.kind){case"audio":r=new aa(r,l,!0,A.audioContext,{loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});break;case"video":r=new ua(r,l,!0,{loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});break;default:throw new Dn("unsupported MediaStreamTrack kind ".concat(r.kind))}else r.updateLoggerOptions({loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});let d;if(A.trackPublications.forEach(v=>{v.track&&v.track===r&&(d=v)}),d)return A.log.warn("track has already been published, skipping",Object.assign(Object.assign({},A.logContext),_e(d))),d;const h="channelCount"in r.mediaStreamTrack.getSettings()&&r.mediaStreamTrack.getSettings().channelCount===2||r.mediaStreamTrack.getConstraints().channelCount===2,f=(a=i==null?void 0:i.forceStereo)!==null&&a!==void 0?a:h;f&&(i||(i={}),i.dtx===void 0&&A.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},A.logContext),_e(r))),i.red===void 0&&A.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(c=i.dtx)!==null&&c!==void 0||(i.dtx=!1),(u=i.red)!==null&&u!==void 0||(i.red=!1));const p=Object.assign(Object.assign({},A.roomOptions.publishDefaults),i);!LF()&&A.roomOptions.e2ee&&(A.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},A.logContext)),p.simulcast=!1),p.source&&(r.source=p.source);const g=new Promise((v,y)=>S(A,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Oe.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:_e(r)}));const B=()=>S(this,void 0,void 0,function*(){try{const b=yield this.publish(r,p,f);v(b)}catch(b){y(b)}});setTimeout(()=>{this.engine.off(D.SignalConnected,B),y(new Sl("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(D.SignalConnected,B),this.engine.on(D.Closing,()=>{this.engine.off(D.SignalConnected,B),y(new Sl("publishing rejected as engine closed",499))})}else try{const B=yield this.publish(r,p,f);v(B)}catch(B){y(B)}}catch(B){y(B)}}));A.pendingPublishPromises.set(r,g);try{return yield g}catch(v){throw v}finally{A.pendingPublishPromises.delete(r)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),_e(e))),!1;const{canPublish:t,canPublishSources:r}=this.permissions;return t&&(r.length===0||r.map(i=>ex(i)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),_e(e))),!1)}publish(e,t,r){return S(this,void 0,void 0,function*(){var i,A,s,o,a,c,u,l,d,h;if(!this.hasPermissionsToPublish(e))throw new Sl("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(w=>Ri(e)&&w.source===e.source)&&e.source!==R.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),_e(e))),t.stopMicTrackOnMute&&Nn(e)&&(e.stopOnMute=!0),e.source===R.Source.ScreenShare&&Qi()&&(t.simulcast=!1),t.videoCodec==="av1"&&!RF()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!PF()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Yl),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(w=>t.videoCodec===Aa(w.mime))||(t.videoCodec=Aa(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(L.Muted,this.onTrackMuted),e.on(L.Unmuted,this.onTrackUnmuted),e.on(L.Ended,this.handleTrackEnded),e.on(L.UpstreamPaused,this.onTrackUpstreamPaused),e.on(L.UpstreamResumed,this.onTrackUpstreamResumed),e.on(L.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const g=new ol({cid:e.mediaStreamTrack.id,name:t.name,type:R.kindToProto(e.kind),muted:e.isMuted,source:R.sourceToProto(e.source),disableDtx:!(!((i=t.dtx)!==null&&i!==void 0)||i),encryption:this.encryptionType,stereo:r,disableRed:this.isE2EEEnabled||!(!((A=t.red)!==null&&A!==void 0)||A),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy});let v;if(e.kind===R.Kind.Video){let w={width:0,height:0};try{w=yield e.waitForDimensions()}catch{const k=(o=(s=this.roomOptions.videoCaptureDefaults)===null||s===void 0?void 0:s.resolution)!==null&&o!==void 0?o:HA.h720.resolution;w={width:k.width,height:k.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),_e(e)),{dims:w}))}g.width=w.width,g.height=w.height,gr(e)&&(KA(p)&&(e.source===R.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),_e(e))))),t.scalabilityMode=(a=t.scalabilityMode)!==null&&a!==void 0?a:"L3T3_KEY"),g.simulcastCodecs=[new sl({codec:p,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Yl}),t.backupCodec&&p!==t.backupCodec.codec&&g.encryption===Wt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),g.simulcastCodecs.push(new sl({codec:t.backupCodec.codec,cid:""})))),v=nd(e.source===R.Source.ScreenShare,g.width,g.height,t),g.layers=E0(g.width,g.height,v,KA(t.videoCodec))}else e.kind===R.Kind.Audio&&(v=[{maxBitrate:(c=t.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(l=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&l!==void 0?l:"high",networkPriority:(h=(d=t.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&h!==void 0?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new lt("cannot publish track when not connected");const y=()=>S(this,void 0,void 0,function*(){var w,_,k;if(!this.engine.pcManager)throw new lt("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,v),gr(e)&&((w=t.degradationPreference)!==null&&w!==void 0||(t.degradationPreference=Tx(e)),e.setDegradationPreference(t.degradationPreference)),v)if(Qi()&&e.kind===R.Kind.Audio){let T;for(const x of this.engine.pcManager.publisher.getTransceivers())if(x.sender===e.sender){T=x;break}T&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:T,codec:"opus",maxbr:!((_=v[0])===null||_===void 0)&&_.maxBitrate?v[0].maxBitrate/1e3:0})}else e.codec&&KA(e.codec)&&(!((k=v[0])===null||k===void 0)&&k.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:g.cid,codec:e.codec,maxbr:v[0].maxBitrate/1e3});yield this.engine.negotiate()});let B;if(this.enabledPublishVideoCodecs.length>0)B=(yield Promise.all([this.engine.addTrack(g),y()]))[0];else{B=yield this.engine.addTrack(g);let w;if(B.codecs.forEach(_=>{w===void 0&&(w=_.mimeType)}),w&&e.kind===R.Kind.Video){const _=Aa(w);_!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),_e(e)),{codec:_})),t.videoCodec=_,v=nd(e.source===R.Source.ScreenShare,g.width,g.height,t))}yield y()}const b=new ad(e.kind,B,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return b.options=t,e.sid=B.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:v,trackInfo:B})),gr(e)?e.startMonitor(this.engine.client):Jr(e)&&e.startMonitor(),this.addTrackPublication(b),this.emit(K.LocalTrackPublished,b),b})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,r){return S(this,void 0,void 0,function*(){var i;if(this.encryptionType!==Wt.NONE)return;let A;if(this.trackPublications.forEach(h=>{h.track&&h.track===e&&(A=h)}),!A)throw new Dn("track is not published");if(!gr(e))throw new Dn("track is not a video track");const s=Object.assign(Object.assign({},(i=this.roomOptions)===null||i===void 0?void 0:i.publishDefaults),r),o=kx(e,t,s);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),_e(e)));return}const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new ol({cid:a.mediaStreamTrack.id,type:R.kindToProto(e.kind),muted:e.isMuted,source:R.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=E0(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new lt("cannot publish track when not connected");const u=()=>S(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,s,o),yield this.engine.negotiate()}),d=(yield Promise.all([this.engine.addTrack(c),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))})}unpublishTrack(e,t){return S(this,void 0,void 0,function*(){var r,i;if(Ri(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),_e(e))),yield c)}const A=this.getPublicationForTrack(e),s=A?_e(A):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),s)),!A||!A.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),s));return}e=A.track,e.off(L.Muted,this.onTrackMuted),e.off(L.Unmuted,this.onTrackUnmuted),e.off(L.Ended,this.handleTrackEnded),e.off(L.UpstreamPaused,this.onTrackUpstreamPaused),e.off(L.UpstreamResumed,this.onTrackUpstreamResumed),e.off(L.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(i=(r=this.roomOptions)===null||r===void 0?void 0:r.stopLocalTrackOnUnpublish)!==null&&i!==void 0?i:!0),t?e.stop():e.stopMonitor();let o=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Ye.FAILED&&a)try{for(const c of this.engine.pcManager.publisher.getTransceivers())c.sender===a&&(c.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),gr(e)){for(const[,c]of e.simulcastCodecs)c.sender&&(this.engine.removeTrack(c.sender)&&(o=!0),c.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),s),{error:c}))}switch(this.trackPublications.delete(A.trackSid),A.kind){case R.Kind.Audio:this.audioTrackPublications.delete(A.trackSid);break;case R.Kind.Video:this.videoTrackPublications.delete(A.trackSid);break}return this.emit(K.LocalTrackUnpublished,A),A.setTrack(void 0),o&&(yield this.engine.negotiate()),A})}unpublishTracks(e){return S(this,void 0,void 0,function*(){return(yield Promise.all(e.map(r=>this.unpublishTrack(r)))).filter(r=>!!r)})}republishAllTracks(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){r.republishPromise&&(yield r.republishPromise),r.republishPromise=new Promise((A,s)=>S(r,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(a=>{a.track&&(t&&(a.options=Object.assign(Object.assign({},a.options),t)),o.push(a))}),yield Promise.all(o.map(a=>S(this,void 0,void 0,function*(){const c=a.track;yield this.unpublishTrack(c,!1),i&&!c.isMuted&&c.source!==R.Source.ScreenShare&&c.source!==R.Source.ScreenShareAudio&&(Jr(c)||gr(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:a.trackSid})),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,a.options,!0)}))),A()}catch(o){s(o)}finally{this.republishPromise=void 0}})),yield r.republishPromise}()})}publishData(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const A=i.reliable?pe.RELIABLE:pe.LOSSY,s=i.destinationIdentities,o=i.topic,a=new Dt({kind:A,value:{case:"user",value:new Fm({participantIdentity:r.identity,payload:t,destinationIdentities:s,topic:o})}});yield r.engine.sendDataPacket(a,A)}()})}publishDtmf(e,t){return S(this,void 0,void 0,function*(){const r=new Dt({kind:pe.RELIABLE,value:{case:"sipDtmf",value:new xm({code:e,digit:t})}});yield this.engine.sendDataPacket(r,pe.RELIABLE)})}sendChatMessage(e,t){return S(this,void 0,void 0,function*(){const r={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},i=new Dt({value:{case:"chatMessage",value:new el(Object.assign(Object.assign({},r),{timestamp:Ke.parse(r.timestamp)}))}});return yield this.engine.sendDataPacket(i,pe.RELIABLE),this.emit(K.ChatMessage,r),r})}editChatMessage(e,t){return S(this,void 0,void 0,function*(){const r=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),i=new Dt({value:{case:"chatMessage",value:new el(Object.assign(Object.assign({},r),{timestamp:Ke.parse(r.timestamp),editTimestamp:Ke.parse(r.editTimestamp)}))}});return yield this.engine.sendDataPacket(i,pe.RELIABLE),this.emit(K.ChatMessage,r),r})}sendText(e,t){return S(this,void 0,void 0,function*(){var r;const i=crypto.randomUUID(),s=new TextEncoder().encode(e).byteLength,o=(r=t==null?void 0:t.attachments)===null||r===void 0?void 0:r.map(()=>crypto.randomUUID()),a=new Array(o?o.length+1:1).fill(0),c=(l,d)=>{var h;a[d]=l;const f=a.reduce((p,g)=>p+g,0);(h=t==null?void 0:t.onProgress)===null||h===void 0||h.call(t,f)},u=yield this.streamText({streamId:i,totalSize:s,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:o,attributes:t==null?void 0:t.attributes});return yield u.write(e),c(1,0),yield u.close(),t!=null&&t.attachments&&o&&(yield Promise.all(t.attachments.map((l,d)=>S(this,void 0,void 0,function*(){return this._sendFile(o[d],l,{topic:t.topic,mimeType:l.type,onProgress:h=>{c(h,d+1)}})})))),u.info})}streamText(e){return S(this,void 0,void 0,function*(){var t,r;const i=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),A={id:i,mimeType:"text/plain",timestamp:Date.now(),topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},s=new nl({streamId:i,mimeType:A.mimeType,topic:A.topic,timestamp:qr(A.timestamp),totalLength:qr(e==null?void 0:e.totalSize),attributes:A.attributes,contentHeader:{case:"textHeader",value:new Vm({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?tl.UPDATE:tl.CREATE})}}),o=e==null?void 0:e.destinationIdentities,a=new Dt({destinationIdentities:o,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(a,pe.RELIABLE);let c=0;const u=this,l=new WritableStream({write(f){return S(this,void 0,void 0,function*(){for(const p of JF(f,R0)){yield u.engine.waitForBufferStatusLow(pe.RELIABLE);const g=new rl({content:p,streamId:i,chunkIndex:qr(c)}),v=new Dt({destinationIdentities:o,value:{case:"streamChunk",value:g}});yield u.engine.sendDataPacket(v,pe.RELIABLE),c+=1}})},close(){return S(this,void 0,void 0,function*(){const f=new il({streamId:i}),p=new Dt({destinationIdentities:o,value:{case:"streamTrailer",value:f}});yield u.engine.sendDataPacket(p,pe.RELIABLE)})},abort(f){console.log("Sink error:",f)}});let d=()=>S(this,void 0,void 0,function*(){yield h.close()});u.engine.once(D.Closing,d);const h=new Lx(l,A,()=>this.engine.off(D.Closing,d));return h})}sendFile(e,t){return S(this,void 0,void 0,function*(){const r=crypto.randomUUID();return yield this._sendFile(r,e,t),{id:r}})}_sendFile(e,t,r){return S(this,void 0,void 0,function*(){var i;const A=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(i=r==null?void 0:r.mimeType)!==null&&i!==void 0?i:t.type,topic:r==null?void 0:r.topic,destinationIdentities:r==null?void 0:r.destinationIdentities}),s=t.stream().getReader();for(;;){const{done:o,value:a}=yield s.read();if(o)break;yield A.write(a)}return yield A.close(),A.info})}streamBytes(e){return S(this,void 0,void 0,function*(){var t,r,i,A,s;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a=e==null?void 0:e.destinationIdentities,c={id:o,mimeType:(r=e==null?void 0:e.mimeType)!==null&&r!==void 0?r:"application/octet-stream",topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(A=e==null?void 0:e.name)!==null&&A!==void 0?A:"unknown"},u=new nl({totalLength:qr((s=c.size)!==null&&s!==void 0?s:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:qr(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Gm({name:c.name})}}),l=new Dt({destinationIdentities:a,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(l,pe.RELIABLE);let d=0;const h=new Mt,f=this.engine,p=this.log,g=new WritableStream({write(y){return S(this,void 0,void 0,function*(){const B=yield h.lock();let b=0;try{for(;b<y.byteLength;){const w=y.slice(b,b+R0);yield f.waitForBufferStatusLow(pe.RELIABLE);const _=new Dt({destinationIdentities:a,value:{case:"streamChunk",value:new rl({content:w,streamId:o,chunkIndex:qr(d)})}});yield f.sendDataPacket(_,pe.RELIABLE),d+=1,b+=w.byteLength}}finally{B()}})},close(){return S(this,void 0,void 0,function*(){const y=new il({streamId:o}),B=new Dt({destinationIdentities:a,value:{case:"streamTrailer",value:y}});yield f.sendDataPacket(B,pe.RELIABLE)})},abort(y){p.error("Sink error:",y)}});return new Dx(g,c)})}performRpc(e){return S(this,arguments,void 0,function(t){var r=this;let{destinationIdentity:i,method:A,payload:s,responseTimeout:o=1e4}=t;return function*(){return new Promise((c,u)=>S(r,void 0,void 0,function*(){var l,d,h,f;if($l(s)>w0){u(Ze.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((d=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||d===void 0)&&d.version&&Wr((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){u(Ze.builtIn("UNSUPPORTED_SERVER"));return}const p=crypto.randomUUID();yield this.publishRpcRequest(i,p,A,s,o-2e3);const g=setTimeout(()=>{this.pendingAcks.delete(p),u(Ze.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(p),clearTimeout(v)},2e3);this.pendingAcks.set(p,{resolve:()=>{clearTimeout(g)},participantIdentity:i});const v=setTimeout(()=>{this.pendingResponses.delete(p),u(Ze.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(p,{resolve:(y,B)=>{clearTimeout(v),this.pendingAcks.has(p)&&(console.warn("RPC response received before ack",p),this.pendingAcks.delete(p),clearTimeout(g)),B?u(B):c(y??"")},participantIdentity:i})}))}()})}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,r){const i=this.pendingResponses.get(e);i?(i.resolve(t,r),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,r,i,A){return S(this,void 0,void 0,function*(){const s=new Dt({destinationIdentities:[e],kind:pe.RELIABLE,value:{case:"rpcRequest",value:new Qm({id:t,method:r,payload:i,responseTimeoutMs:A,version:1})}});yield this.engine.sendDataPacket(s,pe.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:r}]of this.pendingAcks)r===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:r,resolve:i}]of this.pendingResponses)r===e&&(i(null,Ze.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var r,i;const A=this.trackPublications.get(t.sid);if(A){const s=A.isMuted||((i=(r=A.track)===null||r===void 0?void 0:r.isUpstreamPaused)!==null&&i!==void 0?i:!1);s!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),_e(A)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(t.sid,s))}}),!0):!1}getPublicationForTrack(e){let t;return this.trackPublications.forEach(r=>{const i=r.track;i&&(e instanceof MediaStreamTrack?(Jr(i)||gr(i))&&i.mediaStreamTrack===e&&(t=r):e===i&&(t=r))}),t}waitForPendingPublicationOfSource(e){return S(this,void 0,void 0,function*(){const r=Date.now();for(;Date.now()<r+1e4;){const i=Array.from(this.pendingPublishPromises.entries()).find(A=>{let[s]=A;return s.source===e});if(i)return i[1];yield Nt(20)}})}}class Jx extends Hn{constructor(e,t,r,i){super(e,t.sid,t.name,i),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Yt.HIGH,this.handleEnded=A=>{this.setTrack(void 0),this.emit(L.Ended,A)},this.handleVisibilityChange=A=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(A),this.logContext),this.disabled=!A,this.emitTrackUpdate()},this.handleVideoDimensionsChange=A=>{this.log.debug("adaptivestream video dimensions ".concat(A.width,"x").concat(A.height),this.logContext),this.videoDimensions=A,this.emitTrackUpdate()},this.subscribed=r,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,r=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const i=new Go({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Mm({participantSid:"",trackSids:[this.trackSid]})]});this.emit(L.UpdateSubscription,i),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(r)}get subscriptionStatus(){return this.subscribed===!1?Hn.SubscriptionStatus.Unsubscribed:super.isSubscribed?Hn.SubscriptionStatus.Subscribed:Hn.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Hn.PermissionStatus.Allowed:Hn.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,r;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((r=this.videoDimensions)===null||r===void 0?void 0:r.height)===e.height||(Hl(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Hl(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,r=this.permissionStatus,i=this.track;i!==e&&(i&&(i.off(L.VideoDimensionsChanged,this.handleVideoDimensionsChange),i.off(L.VisibilityChanged,this.handleVisibilityChange),i.off(L.Ended,this.handleEnded),i.detach(),i.stopMonitor(),this.emit(L.Unsubscribed,i)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(L.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(L.VisibilityChanged,this.handleVisibilityChange),e.on(L.Ended,this.handleEnded),this.emit(L.Subscribed,e)),this.emitPermissionUpdateIfChanged(r),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,r=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(r),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(L.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?L.Muted:L.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(L.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(L.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===R.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Hl(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Wm({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=Yt.HIGH,this.emit(L.UpdateSettings,e)}}class da extends Q0{static fromParticipantInfo(e,t,r){return new da(e,t.sid,t.identity,t.name,t.metadata,t.attributes,r,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,r,i,A,s,o){let a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Vo.STANDARD;super(t,r||"",i,A,s,o,a),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(L.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),_e(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(L.UpdateSubscription,t=>{t.participantTracks.forEach(r=>{r.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(L.SubscriptionPermissionChanged,t=>{this.emit(K.TrackSubscriptionPermissionChanged,e,t)}),e.on(L.SubscriptionStatusChanged,t=>{this.emit(K.TrackSubscriptionStatusChanged,e,t)}),e.on(L.Subscribed,t=>{this.emit(K.TrackSubscribed,t,e)}),e.on(L.Unsubscribed,t=>{this.emit(K.TrackUnsubscribed,t,e)}),e.on(L.SubscriptionFailed,t=>{this.emit(K.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:R.Source.Microphone;this.volumeMap.set(t,e);const r=this.getTrackPublication(t);r&&r.track&&r.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:R.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,r,i,A,s){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(u=>{!o&&e.kind===u.kind.toString()&&(o=u)}),!o){if(s===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(K.TrackSubscriptionFailed,t);return}s===void 0&&(s=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,r,i,A,s-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),_e(o))),this.emit(K.TrackSubscriptionFailed,t);return}const a=e.kind==="video";let c;return a?c=new Hx(e,t,i,A):c=new Nx(e,t,i,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(r),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&Nl(c)&&Nn(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,r=new Map;return e.tracks.forEach(i=>{var A,s;let o=this.getTrackPublicationBySid(i.sid);if(o)o.updateInfo(i);else{const a=R.kindFromProto(i.type);if(!a)return;o=new Jx(a,i,(A=this.signalClient.connectOptions)===null||A===void 0?void 0:A.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(s=this.loggerOptions)===null||s===void 0?void 0:s.loggerName}),o.updateInfo(i),r.set(i.sid,o);const c=Array.from(this.trackPublications.values()).find(u=>u.source===(o==null?void 0:o.source));c&&o.source!==R.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:_e(c),newTrack:_e(o)})),this.addTrackPublication(o)}t.set(i.sid,o)}),this.trackPublications.forEach(i=>{t.has(i.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),_e(i))),this.unpublishTrack(i.trackSid,!0))}),r.forEach(i=>{this.emit(K.TrackPublished,i)}),!0}unpublishTrack(e,t){const r=this.trackPublications.get(e);if(!r)return;const{track:i}=r;switch(i&&(i.stop(),r.setTrack(void 0)),this.trackPublications.delete(e),r.kind){case R.Kind.Audio:this.audioTrackPublications.delete(e);break;case R.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(K.TrackUnpublished,r)}setAudioOutput(e){return S(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(r=>{var i;Nn(r.track)&&Nl(r.track)&&t.push(r.track.setSinkId((i=e.deviceId)!==null&&i!==void 0?i:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:r})),super.emit(e,...r)}}var fe;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(fe||(fe={}));const zx=4*1e3;class Li extends Sn.EventEmitter{constructor(e){var t,r,i,A;if(super(),t=this,this.state=fe.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ue,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(s,o,a)=>S(this,void 0,void 0,function*(){var c;if(!OF())throw kn()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const u=yield this.disconnectLock.lock();if(this.state===fe.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(fe.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==s&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Rl(new URL(s))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Ad(s,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(h=>{var f;(f=this.regionUrlProvider)===null||f===void 0||f.setServerReportedRegions(h)}).catch(h=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:h}))}));const l=(h,f,p)=>S(this,void 0,void 0,function*(){var g,v;this.abortController&&this.abortController.abort();const y=new AbortController;this.abortController=y,u==null||u();try{yield this.attemptConnection(p??s,o,a,y),this.abortController=void 0,h()}catch(B){if(this.regionUrlProvider&&B instanceof Fe&&B.reason!==de.Cancelled&&B.reason!==de.NotAllowed){let b=null;try{b=yield this.regionUrlProvider.getNextBestRegionUrl((g=this.abortController)===null||g===void 0?void 0:g.signal)}catch(w){if(w instanceof Fe&&(w.status===401||w.reason===de.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),f(w);return}}b&&!(!((v=this.abortController)===null||v===void 0)&&v.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(B.message,". Retrying with another region: ").concat(b),this.logContext),this.recreateEngine(),yield l(h,f,b)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,r0(B)),f(B))}else{let b=sn.UNKNOWN_REASON;B instanceof Fe&&(b=r0(B)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,b),f(B)}}}),d=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ll((h,f)=>{l(h,f,d)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(s,o,a,c,u,l)=>S(this,void 0,void 0,function*(){var d,h,f;const p=yield a.join(s,o,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},l.signal);let g=p.serverInfo;if(g||(g={version:p.serverVersion,region:p.serverRegion}),this.serverInfo=g,this.log.debug("connected to Livekit Server ".concat(Object.entries(g).map(v=>{let[y,B]=v;return"".concat(y,": ").concat(B)}).join(", ")),{room:(d=p.room)===null||d===void 0?void 0:d.name,roomSid:(h=p.room)===null||h===void 0?void 0:h.sid,identity:(f=p.participant)===null||f===void 0?void 0:f.identity}),!g.version)throw new bF("unknown server version");return g.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),p}),this.applyJoinResponse=s=>{const o=s.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(s.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(s.sifTrailer)}catch(a){this.log.error(a instanceof Error?a.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:a}))}this.handleParticipantUpdates([o,...s.otherParticipants]),s.room&&this.handleRoomUpdate(s.room)},this.attemptConnection=(s,o,a,c)=>S(this,void 0,void 0,function*(){var u,l;this.state===fe.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((l=this.regionUrlProvider)===null||l===void 0)&&l.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Zl),a),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const d=yield this.connectSignal(s,o,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(d),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected)}catch(d){yield this.engine.close(),this.recreateEngine();const h=new Fe("could not establish signal connection",de.ServerUnreachable);throw d instanceof Error&&(h.message="".concat(h.message,": ").concat(d.message)),d instanceof Fe&&(h.reason=d.reason,h.status=d.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:d})),h}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new Fe("Connection attempt aborted",de.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(d){throw yield this.engine.close(),this.recreateEngine(),d}Ht()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ht()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(fe.Connected),this.emit(O.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];return S(t,[...o],void 0,function(){var c=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var l,d,h,f;const p=yield c.disconnectLock.lock();try{if(c.state===fe.Disconnected){c.log.debug("already disconnected",c.logContext);return}c.log.info("disconnect from room",Object.assign({},c.logContext)),(c.state===fe.Connecting||c.state===fe.Reconnecting||c.isResuming)&&(c.log.warn("abort connection attempt",c.logContext),(l=c.abortController)===null||l===void 0||l.abort(),(h=(d=c.connectFuture)===null||d===void 0?void 0:d.reject)===null||h===void 0||h.call(d,new Fe("Client initiated disconnect",de.Cancelled)),c.connectFuture=void 0),!((f=c.engine)===null||f===void 0)&&f.client.isDisconnected||(yield c.engine.client.sendLeave()),c.engine&&(yield c.engine.close()),c.handleDisconnect(u,sn.CLIENT_INITIATED),c.engine=void 0}finally{p()}}()})},this.onPageLeave=()=>S(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>S(this,void 0,void 0,function*(){const s=[],o=un();if(o&&o.os==="iOS"){const a="livekit-dummy-audio-el";let c=document.getElementById(a);if(!c){c=document.createElement("audio"),c.id=a,c.autoplay=!0,c.hidden=!0;const u=Ml();u.enabled=!0;const l=new MediaStream([u]);c.srcObject=l,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:l,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(c),this.once(O.Disconnected,()=>{c==null||c.remove(),c=null})}s.push(c)}this.remoteParticipants.forEach(a=>{a.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(u=>{s.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...s.map(a=>(a.muted=!1,a.play()))]),this.handleAudioPlaybackStarted()}catch(a){throw this.handleAudioPlaybackFailed(a),a}}),this.startVideo=()=>S(this,void 0,void 0,function*(){const s=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(a=>{var c;(c=a.track)===null||c===void 0||c.attachedElements.forEach(u=>{s.includes(u)||s.push(u)})});yield Promise.all(s.map(o=>o.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(o=>{o.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const s of this.remoteParticipants.values())this.handleParticipantDisconnected(s.identity,s);this.setAndEmitConnectionState(fe.Reconnecting)&&this.emit(O.Reconnecting)},this.handleSignalRestarted=s=>S(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(s.serverRegion),Object.assign(Object.assign({},this.logContext),{region:s.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(s);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(o){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:o}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:s.serverRegion}))}catch{return}this.setAndEmitConnectionState(fe.Connected),this.emit(O.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=s=>{s.forEach(o=>{var a;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(a=this.sidToIdentity.get(o.sid))!==null&&a!==void 0?a:"");let c=this.remoteParticipants.get(o.identity);o.state===Ei.DISCONNECTED?this.handleParticipantDisconnected(o.identity,c):c=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=s=>{const o=[],a={};s.forEach(c=>{if(a[c.sid]=!0,c.sid===this.localParticipant.sid)this.localParticipant.audioLevel=c.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(c.sid);u&&(u.audioLevel=c.level,u.setIsSpeaking(!0),o.push(u))}}),a[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{a[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(O.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=s=>{const o=new Map;this.activeSpeakers.forEach(c=>{const u=this.remoteParticipants.get(c.identity);u&&u.sid!==c.sid||o.set(c.sid,c)}),s.forEach(c=>{let u=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=c.level,u.setIsSpeaking(c.active),c.active?o.set(c.sid,u):o.delete(c.sid))});const a=Array.from(o.values());a.sort((c,u)=>u.audioLevel-c.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(O.ActiveSpeakersChanged,a)},this.handleStreamStateUpdate=s=>{s.streamStates.forEach(o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);if(!c||!c.track)return;const u=R.streamStateFromProto(o.state);u!==c.track.streamState&&(c.track.streamState=u,a.emit(K.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(O.TrackStreamStateChanged,c,c.track.streamState,a))})},this.handleSubscriptionPermissionUpdate=s=>{const o=this.getRemoteParticipantBySid(s.participantSid);if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setAllowed(s.allowed)},this.handleSubscriptionError=s=>{const o=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(s.trackSid));if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setSubscriptionError(s.err)},this.handleDataPacket=s=>{const o=this.remoteParticipants.get(s.participantIdentity);if(s.value.case==="user")this.handleUserPacket(o,s.value.value,s.kind);else if(s.value.case==="transcription")this.handleTranscription(o,s.value.value);else if(s.value.case==="sipDtmf")this.handleSipDtmf(o,s.value.value);else if(s.value.case==="chatMessage")this.handleChatMessage(o,s.value.value);else if(s.value.case==="metrics")this.handleMetrics(s.value.value,o);else if(s.value.case==="streamHeader")this.handleStreamHeader(s.value.value,s.participantIdentity);else if(s.value.case==="streamChunk")this.handleStreamChunk(s.value.value);else if(s.value.case==="streamTrailer")this.handleStreamTrailer(s.value.value);else if(s.value.case==="rpcRequest"){const a=s.value.value;this.handleIncomingRpcRequest(s.participantIdentity,a.id,a.method,a.payload,a.responseTimeoutMs,a.version)}},this.handleUserPacket=(s,o,a)=>{this.emit(O.DataReceived,o.payload,s,a,o.topic),s==null||s.emit(K.DataReceived,o.payload,a)},this.handleSipDtmf=(s,o)=>{this.emit(O.SipDTMFReceived,o,s),s==null||s.emit(K.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(s,o)=>{const a=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),c=a==null?void 0:a.trackPublications.get(o.trackId),u=GF(o,this.transcriptionReceivedTimes);c==null||c.emit(L.TranscriptionReceived,u),a==null||a.emit(K.TranscriptionReceived,u,c),this.emit(O.TranscriptionReceived,u,a,c)},this.handleChatMessage=(s,o)=>{const a=jF(o);this.emit(O.ChatMessage,a,s)},this.handleMetrics=(s,o)=>{this.emit(O.MetricsReceived,s,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(O.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=s=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:s})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(O.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(O.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(O.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>S(this,void 0,void 0,function*(){var s,o,a;const c=ft.getInstance().previousDevices,u=yield ft.getInstance().getDevices(void 0,!1),l=un();if((l==null?void 0:l.name)==="Chrome"&&l.os!=="iOS")for(let h of u){const f=c.find(p=>p.deviceId===h.deviceId);f&&f.label!==""&&f.kind===h.kind&&f.label!==h.label&&this.getActiveDevice(h.kind)==="default"&&this.emit(O.ActiveDeviceChanged,h.kind,h.deviceId)}const d=["audiooutput","audioinput","videoinput"];for(let h of d){const f=zF(h),p=this.localParticipant.getTrackPublication(f);if(p&&(!((s=p.track)===null||s===void 0)&&s.isUserProvided))continue;const g=u.filter(y=>y.kind===h),v=this.getActiveDevice(h);if(v===((o=c.filter(y=>y.kind===h)[0])===null||o===void 0?void 0:o.deviceId)&&g.length>0&&((a=g[0])===null||a===void 0?void 0:a.deviceId)!==v){yield this.switchActiveDevice(h,g[0].deviceId);continue}h==="audioinput"&&!pr()||h==="videoinput"||g.length>0&&!g.find(y=>y.deviceId===this.getActiveDevice(h))&&(yield this.switchActiveDevice(h,g[0].deviceId))}this.emit(O.MediaDevicesChanged)}),this.handleRoomUpdate=s=>{const o=this.roomInfo;this.roomInfo=s,o&&o.metadata!==s.metadata&&this.emitWhenConnected(O.RoomMetadataChanged,s.metadata),(o==null?void 0:o.activeRecording)!==s.activeRecording&&this.emitWhenConnected(O.RecordingStatusChanged,s.activeRecording)},this.handleConnectionQualityUpdate=s=>{s.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const a=this.getRemoteParticipantBySid(o.participantSid);a&&a.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=s=>{this.emit(O.ParticipantMetadataChanged,s,this.localParticipant)},this.onLocalParticipantNameChanged=s=>{this.emit(O.ParticipantNameChanged,s,this.localParticipant)},this.onLocalAttributesChanged=s=>{this.emit(O.ParticipantAttributesChanged,s,this.localParticipant)},this.onLocalTrackMuted=s=>{this.emit(O.TrackMuted,s,this.localParticipant)},this.onLocalTrackUnmuted=s=>{this.emit(O.TrackUnmuted,s,this.localParticipant)},this.onTrackProcessorUpdate=s=>{var o;(o=s==null?void 0:s.onPublish)===null||o===void 0||o.call(s,this)},this.onLocalTrackPublished=s=>S(this,void 0,void 0,function*(){var o,a,c,u,l,d;(o=s.track)===null||o===void 0||o.on(L.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.on(L.Restarted,this.onLocalTrackRestarted),(l=(u=(c=s.track)===null||c===void 0?void 0:c.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||l===void 0||l.call(u,this),this.emit(O.LocalTrackPublished,s,this.localParticipant),Jr(s.track)&&(yield s.track.checkForSilence())&&this.emit(O.LocalAudioSilenceDetected,s);const h=yield(d=s.track)===null||d===void 0?void 0:d.getDeviceId(!1),f=o0(s.source);f&&h&&h!==this.localParticipant.activeDeviceMap.get(f)&&(this.localParticipant.activeDeviceMap.set(f,h),this.emit(O.ActiveDeviceChanged,f,h))}),this.onLocalTrackUnpublished=s=>{var o,a;(o=s.track)===null||o===void 0||o.off(L.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.off(L.Restarted,this.onLocalTrackRestarted),this.emit(O.LocalTrackUnpublished,s,this.localParticipant)},this.onLocalTrackRestarted=s=>S(this,void 0,void 0,function*(){const o=yield s.getDeviceId(!1),a=o0(s.source);a&&o&&o!==this.localParticipant.activeDeviceMap.get(a)&&(this.log.debug("local track restarted, setting ".concat(a," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(a,o),this.emit(O.ActiveDeviceChanged,a,o))}),this.onLocalConnectionQualityChanged=s=>{this.emit(O.ConnectionQualityChanged,s,this.localParticipant)},this.onMediaDevicesError=s=>{this.emit(O.MediaDevicesError,s)},this.onLocalParticipantPermissionsChanged=s=>{this.emit(O.ParticipantPermissionsChanged,s,this.localParticipant)},this.onLocalChatMessageSent=s=>{this.emit(O.ChatMessage,s,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},gx),e),this.log=Ln((r=this.options.loggerName)!==null&&r!==void 0?r:cn.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},v0),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},y0),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},fx),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Mt,this.localParticipant=new qx("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",fr(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",fr(this.options.audioCaptureDefaults.deviceId)),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&this.switchActiveDevice("audiooutput",fr(this.options.audioOutput.deviceId)).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),Ht()){const s=new AbortController;(A=navigator.mediaDevices)===null||A===void 0||A.addEventListener("devicechange",this.handleDeviceChange,{signal:s.signal}),Li.cleanupRegistry&&Li.cleanupRegistry.register(this,()=>{s.abort()})}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t,r,i,A,s){return S(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),s!==1){yield this.engine.publishRpcResponse(e,t,null,Ze.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(r);if(!o){yield this.engine.publishRpcResponse(e,t,null,Ze.builtIn("UNSUPPORTED_METHOD"));return}let a=null,c=null;try{const u=yield o({requestId:t,callerIdentity:e,payload:i,responseTimeout:A});$l(u)>w0?(a=Ze.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(r))):c=u}catch(u){u instanceof Ze?a=u:(console.warn("Uncaught error returned by RPC handler for ".concat(r,". Returning APPLICATION_ERROR instead."),u),a=Ze.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)})}setE2EEEnabled(e){return S(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new tx(this.options.e2ee),this.e2eeManager.on(dr.ParticipantEncryptionStatusChanged,(t,r)=>{qF(r)&&(this.isE2EEEnabled=t),this.emit(O.ParticipantEncryptionStatusChanged,t,r)}),this.e2eeManager.on(dr.EncryptionError,t=>this.emit(O.EncryptionError,t)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return S(this,void 0,void 0,function*(){return this.state===fe.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const r=i=>{i.sid!==""&&(this.engine.off(D.RoomUpdate,r),e(i.sid))};this.engine.on(D.RoomUpdate,r),this.once(O.Disconnected,()=>{this.engine.off(D.RoomUpdate,r),t("Room disconnected before room server id was available")})})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new xx(this.options),this.engine.on(D.ParticipantUpdate,this.handleParticipantUpdates).on(D.RoomUpdate,this.handleRoomUpdate).on(D.SpeakersChanged,this.handleSpeakersChanged).on(D.StreamStateChanged,this.handleStreamStateUpdate).on(D.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(D.SubscriptionError,this.handleSubscriptionError).on(D.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(D.MediaTrackAdded,(e,t,r)=>{this.onTrackAdded(e,t,r)}).on(D.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(D.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(D.DataPacketReceived,this.handleDataPacket).on(D.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(fe.SignalReconnecting)&&this.emit(O.SignalReconnecting)}).on(D.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(fe.Connected)&&this.emit(O.Reconnected)}).on(D.SignalResumed,()=>{this.bufferedEvents=[],(this.state===fe.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(D.Restarting,this.handleRestarting).on(D.SignalRestarted,this.handleSignalRestarted).on(D.Offline,()=>{this.setAndEmitConnectionState(fe.Reconnecting)&&this.emit(O.Reconnecting)}).on(D.DCBufferStatusChanged,(e,t)=>{this.emit(O.DCBufferStatusChanged,e,t)}).on(D.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(r=>{let{trackSid:i}=r;return i===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(K.LocalTrackSubscribed,t),this.emitWhenConnected(O.LocalTrackSubscribed,t,this.localParticipant)}).on(D.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,r)=>{this.handleParticipantDisconnected(r,t)}),this.emit(O.Moved,e.room.name,e.token),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return ft.getInstance().getDevices(e,t)}prepareConnection(e,t){return S(this,void 0,void 0,function*(){if(this.state===fe.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Rl(new URL(e))&&t){this.regionUrlProvider=new Ad(e,t);const r=yield this.regionUrlProvider.getNextBestRegionUrl();r&&this.state===fe.Disconnected&&(this.regionUrl=r,yield fetch(Dl(r),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(r),this.logContext))}else yield fetch(Dl(e),{method:"HEAD"})}catch(r){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:r}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return S(this,void 0,void 0,function*(){let r=()=>{},i;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new _n({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new _n({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new _n({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new _n({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":r=()=>S(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new _n({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":r=()=>S(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new _n({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":i=new _n({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),r=()=>S(this,void 0,void 0,function*(){const A=this.engine.client.onLeave;A&&A(new jo({reason:sn.CLIENT_INITIATED,action:Ti.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");i=new _n({scenario:{case:"subscriberBandwidth",value:qr(t)}});break;case"leave-full-reconnect":i=new _n({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield r())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,a,c,u,l,d,h,f;let p=!0,g=!1;const v=s?{exact:i}:i;if(r==="audioinput"){g=A.localParticipant.audioTrackPublications.size===0;const y=(o=A.getActiveDevice(r))!==null&&o!==void 0?o:A.options.audioCaptureDefaults.deviceId;A.options.audioCaptureDefaults.deviceId=v;const B=Array.from(A.localParticipant.audioTrackPublications.values()).filter(b=>b.source===R.Source.Microphone);try{p=(yield Promise.all(B.map(b=>{var w;return(w=b.audioTrack)===null||w===void 0?void 0:w.setDeviceId(v)}))).every(b=>b===!0)}catch(b){throw A.options.audioCaptureDefaults.deviceId=y,b}}else if(r==="videoinput"){g=A.localParticipant.videoTrackPublications.size===0;const y=(a=A.getActiveDevice(r))!==null&&a!==void 0?a:A.options.videoCaptureDefaults.deviceId;A.options.videoCaptureDefaults.deviceId=v;const B=Array.from(A.localParticipant.videoTrackPublications.values()).filter(b=>b.source===R.Source.Camera);try{p=(yield Promise.all(B.map(b=>{var w;return(w=b.videoTrack)===null||w===void 0?void 0:w.setDeviceId(v)}))).every(b=>b===!0)}catch(b){throw A.options.videoCaptureDefaults.deviceId=y,b}}else if(r==="audiooutput"){if(!Ql()&&!A.options.webAudioMix||A.options.webAudioMix&&A.audioContext&&!("setSinkId"in A.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");A.options.webAudioMix&&(i=(c=yield ft.getInstance().normalizeDeviceId("audiooutput",i))!==null&&c!==void 0?c:""),(u=(f=A.options).audioOutput)!==null&&u!==void 0||(f.audioOutput={});const y=(l=A.getActiveDevice(r))!==null&&l!==void 0?l:A.options.audioOutput.deviceId;A.options.audioOutput.deviceId=i;try{A.options.webAudioMix&&((d=A.audioContext)===null||d===void 0||d.setSinkId(i)),yield Promise.all(Array.from(A.remoteParticipants.values()).map(B=>B.setAudioOutput({deviceId:i})))}catch(B){throw A.options.audioOutput.deviceId=y,B}}return(g||r==="audiooutput")&&(A.localParticipant.activeDeviceMap.set(r,r==="audiooutput"&&((h=A.options.audioOutput)===null||h===void 0?void 0:h.deviceId)||i),A.emit(O.ActiveDeviceChanged,r,i)),p}()})}setupLocalParticipantEvents(){this.localParticipant.on(K.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(K.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(K.AttributesChanged,this.onLocalAttributesChanged).on(K.TrackMuted,this.onLocalTrackMuted).on(K.TrackUnmuted,this.onLocalTrackUnmuted).on(K.LocalTrackPublished,this.onLocalTrackPublished).on(K.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(K.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(K.MediaDevicesError,this.onMediaDevicesError).on(K.AudioStreamAcquired,this.startAudio).on(K.ChatMessage,this.onLocalChatMessageSent).on(K.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,r){if(this.state===fe.Connecting||this.state===fe.Reconnecting){const u=()=>{this.onTrackAdded(e,t,r),l()},l=()=>{this.off(O.Reconnected,u),this.off(O.Connected,u),this.off(O.Disconnected,l)};this.once(O.Reconnected,u),this.once(O.Connected,u),this.once(O.Disconnected,l);return}if(this.state===fe.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const i=QF(t.id),A=i[0];let s=i[1],o=e.id;if(s&&s.startsWith("TR")&&(o=s),A===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const a=Array.from(this.remoteParticipants.values()).find(u=>u.sid===A);if(!a){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(A),this.logContext);return}let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={}),a.addSubscribedMediaTrack(e,o,t,r,c)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==fe.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(i=>{i.trackPublications.forEach(A=>{i.unpublishTrack(A.trackSid)})}),this.localParticipant.trackPublications.forEach(i=>{var A,s,o;i.track&&this.localParticipant.unpublishTrack(i.track,e),e?((A=i.track)===null||A===void 0||A.detach(),(s=i.track)===null||s===void 0||s.stop()):(o=i.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(K.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(K.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(K.AttributesChanged,this.onLocalAttributesChanged).off(K.TrackMuted,this.onLocalTrackMuted).off(K.TrackUnmuted,this.onLocalTrackUnmuted).off(K.LocalTrackPublished,this.onLocalTrackPublished).off(K.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(K.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(K.MediaDevicesError,this.onMediaDevicesError).off(K.AudioStreamAcquired,this.startAudio).off(K.ChatMessage,this.onLocalChatMessageSent).off(K.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),Ht()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(r=navigator.mediaDevices)===null||r===void 0||r.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(fe.Disconnected),this.emit(O.Disconnected,t)}}}handleParticipantDisconnected(e,t){var r;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(i=>{t.unpublishTrack(i.trackSid,!0)}),this.emit(O.ParticipantDisconnected,t),t.setDisconnected(),(r=this.localParticipant)===null||r===void 0||r.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return S(this,void 0,void 0,function*(){var r;if(e.contentHeader.case==="byteHeader"){const i=this.byteStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let A;const s={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:ia(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{A=a,this.byteStreamControllers.set(e.streamId,{info:s,controller:A,startTime:Date.now()})}});i(new Ox(s,o,ia(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const i=this.textStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let A;const s={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{A=a,this.textStreamControllers.set(e.streamId,{info:s,controller:A,startTime:Date.now()})}});i(new Mx(s,o,ia(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const r=this.textStreamControllers.get(e.streamId);r&&e.content.length>0&&r.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const r=this.byteStreamControllers.get(e.streamId);r&&(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return S(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=s0())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(i=>i.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Nt(200)])}catch(i){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:i}))}const r=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";r!==this.canPlaybackAudio&&(this.audioEnabled=r,this.emit(O.AudioPlaybackStatusChanged,r))})}createParticipant(e,t){var r;let i;return t?i=da.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):i=new da(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&i.setAudioOutput(this.options.audioOutput).catch(A=>this.log.warn("Could not set audio output: ".concat(A.message),this.logContext)),i}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}const r=this.createParticipant(e,t);return this.remoteParticipants.set(e,r),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(O.ParticipantConnected,r),r.on(K.TrackPublished,i=>{this.emitWhenConnected(O.TrackPublished,i,r)}).on(K.TrackSubscribed,(i,A)=>{i.kind===R.Kind.Audio?(i.on(L.AudioPlaybackStarted,this.handleAudioPlaybackStarted),i.on(L.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):i.kind===R.Kind.Video&&(i.on(L.VideoPlaybackFailed,this.handleVideoPlaybackFailed),i.on(L.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(O.TrackSubscribed,i,A,r)}).on(K.TrackUnpublished,i=>{this.emit(O.TrackUnpublished,i,r)}).on(K.TrackUnsubscribed,(i,A)=>{this.emit(O.TrackUnsubscribed,i,A,r)}).on(K.TrackMuted,i=>{this.emitWhenConnected(O.TrackMuted,i,r)}).on(K.TrackUnmuted,i=>{this.emitWhenConnected(O.TrackUnmuted,i,r)}).on(K.ParticipantMetadataChanged,i=>{this.emitWhenConnected(O.ParticipantMetadataChanged,i,r)}).on(K.ParticipantNameChanged,i=>{this.emitWhenConnected(O.ParticipantNameChanged,i,r)}).on(K.AttributesChanged,i=>{this.emitWhenConnected(O.ParticipantAttributesChanged,i,r)}).on(K.ConnectionQualityChanged,i=>{this.emitWhenConnected(O.ConnectionQualityChanged,i,r)}).on(K.ParticipantPermissionsChanged,i=>{this.emitWhenConnected(O.ParticipantPermissionsChanged,i,r)}).on(K.TrackSubscriptionStatusChanged,(i,A)=>{this.emitWhenConnected(O.TrackSubscriptionStatusChanged,i,A,r)}).on(K.TrackSubscriptionFailed,(i,A)=>{this.emit(O.TrackSubscriptionFailed,i,r,A)}).on(K.TrackSubscriptionPermissionChanged,(i,A)=>{this.emitWhenConnected(O.TrackSubscriptionPermissionChanged,i,A,r)}).on(K.Active,()=>{this.emitWhenConnected(O.ParticipantActive,r)}),t&&r.updateInfo(t),r}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((r,i)=>(r.push(...i.getTrackPublications()),r),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&WF(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=wt.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,sn.STATE_MISMATCH))):e=0},zx)}clearConnectionReconcile(){this.connectionReconcileInterval&&wt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(O.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,r]=e;this.emit(t,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];if(this.state===fe.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,r]);else if(this.state===fe.Connected)return this.emit(e,...r);return!1}simulateParticipants(e){return S(this,void 0,void 0,function*(){var t,r;const i=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),A=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Ho({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Ke.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Kr({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected),this.emit(O.Connected),this.setAndEmitConnectionState(fe.Connected),i.video){const s=new ad(R.Kind.Video,new Ui({source:at.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:An.AUDIO,name:"video-dummy"}),new ua(i.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:n0(160*((t=A.aspectRatios[0])!==null&&t!==void 0?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(K.LocalTrackPublished,s)}if(i.audio){const s=new ad(R.Kind.Audio,new Ui({source:at.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:An.AUDIO}),new aa(i.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ml(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(K.LocalTrackPublished,s)}for(let s=0;s<A.count-1;s+=1){let o=new Kr({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(s),state:Ei.ACTIVE,tracks:[],joinedAt:Ke.parse(Date.now())});const a=this.getOrCreateParticipant(o.identity,o);if(A.video){const c=n0(160*((r=A.aspectRatios[s%A.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),u=new Ui({source:at.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:An.AUDIO});a.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}if(A.audio){const c=Ml(),u=new Ui({source:at.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:An.AUDIO});a.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}a.updateInfo(o)}})}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];if(e!==O.ActiveSpeakersChanged&&e!==O.TranscriptionReceived){const A=P0(r).filter(s=>s!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:A}))}return super.emit(e,...r)}}Li.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function P0(n){return n.map(e=>{if(e)return Array.isArray(e)?P0(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var hn;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(hn||(hn={}));class yr extends Sn.EventEmitter{constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=hn.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Li(r.roomOptions),this.connectOptions=r.connectOptions,this.options=r}run(e){return S(this,void 0,void 0,function*(){if(this.status!==hn.IDLE)throw Error("check is running already");this.setStatus(hn.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==hn.SKIPPED&&this.setStatus(this.isSuccess()?hn.SUCCESS:hn.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return S(this,void 0,void 0,function*(){return this.room.state===fe.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return S(this,void 0,void 0,function*(){this.room&&this.room.state!==fe.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(hn.SKIPPED)}switchProtocol(e){return S(this,void 0,void 0,function*(){let t=!1,r=!1;if(this.room.on(O.Reconnecting,()=>{t=!0}),this.room.once(O.Reconnected,()=>{r=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(A=>setTimeout(A,1e3)),!t)return;const i=Date.now()+1e4;for(;Date.now()<i;){if(r)return;yield Nt(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Xx extends yr{get description(){return"Cloud regions"}perform(){return S(this,void 0,void 0,function*(){const e=new Ad(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],r=new Set;for(let A=0;A<3;A++){const s=yield e.getNextBestRegionUrl();if(!s)break;if(r.has(s))continue;r.add(s);const o=yield this.checkCloudRegion(s);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((A,s)=>(A.duration-s.duration)*.5+(A.rtt-s.rtt)*.5);const i=t[0];this.bestStats=i,this.appendMessage("best Cloud region: ".concat(i.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return S(this,void 0,void 0,function*(){var t,r;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const i=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!i)throw new Error("Region not found");const A=yield this.room.localParticipant.streamText({topic:"test"}),s=1e3,a=1e6/s,c="A".repeat(s),u=Date.now();for(let f=0;f<a;f++)yield A.write(c);yield A.close();const l=Date.now(),d=yield(r=this.room.engine.pcManager)===null||r===void 0?void 0:r.publisher.getStats(),h={region:i,rtt:1e4,duration:l-u};return d==null||d.forEach(f=>{f.type==="candidate-pair"&&f.nominated&&(h.rtt=f.currentRoundTripTime*1e3)}),yield this.disconnect(),h})}}const cd=1e4;class Yx extends yr{get description(){return"Connection via UDP vs TCP"}perform(){return S(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const r=this.bestStats;this.appendMessage("upstream bitrate: ".concat((r.bitrateTotal/r.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((r.rttTotal/r.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((r.jitterTotal/r.count*1e3).toFixed(2)," ms")),r.packetsLost>0&&this.appendWarning("packets lost: ".concat((r.packetsLost/r.packetsSent*100).toFixed(2),"%")),r.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((r.qualityLimitationDurations.bandwidth/(cd/1e3)*100).toFixed(2),"%")),r.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((r.qualityLimitationDurations.cpu/(cd/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return S(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const r=t.getContext("2d");if(!r)throw new Error("Could not get canvas context");let i=0;const A=()=>{i=(i+1)%360,r.fillStyle="hsl(".concat(i,", 100%, 50%)"),r.fillRect(0,0,t.width,t.height),requestAnimationFrame(A)};A();const o=t.captureStream(30).getVideoTracks()[0],c=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,u={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},l=setInterval(()=>S(this,void 0,void 0,function*(){const d=yield c.getRTCStatsReport();d==null||d.forEach(h=>{h.type==="outbound-rtp"?(u.packetsSent=h.packetsSent,u.qualityLimitationDurations=h.qualityLimitationDurations,u.bitrateTotal+=h.targetBitrate,u.count++):h.type==="remote-inbound-rtp"&&(u.packetsLost=h.packetsLost,u.rttTotal+=h.roundTripTime,u.jitterTotal+=h.jitter)})}),1e3);return yield new Promise(d=>setTimeout(d,cd)),clearInterval(l),o.stop(),t.remove(),yield this.disconnect(),u})}}class Zx extends yr{get description(){return"Can publish audio"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect(),r=yield Gx();if(yield A0(r,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(r),yield new Promise(o=>setTimeout(o,3e3));const A=yield(e=r.sender)===null||e===void 0?void 0:e.getStats();if(!A)throw new Error("Could not get RTCStats");let s=0;if(A.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(s=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," audio packets"))})}}class $x extends yr{get description(){return"Can publish video"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect(),r=yield Vx();yield this.checkForVideo(r.mediaStreamTrack),t.localParticipant.publishTrack(r),yield new Promise(s=>setTimeout(s,5e3));const i=yield(e=r.sender)===null||e===void 0?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let A=0;if(i.forEach(s=>{s.type==="outbound-rtp"&&(s.kind==="video"||!s.kind&&s.mediaType==="video")&&(A+=s.packetsSent)}),A===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(A," video packets"))})}checkForVideo(e){return S(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const r=document.createElement("video");r.srcObject=t,r.muted=!0,yield new Promise(i=>{r.onplay=()=>{setTimeout(()=>{var A,s,o,a;const c=document.createElement("canvas"),u=e.getSettings(),l=(s=(A=u.width)!==null&&A!==void 0?A:r.videoWidth)!==null&&s!==void 0?s:1280,d=(a=(o=u.height)!==null&&o!==void 0?o:r.videoHeight)!==null&&a!==void 0?a:720;c.width=l,c.height=d;const h=c.getContext("2d");h.drawImage(r,0,0);const p=h.getImageData(0,0,c.width,c.height).data;let g=!0;for(let v=0;v<p.length;v+=4)if(p[v]!==0||p[v+1]!==0||p[v+2]!==0){g=!1;break}g?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),i()},1e3)},r.play()}),r.remove()})}}class eQ extends yr{get description(){return"Resuming connection after interruption"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect();let r=!1,i=!1,A;const s=new Promise(c=>{setTimeout(c,5e3),A=c}),o=()=>{r=!0};t.on(O.SignalReconnecting,o).on(O.Reconnecting,o).on(O.Reconnected,()=>{i=!0,A(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const a=t.engine.client.onClose;if(a&&a(""),yield s,r){if(!i||t.state!==fe.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class tQ extends yr{get description(){return"Can connect via TURN"}perform(){return S(this,void 0,void 0,function*(){var e,t;const r=new jl,i=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let A=!1,s=!1,o=!1;for(let a of i.iceServers)for(let c of a.urls)c.startsWith("turn:")?(s=!0,o=!0):c.startsWith("turns:")&&(s=!0,o=!0,A=!0),c.startsWith("stun:")&&(o=!0);o?s&&!A&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(a=>setTimeout(a,0)))})}}class nQ extends yr{get description(){return"Establishing WebRTC connection"}perform(){return S(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(O.SignalConnected,()=>{const r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,A)=>{if(i.candidate){const s=new RTCIceCandidate(i);let o="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(rQ(s.address)?o+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,o+=" (passive)"):s.protocol==="udp"&&(t=!0)),this.appendMessage(o)}r&&r(i,A)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=i=>{i instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(i.errorCode," ").concat(i.errorText," ").concat(i.url))})});try{yield this.connect(),ue.info("now the room is connected")}catch(r){throw this.appendWarning("ports need to be open on firewall in order to connect."),r}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function rQ(n){const e=n.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class iQ extends yr{get description(){return"Connecting to signal connection via WebSocket"}perform(){return S(this,void 0,void 0,function*(){var e,t,r;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new jl;const A=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(A.serverVersion,".")),((e=A.serverInfo)===null||e===void 0?void 0:e.edition)===Lm.Cloud&&(!((t=A.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((r=A.serverInfo)===null||r===void 0?void 0:r.region)),yield i.close()})}}class Q4 extends Sn.EventEmitter{constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=r}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:hn.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==hn.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return S(this,void 0,void 0,function*(){const t=this.getNextCheckId(),r=new e(this.url,this.token,this.options),i=s=>{this.updateCheck(t,s)};r.on("update",i);const A=yield r.run();return r.off("update",i),A})}checkWebsocket(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(iQ)})}checkWebRTC(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(nQ)})}checkTURN(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(tQ)})}checkReconnect(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(eQ)})}checkPublishAudio(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Zx)})}checkPublishVideo(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck($x)})}checkConnectionProtocol(){return S(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Yx);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Xx)})}}const AQ=/\{[^{}]+\}/g;function sQ(){return Math.random().toString(36).slice(2,11)}function oQ(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:r=globalThis.fetch,querySerializer:i,bodySerializer:A,headers:s,...o}={...n};e=D0(e);const a=[];async function c(u,l){const{baseUrl:d,fetch:h=r,Request:f=t,headers:p,params:g={},parseAs:v="json",querySerializer:y,bodySerializer:B=A??cQ,body:b,...w}=l||{};d&&(e=D0(d));let _=typeof i=="function"?i:L0(i);y&&(_=typeof y=="function"?y:L0({...typeof i=="object"?i:{},...y}));const k=b===void 0?void 0:B(b),T=k===void 0||k instanceof FormData?{}:{"Content-Type":"application/json"},x={redirect:"follow",...o,...w,body:k,headers:lQ(T,s,p,g.header)};let P,E,F=new t(uQ(u,{baseUrl:e,params:g,querySerializer:_}),x);for(const N in w)N in F||(F[N]=w[N]);if(a.length){P=sQ(),E=Object.freeze({baseUrl:e,fetch:h,parseAs:v,querySerializer:_,bodySerializer:B});for(const N of a)if(N&&typeof N=="object"&&typeof N.onRequest=="function"){const q=await N.onRequest({request:F,schemaPath:u,params:g,options:E,id:P});if(q){if(!(q instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");F=q}}}let M=await h(F);if(a.length)for(let N=a.length-1;N>=0;N--){const q=a[N];if(q&&typeof q=="object"&&typeof q.onResponse=="function"){const ve=await q.onResponse({request:F,response:M,schemaPath:u,params:g,options:E,id:P});if(ve){if(!(ve instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");M=ve}}}if(M.status===204||M.headers.get("Content-Length")==="0")return M.ok?{data:{},response:M}:{error:{},response:M};if(M.ok)return v==="stream"?{data:M.body,response:M}:{data:await M[v](),response:M};let J=await M.text();try{J=JSON.parse(J)}catch{}return{error:J,response:M}}return{GET(u,l){return c(u,{...l,method:"GET"})},PUT(u,l){return c(u,{...l,method:"PUT"})},POST(u,l){return c(u,{...l,method:"POST"})},DELETE(u,l){return c(u,{...l,method:"DELETE"})},OPTIONS(u,l){return c(u,{...l,method:"OPTIONS"})},HEAD(u,l){return c(u,{...l,method:"HEAD"})},PATCH(u,l){return c(u,{...l,method:"PATCH"})},TRACE(u,l){return c(u,{...l,method:"TRACE"})},use(...u){for(const l of u)if(l){if(typeof l!="object"||!("onRequest"in l||"onResponse"in l))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");a.push(l)}},eject(...u){for(const l of u){const d=a.indexOf(l);d!==-1&&a.splice(d,1)}}}}function ha(n,e,t){if(e==null)return"";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${n}=${(t==null?void 0:t.allowReserved)===!0?e:encodeURIComponent(e)}`}function O0(n,e,t){if(!e||typeof e!="object")return"";const r=[],i={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(const o in e)r.push(o,t.allowReserved===!0?e[o]:encodeURIComponent(e[o]));const s=r.join(",");switch(t.style){case"form":return`${n}=${s}`;case"label":return`.${s}`;case"matrix":return`;${n}=${s}`;default:return s}}for(const s in e){const o=t.style==="deepObject"?`${n}[${s}]`:s;r.push(ha(o,e[s],t))}const A=r.join(i);return t.style==="label"||t.style==="matrix"?`${i}${A}`:A}function M0(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){const A={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",s=(t.allowReserved===!0?e:e.map(o=>encodeURIComponent(o))).join(A);switch(t.style){case"simple":return s;case"label":return`.${s}`;case"matrix":return`;${n}=${s}`;default:return`${n}=${s}`}}const r={simple:",",label:".",matrix:";"}[t.style]||"&",i=[];for(const A of e)t.style==="simple"||t.style==="label"?i.push(t.allowReserved===!0?A:encodeURIComponent(A)):i.push(ha(n,A,t));return t.style==="label"||t.style==="matrix"?`${r}${i.join(r)}`:i.join(r)}function L0(n){return function(t){const r=[];if(t&&typeof t=="object")for(const i in t){const A=t[i];if(A!=null){if(Array.isArray(A)){if(A.length===0)continue;r.push(M0(i,A,{style:"form",explode:!0,...n==null?void 0:n.array,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}if(typeof A=="object"){r.push(O0(i,A,{style:"deepObject",explode:!0,...n==null?void 0:n.object,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}r.push(ha(i,A,n))}}return r.join("&")}}function aQ(n,e){let t=n;for(const r of n.match(AQ)??[]){let i=r.substring(1,r.length-1),A=!1,s="simple";if(i.endsWith("*")&&(A=!0,i=i.substring(0,i.length-1)),i.startsWith(".")?(s="label",i=i.substring(1)):i.startsWith(";")&&(s="matrix",i=i.substring(1)),!e||e[i]===void 0||e[i]===null)continue;const o=e[i];if(Array.isArray(o)){t=t.replace(r,M0(i,o,{style:s,explode:A}));continue}if(typeof o=="object"){t=t.replace(r,O0(i,o,{style:s,explode:A}));continue}if(s==="matrix"){t=t.replace(r,`;${ha(i,o)}`);continue}t=t.replace(r,s==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function cQ(n){return n instanceof FormData?n:JSON.stringify(n)}function uQ(n,e){var i;let t=`${e.baseUrl}${n}`;(i=e.params)!=null&&i.path&&(t=aQ(t,e.params.path));let r=e.querySerializer(e.params.query??{});return r.startsWith("?")&&(r=r.substring(1)),r&&(t+=`?${r}`),t}function lQ(...n){const e=new Headers;for(const t of n){if(!t||typeof t!="object")continue;const r=t instanceof Headers?t.entries():Object.entries(t);for(const[i,A]of r)if(A===null)e.delete(i);else if(Array.isArray(A))for(const s of A)e.append(i,s);else A!==void 0&&e.set(i,A)}return e}function D0(n){return n.endsWith("/")?n.substring(0,n.length-1):n}const N0="Onboardee-Session-Token",H0="OnboardeeSessionToken";class K0{constructor(e){this.client=oQ({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch}),this.client.use({onRequest({request:t}){if(window.localStorage){const r=window.localStorage.getItem(H0);r&&t.headers.set(N0,r)}return t},onResponse({response:t}){const r=t.headers.get(N0);return r&&window.localStorage&&window.localStorage.setItem(H0,r),t}})}setAuthToken(e){this.client.use({onRequest({request:t}){return t.headers.set("Authorization",`Bearer ${e}`),t}})}setApiToken(e){this.client.use({onRequest({request:t}){return t.headers.set("Authorization",`Token ${e}`),t}})}async getAuthUrl(e){return await this.client.GET("/api/auth/{type}",{params:{path:{type:e}}})}async getConnectUrl(e){return await this.client.GET("/api/connect/{type}",{params:{path:{type:e}}})}async logout(){return await this.client.POST("/api/logout")}async getCurrentUser(){return await this.client.GET("/api/me")}async clientInitialise(e,t={}){return await this.client.POST("/api/client/{appToken}/initialise",{params:{path:{appToken:e}},body:t})}async clientStartSession(e,t){return await this.client.POST("/api/client/{appToken}/start-session",{params:{path:{appToken:e}},body:t})}async createPresignedUploadUrl(e){return await this.client.POST("/api/files",{body:e})}async createKnowledgeBlock(e){return await this.client.POST("/api/knowledge",{body:e})}async listOnboardees(){return await this.client.GET("/api/onboardees")}async getOnboardee(e){return await this.client.GET("/api/onboardees/{id}",{params:{path:{id:e}}})}async getOnboardeeWidgetConfig(e,t){return await this.client.GET("/api/onboardees/{id}/config",{params:{path:{id:e}},signal:t})}async listPlans(e){return await this.client.GET("/api/plans",{params:{query:{...e&&{client_type:e}}}})}async listPlansWithStatus(){return await this.client.GET("/api/plans-with-status")}async listProducts(){return await this.client.GET("/api/products")}async getProduct(e){return await this.client.GET("/api/products/{id}",{params:{path:{id:e}}})}async getProductAnalytics(e,t,r,i){return await this.client.GET("/api/products/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...r&&{end_date:r},...i&&{course_id:i}}}})}async createProduct(e){return await this.client.POST("/api/products",{body:e})}async updateProduct(e,t){return await this.client.PATCH("/api/products/{id}",{params:{path:{id:e}},body:t})}async getProductNavigationIndex(e){return await this.client.GET("/api/products/{id}/navigation-index",{params:{path:{id:e}}})}async replaceProductNavigationIndex(e,t){return await this.client.PUT("/api/products/{id}/navigation-index",{params:{path:{id:e}},body:t})}async listProductKnowledgeBlocks(e){return await this.client.GET("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createProductKnowledgeBlock(e,t){return await this.client.POST("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async searchProductKnowledgeBlocks(e,t,r){return await this.client.GET("/api/products/{id}/knowledge-blocks/search",{params:{path:{id:e},query:{q:t,...r&&{limit:r.toString()}}}})}async updateProductKnowledgeBlock(e,t,r){return await this.client.PATCH("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deleteProductKnowledgeBlock(e,t){return await this.client.DELETE("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async createPlan(e){return await this.client.POST("/api/plans",{body:e})}async getPlan(e){return await this.client.GET("/api/plans/{id}",{params:{path:{id:e}}})}async getAdminPlan(e){return await this.client.GET("/api/admin/plans/{id}",{params:{path:{id:e}}})}async getPlanAnalytics(e,t,r){return await this.client.GET("/api/plans/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...r&&{end_date:r}}}})}async replacePlan(e,t){return await this.client.PUT("/api/plans/{id}",{params:{path:{id:e}},body:t})}async updatePlan(e,t){return await this.client.PATCH("/api/plans/{id}",{params:{path:{id:e}},body:t})}async getPlanVideoUrl(e){return await this.client.GET("/api/plans/{id}/video-url",{params:{path:{id:e}}})}async getPlanVideoMetadata(e){return await this.client.GET("/api/plans/{id}/video-metadata",{params:{path:{id:e}}})}async deletePlan(e){return await this.client.DELETE("/api/admin/plans/{id}",{params:{path:{id:e}}})}async publishPlanRevision(e,t){return await this.client.POST("/api/plans/{id}/publish",{params:{path:{id:e}},body:t})}async listPlanRevisions(e){return await this.client.GET("/api/plans/{id}/revisions",{params:{path:{id:e}}})}async listPlanKnowledgeBlocks(e){return await this.client.GET("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createPlanKnowledgeBlock(e,t){return await this.client.POST("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async updatePlanKnowledgeBlock(e,t,r){return await this.client.PUT("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deletePlanKnowledgeBlock(e,t){return await this.client.DELETE("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async getPlanNavigationIndex(e){return await this.client.GET("/api/plans/{id}/navigation-index",{params:{path:{id:e}}})}async replacePlanNavigationIndex(e,t){return await this.client.POST("/api/plans/{id}/navigation-index",{params:{path:{id:e}},body:t})}async getRevisionNavigationIndex(e){return await this.client.GET("/api/revisions/{id}/navigation-index",{params:{path:{id:e}}})}async replaceRevisionNavigationIndex(e,t){return await this.client.PUT("/api/revisions/{id}/navigation-index",{params:{path:{id:e}},body:t})}async getPlanFAQ(e){return await this.client.GET("/api/plans/{id}/faq",{params:{path:{id:e}}})}async getRevisionFAQ(e){return await this.client.GET("/api/revisions/{id}/faq",{params:{path:{id:e}}})}async replaceRevisionFAQ(e,t){return await this.client.PUT("/api/revisions/{id}/faq",{params:{path:{id:e}},body:t})}async listRevisionKnowledgeBlocks(e){return await this.client.GET("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}}})}async getRevisionSteps(e){return await this.client.GET("/api/revisions/{id}/steps",{params:{path:{id:e}}})}async replaceRevisionKnowledgeBlocks(e,t){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async createRevisionKnowledgeBlock(e,t){return await this.client.POST("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async updateRevisionKnowledgeBlock(e,t,r){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deleteRevisionKnowledgeBlock(e,t){return await this.client.DELETE("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async listSessions(e,t){const r={token:e};return t!=null&&t.productId&&(r.product_id=t.productId),t!=null&&t.startDate&&(r.start_date=t.startDate),t!=null&&t.endDate&&(r.end_date=t.endDate),await this.client.GET("/api/sessions",{params:{query:r}})}async createSession(e){return await this.client.POST("/api/sessions",{body:e})}async getSession(e){return await this.client.GET("/api/sessions/{id}",{params:{path:{id:e}}})}async startSession(e,t){return await this.client.GET("/api/sessions/{id}/start-session",{params:{path:{id:e},query:{token:t}}})}async getSessionRecording(e){return await this.client.GET("/api/sessions/{id}/recording",{params:{path:{id:e}}})}async getSessionSummary(e){return await this.client.GET("/api/sessions/{id}/summary",{params:{path:{id:e}}})}async getSessionProductUrl(e){return await this.client.GET("/api/sessions/{id}/product-url",{params:{path:{id:e}}})}async updateSession(e,t){return await this.client.PATCH("/api/sessions/{id}",{params:{path:{id:e}},body:t})}async listUserSessions(e){const t={};return e!=null&&e.productId&&(t.product_id=e.productId),e!=null&&e.courseId&&(t.course_id=e.courseId),e!=null&&e.startDate&&(t.start_date=e.startDate),e!=null&&e.endDate&&(t.end_date=e.endDate),e!=null&&e.page&&(t.page=e.page),e!=null&&e.limit&&(t.limit=e.limit),e!=null&&e.courseName&&(t.course_name=e.courseName),e!=null&&e.userName&&(t.user_name=e.userName),e!=null&&e.company&&(t.company=e.company),e!=null&&e.email&&(t.email=e.email),e!=null&&e.sortBy&&(t.sort_by=e.sortBy),e!=null&&e.sortOrder&&(t.sort_order=e.sortOrder),await this.client.GET("/api/user-sessions",{params:Object.keys(t).length>0?{query:t}:void 0})}async listUserSessionsAggregate(e){const t={};return e!=null&&e.productId&&(t.product_id=e.productId),e!=null&&e.courseId&&(t.course_id=e.courseId),e!=null&&e.startDate&&(t.start_date=e.startDate),e!=null&&e.endDate&&(t.end_date=e.endDate),await this.client.GET("/api/user-sessions-aggregate",{params:Object.keys(t).length>0?{query:t}:void 0})}async getJoinToken(e,{clientType:t,user:r}={}){return await this.client.GET("/api/join-token",{params:{query:{token:e,...t&&{client_type:t},...r&&{user:encodeURIComponent(r)}}}})}async getSessionPlan(e){return await this.client.GET("/api/sessions/{id}/plan",{params:{path:{id:e}}})}getClient(){return this.client}}const V0="https://app.coragents.ai";class pa extends jc{constructor(e,t,r,i){super(),this.state=null,this.isPaused=!1,this.speakingState=null,this.captureScreen=null,this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.room=null,this.agentAnalyser=null,this.userAnalyser=null,this.appToken=e,this.planId=t,this.clientType=r,this.api=i.api||new K0({baseUrl:V0}),this.identity=i.identity||null,this.roomFactory=i.roomFactory||(A=>new Li(A)),this.captureScreen=i.captureScreen||null}async start(){this.planId,this.setState("connecting"),this.speakingStateChanged("thinking");try{const t=(await this.api.clientStartSession(this.appToken,{client_type:this.clientType,onboarding_plan:this.planId})).data;if(!(t!=null&&t.url)||!(t!=null&&t.token)||!(t!=null&&t.room)||!(t!=null&&t.session_uuid))throw new Error("Invalid room info");this.sessionUuid=t==null?void 0:t.session_uuid,this.roomId=t==null?void 0:t.room,this.joinToken=t==null?void 0:t.token,this.roomUrl=t==null?void 0:t.url,await this.joinRoom(),this.setState("connected"),this.planId,this.sessionUuid}catch(e){console.error("[obi] error starting session",{error:e}),this.setState("error")}}async joinRoom({withMicrophone:e=!1,withStateRecovery:t=!1}={}){this.room=this.roomFactory({adaptiveStream:!0,dynacast:!0}),this.room.on(O.Disconnected,r=>{if(!this.room)return;let i=null;switch(r){case 12:i="invalid-room";break}this.shutdown(i)}),this.room.on(O.TrackSubscribed,r=>{r.kind==="audio"&&(r.attach(),r.source===R.Source.Microphone&&(this.agentAnalyser&&this.agentAnalyser.disconnect(),this.agentAnalyser=this.createFFT(r.mediaStream)))}),this.room.on(O.LocalTrackPublished,r=>{r.kind==="audio"&&(this.userAnalyser&&this.userAnalyser.disconnect(),this.userAnalyser=this.createFFT(r.audioTrack.mediaStream))}),this.room.on(O.ParticipantAttributesChanged,r=>{if(!r["lk.agent.state"])return;const i=r["lk.agent.state"];switch(i){case"speaking":this.speakingStateChanged("speaking");break;case"listening":this.state!=="connected"&&this.speakingStateChanged("listening");break;case"thinking":this.speakingStateChanged("thinking");break;default:console.warn("[obi] unknown speaking state",i)}}),this.room.on(O.DataReceived,async r=>{try{const i=new TextDecoder().decode(r),A=JSON.parse(i);switch(A.status||A.request||A.type){case"course_progress":typeof A.current_step=="number"&&typeof A.total_steps=="number"&&Array.isArray(A.step_names)&&this.emit("courseProgress",{currentStep:Math.max(1,A.current_step),totalSteps:Math.max(1,A.total_steps),stepNames:A.step_names});break;case"using_tool":this.speakingStateChanged("busy");break;case"using_tool_ended":this.speakingStateChanged("speaking");break;case"prompt_user":this.setState("volume-check");break;case"mic_check":this.setState("mic-check");break;case"share_mic":this.setState("mic-share");break;case"share_screen":this.setState("screen-share");break;case"navigate":this.setState("navigate");break;default:console.warn("[obi] unknown data received",A)}}catch(i){console.error("[obi] error parsing data",i)}}),this.room.localParticipant.registerRpcMethod("mic_check",async r=>(this.sessionUuid,await this.checkMicrophone()?"ok":"error")),this.room.localParticipant.registerRpcMethod("screen_capture",async r=>{if(!this.captureScreen)return console.error("[obi] no captureScreen function provided"),"error";let i=null,A=null;try{i=await this.captureScreen()}catch(s){i=null,s=s}if(!i||A)return console.error("[obi] error capturing screen",{error:A}),"error";try{return await this.room.localParticipant.sendFile(new File([i],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),"ok"}catch(s){return console.error("[obi] error sending screen capture",{error:s}),"error"}}),await this.room.connect(this.roomUrl,this.joinToken);for(let r=0;r<9&&!(this.room.state===fe.Connected&&this.room.remoteParticipants.size>=1);r++)await new Promise(i=>setTimeout(i,1e3));if(!(this.room.state===fe.Connected&&this.room.remoteParticipants.size>=1)){console.error("[obi] room not connected",{state:this.room.state,numParticipants:this.room.remoteParticipants.size}),this.shutdown("invalid-room");return}if(e&&await this.room.localParticipant.setMicrophoneEnabled(!0),t){let r=!1;for(const i of this.room.remoteParticipants.values())i.isSpeaking&&(r=!0);r?this.speakingState="speaking":this.speakingState="listening"}}async continue(){this.sessionUuid,this.speakingStateChanged("thinking"),await this.sendData({request:"prompt_user",success:!0})}async checkMicrophone(){let e=!1;try{e=(await navigator.permissions.query({name:"microphone"})).state==="granted"}catch(t){console.error("[obi] error checking microphone permission:",t)}return e?(this.sessionUuid,await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0):this.sessionUuid,e&&this.clientType==="sdk"&&this.setState("in-progress"),this.emit("micCheckComplete",e),e}async shareMicrophone(){this.sessionUuid,this.speakingStateChanged("thinking");let e=null,t=null;try{e=await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0}catch(r){r=r,this.isMicShared=!1}e?this.sessionUuid:console.error("[obi] failed to share microphone",{error:t}),await this.sendData({request:"share_mic",success:!!e}),this.clientType==="sdk"&&this.setState("in-progress")}async shareMicrophoneFailed(){this.isMicShared=!1,await this.sendData({request:"share_mic",success:!1}),this.clientType==="sdk"&&this.setState("in-progress")}async shareScreen(){this.sessionUuid,this.speakingStateChanged("thinking"),await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),await this.sendData({request:"share_screen",success:!0}),this.setState("navigate")}async pause(){this.muteMicrophone(),this.isPaused=!0,this.emit("paused"),await this.sendData({request:"pause"}),console.log("[obi] paused session",{sessionUuid:this.sessionUuid})}async unpause(){this.unmuteMicrophone(),this.isPaused=!1,this.emit("unpaused"),await this.sendData({request:"unpause"}),console.log("[obi] unpaused session",{sessionUuid:this.sessionUuid})}muteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var t,r;e.handleMuted(),(r=(t=e.track)==null?void 0:t.mediaStream)==null||r.getTracks().forEach(i=>i.enabled=!1)})}unmuteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var t,r;e.handleUnmuted(),(r=(t=e.track)==null?void 0:t.mediaStream)==null||r.getTracks().forEach(i=>i.enabled=!0)})}async stop(){this.emit("stopped"),await this.shutdown()}async shutdown(e=null){if(this.room){this.sessionUuid;const t=this.room;this.room=null,await t.disconnect(),this.sessionUuid}this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.emit("shutdown",e)}async say(e){this.speakingStateChanged("thinking"),this.isPaused&&await this.unpause(),await this.sendData({request:"say",message:e})}serialise(){return JSON.stringify({state:this.state,speakingState:this.speakingState,appToken:this.appToken,planId:this.planId,clientType:this.clientType,isPaused:this.isPaused,identity:this.identity,sessionUuid:this.sessionUuid,roomId:this.roomId,joinToken:this.joinToken,roomUrl:this.roomUrl})}audioSpectrum(){return this.speakingState==="speaking"&&this.agentAnalyser?this.normaliseSpectrum(this.agentAnalyser):this.speakingState==="listening"&&this.userAnalyser?this.normaliseSpectrum(this.userAnalyser):null}normaliseSpectrum(e){const r=e.context.sampleRate/2/e.frequencyBinCount,i=new Uint8Array(e.frequencyBinCount);e.getByteFrequencyData(i);const A=[],s=50,o=5e3,a=8,c=Math.pow(o/s,1/a);for(let u=0;u<a;u++){const l=s*Math.pow(c,u),d=s*Math.pow(c,u+1),h=Math.floor(l/r),f=Math.floor(d/r),p=Math.min(f,i.length),g=Math.min(h,p);if(g<p){const v=i.slice(g,p).reduce((y,B)=>y+B,0)/(p-g)/255;A.push(v)}else A.push(0)}return A}setState(e){this.state;const t=this.state;this.state=e,this.emit("stateChanged",e,t)}static deserialise(e,t,r,i={}){const A=JSON.parse(e),s=new pa(t,A.planId,r,i);return s.state=A.state,s.speakingState=A.speakingState,s.identity=A.identity||null,s.isPaused=A.isPaused||!1,s.sessionUuid=A.sessionUuid||null,s.roomId=A.roomId||null,s.joinToken=A.joinToken||null,s.roomUrl=A.roomUrl||null,s}speakingStateChanged(e){this.speakingState;const t=this.speakingState;this.speakingState=e,this.emit("speakingStateChanged",e,t)}async sendData(e){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0})}createFFT(e){const t=new AudioContext,r=t.createAnalyser();return t.createMediaStreamSource(e).connect(r),r.fftSize=2048,r.smoothingTimeConstant=.6,r}}class fa extends jc{constructor(e,t,r={}){super(),this.state="loading",this.error=null,this.identity=null,this.product=null,this.plans=[],this.planIsCompleted=[],this.selectedPlan=null,this.selectedPlanUuid=null,this.showWidget=!1,this.session=null,this.captureScreen=null,this.appToken=e,this.clientType=t,this.api=r.api||new K0({baseUrl:r.apiBaseUrl||V0}),this.sessionFactory=r.sessionFactory||((i,A,s,o)=>new pa(i,A,s,o)),this.captureScreen=r.captureScreen||null}async initialise(e={}){var t,r,i,A,s;if(!this.appToken)throw new Error("App token is required");this.setState("loading");try{const o=await this.api.clientInitialise(this.appToken,{identity:e.identity,client_type:this.clientType});if(this.identity=e.identity||null,this.product=((t=o.data)==null?void 0:t.product)||null,this.plans=((r=o.data)==null?void 0:r.onboarding_plans)||[],this.selectedPlan=((i=o.data)==null?void 0:i.selected_plan)||null,this.planIsCompleted=((A=o.data)==null?void 0:A.plan_is_completed)||[],this.showWidget=((s=o.data)==null?void 0:s.show_widget)||!1,e.planUuid){let a=this.plans.find(c=>c.uuid===e.planUuid)||null;if(!a)try{const c=await this.api.getSessionPlan(e.planUuid);a=this.plans.find(u=>{var l;return u.uuid===((l=c.data)==null?void 0:l.plan_uuid)})||null}catch(c){console.error("[obi] error getting session plan",c)}a?(this.selectedPlan=a,this.selectedPlanUuid=e.planUuid):console.warn("[obi] plan not found",{planUuid:e.planUuid})}this.identity,this.product,this.plans,this.selectedPlan,this.showWidget}catch(o){throw this.error=o instanceof Error?o:new Error(String(o)),this.setState("error"),o}finally{this.setState("ready")}}selectPlan(e){this.selectedPlan=e,this.selectedPlanUuid=(e==null?void 0:e.uuid)||null,this.emit("planSelected",e)}async startSession(e,t){return await this._stopSession(),this.session=this.sessionFactory(this.appToken,e,this.clientType,{api:this.api,identity:this.identity,captureScreen:this.captureScreen}),this.prepareSession(t),this.session.start().then(()=>{this.emit("sessionStarted",this.session)}).catch(r=>{this.session=null,console.error("[obi] error starting session",r)}),this.session}async resumeSession(e){var t,r;return this.state,(t=this.session)==null||t.state,(r=this.session)==null||r.speakingState,this.session.captureScreen=this.captureScreen,this.prepareSession(e),this.session.joinRoom({withMicrophone:!0,withStateRecovery:!0}).then(()=>{this.emit("sessionResumed",this.session)}).catch(i=>{console.error("[obi] error joining room",{error:i}),i instanceof Error&&i.message==="Room is not connected"&&this.session.stop()}),this.session}prepareSession(e){if(!this.session)throw new Error("No session to prepare");return e(this.session),this.session.on("stopped",()=>{this.emit("sessionStopped")}),this.session.on("shutdown",t=>{var r,i;(i=(r=this.session)==null?void 0:r.removeAllListeners)==null||i.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,plans:this.plans,selectedPlan:this.selectedPlan,selectedPlanUuid:this.selectedPlanUuid,showWidget:this.showWidget,session:(e=this.session)==null?void 0:e.serialise(),serialisedAt:new Date().toISOString()})}static deserialise(e,t,r,i={}){const A=JSON.parse(e);if(A.serialisedAt){const o=new Date(A.serialisedAt);if(new Date().getTime()-o.getTime()>1e3*20)throw new Error("Client was serialised more than 20 seconds ago, assuming it's dead.")}else throw new Error("Client was not serialised, assuming it's dead.");const s=new fa(t,r,i);return s.state=A.state,s.identity=A.identity||null,s.product=A.product||null,s.plans=A.plans||[],s.selectedPlan=A.selectedPlan||null,s.selectedPlanUuid=A.selectedPlanUuid||null,s.showWidget=A.showWidget||!1,A.session&&(s.session=pa.deserialise(A.session,t,r,{api:s.api})),s}setState(e){const t=this.state;this.state=e,this.emit("stateChanged",e,t)}trackEvent(e,t={}){var r,i,A;this.emit("trackEvent",e,{...t,clientType:this.clientType,planId:(r=this.selectedPlan)==null?void 0:r.uuid,productId:(i=this.product)==null?void 0:i.uuid,sessionId:(A=this.session)==null?void 0:A.sessionUuid})}}var ga,ee,G0,zr,j0,W0,q0,J0,ud,ld,dd,z0,WA={},X0=[],dQ=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,qA=Array.isArray;function Kn(n,e){for(var t in e)n[t]=e[t];return n}function hd(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function pd(n,e,t){var r,i,A,s={};for(A in e)A=="key"?r=e[A]:A=="ref"?i=e[A]:s[A]=e[A];if(arguments.length>2&&(s.children=arguments.length>3?ga.call(arguments,2):t),typeof n=="function"&&n.defaultProps!=null)for(A in n.defaultProps)s[A]==null&&(s[A]=n.defaultProps[A]);return ma(n,s,r,i,null)}function ma(n,e,t,r,i){var A={type:n,props:e,key:t,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++G0,__i:-1,__u:0};return i==null&&ee.vnode!=null&&ee.vnode(A),A}function St(n){return n.children}function Vn(n,e){this.props=n,this.context=e}function Di(n,e){if(e==null)return n.__?Di(n.__,n.__i+1):null;for(var t;e<n.__k.length;e++)if((t=n.__k[e])!=null&&t.__e!=null)return t.__e;return typeof n.type=="function"?Di(n):null}function Y0(n){var e,t;if((n=n.__)!=null&&n.__c!=null){for(n.__e=n.__c.base=null,e=0;e<n.__k.length;e++)if((t=n.__k[e])!=null&&t.__e!=null){n.__e=n.__c.base=t.__e;break}return Y0(n)}}function fd(n){(!n.__d&&(n.__d=!0)&&zr.push(n)&&!va.__r++||j0!=ee.debounceRendering)&&((j0=ee.debounceRendering)||W0)(va)}function va(){for(var n,e,t,r,i,A,s,o=1;zr.length;)zr.length>o&&zr.sort(q0),n=zr.shift(),o=zr.length,n.__d&&(t=void 0,i=(r=(e=n).__v).__e,A=[],s=[],e.__P&&((t=Kn({},r)).__v=r.__v+1,ee.vnode&&ee.vnode(t),gd(e.__P,t,r,e.__n,e.__P.namespaceURI,32&r.__u?[i]:null,A,i??Di(r),!!(32&r.__u),s),t.__v=r.__v,t.__.__k[t.__i]=t,ny(A,t,s),t.__e!=i&&Y0(t)));va.__r=0}function Z0(n,e,t,r,i,A,s,o,a,c,u){var l,d,h,f,p,g,v=r&&r.__k||X0,y=e.length;for(a=hQ(t,e,v,a,y),l=0;l<y;l++)(h=t.__k[l])!=null&&(d=h.__i==-1?WA:v[h.__i]||WA,h.__i=l,g=gd(n,h,d,i,A,s,o,a,c,u),f=h.__e,h.ref&&d.ref!=h.ref&&(d.ref&&md(d.ref,null,h),u.push(h.ref,h.__c||f,h)),p==null&&f!=null&&(p=f),4&h.__u||d.__k===h.__k?a=$0(h,a,n):typeof h.type=="function"&&g!==void 0?a=g:f&&(a=f.nextSibling),h.__u&=-7);return t.__e=p,a}function hQ(n,e,t,r,i){var A,s,o,a,c,u=t.length,l=u,d=0;for(n.__k=new Array(i),A=0;A<i;A++)(s=e[A])!=null&&typeof s!="boolean"&&typeof s!="function"?(a=A+d,(s=n.__k[A]=typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?ma(null,s,null,null,null):qA(s)?ma(St,{children:s},null,null,null):s.constructor==null&&s.__b>0?ma(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):s).__=n,s.__b=n.__b+1,o=null,(c=s.__i=pQ(s,t,a,l))!=-1&&(l--,(o=t[c])&&(o.__u|=2)),o==null||o.__v==null?(c==-1&&(i>u?d--:i<u&&d++),typeof s.type!="function"&&(s.__u|=4)):c!=a&&(c==a-1?d--:c==a+1?d++:(c>a?d--:d++,s.__u|=4))):n.__k[A]=null;if(l)for(A=0;A<u;A++)(o=t[A])!=null&&!(2&o.__u)&&(o.__e==r&&(r=Di(o)),iy(o,o));return r}function $0(n,e,t){var r,i;if(typeof n.type=="function"){for(r=n.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=n,e=$0(r[i],e,t));return e}n.__e!=e&&(e&&n.type&&!t.contains(e)&&(e=Di(n)),t.insertBefore(n.__e,e||null),e=n.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ya(n,e){return e=e||[],n==null||typeof n=="boolean"||(qA(n)?n.some(function(t){ya(t,e)}):e.push(n)),e}function pQ(n,e,t,r){var i,A,s=n.key,o=n.type,a=e[t];if(a===null&&n.key==null||a&&s==a.key&&o==a.type&&!(2&a.__u))return t;if(r>(a!=null&&!(2&a.__u)?1:0))for(i=t-1,A=t+1;i>=0||A<e.length;){if(i>=0){if((a=e[i])&&!(2&a.__u)&&s==a.key&&o==a.type)return i;i--}if(A<e.length){if((a=e[A])&&!(2&a.__u)&&s==a.key&&o==a.type)return A;A++}}return-1}function ey(n,e,t){e[0]=="-"?n.setProperty(e,t??""):n[e]=t==null?"":typeof t!="number"||dQ.test(e)?t:t+"px"}function wa(n,e,t,r,i){var A;e:if(e=="style")if(typeof t=="string")n.style.cssText=t;else{if(typeof r=="string"&&(n.style.cssText=r=""),r)for(e in r)t&&e in t||ey(n.style,e,"");if(t)for(e in t)r&&t[e]==r[e]||ey(n.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")A=e!=(e=e.replace(J0,"$1")),e=e.toLowerCase()in n||e=="onFocusOut"||e=="onFocusIn"?e.toLowerCase().slice(2):e.slice(2),n.l||(n.l={}),n.l[e+A]=t,t?r?t.u=r.u:(t.u=ud,n.addEventListener(e,A?dd:ld,A)):n.removeEventListener(e,A?dd:ld,A);else{if(i=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in n)try{n[e]=t??"";break e}catch{}typeof t=="function"||(t==null||t===!1&&e[4]!="-"?n.removeAttribute(e):n.setAttribute(e,e=="popover"&&t==1?"":t))}}function ty(n){return function(e){if(this.l){var t=this.l[e.type+n];if(e.t==null)e.t=ud++;else if(e.t<t.u)return;return t(ee.event?ee.event(e):e)}}}function gd(n,e,t,r,i,A,s,o,a,c){var u,l,d,h,f,p,g,v,y,B,b,w,_,k,T,x,P,E=e.type;if(e.constructor!=null)return null;128&t.__u&&(a=!!(32&t.__u),A=[o=e.__e=t.__e]),(u=ee.__b)&&u(e);e:if(typeof E=="function")try{if(v=e.props,y="prototype"in E&&E.prototype.render,B=(u=E.contextType)&&r[u.__c],b=u?B?B.props.value:u.__:r,t.__c?g=(l=e.__c=t.__c).__=l.__E:(y?e.__c=l=new E(v,b):(e.__c=l=new Vn(v,b),l.constructor=E,l.render=gQ),B&&B.sub(l),l.props=v,l.state||(l.state={}),l.context=b,l.__n=r,d=l.__d=!0,l.__h=[],l._sb=[]),y&&l.__s==null&&(l.__s=l.state),y&&E.getDerivedStateFromProps!=null&&(l.__s==l.state&&(l.__s=Kn({},l.__s)),Kn(l.__s,E.getDerivedStateFromProps(v,l.__s))),h=l.props,f=l.state,l.__v=e,d)y&&E.getDerivedStateFromProps==null&&l.componentWillMount!=null&&l.componentWillMount(),y&&l.componentDidMount!=null&&l.__h.push(l.componentDidMount);else{if(y&&E.getDerivedStateFromProps==null&&v!==h&&l.componentWillReceiveProps!=null&&l.componentWillReceiveProps(v,b),!l.__e&&l.shouldComponentUpdate!=null&&l.shouldComponentUpdate(v,l.__s,b)===!1||e.__v==t.__v){for(e.__v!=t.__v&&(l.props=v,l.state=l.__s,l.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.some(function(F){F&&(F.__=e)}),w=0;w<l._sb.length;w++)l.__h.push(l._sb[w]);l._sb=[],l.__h.length&&s.push(l);break e}l.componentWillUpdate!=null&&l.componentWillUpdate(v,l.__s,b),y&&l.componentDidUpdate!=null&&l.__h.push(function(){l.componentDidUpdate(h,f,p)})}if(l.context=b,l.props=v,l.__P=n,l.__e=!1,_=ee.__r,k=0,y){for(l.state=l.__s,l.__d=!1,_&&_(e),u=l.render(l.props,l.state,l.context),T=0;T<l._sb.length;T++)l.__h.push(l._sb[T]);l._sb=[]}else do l.__d=!1,_&&_(e),u=l.render(l.props,l.state,l.context),l.state=l.__s;while(l.__d&&++k<25);l.state=l.__s,l.getChildContext!=null&&(r=Kn(Kn({},r),l.getChildContext())),y&&!d&&l.getSnapshotBeforeUpdate!=null&&(p=l.getSnapshotBeforeUpdate(h,f)),x=u,u!=null&&u.type===St&&u.key==null&&(x=ry(u.props.children)),o=Z0(n,qA(x)?x:[x],e,t,r,i,A,s,o,a,c),l.base=e.__e,e.__u&=-161,l.__h.length&&s.push(l),g&&(l.__E=l.__=null)}catch(F){if(e.__v=null,a||A!=null)if(F.then){for(e.__u|=a?160:128;o&&o.nodeType==8&&o.nextSibling;)o=o.nextSibling;A[A.indexOf(o)]=null,e.__e=o}else for(P=A.length;P--;)hd(A[P]);else e.__e=t.__e,e.__k=t.__k;ee.__e(F,e,t)}else A==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):o=e.__e=fQ(t.__e,e,t,r,i,A,s,a,c);return(u=ee.diffed)&&u(e),128&e.__u?void 0:o}function ny(n,e,t){for(var r=0;r<t.length;r++)md(t[r],t[++r],t[++r]);ee.__c&&ee.__c(e,n),n.some(function(i){try{n=i.__h,i.__h=[],n.some(function(A){A.call(i)})}catch(A){ee.__e(A,i.__v)}})}function ry(n){return typeof n!="object"||n==null||n.__b&&n.__b>0?n:qA(n)?n.map(ry):Kn({},n)}function fQ(n,e,t,r,i,A,s,o,a){var c,u,l,d,h,f,p,g=t.props,v=e.props,y=e.type;if(y=="svg"?i="http://www.w3.org/2000/svg":y=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),A!=null){for(c=0;c<A.length;c++)if((h=A[c])&&"setAttribute"in h==!!y&&(y?h.localName==y:h.nodeType==3)){n=h,A[c]=null;break}}if(n==null){if(y==null)return document.createTextNode(v);n=document.createElementNS(i,y,v.is&&v),o&&(ee.__m&&ee.__m(e,A),o=!1),A=null}if(y==null)g===v||o&&n.data==v||(n.data=v);else{if(A=A&&ga.call(n.childNodes),g=t.props||WA,!o&&A!=null)for(g={},c=0;c<n.attributes.length;c++)g[(h=n.attributes[c]).name]=h.value;for(c in g)if(h=g[c],c!="children"){if(c=="dangerouslySetInnerHTML")l=h;else if(!(c in v)){if(c=="value"&&"defaultValue"in v||c=="checked"&&"defaultChecked"in v)continue;wa(n,c,null,h,i)}}for(c in v)h=v[c],c=="children"?d=h:c=="dangerouslySetInnerHTML"?u=h:c=="value"?f=h:c=="checked"?p=h:o&&typeof h!="function"||g[c]===h||wa(n,c,h,g[c],i);if(u)o||l&&(u.__html==l.__html||u.__html==n.innerHTML)||(n.innerHTML=u.__html),e.__k=[];else if(l&&(n.innerHTML=""),Z0(e.type=="template"?n.content:n,qA(d)?d:[d],e,t,r,y=="foreignObject"?"http://www.w3.org/1999/xhtml":i,A,s,A?A[0]:t.__k&&Di(t,0),o,a),A!=null)for(c=A.length;c--;)hd(A[c]);o||(c="value",y=="progress"&&f==null?n.removeAttribute("value"):f!=null&&(f!==n[c]||y=="progress"&&!f||y=="option"&&f!=g[c])&&wa(n,c,f,g[c],i),c="checked",p!=null&&p!=n[c]&&wa(n,c,p,g[c],i))}return n}function md(n,e,t){try{if(typeof n=="function"){var r=typeof n.__u=="function";r&&n.__u(),r&&e==null||(n.__u=n(e))}else n.current=e}catch(i){ee.__e(i,t)}}function iy(n,e,t){var r,i;if(ee.unmount&&ee.unmount(n),(r=n.ref)&&(r.current&&r.current!=n.__e||md(r,null,e)),(r=n.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(A){ee.__e(A,e)}r.base=r.__P=null}if(r=n.__k)for(i=0;i<r.length;i++)r[i]&&iy(r[i],e,t||typeof n.type!="function");t||hd(n.__e),n.__c=n.__=n.__e=void 0}function gQ(n,e,t){return this.constructor(n,t)}function mQ(n,e,t){var r,i,A,s;e==document&&(e=document.documentElement),ee.__&&ee.__(n,e),i=(r=typeof t=="function")?null:t&&t.__k||e.__k,A=[],s=[],gd(e,n=(!r&&t||e).__k=pd(St,null,[n]),i||WA,WA,e.namespaceURI,!r&&t?[t]:i?null:e.firstChild?ga.call(e.childNodes):null,A,!r&&t?t:i?i.__e:e.firstChild,r,s),ny(A,n,s)}function Ay(n){function e(t){var r,i;return this.getChildContext||(r=new Set,(i={})[e.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(A){this.props.value!=A.value&&r.forEach(function(s){s.__e=!0,fd(s)})},this.sub=function(A){r.add(A);var s=A.componentWillUnmount;A.componentWillUnmount=function(){r&&r.delete(A),s&&s.call(A)}}),t.children}return e.__c="__cC"+z0++,e.__=n,e.Provider=e.__l=(e.Consumer=function(t,r){return t.children(r)}).contextType=e,e}ga=X0.slice,ee={__e:function(n,e,t,r){for(var i,A,s;e=e.__;)if((i=e.__c)&&!i.__)try{if((A=i.constructor)&&A.getDerivedStateFromError!=null&&(i.setState(A.getDerivedStateFromError(n)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(n,r||{}),s=i.__d),s)return i.__E=i}catch(o){n=o}throw n}},G0=0,Vn.prototype.setState=function(n,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Kn({},this.state),typeof n=="function"&&(n=n(Kn({},t),this.props)),n&&Kn(t,n),n!=null&&this.__v&&(e&&this._sb.push(e),fd(this))},Vn.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),fd(this))},Vn.prototype.render=St,zr=[],W0=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,q0=function(n,e){return n.__v.__b-e.__v.__b},va.__r=0,J0=/(PointerCapture)$|Capture$/i,ud=0,ld=ty(!1),dd=ty(!0),z0=0;var vQ=0;function C(n,e,t,r,i,A){e||(e={});var s,o,a=e;if("ref"in a)for(o in a={},e)o=="ref"?s=e[o]:a[o]=e[o];var c={type:n,props:a,key:t,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--vQ,__i:-1,__u:0,__source:i,__self:A};if(typeof n=="function"&&(s=n.defaultProps))for(o in s)a[o]===void 0&&(a[o]=s[o]);return ee.vnode&&ee.vnode(c),c}var Xr,Ve,vd,sy,JA=0,oy=[],it=ee,ay=it.__b,cy=it.__r,uy=it.diffed,ly=it.__c,dy=it.unmount,hy=it.__;function zA(n,e){it.__h&&it.__h(Ve,n,JA||e),JA=0;var t=Ve.__H||(Ve.__H={__:[],__h:[]});return n>=t.__.length&&t.__.push({}),t.__[n]}function ge(n){return JA=1,yQ(gy,n)}function yQ(n,e,t){var r=zA(Xr++,2);if(r.t=n,!r.__c&&(r.__=[t?t(e):gy(void 0,e),function(o){var a=r.__N?r.__N[0]:r.__[0],c=r.t(a,o);a!==c&&(r.__N=[c,r.__[1]],r.__c.setState({}))}],r.__c=Ve,!Ve.__f)){var i=function(o,a,c){if(!r.__c.__H)return!0;var u=r.__c.__H.__.filter(function(d){return!!d.__c});if(u.every(function(d){return!d.__N}))return!A||A.call(this,o,a,c);var l=r.__c.props!==o;return u.forEach(function(d){if(d.__N){var h=d.__[0];d.__=d.__N,d.__N=void 0,h!==d.__[0]&&(l=!0)}}),A&&A.call(this,o,a,c)||l};Ve.__f=!0;var A=Ve.shouldComponentUpdate,s=Ve.componentWillUpdate;Ve.componentWillUpdate=function(o,a,c){if(this.__e){var u=A;A=void 0,i(o,a,c),A=u}s&&s.call(this,o,a,c)},Ve.shouldComponentUpdate=i}return r.__N||r.__}function Kt(n,e){var t=zA(Xr++,3);!it.__s&&Bd(t.__H,e)&&(t.__=n,t.u=e,Ve.__H.__h.push(t))}function yd(n,e){var t=zA(Xr++,4);!it.__s&&Bd(t.__H,e)&&(t.__=n,t.u=e,Ve.__h.push(t))}function En(n){return JA=5,wd(function(){return{current:n}},[])}function wd(n,e){var t=zA(Xr++,7);return Bd(t.__H,e)&&(t.__=n(),t.__H=e,t.__h=n),t.__}function wQ(n,e){return JA=8,wd(function(){return n},e)}function py(n){var e=Ve.context[n.__c],t=zA(Xr++,9);return t.c=n,e?(t.__==null&&(t.__=!0,e.sub(Ve)),e.props.value):n.__}function bQ(){for(var n;n=oy.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(ba),n.__H.__h.forEach(bd),n.__H.__h=[]}catch(e){n.__H.__h=[],it.__e(e,n.__v)}}it.__b=function(n){Ve=null,ay&&ay(n)},it.__=function(n,e){n&&e.__k&&e.__k.__m&&(n.__m=e.__k.__m),hy&&hy(n,e)},it.__r=function(n){cy&&cy(n),Xr=0;var e=(Ve=n.__c).__H;e&&(vd===Ve?(e.__h=[],Ve.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.forEach(ba),e.__h.forEach(bd),e.__h=[],Xr=0)),vd=Ve},it.diffed=function(n){uy&&uy(n);var e=n.__c;e&&e.__H&&(e.__H.__h.length&&(oy.push(e)!==1&&sy===it.requestAnimationFrame||((sy=it.requestAnimationFrame)||BQ)(bQ)),e.__H.__.forEach(function(t){t.u&&(t.__H=t.u),t.u=void 0})),vd=Ve=null},it.__c=function(n,e){e.some(function(t){try{t.__h.forEach(ba),t.__h=t.__h.filter(function(r){return!r.__||bd(r)})}catch(r){e.some(function(i){i.__h&&(i.__h=[])}),e=[],it.__e(r,t.__v)}}),ly&&ly(n,e)},it.unmount=function(n){dy&&dy(n);var e,t=n.__c;t&&t.__H&&(t.__H.__.forEach(function(r){try{ba(r)}catch(i){e=i}}),t.__H=void 0,e&&it.__e(e,t.__v))};var fy=typeof requestAnimationFrame=="function";function BQ(n){var e,t=function(){clearTimeout(r),fy&&cancelAnimationFrame(e),setTimeout(n)},r=setTimeout(t,100);fy&&(e=requestAnimationFrame(t))}function ba(n){var e=Ve,t=n.__c;typeof t=="function"&&(n.__c=void 0,t()),Ve=e}function bd(n){var e=Ve;n.__c=n.__(),Ve=e}function Bd(n,e){return!n||n.length!==e.length||e.some(function(t,r){return t!==n[r]})}function gy(n,e){return typeof e=="function"?e(n):e}function CQ({size:n=24,color:e="#000"}){return C("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:e,"stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"lucide lucide-x-icon lucide-x",children:[C("path",{d:"M18 6 6 18"}),C("path",{d:"m6 6 12 12"})]})}function my({onClose:n}){return C("button",{class:"obi-button obi-close-button",onClick:n,"aria-label":"Close",type:"button",children:C(CQ,{})})}function vy({open:n=!1,children:e,onClose:t,size:r="medium"}){const i=En(null),A=En(null);Kt(()=>{const c=i.current;c&&(n&&!c.open?c.showModal():!n&&c.open&&(A.current="programmatic",c.close()))},[n]);const s=c=>{const u=i.current;c.target===u&&(A.current="user-initiated",u==null||u.close())},o=c=>{c.preventDefault(),A.current||(A.current="user-initiated");const u=A.current;A.current=null,t==null||t(u)},a=()=>{var c;A.current="user-initiated",(c=i.current)==null||c.close()};return Kt(()=>{const c=i.current;if(c)return c.addEventListener("click",s),c.addEventListener("close",o),()=>{c.removeEventListener("click",s),c.removeEventListener("close",o)}},[t]),C("dialog",{ref:i,className:`modal-${r}`,children:[C(my,{onClose:a}),C("div",{class:"modal-content",children:n?typeof e=="function"?e():e:null})]})}function Cd(n){const{children:e,className:t="",...r}=n;return C("div",{className:`${t} obi-panel`,...r,children:e})}function _d({className:n="",isActive:e=!1,speakingStatus:t,onClick:r,onMouseEnter:i,onMouseLeave:A,children:s}){let o=`obi-pill container ${e&&"active"}`;return t==="user-speaking"&&(o+=" user-speaking"),t==="busy"&&(o+=" busy"),C("div",{className:o,onMouseEnter:i,onMouseLeave:A,children:C("div",{className:`obi-pill pill ${n}`,onClick:r,children:s})})}function yy({className:n="",active:e,speakingStatus:t,onClick:r,onMouseEnter:i,onMouseLeave:A,children:s,...o}){const a=`obi-pill2 container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return C("div",{className:a,...o,children:C("div",{className:"pill",onClick:r,onMouseEnter:i,onMouseLeave:A,children:s})})}function Yr({type:n,size:e=24}){return C("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:_Q(n)})}function _Q(n){switch(n){case"pause":return C(St,{children:[C("rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}),C("rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"})]});case"play":return C(St,{children:C("path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"})});case"close":return C(St,{children:[C("path",{d:"M18 6 6 18"}),C("path",{d:"m6 6 12 12"})]});case"message":return C(St,{children:C("path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"})});case"minimize":return C(St,{children:[C("path",{d:"m14 10 7-7"}),C("path",{d:"M20 10h-6V4"}),C("path",{d:"m3 21 7-7"}),C("path",{d:"M4 14h6v6"})]});case"voice":return C(St,{children:[C("path",{d:"M2 10v3"}),C("path",{d:"M6 6v11"}),C("path",{d:"M10 3v18"}),C("path",{d:"M14 8v7"}),C("path",{d:"M18 5v13"}),C("path",{d:"M22 10v3"})]});case"open":return C(St,{children:[C("path",{d:"M12 7v14"}),C("path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"})]})}}const Sd=Ay(null);function SQ({children:n}){const e=py(Sd);if(!e)throw new Error("PopoutTarget must be used within a Popout component");const{controlledOpen:t,isOpen:r,setIsOpen:i,setAnimating:A,targetRef:s,trigger:o,onChange:a,delayMs:c}=e,u=En(null),l=wy(s,A),[d,h]=ge(!1);Kt(()=>{t!==void 0&&t!==d&&(t?p():g()),h(t)},[t]),Kt(()=>()=>{u.current&&clearTimeout(u.current)},[]);function f(){u.current&&(clearTimeout(u.current),u.current=null)}function p(){f(),c>0?u.current=setTimeout(()=>{a==null||a(!0),i(!0),u.current=null},c):(a==null||a(!0),i(!0))}function g(){f(),a==null||a(!1),i(!1)}const v=()=>{o==="click"&&(r?g():p())};function y(){o==="hover"&&p()}function B(){o==="hover"&&g()}return C("div",{ref:l,class:"target",onClick:v,onMouseEnter:y,onMouseLeave:B,children:n})}function kQ({children:n}){const e=py(Sd);if(!e)throw new Error("PopoutContent must be used within a Popout component");const{isOpen:t,animating:r,setAnimating:i,targetRef:A,contentRef:s}=e,o=wy(s,i);return yd(()=>{if(t&&!r&&A.current&&s.current){const a=s.current;if(!a)return;const c=A.current;if(!c)return;const u=a.getBoundingClientRect(),l=c.getBoundingClientRect(),d=l.right-l.left;a.style.top=`${u.top-u.bottom-(8+e.offset)}px`,a.style.left=`${-(u.right-u.left-d)/2}px`}},[t,r]),t?C("div",{ref:o,class:"content",style:{opacity:r?0:1},children:n}):null}function Vt({trigger:n="click",open:e,onChange:t,children:r,delayMs:i=0,offset:A=0,className:s=""}){const[o,a]=ge(!1),[c,u]=ge(!1),l=En(null),d=En(null),h={controlledOpen:e,isOpen:o,setIsOpen:a,animating:c,setAnimating:u,targetRef:l,contentRef:d,trigger:n,onChange:t,delayMs:i,offset:A};return C(Sd.Provider,{value:h,children:C("div",{class:`obi-popout ${s}`,children:r})})}Vt.Target=SQ,Vt.Content=kQ;function wy(n,e){const t=En(null),r=En(null),i=En(!0),A=wQ(s=>{if(n.current=s,!s){r.current&&(r.current.disconnect(),r.current=null),i.current=!0;return}function o(){if(i.current){i.current=!1;return}t.current?clearTimeout(t.current):e(!0),t.current=setTimeout(()=>{e(!1),t.current=null},200)}r.current=new ResizeObserver(o),r.current.observe(s,{box:"border-box"})},[]);return Kt(()=>()=>{r.current&&(r.current.disconnect(),r.current=null)},[]),A}function pn({className:n,onClick:e,type:t,disabled:r,title:i}){const A={cancel:C(Yr,{type:"close",size:16}),pause:C(Yr,{type:"pause",size:16}),play:C(Yr,{type:"play",size:16}),message:C(Yr,{type:"message",size:16}),minimize:C(Yr,{type:"minimize",size:16}),voice:C(Yr,{type:"voice",size:16}),open:C(Yr,{type:"open",size:16})}[t],s={cancel:"",pause:"",play:"",message:"",minimize:"",voice:"",open:""}[t],o=C("button",{class:`obi-button obi-round-button ${s} ${n}`,onClick:r?void 0:e,disabled:r,children:A});return i?C(Vt,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[C(Vt.Target,{children:o}),C(Vt.Content,{children:C("div",{className:"obi-round-button-title",children:i})})]}):o}const by=8,Ba=8,EQ=50,UQ=.7,Ni=3;function By({getBands:n,color:e="white"}){const t=En(null);return Kt(()=>{if(!n)return;const r=setInterval(()=>{try{const i=n();if(!t.current)return;const A=t.current.querySelectorAll(".bar"),s=i&&i.length>0?i.slice(0,Ba).map(o=>{const a=Math.abs(o);return Math.min(a/UQ*by,by)||Ni}):Array(Ba).fill(Ni);for(;s.length<Ba;)s.push(Ni);s.forEach((o,a)=>{if(o<Ni&&(o=Ni),A[a]){const c=o*2;A[a].style.height=`${c}px`,A[a].style.display=o>0?"block":"none"}})}catch(i){console.warn("Error updating equaliser:",i)}},EQ);return()=>{clearInterval(r)}},[n]),C("div",{className:"obi-equaliser",ref:t,children:Array.from({length:Ba},(r,i)=>C("div",{className:"column",children:C("div",{className:"bar",style:{height:`${Ni}px`,backgroundColor:e,display:"block"}})},i))})}function XA({className:n,children:e,onClick:t}){return t?C("button",{class:`obi-button obi-message ${n} clickable`,onClick:t,children:e}):C("div",{class:`obi-message ${n}`,children:e})}const TQ=8;function Cy({color:n="white"}){return C("div",{className:"obi-loading-dots",children:Array.from({length:TQ},(e,t)=>C("div",{className:"column",children:[C("div",{className:"bar",style:{backgroundColor:n,animationDelay:`${t*.15}s`}}),C("div",{className:"dot",style:{backgroundColor:n}})]},t))})}function IQ({onContinue:n,onWrapUp:e}){return C(Cd,{className:"obi-exit-survey",children:C(xQ,{onContinue:n,onWrapUp:()=>{e()}})})}function FQ({onOtherSelect:n,onReasonSelect:e,onClose:t}){const[r,i]=ge("reason"),A=s=>{s==="other"?(n(),i("other-reason")):e(s)};return C(Cd,{className:`obi-exit-survey ${r==="reason"?"obi-exit-survey-reason":""}`,children:r==="reason"?C(QQ,{onReasonSelect:A}):C(RQ,{onReasonSelect:A,onClose:t})})}function xQ({onContinue:n,onWrapUp:e}){return C("div",{className:"obi-exit-survey-container",children:[C("h2",{className:"obi-exit-survey-title",children:"Wrapping up early?"}),C("div",{className:"obi-exit-survey-options",children:[C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-continue",onClick:n,type:"button",children:"No, let's continue"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:e,type:"button",children:"Yes, let's wrap up"})]})]})}function QQ({onReasonSelect:n}){return C("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[C("div",{className:"obi-exit-survey-header",children:C("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Quick feedback?"})}),C("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("do-later"),type:"button",children:"Will do later"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("cant-talk"),type:"button",children:"Can't talk right now"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("prefer-written"),type:"button",children:"Prefer written instructions"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("technical-issues"),type:"button",children:"Experienced technical issues"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("other"),type:"button",children:"Other"})]})]})}function RQ({onReasonSelect:n,onClose:e}){const[t,r]=ge("");return C("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[C("div",{className:"obi-exit-survey-header",children:[C(my,{onClose:e}),C("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Tell us more"})]}),C("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[C("textarea",{className:"obi-exit-survey-button obi-exit-survey-reason-button",placeholder:"What's on your mind?",value:t,onChange:i=>r(i.target.value)}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:()=>n("other-feedback",t),type:"button",children:"Send feedback"})]})]})}function PQ(n,e){for(var t in e)n[t]=e[t];return n}function _y(n,e){for(var t in n)if(t!=="__source"&&!(t in e))return!0;for(var r in e)if(r!=="__source"&&n[r]!==e[r])return!0;return!1}function Sy(n,e){this.props=n,this.context=e}(Sy.prototype=new Vn).isPureReactComponent=!0,Sy.prototype.shouldComponentUpdate=function(n,e){return _y(this.props,n)||_y(this.state,e)};var ky=ee.__b;ee.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),ky&&ky(n)};var OQ=ee.__e;ee.__e=function(n,e,t,r){if(n.then){for(var i,A=e;A=A.__;)if((i=A.__c)&&i.__c)return e.__e==null&&(e.__e=t.__e,e.__k=t.__k),i.__c(n,e)}OQ(n,e,t,r)};var Ey=ee.unmount;function Uy(n,e,t){return n&&(n.__c&&n.__c.__H&&(n.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),n.__c.__H=null),(n=PQ({},n)).__c!=null&&(n.__c.__P===t&&(n.__c.__P=e),n.__c.__e=!0,n.__c=null),n.__k=n.__k&&n.__k.map(function(r){return Uy(r,e,t)})),n}function Ty(n,e,t){return n&&t&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(r){return Ty(r,e,t)}),n.__c&&n.__c.__P===e&&(n.__e&&t.appendChild(n.__e),n.__c.__e=!0,n.__c.__P=t)),n}function kd(){this.__u=0,this.o=null,this.__b=null}function Iy(n){var e=n.__.__c;return e&&e.__a&&e.__a(n)}function Ca(){this.i=null,this.l=null}ee.unmount=function(n){var e=n.__c;e&&e.__R&&e.__R(),e&&32&n.__u&&(n.type=null),Ey&&Ey(n)},(kd.prototype=new Vn).__c=function(n,e){var t=e.__c,r=this;r.o==null&&(r.o=[]),r.o.push(t);var i=Iy(r.__v),A=!1,s=function(){A||(A=!0,t.__R=null,i?i(o):o())};t.__R=s;var o=function(){if(!--r.__u){if(r.state.__a){var a=r.state.__a;r.__v.__k[0]=Ty(a,a.__c.__P,a.__c.__O)}var c;for(r.setState({__a:r.__b=null});c=r.o.pop();)c.forceUpdate()}};r.__u++||32&e.__u||r.setState({__a:r.__b=r.__v.__k[0]}),n.then(s,s)},kd.prototype.componentWillUnmount=function(){this.o=[]},kd.prototype.render=function(n,e){if(this.__b){if(this.__v.__k){var t=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=Uy(this.__b,t,r.__O=r.__P)}this.__b=null}var i=e.__a&&pd(St,null,n.fallback);return i&&(i.__u&=-33),[pd(St,null,e.__a?null:n.children),i]};var Fy=function(n,e,t){if(++t[1]===t[0]&&n.l.delete(e),n.props.revealOrder&&(n.props.revealOrder[0]!=="t"||!n.l.size))for(t=n.i;t;){for(;t.length>3;)t.pop()();if(t[1]<t[0])break;n.i=t=t[2]}};(Ca.prototype=new Vn).__a=function(n){var e=this,t=Iy(e.__v),r=e.l.get(n);return r[0]++,function(i){var A=function(){e.props.revealOrder?(r.push(i),Fy(e,n,r)):i()};t?t(A):A()}},Ca.prototype.render=function(n){this.i=null,this.l=new Map;var e=ya(n.children);n.revealOrder&&n.revealOrder[0]==="b"&&e.reverse();for(var t=e.length;t--;)this.l.set(e[t],this.i=[1,0,this.i]);return n.children},Ca.prototype.componentDidUpdate=Ca.prototype.componentDidMount=function(){var n=this;this.l.forEach(function(e,t){Fy(n,t,e)})};var MQ=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,LQ=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,DQ=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,NQ=/[A-Z0-9]/g,HQ=typeof document<"u",KQ=function(n){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(n)};Vn.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(n){Object.defineProperty(Vn.prototype,n,{configurable:!0,get:function(){return this["UNSAFE_"+n]},set:function(e){Object.defineProperty(this,n,{configurable:!0,writable:!0,value:e})}})});var xy=ee.event;function VQ(){}function GQ(){return this.cancelBubble}function jQ(){return this.defaultPrevented}ee.event=function(n){return xy&&(n=xy(n)),n.persist=VQ,n.isPropagationStopped=GQ,n.isDefaultPrevented=jQ,n.nativeEvent=n};var WQ={enumerable:!1,configurable:!0,get:function(){return this.class}},Qy=ee.vnode;ee.vnode=function(n){typeof n.type=="string"&&function(e){var t=e.props,r=e.type,i={},A=r.indexOf("-")===-1;for(var s in t){var o=t[s];if(!(s==="value"&&"defaultValue"in t&&o==null||HQ&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var a=s.toLowerCase();s==="defaultValue"&&"value"in t&&t.value==null?s="value":s==="download"&&o===!0?o="":a==="translate"&&o==="no"?o=!1:a[0]==="o"&&a[1]==="n"?a==="ondoubleclick"?s="ondblclick":a!=="onchange"||r!=="input"&&r!=="textarea"||KQ(t.type)?a==="onfocus"?s="onfocusin":a==="onblur"?s="onfocusout":DQ.test(s)&&(s=a):a=s="oninput":A&&LQ.test(s)?s=s.replace(NQ,"-$&").toLowerCase():o===null&&(o=void 0),a==="oninput"&&i[s=a]&&(s="oninputCapture"),i[s]=o}}r=="select"&&i.multiple&&Array.isArray(i.value)&&(i.value=ya(t.children).forEach(function(c){c.props.selected=i.value.indexOf(c.props.value)!=-1})),r=="select"&&i.defaultValue!=null&&(i.value=ya(t.children).forEach(function(c){c.props.selected=i.multiple?i.defaultValue.indexOf(c.props.value)!=-1:i.defaultValue==c.props.value})),t.class&&!t.className?(i.class=t.class,Object.defineProperty(i,"className",WQ)):(t.className&&!t.class||t.class&&t.className)&&(i.class=i.className=t.className),e.props=i}(n),n.$$typeof=MQ,Qy&&Qy(n)};var Ry=ee.__r;ee.__r=function(n){Ry&&Ry(n),n.__c};var Py=ee.diffed;ee.diffed=function(n){Py&&Py(n);var e=n.props,t=n.__e;t!=null&&n.type==="textarea"&&"value"in e&&e.value!==t.value&&(t.value=e.value==null?"":e.value)};function qQ(n){const{placeholder:e="Type your message...",value:t,defaultValue:r,onChange:i,onSend:A,onCancel:s,onExpand:o,isLoading:a=!1,disabled:c=!1,maxLength:u=500,children:l}=n,[d,h]=ge(t||r||""),[f,p]=ge((t||r||"").length>24),g=En(null);yd(()=>{f&&(o==null||o(!0))},[]);const v=t!==void 0?t:d,y=w=>{const _=w.currentTarget.value;t===void 0&&h(_),i==null||i(_)},B=w=>{w.key==="Escape"&&(h(t||r||""),p(!1),s==null||s()),w.key==="Enter"&&!w.shiftKey&&v.trim()&&(w.preventDefault(),h(t||r||""),p(!1),b()),(v||"").length>=24&&!f&&(p(!0),o==null||o(!0))};Kt(()=>{g.current&&g.current.focus()},[g.current]);const b=()=>{!v.trim()||a||c||(A==null||A(v.trim()),t===void 0&&h(""))};return C("div",{className:`obi-message-input ${f?"expanded":""}`,children:[C("div",{className:"container",children:C("textarea",{ref:g,className:"field",placeholder:e,value:v,onInput:y,onKeyDown:B,disabled:c||a,maxLength:u,rows:1})}),C("div",{className:"button-container",children:[f&&C("div",{children:l}),C("button",{className:"obi-button send",onClick:b,disabled:!v.trim()||a||c,type:"button",children:C("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:C("path",{d:"M6.00016 10.6673V1.33398M6.00016 1.33398L1.3335 6.00065M6.00016 1.33398L10.6668 6.00065",stroke:"#F3F3F3","stroke-width":"1.6","stroke-linecap":"round","stroke-linejoin":"round"})})})]})]})}function JQ(n){const{currentStep:e,totalSteps:t,stepNames:r,className:i}=n,A=Array.from({length:t},(a,c)=>({isCompleted:c<e,stepNumber:c+1})),s=r[e-1]||`Step ${e}`,o=`${e}/${t} \u2022 ${s}`;return C("div",{class:`obi-course-progress ${i||""}`,children:[C("div",{class:"obi-course-progress-steps",children:A.map((a,c)=>C("div",{class:"obi-course-progress-container",children:C("div",{class:`obi-course-progress-step ${a.isCompleted?"completed":""}`})},c))}),C("div",{class:"obi-course-progress-description",children:o})]})}function Ed({className:n="",size:e=64}){return C("svg",{width:e,height:e,viewBox:"0 0 256 256",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:n,children:C("path",{d:"M158.803 0L160.352 0.0399439C176.267 0.844061 188.922 13.9634 188.922 30.0311C188.922 46.6174 175.438 60.0653 158.803 60.0656H99.0263L98.9061 60.0722C78.8071 61.4795 62.6269 77.004 60.2644 96.7673L60.241 96.9704V158.93L60.2644 159.13C62.7406 179.86 80.4234 195.934 101.881 195.935H153.842C176.993 195.935 195.759 177.223 195.759 154.14V96.9138L195.799 95.3693C196.606 79.5009 209.766 66.8827 225.881 66.8827C242.515 66.8834 256 80.328 256 96.9138V159.086L255.963 160.564C255.225 175.748 243.176 187.971 228.038 189.038V189.214C207.121 190.591 190.4 207.263 189.019 228.119H188.842C187.738 243.7 174.712 256 158.803 256H96.4491C79.8147 256 66.3309 242.555 66.3302 225.969C66.3302 225.673 66.3349 225.375 66.3436 225.077H66.3503H66.3035C63.3344 206.008 47.4427 190.589 27.8321 189.231L27.8354 189.031C12.2702 187.868 0.000167669 174.905 0 159.086V96.9138L0.0367222 95.4192C0.791087 80.0787 13.0909 67.7634 28.453 66.9293C47.7697 65.3039 63.3522 50.3234 66.2969 31.4658L66.3469 31.1595L66.3369 30.85C66.3301 30.5933 66.3302 30.3238 66.3302 30.0311C66.3309 13.4454 79.8148 0.000165137 96.4491 0H158.803Z",fill:"currentColor"})})}function zQ({children:n}){const e={container:{position:"relative",width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},logo:{display:"flex",width:"120px",height:"120px",justifyContent:"center",alignItems:"center",aspectRatio:"1/1",borderRadius:"8px",color:"#FFFFFF",position:"relative",overflow:"hidden",background:"var(--obi-color-primary)",boxShadow:`
42
+ `},zl}var p0;function lx(){if(p0)return ln;p0=1;var n=cx(),e=ux(),t=Jl();return ln.grammar=t,ln.write=e,ln.parse=n.parse,ln.parseParams=n.parseParams,ln.parseFmtpConfig=n.parseFmtpConfig,ln.parsePayloads=n.parsePayloads,ln.parseRemoteCandidates=n.parseRemoteCandidates,ln.parseImageAttributes=n.parseImageAttributes,ln.parseSimulcastStreamList=n.parseSimulcastStreamList,ln}var mr=lx();function Xl(n,e,t){var r,i,A;e===void 0&&(e=50),t===void 0&&(t={});var s=(r=t.isImmediate)!=null&&r,o=(i=t.callback)!=null&&i,a=t.maxWait,c=Date.now(),u=[];function l(){if(a!==void 0){var h=Date.now()-c;if(h+e>=a)return a-h}return e}var d=function(){var h=[].slice.call(arguments),f=this;return new Promise(function(p,g){var v=s&&A===void 0;if(A!==void 0&&clearTimeout(A),A=setTimeout(function(){if(A=void 0,c=Date.now(),!s){var B=n.apply(f,h);o&&o(B),u.forEach(function(b){return(0,b.resolve)(B)}),u=[]}},l()),v){var y=n.apply(f,h);return o&&o(y),p(y)}u.push({resolve:p,reject:g})})};return d.cancel=function(h){A!==void 0&&clearTimeout(A),u.forEach(function(f){return(0,f.reject)(h)}),u=[]},d}const dx=.7,hx=20,Oi={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class f0 extends Sn.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var r;super(),this.log=ue,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Xl(i=>S(this,void 0,void 0,function*(){this.emit(Oi.NegotiationStarted);try{yield this.createAndSendOffer()}catch(A){if(i)i(A);else throw A}}),hx),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=Ln((r=t.loggerName)!==null&&r!==void 0?r:cn.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var r;t.candidate&&((r=this.onIceCandidate)===null||r===void 0||r.call(this,t.candidate))},e.onicecandidateerror=t=>{var r;(r=this.onIceCandidateError)===null||r===void 0||r.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var r;(r=this.onDataChannel)===null||r===void 0||r.call(this,t)},e.ontrack=t=>{var r;(r=this.onTrack)===null||r===void 0||r.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return S(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return S(this,void 0,void 0,function*(){var t;let r;if(e.type==="offer"){let{stereoMids:i,nackMids:A}=px(e);this.remoteStereoMids=i,this.remoteNackMids=A}else if(e.type==="answer"){const i=mr.parse((t=e.sdp)!==null&&t!==void 0?t:"");i.media.forEach(A=>{A.type==="audio"&&this.trackBitrates.some(s=>{if(!s.transceiver||A.mid!=s.transceiver.mid)return!1;let o=0;if(A.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0)return!0;let a=!1;for(const c of A.fmtp)if(c.payload===o){c.config=c.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),s.maxbr>0&&(c.config+=";maxaveragebitrate=".concat(s.maxbr*1e3)),a=!0;break}return a||s.maxbr>0&&A.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(s.maxbr*1e3)}),!0})}),r=mr.write(i)}yield this.setMungedSDP(e,r,!0),this.pendingCandidates.forEach(i=>{this.pc.addIceCandidate(i)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Oi.NegotiationComplete),e.sdp&&mr.parse(e.sdp).media.forEach(A=>{A.type==="video"&&this.emit(Oi.RTPVideoPayloadTypes,A.rtp)}))})}createAndSendOffer(e){return S(this,void 0,void 0,function*(){var t;if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const A=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&A)yield this._pc.setRemoteDescription(A);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const i=mr.parse((t=r.sdp)!==null&&t!==void 0?t:"");i.media.forEach(A=>{m0(A),A.type==="audio"?g0(A,[],[]):A.type==="video"&&this.trackBitrates.some(s=>{if(!A.msid||!s.cid||!A.msid.includes(s.cid))return!1;let o=0;if(A.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0||(KA(s.codec)&&this.ensureVideoDDExtensionForSVC(A,i),s.codec!=="av1"))return!0;const a=Math.round(s.maxbr*dx);for(const c of A.fmtp)if(c.payload===o){c.config.includes("x-google-start-bitrate")||(c.config+=";x-google-start-bitrate=".concat(a));break}return!0})}),yield this.setMungedSDP(r,mr.write(i)),this.onOffer(r)})}createAndSetAnswer(){return S(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),r=mr.parse((e=t.sdp)!==null&&e!==void 0?e:"");return r.media.forEach(i=>{m0(i),i.type==="audio"&&g0(i,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,mr.write(r)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new lt("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var t;if(!this._pc)throw new lt("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return S(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const r=new Map,i=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),r.set(o.id,o);break;case"remote-candidate":i.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const s=(e=r.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(s!==void 0)return i.get(s)})}setMungedSDP(e,t,r){return S(this,void 0,void 0,function*(){if(t){const i=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(r?"remote":"local"," description"),this.logContext),r?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(A){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:A,sdp:t})),e.sdp=i}}try{r?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(i){let A="unknown error";i instanceof Error?A=i.message:typeof i=="string"&&(A=i);const s={error:A,sdp:e.sdp};throw!r&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new _l(A)}})}ensureVideoDDExtensionForSVC(e,t){var r,i;if(!((r=e.ext)===null||r===void 0?void 0:r.some(s=>s.uri===zv))){if(this.ddExtID===0){let s=0;t.media.forEach(o=>{var a;o.type==="video"&&((a=o.ext)===null||a===void 0||a.forEach(c=>{c.value>s&&(s=c.value)}))}),this.ddExtID=s+1}(i=e.ext)===null||i===void 0||i.push({value:this.ddExtID,uri:zv})}}}function g0(n,e,t){let r=0;n.rtp.some(i=>i.codec==="opus"?(r=i.payload,!0):!1),r>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(n.mid)&&!n.rtcpFb.some(i=>i.payload===r&&i.type==="nack")&&n.rtcpFb.push({payload:r,type:"nack"}),e.includes(n.mid)&&n.fmtp.some(i=>i.payload===r?(i.config.includes("stereo=1")||(i.config+=";stereo=1"),!0):!1))}function px(n){var e;const t=[],r=[],i=mr.parse((e=n.sdp)!==null&&e!==void 0?e:"");let A=0;return i.media.forEach(s=>{var o;s.type==="audio"&&(s.rtp.some(a=>a.codec==="opus"?(A=a.payload,!0):!1),!((o=s.rtcpFb)===null||o===void 0)&&o.some(a=>a.payload===A&&a.type==="nack")&&r.push(s.mid),s.fmtp.some(a=>a.payload===A?(a.config.includes("sprop-stereo=1")&&t.push(s.mid),!0):!1))}),{stereoMids:t,nackMids:r}}function m0(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}const Yl="vp8",fx={audioPreset:Ul.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Il.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Yl,backupCodec:!0},v0={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},y0={deviceId:{ideal:"default"},resolution:HA.h720.resolution},gx={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new sF,disconnectOnPageLeave:!0,webAudioMix:!1},Zl={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Ye;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(Ye||(Ye={}));class mx{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,r){var i;this.peerConnectionTimeout=Zl.peerConnectionTimeout,this.log=ue,this.updateState=()=>{var A;const s=this.state,o=this.requiredTransports.map(a=>a.getConnectionState());o.every(a=>a==="connected")?this.state=Ye.CONNECTED:o.some(a=>a==="failed")?this.state=Ye.FAILED:o.some(a=>a==="connecting")?this.state=Ye.CONNECTING:o.every(a=>a==="closed")?this.state=Ye.CLOSED:o.some(a=>a==="closed")?this.state=Ye.CLOSING:o.every(a=>a==="new")&&(this.state=Ye.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(Ye[s]," to ").concat(Ye[this.state]),this.logContext),(A=this.onStateChange)===null||A===void 0||A.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=Ln((i=r.loggerName)!==null&&i!==void 0?i:cn.PCManager),this.loggerOptions=r,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new f0(e,r),this.subscriber=new f0(e,r),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=A=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,A,an.PUBLISHER)},this.subscriber.onIceCandidate=A=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,A,an.SUBSCRIBER)},this.subscriber.onDataChannel=A=>{var s;(s=this.onDataChannel)===null||s===void 0||s.call(this,A)},this.subscriber.onTrack=A=>{var s;(s=this.onTrack)===null||s===void 0||s.call(this,A)},this.publisher.onOffer=A=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,A)},this.state=Ye.NEW,this.connectionLock=new Mt,this.remoteOfferLock=new Mt}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e){return this.publisher.setRemoteDescription(e)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return S(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(r){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:r}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return S(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return S(this,void 0,void 0,function*(){t===an.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){return S(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return S(this,void 0,void 0,function*(){var r;const i=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((r=this.requiredTransports)===null||r===void 0?void 0:r.map(A=>this.ensureTransportConnected(A,e,t)))}finally{i()}})}negotiate(e){return S(this,void 0,void 0,function*(){return new Promise((t,r)=>S(this,void 0,void 0,function*(){const i=setTimeout(()=>{r("negotiation timed out")},this.peerConnectionTimeout),A=()=>{clearTimeout(i),r("negotiation aborted")};e.signal.addEventListener("abort",A),this.publisher.once(Oi.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Oi.NegotiationComplete,()=>{clearTimeout(i),t()})}),yield this.publisher.negotiate(s=>{clearTimeout(i),r(s)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===an.PUBLISHER?this.publisher.getConnectedAddress():e===an.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(r.getConnectionState()!=="connected")return new Promise((a,c)=>S(A,void 0,void 0,function*(){const u=()=>{this.log.warn("abort transport connection",this.logContext),wt.clearTimeout(l),c(new Fe("room connection has been cancelled",de.Cancelled))};i!=null&&i.signal.aborted&&u(),i==null||i.signal.addEventListener("abort",u);const l=wt.setTimeout(()=>{i==null||i.signal.removeEventListener("abort",u),c(new Fe("could not establish pc connection",de.InternalError))},s);for(;this.state!==Ye.CONNECTED;)if(yield Nt(50),i!=null&&i.signal.aborted){c(new Fe("room connection has been cancelled",de.Cancelled));return}wt.clearTimeout(l),i==null||i.signal.removeEventListener("abort",u),a()}))}()})}}class Ze extends Error{constructor(e,t,r){super(t),this.code=e,this.message=b0(t,Ze.MAX_MESSAGE_BYTES),this.data=r?b0(r,Ze.MAX_DATA_BYTES):void 0}static fromProto(e){return new Ze(e.code,e.message,e.data)}toProto(){return new Om({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new Ze(Ze.ErrorCode[e],Ze.ErrorMessage[e],t)}}Ze.MAX_MESSAGE_BYTES=256,Ze.MAX_DATA_BYTES=15360,Ze.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},Ze.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const w0=15360;function $l(n){return new TextEncoder().encode(n).length}function b0(n,e){if($l(n)<=e)return n;let t=0,r=n.length;const i=new TextEncoder;for(;t<r;){const A=Math.floor((t+r+1)/2);i.encode(n.slice(0,A)).length<=e?t=A:r=A-1}return n.slice(0,t)}const ed=2e3;function oa(n,e){if(!e)return 0;let t,r;return"bytesReceived"in n?(t=n.bytesReceived,r=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,r=e.bytesSent),t===void 0||r===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-r)*8*1e3/(n.timestamp-e.timestamp)}const vx=1e3;class B0 extends R{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,r){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,A=arguments.length>4?arguments[4]:void 0;super(e,t,A),this.manuallyStopped=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=Xl(()=>S(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>S(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(L.Ended,this)},this.reacquireTrack=!1,this.providedByUser=i,this.muteLock=new Mt,this.pauseUpstreamLock=new Mt,this.processorLock=new Mt,this.restartLock=new Mt,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),r&&(this._constraints=r)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==R.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(t=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&t!==void 0?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return S(this,void 0,void 0,function*(){var r;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(A=>{xi(this._mediaStreamTrack,A)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let i;if(this.processor&&e){const A=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Fi(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}finally{A()}}this.sender&&((r=this.sender.transport)===null||r===void 0?void 0:r.state)!=="closed"&&(yield this.sender.replaceTrack(i??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(A=>{Fi(i??e,A)}))})}waitForDimensions(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:vx;return function*(){var r;if(e.kind===R.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((r=un())===null||r===void 0?void 0:r.os)==="iOS"&&(yield Nt(10));const i=Date.now();for(;Date.now()-i<t;){const A=e.dimensions;if(A)return A;yield Nt(50)}throw new Dn("unable to get track dimensions after timeout")}()})}setDeviceId(e){return S(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===fr(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),fr(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===R.Source.ScreenShare)return;const{deviceId:r,groupId:i}=e._mediaStreamTrack.getSettings(),A=e.kind===R.Kind.Audio?"audioinput":"videoinput";return t?ft.getInstance().normalizeDeviceId(A,r,i):r}()})}mute(){return S(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return S(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return S(this,void 0,void 0,function*(){if(!this.sender)throw new Dn("unable to replace an unpublished track");let r,i;return typeof t=="boolean"?r=t:t!==void 0&&(r=t.userProvidedTrack,i=t.stopProcessor),this.providedByUser=r??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return S(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:r,facingMode:i}=e,A=oF(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===R.Kind.Video?s.video=r||i?{deviceId:r,facingMode:i}:!0:s.audio=r?{deviceId:r}:!0,this.attachedElements.forEach(c=>{xi(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const a=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return yield a.applyConstraints(A),a.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(a),this._constraints=e,this.emit(L.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}setTrackMuted(e){this.log.debug("setting ".concat(this.kind," track ").concat(e?"muted":"unmuted"),this.logContext),!(this.isMuted===e&&this._mediaStreamTrack.enabled!==e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?L.Muted:L.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Xv()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return S(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(L.UpstreamPaused,this);const r=un();if((r==null?void 0:r.name)==="Safari"&&Wr(r.version,"12.0")<0)throw new Cl("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return S(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(L.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return S(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var A;const s=yield r.processorLock.lock();try{r.log.debug("setting up processor",r.logContext);const o=document.createElement(r.kind),a={kind:r.kind,track:r._mediaStreamTrack,element:o,audioContext:r.audioContext};if(yield t.init(a),r.log.debug("processor initialized",r.logContext),r.processor&&(yield r.stopProcessor()),r.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Fi(r._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>r.log.error("failed to play processor element",Object.assign(Object.assign({},r.logContext),{error:c}))),r.processor=t,r.processorElement=o,r.processor.processedTrack){for(const c of r.attachedElements)c!==r.processorElement&&i&&(xi(r._mediaStreamTrack,c),Fi(r.processor.processedTrack,c));yield(A=r.sender)===null||A===void 0?void 0:A.replaceTrack(r.processor.processedTrack)}r.emit(L.TrackProcessorUpdate,r.processor)}finally{s()}}()})}getProcessor(){return this.processor}stopProcessor(){return S(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var r,i;e.processor&&(e.log.debug("stopping processor",e.logContext),(r=e.processor.processedTrack)===null||r===void 0||r.stop(),yield e.processor.destroy(),e.processor=void 0,t||((i=e.processorElement)===null||i===void 0||i.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(L.TrackProcessorUpdate))}()})}}class aa extends B0{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0,A=arguments.length>4?arguments[4]:void 0;super(e,R.Kind.Audio,t,r,A),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>S(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}s&&this.prevStats&&(this._currentBitrate=oa(s,this.prevStats)),this.prevStats=s}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(L.AudioTrackFeatureUpdate,this,on.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(L.AudioTrackFeatureUpdate,this,on.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===R.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const r=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==fr(this._constraints.deviceId);return this.source===R.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||r)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return S(this,void 0,void 0,function*(){let t;if(e){const r=Vl({audio:e});typeof r.audio!="boolean"&&(t=r.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return S(this,void 0,void 0,function*(){const r=yield t.restart.call(this,e);return this.checkForSilence(),r})}startMonitor(){Ht()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},ed)))}setProcessor(e){return S(this,void 0,void 0,function*(){var t;const r=yield this.processorLock.lock();try{if(!kn()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield(t=this.sender)===null||t===void 0?void 0:t.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener("enable-lk-krisp-noise-filter",this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener("disable-lk-krisp-noise-filter",this.handleKrispNoiseFilterDisable)),this.emit(L.TrackProcessorUpdate,this.processor)}finally{r()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return S(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let r;return t.forEach(i=>{i.type==="outbound-rtp"&&(r={type:"audio",streamId:i.id,packetsSent:i.packetsSent,packetsLost:i.packetsLost,bytesSent:i.bytesSent,timestamp:i.timestamp,roundTripTime:i.roundTripTime,jitter:i.jitter})}),r})}checkForSilence(){return S(this,void 0,void 0,function*(){const e=yield A0(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(L.AudioSilenceDetected)),e})}}function yx(n,e,t){switch(n.kind){case"audio":return new aa(n,e,!1,void 0,t);case"video":return new ua(n,e,!1,t);default:throw new Dn("unsupported track type: ".concat(n.kind))}}const wx=Object.values(HA),bx=Object.values(Tl),Bx=Object.values(Il),Cx=[HA.h180,HA.h360],_x=[Tl.h180,Tl.h360],Sx=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var r,i;return new Te(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((r=n.encoding.maxFramerate)!==null&&r!==void 0?r:30)/((i=t.fps)!==null&&i!==void 0?i:30))))),t.fps,n.encoding.priority)}),td=["q","h","f"];function nd(n,e,t,r){var i,A;let s=r==null?void 0:r.videoEncoding;n&&(s=r==null?void 0:r.screenShareEncoding);const o=r==null?void 0:r.simulcast,a=r==null?void 0:r.scalabilityMode,c=r==null?void 0:r.videoCodec;if(!s&&!o&&!a||!e||!t)return[{}];s||(s=Ex(n,e,t,c),ue.debug("using video encoding",s));const u=s.maxFramerate,l=new Te(e,t,s.maxBitrate,s.maxFramerate,s.priority);if(a&&KA(c)){const f=new ca(a),p=[];if(f.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(a));const g=un();if(pr()||kn()||(g==null?void 0:g.name)==="Chrome"&&Wr(g==null?void 0:g.version,"113")<0){const v=f.suffix=="h"?2:3;for(let y=0;y<f.spatial;y+=1)p.push({rid:td[2-y],maxBitrate:s.maxBitrate/Math.pow(v,y),maxFramerate:l.encoding.maxFramerate});p[0].scalabilityMode=a}else p.push({maxBitrate:s.maxBitrate,maxFramerate:l.encoding.maxFramerate,scalabilityMode:a});return l.encoding.priority&&(p[0].priority=l.encoding.priority,p[0].networkPriority=l.encoding.priority),ue.debug("using svc encoding",{encodings:p}),p}if(!o)return[s];let d=[];n?d=(i=_0(r==null?void 0:r.screenShareSimulcastLayers))!==null&&i!==void 0?i:C0(n,l):d=(A=_0(r==null?void 0:r.videoSimulcastLayers))!==null&&A!==void 0?A:C0(n,l);let h;if(d.length>0){const f=d[0];d.length>1&&([,h]=d);const p=Math.max(e,t);if(p>=960&&h)return rd(e,t,[f,h,l],u);if(p>=480)return rd(e,t,[f,l],u)}return rd(e,t,[l])}function kx(n,e,t){var r,i,A,s;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&ue.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),a=(r=o.width)!==null&&r!==void 0?r:(i=n.dimensions)===null||i===void 0?void 0:i.width,c=(A=o.height)!==null&&A!==void 0?A:(s=n.dimensions)===null||s===void 0?void 0:s.height;return n.source===R.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),nd(n.source===R.Source.ScreenShare,a,c,t)}function Ex(n,e,t,r){const i=Ux(n,e,t);let{encoding:A}=i[0];const s=Math.max(e,t);for(let o=0;o<i.length;o+=1){const a=i[o];if(A=a.encoding,a.width>=s)break}if(r)switch(r){case"av1":A=Object.assign({},A),A.maxBitrate=A.maxBitrate*.7;break;case"vp9":A=Object.assign({},A),A.maxBitrate=A.maxBitrate*.85;break}return A}function Ux(n,e,t){if(n)return Bx;const r=e>t?e/t:t/e;return Math.abs(r-16/9)<Math.abs(r-4/3)?wx:bx}function C0(n,e){if(n)return Sx(e);const{width:t,height:r}=e,i=t>r?t/r:r/t;return Math.abs(i-16/9)<Math.abs(i-4/3)?Cx:_x}function rd(n,e,t,r){const i=[];if(t.forEach((A,s)=>{if(s>=td.length)return;const o=Math.min(n,e),c={rid:td[s],scaleResolutionDownBy:Math.max(1,o/Math.min(A.width,A.height)),maxBitrate:A.encoding.maxBitrate},u=r&&A.encoding.maxFramerate?Math.min(r,A.encoding.maxFramerate):A.encoding.maxFramerate;u&&(c.maxFramerate=u);const l=Qi()||s===0;A.encoding.priority&&l&&(c.priority=A.encoding.priority,c.networkPriority=A.encoding.priority),i.push(c)}),kn()&&Zv()==="ios"){let A;i.forEach(o=>{A?o.maxFramerate&&o.maxFramerate>A&&(A=o.maxFramerate):A=o.maxFramerate});let s=!0;i.forEach(o=>{var a;o.maxFramerate!=A&&(s&&(s=!1,ue.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ue.info('Setting framerate of encoding "'.concat((a=o.rid)!==null&&a!==void 0?a:"",'" to ').concat(A)),o.maxFramerate=A)})}return i}function _0(n){if(n)return n.sort((e,t)=>{const{encoding:r}=e,{encoding:i}=t;return r.maxBitrate>i.maxBitrate?1:r.maxBitrate<i.maxBitrate?-1:r.maxBitrate===i.maxBitrate&&r.maxFramerate&&i.maxFramerate?r.maxFramerate>i.maxFramerate?1:-1:0})}class ca{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function Tx(n){return n.source===R.Source.ScreenShare||n.constraints.height&&fr(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const Ix=5e3;class ua extends B0{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0;super(e,R.Kind.Video,t,r,i),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>S(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let A;try{A=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}const s=new Map(A.map(o=>[o.rid,o]));if(this.prevStats){let o=0;s.forEach((a,c)=>{var u;const l=(u=this.prevStats)===null||u===void 0?void 0:u.get(c);o+=oa(a,l)}),this._currentBitrate=o}this.prevStats=s}),this.senderLock=new Mt}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Ht())return;const r=(t=this.sender)===null||t===void 0?void 0:t.getParameters();r&&(this.encodings=r.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},ed))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return S(this,void 0,void 0,function*(){var t,r,i,A,s;yield e.pauseUpstream.call(this);try{for(var o=!0,a=ur(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0)A=c.value,o=!1,yield(s=A.sender)===null||s===void 0?void 0:s.replaceTrack(null)}catch(u){r={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(r)throw r.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return S(this,void 0,void 0,function*(){var t,r,i,A,s;yield e.resumeUpstream.call(this);try{for(var o=!0,a=ur(this.simulcastCodecs.values()),c;c=yield a.next(),t=c.done,!t;o=!0){A=c.value,o=!1;const u=A;yield(s=u.sender)===null||s===void 0?void 0:s.replaceTrack(u.mediaStreamTrack)}}catch(u){r={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.call(a))}finally{if(r)throw r.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===R.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return S(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===R.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return S(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],r=yield this.sender.getStats();return r.forEach(i=>{var A;if(i.type==="outbound-rtp"){const s={type:"video",streamId:i.id,frameHeight:i.frameHeight,frameWidth:i.frameWidth,framesPerSecond:i.framesPerSecond,framesSent:i.framesSent,firCount:i.firCount,pliCount:i.pliCount,nackCount:i.nackCount,packetsSent:i.packetsSent,bytesSent:i.bytesSent,qualityLimitationReason:i.qualityLimitationReason,qualityLimitationDurations:i.qualityLimitationDurations,qualityLimitationResolutionChanges:i.qualityLimitationResolutionChanges,rid:(A=i.rid)!==null&&A!==void 0?A:i.id,retransmittedPacketsSent:i.retransmittedPacketsSent,targetBitrate:i.targetBitrate,timestamp:i.timestamp},o=r.get(i.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),t.push(s)}}),t.sort((i,A)=>{var s,o;return((s=A.frameWidth)!==null&&s!==void 0?s:0)-((o=i.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let r=Yt.LOW;r<=Yt.HIGH;r+=1)t.push(new ll({quality:r,enabled:r<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return S(this,void 0,void 0,function*(){var t,r,i,A,s;let o;if(e){const l=Vl({video:e});typeof l.video!="boolean"&&(o=l.video)}yield this.restart(o);try{for(var a=!0,c=ur(this.simulcastCodecs.values()),u;u=yield c.next(),t=u.done,!t;a=!0){A=u.value,a=!1;const l=A;l.sender&&((s=l.sender.transport)===null||s===void 0?void 0:s.state)!=="closed"&&(l.mediaStreamTrack=this.mediaStreamTrack.clone(),yield l.sender.replaceTrack(l.mediaStreamTrack))}}catch(l){r={error:l}}finally{try{!a&&!t&&(i=c.return)&&(yield i.call(c))}finally{if(r)throw r.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return S(this,arguments,void 0,function(r){var i=this;let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s,o,a,c,u,l;if(yield t.setProcessor.call(i,r,A),!((u=i.processor)===null||u===void 0)&&u.processedTrack)try{for(var d=!0,h=ur(i.simulcastCodecs.values()),f;f=yield h.next(),s=f.done,!s;d=!0)c=f.value,d=!1,yield(l=c.sender)===null||l===void 0?void 0:l.replaceTrack(i.processor.processedTrack)}catch(p){o={error:p}}finally{try{!d&&!s&&(a=h.return)&&(yield a.call(h))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return S(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(t){this.log.warn("failed to set degradationPreference",Object.assign({error:t},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const r={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,r),r}setSimulcastTrackSender(e,t){const r=this.simulcastCodecs.get(e);r&&(r.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Ix))}setPublishingCodecs(e){return S(this,void 0,void 0,function*(){var t,r,i,A,s,o,a;if(this.log.debug("setting publishing codecs",Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,r=ur(e);i=yield r.next(),A=i.done,!A;t=!0){a=i.value,t=!1;const u=a;if(!this.codec||this.codec===u.codec)yield this.setPublishingLayers(u.qualities);else{const l=this.simulcastCodecs.get(u.codec);if(this.log.debug("try setPublishingCodec for ".concat(u.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:l})),!l||!l.sender){for(const d of u.qualities)if(d.enabled){c.push(u.codec);break}}else l.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(u.codec),this.logContext),yield S0(l.sender,l.encodings,u.qualities,this.senderLock,this.log,this.logContext))}}}catch(u){s={error:u}}finally{try{!t&&!A&&(o=r.return)&&(yield o.call(r))}finally{if(s)throw s.error}}return c})}setPublishingLayers(e){return S(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield S0(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Xv()&&this.isInBackground&&this.source===R.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function S0(n,e,t,r,i,A){return S(this,void 0,void 0,function*(){const s=yield r.lock();i.debug("setPublishingLayersForSender",Object.assign(Object.assign({},A),{sender:n,qualities:t,senderEncodings:e}));try{const o=n.getParameters(),{encodings:a}=o;if(!a)return;if(a.length!==e.length){i.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},A),{encodings:a,senderEncodings:e}));return}let c=!1;const u=un();if((u==null?void 0:u.name)==="Chrome"&&Wr(u==null?void 0:u.version,"133")>0&&a[0].scalabilityMode){const d=a[0],h=new ca(d.scalabilityMode);let f=Si.OFF;if(t.forEach(p=>{p.enabled&&(f===Si.OFF||p.quality>f)&&(f=p.quality)}),f===Si.OFF)d.active&&(d.active=!1,c=!0);else if(!d.active||h.spatial!==f+1){c=!0,d.active=!0;const p=new ca(e[0].scalabilityMode);h.spatial=f+1,h.suffix=p.suffix,h.spatial===1&&(h.suffix=void 0),d.scalabilityMode=h.toString(),d.scaleResolutionDownBy=Math.pow(2,2-f),e[0].maxBitrate&&(d.maxBitrate=e[0].maxBitrate/(d.scaleResolutionDownBy*d.scaleResolutionDownBy))}}else a.forEach((d,h)=>{var f;let p=(f=d.rid)!==null&&f!==void 0?f:"";p===""&&(p="q");const g=k0(p),v=t.find(y=>y.quality===g);v&&d.active!==v.enabled&&(c=!0,d.active=v.enabled,i.debug("setting layer ".concat(v.quality," to ").concat(d.active?"enabled":"disabled"),A),Qi()&&(v.enabled?(d.scaleResolutionDownBy=e[h].scaleResolutionDownBy,d.maxBitrate=e[h].maxBitrate,d.maxFrameRate=e[h].maxFrameRate):(d.scaleResolutionDownBy=4,d.maxBitrate=10,d.maxFrameRate=2)))});c&&(o.encodings=a,i.debug("setting encodings",Object.assign(Object.assign({},A),{encodings:o.encodings})),yield n.setParameters(o))}finally{s()}})}function k0(n){switch(n){case"f":return Yt.HIGH;case"h":return Yt.MEDIUM;case"q":return Yt.LOW;default:return Yt.HIGH}}function E0(n,e,t,r){if(!t)return[new Vr({quality:Yt.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(r){const i=t[0].scalabilityMode,A=new ca(i),s=[],o=A.suffix=="h"?1.5:2,a=A.suffix=="h"?2:3;for(let c=0;c<A.spatial;c+=1)s.push(new Vr({quality:Math.min(Yt.HIGH,A.spatial-1)-c,width:Math.ceil(n/Math.pow(o,c)),height:Math.ceil(e/Math.pow(o,c)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(a,c)):0,ssrc:0}));return s}return t.map(i=>{var A,s,o;const a=(A=i.scaleResolutionDownBy)!==null&&A!==void 0?A:1;let c=k0((s=i.rid)!==null&&s!==void 0?s:"");return new Vr({quality:c,width:Math.ceil(n/a),height:Math.ceil(e/a),bitrate:(o=i.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const U0="_lossy",T0="_reliable",Fx=2*1e3,id="leave-reconnect";var dn;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(dn||(dn={}));class xx extends Sn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Zl.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=dn.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=ue,this.handleDataChannel=r=>S(this,[r],void 0,function(i){var A=this;let{channel:s}=i;return function*(){if(s){if(s.label===T0)A.reliableDCSub=s;else if(s.label===U0)A.lossyDCSub=s;else return;A.log.debug("on data channel ".concat(s.id,", ").concat(s.label),A.logContext),s.onmessage=A.handleDataMessage}}()}),this.handleDataMessage=r=>S(this,void 0,void 0,function*(){var i,A;const s=yield this.dataProcessLock.lock();try{let o;if(r.data instanceof ArrayBuffer)o=r.data;else if(r.data instanceof Blob)o=yield r.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:r.data}));return}const a=Dt.fromBinary(new Uint8Array(o));((i=a.value)===null||i===void 0?void 0:i.case)==="speaker"?this.emit(D.ActiveSpeakersUpdate,a.value.value.speakers):(((A=a.value)===null||A===void 0?void 0:A.case)==="user"&&Rx(a,a.value.value),this.emit(D.DataPacketReceived,a))}finally{s()}}),this.handleDataError=r=>{const A=r.currentTarget.maxRetransmits===0?"lossy":"reliable";if(r instanceof ErrorEvent&&r.error){const{error:s}=r.error;this.log.error("DataChannel error on ".concat(A,": ").concat(r.message),Object.assign(Object.assign({},this.logContext),{error:s}))}else this.log.error("Unknown DataChannel error on ".concat(A),Object.assign(Object.assign({},this.logContext),{event:r}))},this.handleBufferedAmountLow=r=>{const A=r.currentTarget.maxRetransmits===0?pe.LOSSY:pe.RELIABLE;this.updateAndEmitDCBufferStatus(A)},this.handleDisconnect=(r,i)=>{if(this._isClosed)return;this.log.warn("".concat(r," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const A=a=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(a,"ms. giving up"),this.logContext),this.emit(D.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});if(o===null){A(s);return}r===id&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=wt.setTimeout(()=>this.attemptReconnect(i).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((r,i)=>{this.pcState===dn.Connected&&r();const A=()=>{this.off(D.Disconnected,s),r()},s=()=>{this.off(D.Restarted,A),i()};this.once(D.Restarted,A),this.once(D.Disconnected,s)}),this.updateAndEmitDCBufferStatus=r=>{const i=this.isBufferStatusLow(r);typeof i<"u"&&i!==this.dcBufferStatus.get(r)&&(this.dcBufferStatus.set(r,i),this.emit(D.DCBufferStatusChanged,i,r))},this.isBufferStatusLow=r=>{const i=this.dataChannelForKind(r);if(i)return i.bufferedAmount<=i.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Oe.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ki.RR_SIGNAL_DISCONNECTED))},this.log=Ln((t=e.loggerName)!==null&&t!==void 0?t:cn.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new jl(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Mt,this.dataProcessLock=new Mt,this.dcBufferStatus=new Map([[pe.LOSSY,!0],[pe.RELIABLE,!0]]),this.client.onParticipantUpdate=r=>this.emit(D.ParticipantUpdate,r),this.client.onConnectionQuality=r=>this.emit(D.ConnectionQualityUpdate,r),this.client.onRoomUpdate=r=>this.emit(D.RoomUpdate,r),this.client.onSubscriptionError=r=>this.emit(D.SubscriptionError,r),this.client.onSubscriptionPermissionUpdate=r=>this.emit(D.SubscriptionPermissionUpdate,r),this.client.onSpeakersChanged=r=>this.emit(D.SpeakersChanged,r),this.client.onStreamStateUpdate=r=>this.emit(D.StreamStateChanged,r),this.client.onRequestResponse=r=>this.emit(D.SignalRequestResponse,r)}get logContext(){var e,t,r,i,A,s,o,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(i=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.room)===null||i===void 0?void 0:i.sid,participant:(s=(A=this.latestJoinResponse)===null||A===void 0?void 0:A.participant)===null||s===void 0?void 0:s.identity,pID:(a=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||a===void 0?void 0:a.sid}}join(e,t,r,i){return S(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=r,this.maxJoinAttempts=r.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const A=yield this.client.join(e,t,r,i);return this._isClosed=!1,this.latestJoinResponse=A,this.subscriberPrimary=A.subscriberPrimary,this.pcManager||(yield this.configure(A)),(!this.subscriberPrimary||A.fastPublish)&&this.negotiate(),this.clientConfiguration=A.clientConfiguration,setTimeout(()=>{this.emit(D.SignalConnected)},10),A}catch(A){if(A instanceof Fe&&A.reason===de.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,r,i);throw A}})}close(){return S(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(D.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return S(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=r=>{r&&(r.close(),r.onbufferedamountlow=null,r.onclose=null,r.onclosing=null,r.onerror=null,r.onmessage=null,r.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0})}cleanupClient(){return S(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new Dn("a track with the same ID has already been published");return new Promise((t,r)=>{const i=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],r(new Fe("publication of local track timed out, no response from server",de.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:A=>{clearTimeout(i),t(A)},reject:()=>{clearTimeout(i),r(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return S(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return S(this,void 0,void 0,function*(){var t,r;if(this.pcManager&&this.pcManager.currentState!==Ye.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const i=this.makeRTCConfiguration(e);this.pcManager=new mx(i,e.subscriberPrimary,this.loggerOptions),this.emit(D.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(A,s)=>{this.client.sendIceCandidate(A,s)},this.pcManager.onPublisherOffer=A=>{this.client.sendOffer(A)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(A,s,o)=>S(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(A),this.logContext),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),A===Ye.CONNECTED){const u=this.pcState===dn.New;this.pcState=dn.Connected,u&&this.emit(D.Connected,e)}else A===Ye.FAILED&&this.pcState===dn.Connected&&(this.pcState=dn.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?ki.RR_SUBSCRIBER_FAILED:ki.RR_PUBLISHER_FAILED));const a=this.client.isDisconnected||this.client.currentState===Oe.RECONNECTING,c=[Ye.FAILED,Ye.CLOSING,Ye.CLOSED].includes(A);a&&c&&!this._isClosed&&this.emit(D.Offline)}),this.pcManager.onTrack=A=>{this.emit(D.MediaTrackAdded,A.track,A.streams[0],A.receiver)},Qx((r=e.serverInfo)===null||r===void 0?void 0:r.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>S(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=e=>S(this,void 0,void 0,function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid})),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:r}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],r(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(D.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(D.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(D.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(D.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid,this.emit(D.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",ki.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Ti.DISCONNECT:this.emit(D.Disconnected,e==null?void 0:e.reason),this.close();break;case Ti.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(id);break;case Ti.RESUME:this.handleDisconnect(id)}}}makeRTCConfiguration(e){var t;const r=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),r.encodedInsertableStreams=!0),e.iceServers&&!r.iceServers){const i=[];e.iceServers.forEach(A=>{const s={urls:A.urls};A.username&&(s.username=A.username),A.credential&&(s.credential=A.credential),i.push(s)}),r.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===LA.ENABLED&&(r.iceTransportPolicy="relay"),r.sdpSemantics="unified-plan",r.continualGatheringPolicy="gather_continually",r}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(U0,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(T0,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,r){return S(this,void 0,void 0,function*(){if(Fl())return yield this.createTransceiverRTCRtpSender(e,t,r);if(xl())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new lt("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,r,i){return S(this,void 0,void 0,function*(){if(Fl())return this.createSimulcastTransceiverSender(e,t,r,i);if(xl())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new lt("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,r){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new lt("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),Pi(e)&&(e.codec=t.videoCodec);const A={direction:"sendonly",streams:i};return r&&(A.sendEncodings=r),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,A)).sender})}createSimulcastTransceiverSender(e,t,r,i){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new lt("publisher is closed");const A={direction:"sendonly"};i&&(A.sendEncodings=i);const s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,A);if(r.videoCodec)return e.setSimulcastTrackSender(r.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new lt("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return S(this,void 0,void 0,function*(){var t,r,i;if(!this._isClosed){if(this.attemptingReconnect){ue.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===LA.DISABLED||((i=(r=this.pcManager)===null||r===void 0?void 0:r.currentState)!==null&&i!==void 0?i:Ye.NEW)===Ye.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(A){this.reconnectAttempts+=1;let s=!0;A instanceof lt?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:A})),s=!1):A instanceof Mi||(this.fullReconnectOnNext=!0),s?this.handleDisconnect("reconnect",ki.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(D.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(t){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return S(this,void 0,void 0,function*(){var t,r,i;try{if(!this.url||!this.token)throw new lt("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(D.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let A;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new Mi;A=yield this.join(e??this.url,this.token,this.signalOpts)}catch(s){throw s instanceof Fe&&s.reason===de.NotAllowed?new lt("could not reconnect, token might be expired"):new Mi}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(D.SignalRestarted,A),yield this.waitForPCReconnected(),this.client.currentState!==Oe.CONNECTED)throw new Mi("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(D.Restarted)}catch(A){const s=yield(r=this.regionUrlProvider)===null||r===void 0?void 0:r.getNextBestRegionUrl();if(s){yield this.restartConnection(s);return}else throw(i=this.regionUrlProvider)===null||i===void 0||i.resetAttempts(),A}})}resumeConnection(e){return S(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new lt("could not reconnect, url or token not saved");if(!this.pcManager)throw new lt("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(D.Resuming);let r;try{this.setupSignalClientCallbacks(),r=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(i){let A="";throw i instanceof Error&&(A=i.message,this.log.error(i.message,Object.assign(Object.assign({},this.logContext),{error:i}))),i instanceof Fe&&i.reason===de.NotAllowed?new lt("could not reconnect, token might be expired"):i instanceof Fe&&i.reason===de.LeaveRequest?i:new Mi(A)}if(this.emit(D.SignalResumed),r){const i=this.makeRTCConfiguration(r);this.pcManager.updateConfiguration(i)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Oe.CONNECTED)throw new Mi("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),this.emit(D.Resumed)})}waitForPCInitialConnection(e,t){return S(this,void 0,void 0,function*(){if(!this.pcManager)throw new lt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return S(this,void 0,void 0,function*(){this.pcState=dn.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Nt(Fx),!this.pcManager)throw new lt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=dn.Connected}catch(e){throw this.pcState=dn.Disconnected,new Fe("could not establish PC connection, ".concat(e.message),de.InternalError)}})}publishRpcResponse(e,t,r,i){return S(this,void 0,void 0,function*(){const A=new Dt({destinationIdentities:[e],kind:pe.RELIABLE,value:{case:"rpcResponse",value:new Pm({requestId:t,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:r??""}})}});yield this.sendDataPacket(A,pe.RELIABLE)})}publishRpcAck(e,t){return S(this,void 0,void 0,function*(){const r=new Dt({destinationIdentities:[e],kind:pe.RELIABLE,value:{case:"rpcAck",value:new Rm({requestId:t})}});yield this.sendDataPacket(r,pe.RELIABLE)})}sendDataPacket(e,t){return S(this,void 0,void 0,function*(){const r=e.toBinary();yield this.ensurePublisherConnected(t);const i=this.dataChannelForKind(t);i&&i.send(r),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,r)=>S(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const i=()=>r("Engine closed");for(this.once(D.Closing,i);!this.dcBufferStatus.get(e);)yield Nt(10);this.off(D.Closing,i),t()}}))}ensureDataTransportConnected(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var A;if(!r.pcManager)throw new lt("PC manager is closed");const s=i?r.pcManager.subscriber:r.pcManager.publisher,o=i?"Subscriber":"Publisher";if(!s)throw new Fe("".concat(o," connection not set"),de.InternalError);let a=!1;!i&&!r.dataChannelForKind(t,i)&&(r.createDataChannels(),a=!0),!a&&!i&&!r.pcManager.publisher.isICEConnected&&r.pcManager.publisher.getICEConnectionState()!=="checking"&&(a=!0),a&&r.negotiate();const c=r.dataChannelForKind(t,i);if((c==null?void 0:c.readyState)==="open")return;const u=new Date().getTime()+r.peerConnectionTimeout;for(;new Date().getTime()<u;){if(s.isICEConnected&&((A=r.dataChannelForKind(t,i))===null||A===void 0?void 0:A.readyState)==="open")return;yield Nt(50)}throw new Fe("could not establish ".concat(o," connection, state: ").concat(s.getICEConnectionState()),de.InternalError)}()})}ensurePublisherConnected(e){return S(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Ye.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return S(this,void 0,void 0,function*(){return new Promise((e,t)=>S(this,void 0,void 0,function*(){if(!this.pcManager){t(new _l("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const r=new AbortController,i=()=>{r.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(D.Closing,i),this.pcManager.publisher.once(Oi.RTPVideoPayloadTypes,A=>{const s=new Map;A.forEach(o=>{const a=o.codec.toLowerCase();KF(a)&&s.set(o.payload,a)}),this.emit(D.RTPVideoMapUpdate,s)});try{yield this.pcManager.negotiate(r),e()}catch(A){A instanceof _l&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ki.RR_UNKNOWN),t(A)}finally{this.off(D.Closing,i)}}))})}dataChannelForKind(e,t){if(t){if(e===pe.LOSSY)return this.lossyDCSub;if(e===pe.RELIABLE)return this.reliableDCSub}else{if(e===pe.LOSSY)return this.lossyDC;if(e===pe.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var r,i;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const A=this.pcManager.subscriber.getLocalDescription(),s=this.pcManager.subscriber.getRemoteDescription(),o=(i=(r=this.signalOpts)===null||r===void 0?void 0:r.autoSubscribe)!==null&&i!==void 0?i:!0,a=new Array,c=new Array;e.forEach(u=>{u.isDesired!==o&&a.push(u.trackSid),u.isEnabled||c.push(u.trackSid)}),this.client.sendSyncState(new $m({answer:A?sa({sdp:A.sdp,type:A.type}):void 0,offer:s?sa({sdp:s.sdp,type:s.type}):void 0,subscription:new Go({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:YF(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(r,i)=>{(r==null?void 0:r.id)!==void 0&&r.id!==null&&e.push(new ev({label:r.label,id:r.id,target:i}))};return t(this.dataChannelForKind(pe.LOSSY),an.PUBLISHER),t(this.dataChannelForKind(pe.RELIABLE),an.PUBLISHER),t(this.dataChannelForKind(pe.LOSSY,!0),an.SUBSCRIBER),t(this.dataChannelForKind(pe.RELIABLE,!0),an.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&wt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ht()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Ht()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Mi extends Error{}function Qx(n){return n!==void 0&&n>13}function Rx(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const r=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=r,e.destinationIdentities=r}class Ad{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Rl(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return S(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter(r=>!this.attemptedRegions.find(i=>i.url===r.url));if(t.length>0){const r=t[0];return this.attemptedRegions.push(r),ue.debug("next region: ".concat(r.region)),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return S(this,void 0,void 0,function*(){const t=yield fetch("".concat(Px(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const r=yield t.json();return this.lastUpdateAt=Date.now(),r}else throw new Fe("Could not fetch region settings: ".concat(t.statusText),t.status===401?de.NotAllowed:de.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function Px(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class I0{get info(){return this._info}constructor(e,t,r){this.reader=t,this.totalByteSize=r,this._info=e,this.bytesReceived=0}}class Ox extends I0{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>S(this,void 0,void 0,function*(){try{const{done:t,value:r}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(r),{done:!1,value:r.content})}catch{return{done:!0,value:void 0}}}),return(){return S(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return S(this,void 0,void 0,function*(){var e,t,r,i;let A=new Set;try{for(var s=!0,o=ur(this),a;a=yield o.next(),e=a.done,!e;s=!0){i=a.value,s=!1;const c=i;A.add(c)}}catch(c){t={error:c}}finally{try{!s&&!e&&(r=o.return)&&(yield r.call(o))}finally{if(t)throw t.error}}return Array.from(A)})}}class Mx extends I0{constructor(e,t,r){super(e,t,r),this.receivedChunks=new Map}handleChunkReceived(e){var t;const r=ia(e.chunkIndex),i=this.receivedChunks.get(r);if(i&&i.version>e.version)return;this.receivedChunks.set(r,e),this.bytesReceived+=e.content.byteLength;const A=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,A)}[Symbol.asyncIterator](){const e=this.reader.getReader(),t=new TextDecoder;return{next:()=>S(this,void 0,void 0,function*(){try{const{done:r,value:i}=yield e.read();return r?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:t.decode(i.content)})}catch{return{done:!0,value:void 0}}}),return(){return S(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return S(this,void 0,void 0,function*(){var e,t,r,i;let A="";try{for(var s=!0,o=ur(this),a;a=yield o.next(),e=a.done,!e;s=!0)i=a.value,s=!1,A+=i}catch(c){t={error:c}}finally{try{!s&&!e&&(r=o.return)&&(yield r.call(o))}finally{if(t)throw t.error}}return A})}}class F0{constructor(e,t,r){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=r,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return S(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class Lx extends F0{}class Dx extends F0{}class x0 extends R{constructor(e,t,r,i,A){super(e,r,A),this.sid=t,this.receiver=i}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?L.Muted:L.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=r=>{r.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(L.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return S(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),ed)),ZF()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const r=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(r){const{timestamp:i,rtpTimestamp:A}=r;A&&this.rtpTimestamp!==A&&(this.emit(L.TimeSyncUpdate,{timestamp:i,rtpTimestamp:A}),this.rtpTimestamp=A)}};e()}}class Nx extends x0{constructor(e,t,r,i,A,s){super(e,t,R.Kind.Audio,r,s),this.monitorReceiver=()=>S(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=oa(o,this.prevStats)),this.prevStats=o}),this.audioContext=i,this.webAudioPluginNodes=[],A&&(this.sinkId=A.deviceId)}setVolume(e){var t;for(const r of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):r.volume=e;kn()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(kn())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return S(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Ql(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Ql(e)&&e.setSinkId(this.sinkId).catch(r=>{this.log.error("Failed to set sink id on remote audio track",r,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let r=this.sourceNode;this.webAudioPluginNodes.forEach(i=>{r.connect(i),r=i}),this.gainNode=e.createGain(),r.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(L.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(i=>{this.emit(L.AudioPlaybackFailed,i)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return S(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(r=>{r.type==="inbound-rtp"&&(t={type:"audio",streamId:r.id,timestamp:r.timestamp,jitter:r.jitter,bytesReceived:r.bytesReceived,concealedSamples:r.concealedSamples,concealmentEvents:r.concealmentEvents,silentConcealedSamples:r.silentConcealedSamples,silentConcealmentEvents:r.silentConcealmentEvents,totalAudioEnergy:r.totalAudioEnergy,totalSamplesDuration:r.totalSamplesDuration})}),t})}}const sd=100;class Hx extends x0{constructor(e,t,r,i,A){super(e,t,R.Kind.Video,r,A),this.elementInfos=[],this.monitorReceiver=()=>S(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const s=yield this.getReceiverStats();s&&this.prevStats&&this.receiver&&(this._currentBitrate=oa(s,this.prevStats)),this.prevStats=s}),this.debouncedHandleResize=Xl(()=>{this.updateDimensions()},sd),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?xi(this._mediaStreamTrack,t):Fi(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new Kx(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(r=>r===e);for(const r of t)r.stopObserving();this.elementInfos=this.elementInfos.filter(r=>r!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const r of t)this.stopObservingElement(r);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return S(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,r="",i=new Map;return e.forEach(A=>{A.type==="inbound-rtp"?(r=A.codecId,t={type:"video",streamId:A.id,framesDecoded:A.framesDecoded,framesDropped:A.framesDropped,framesReceived:A.framesReceived,packetsReceived:A.packetsReceived,packetsLost:A.packetsLost,frameWidth:A.frameWidth,frameHeight:A.frameHeight,pliCount:A.pliCount,firCount:A.firCount,nackCount:A.nackCount,jitter:A.jitter,timestamp:A.timestamp,bytesReceived:A.bytesReceived,decoderImplementation:A.decoderImplementation}):A.type==="codec"&&i.set(A.id,A)}),t&&r!==""&&i.get(r)&&(t.mimeType=i.get(r).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(r=>r.element===e);for(const r of t)this.stopObservingElementInfo(r)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return S(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const r=this.elementInfos.reduce((o,a)=>Math.max(o,a.visibilityChangedAt||0),0),i=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,A=this.elementInfos.some(o=>o.pictureInPicture),s=this.elementInfos.some(o=>o.visible)&&!i||A;if(this.lastVisible!==s){if(!s&&Date.now()-r<sd){wt.setTimeout(()=>{this.updateVisibility()},sd);return}this.lastVisible=s,this.emit(L.VisibilityChanged,s,this)}}updateDimensions(){var e,t;let r=0,i=0;const A=this.getPixelDensity();for(const s of this.elementInfos){const o=s.width()*A,a=s.height()*A;o+a>r+i&&(r=o,i=a)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===r&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===i||(this.lastDimensions={width:r,height:i},this.emit(L.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?$v():t||($v()>2?2:1)}}class Kx{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=r=>{var i;const{target:A,isIntersecting:s}=r;A===this.element&&(this.isIntersecting=s,this.isPiP=jA(this.element),this.visibilityChangedAt=Date.now(),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this))},this.onEnterPiP=()=>{var r,i,A;(i=(r=window.documentPictureInPicture)===null||r===void 0?void 0:r.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP),this.isPiP=jA(this.element),(A=this.handleVisibilityChanged)===null||A===void 0||A.call(this)},this.onLeavePiP=()=>{var r;this.isPiP=jA(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.element=e,this.isIntersecting=t??od(e),this.isPiP=Ht()&&jA(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,r;this.isIntersecting=od(this.element),this.isPiP=jA(this.element),this.element.handleResize=()=>{var i;(i=this.handleResize)===null||i===void 0||i.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,t0().observe(this.element),e0().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(r=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,r,i,A;(e=t0())===null||e===void 0||e.unobserve(this.element),(t=e0())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(r=window.documentPictureInPicture)===null||r===void 0||r.removeEventListener("enter",this.onEnterPiP),(A=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||A===void 0||A.removeEventListener("pagehide",this.onLeavePiP)}}function jA(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?od(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function od(n,e){const t=e||window;let r=n.offsetTop,i=n.offsetLeft;const A=n.offsetWidth,s=n.offsetHeight,{hidden:o}=n,{display:a}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,r+=n.offsetTop,i+=n.offsetLeft;return r<t.pageYOffset+t.innerHeight&&i<t.pageXOffset+t.innerWidth&&r+s>t.pageYOffset&&i+A>t.pageXOffset&&!o&&a!=="none"}class Hn extends Sn.EventEmitter{constructor(e,t,r,i){var A;super(),this.metadataMuted=!1,this.encryption=Wt.NONE,this.log=ue,this.handleMuted=()=>{this.emit(L.Muted)},this.handleUnmuted=()=>{this.emit(L.Unmuted)},this.log=Ln((A=i==null?void 0:i.loggerName)!==null&&A!==void 0?A:cn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=r,this.source=R.Source.Unknown}setTrack(e){this.track&&(this.track.off(L.Muted,this.handleMuted),this.track.off(L.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(L.Muted,this.handleMuted),e.on(L.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),_e(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==Wt.NONE}get audioTrack(){if(Nn(this.track))return this.track}get videoTrack(){if(Pi(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=R.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===R.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(n.PermissionStatus||(n.PermissionStatus={}))})(Hn||(Hn={}));class ad extends Hn{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,r,i){super(e,t.sid,t.name,i),this.track=void 0,this.handleTrackEnded=()=>{this.emit(L.Ended)},this.updateInfo(t),this.setTrack(r)}setTrack(e){this.track&&this.track.off(L.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(L.Ended,this.handleTrackEnded)}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return S(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return S(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return S(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return S(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Nn(this.track)){const t=this.track.getSourceTrackSettings(),r=new Set;return t.autoGainControl&&r.add(on.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&r.add(on.TF_ECHO_CANCELLATION),t.noiseSuppression&&r.add(on.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&r.add(on.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||r.add(on.TF_NO_DTX),this.track.enhancedNoiseCancellation&&r.add(on.TF_ENHANCED_NOISE_CANCELLATION),Array.from(r.values())}else return[]}}function la(n,e){return S(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:r,videoProcessor:i,optionsWithoutProcessor:A}=a0(n);let s=A.audio,o=A.video;if(r&&typeof A.audio=="object"&&(A.audio.processor=r),i&&typeof A.video=="object"&&(A.video.processor=i),n.audio&&typeof A.audio=="object"&&typeof A.audio.deviceId=="string"){const l=A.audio.deviceId;A.audio.deviceId={exact:l},t=!0,s=Object.assign(Object.assign({},A.audio),{deviceId:{ideal:l}})}if(A.video&&typeof A.video=="object"&&typeof A.video.deviceId=="string"){const l=A.video.deviceId;A.video.deviceId={exact:l},t=!0,o=Object.assign(Object.assign({},A.video),{deviceId:{ideal:l}})}(A.audio===!0||typeof A.audio=="object"&&!A.audio.deviceId)&&(A.audio={deviceId:"default"}),A.video===!0?A.video={deviceId:"default"}:typeof A.video=="object"&&!A.video.deviceId&&(A.video.deviceId="default");const a=i0(A,v0,y0),c=Vl(a),u=navigator.mediaDevices.getUserMedia(c);A.audio&&(ft.userMediaPromiseMap.set("audioinput",u),u.catch(()=>ft.userMediaPromiseMap.delete("audioinput"))),A.video&&(ft.userMediaPromiseMap.set("videoinput",u),u.catch(()=>ft.userMediaPromiseMap.delete("videoinput")));try{const l=yield u;return yield Promise.all(l.getTracks().map(d=>S(this,void 0,void 0,function*(){const h=d.kind==="audio";let f=h?a.audio:a.video;(typeof f=="boolean"||!f)&&(f={});let p;const g=h?c.audio:c.video;typeof g!="boolean"&&(p=g);const v=d.getSettings().deviceId;p!=null&&p.deviceId&&fr(p.deviceId)!==v?p.deviceId=v:p||(p={deviceId:v});const y=yx(d,p,e);return y.kind===R.Kind.Video?y.source=R.Source.Camera:y.kind===R.Kind.Audio&&(y.source=R.Source.Microphone),y.mediaStream=l,Nn(y)&&r?yield y.setProcessor(r):Pi(y)&&i&&(yield y.setProcessor(i)),y})))}catch(l){if(!t)throw l;return la(Object.assign(Object.assign({},n),{audio:s,video:o}),e)}})}function Vx(n){return S(this,void 0,void 0,function*(){return(yield la({audio:!1,video:n??!0}))[0]})}function Gx(n){return S(this,void 0,void 0,function*(){return(yield la({audio:n??!0,video:!1}))[0]})}var vr;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(vr||(vr={}));function jx(n){switch(n){case MA.EXCELLENT:return vr.Excellent;case MA.GOOD:return vr.Good;case MA.POOR:return vr.Poor;case MA.LOST:return vr.Lost;default:return vr.Unknown}}class Q0 extends Sn.EventEmitter{get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){var e;return((e=this.permissions)===null||e===void 0?void 0:e.agent)||this.kind===Vo.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Ei.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,r,i,A,s){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Vo.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=vr.Unknown,this.log=ue,this.log=Ln((a=s==null?void 0:s.loggerName)!==null&&a!==void 0?a:cn.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=r,this.metadata=i,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=A??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Ll,this.once(K.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(R.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(R.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(R.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var t;return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===Ei.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Ei.ACTIVE&&this.emit(K.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,r=this.metadata;this.metadata=e,t&&this.emit(K.ParticipantMetadataChanged,r)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(K.ParticipantNameChanged,e)}_setAttributes(e){const t=$F(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(K.AttributesChanged,t)}setPermissions(e){var t,r,i,A,s,o;const a=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((r=this.permissions)===null||r===void 0?void 0:r.canSubscribe)||e.canPublishData!==((i=this.permissions)===null||i===void 0?void 0:i.canPublishData)||e.hidden!==((A=this.permissions)===null||A===void 0?void 0:A.hidden)||e.recorder!==((s=this.permissions)===null||s===void 0?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((u,l)=>{var d;return u!==((d=this.permissions)===null||d===void 0?void 0:d.canPublishSources[l])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(K.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(K.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=jx(e),t!==this._connectionQuality&&this.emit(K.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>Nn(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(L.Muted,()=>{this.emit(K.TrackMuted,e)}),e.on(L.Unmuted,()=>{this.emit(K.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case R.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case R.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Wx(n){var e,t,r;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Ym({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(r=n.allowAll)!==null&&r!==void 0?r:!1,trackSids:n.allowedTrackSids||[]})}const R0=15e3;class qx extends Q0{constructor(e,t,r,i,A){super(e,t,void 0,void 0,void 0,{loggerName:i.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=Wt.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Ll)},this.handleReconnected=()=>{var s,o;(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.resolve)===null||o===void 0||o.call(s),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var s,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(a=>this.log.warn(a.message,this.logContext)),(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.reject)===null||o===void 0||o.call(s,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=s=>{const{requestId:o,reason:a,message:c}=s,u=this.pendingSignalRequests.get(o);u&&(a!==dl.OK&&u.reject(new Wv(c,a)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=s=>{switch(s.value.case){case"rpcResponse":let o=s.value.value,a=null,c=null;o.value.case==="payload"?a=o.value.value:o.value.case==="error"&&(c=Ze.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,a,c);break;case"rpcAck":let u=s.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(s=>Wx(s)))},this.onTrackUnmuted=s=>{this.onTrackMuted(s,s.isUpstreamPaused)},this.onTrackMuted=(s,o)=>{if(o===void 0&&(o=!0),!s.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),_e(s)));return}this.engine.updateMuteStatus(s.sid,o)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),_e(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),_e(s))),this.onTrackMuted(s,s.isMuted)},this.onTrackFeatureUpdate=s=>{const o=this.audioTrackPublications.get(s.sid);if(!o){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(s.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.handleSubscribedQualityUpdate=s=>S(this,void 0,void 0,function*(){var o,a,c,u,l,d;if(!(!((l=this.roomOptions)===null||l===void 0)&&l.dynacast))return;const h=this.videoTrackPublications.get(s.trackSid);if(!h){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}if(s.subscribedCodecs.length>0){if(!h.videoTrack)return;const v=yield h.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var f=!0,p=ur(v),g;g=yield p.next(),o=g.done,!o;f=!0){u=g.value,f=!1;const y=u;FF(y)&&(this.log.debug("publish ".concat(y," for ").concat(h.videoTrack.sid),Object.assign(Object.assign({},this.logContext),_e(h))),yield this.publishAdditionalCodecForTrack(h.videoTrack,y,h.options))}}catch(y){a={error:y}}finally{try{!f&&!o&&(c=p.return)&&(yield c.call(p))}finally{if(a)throw a.error}}}else s.subscribedQualities.length>0&&(yield(d=h.videoTrack)===null||d===void 0?void 0:d.setPublishingLayers(s.subscribedQualities))}),this.handleLocalTrackUnpublished=s=>{const o=this.trackPublications.get(s.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=s=>S(this,void 0,void 0,function*(){if(s.source===R.Source.ScreenShare||s.source===R.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),_e(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(Jr(s)||gr(s))try{if(Ht())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:s.source===R.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(s.source),Object.assign(Object.assign({},this.logContext),_e(s))),o.onchange=()=>{o.state!=="denied"&&(s.isMuted||s.restartTrack(),o.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}s.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),_e(s))),Jr(s)?yield s.restartTrack({deviceId:"default"}):yield s.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),_e(s))),yield s.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=r,this.roomOptions=i,this.setupEngine(r),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=A}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==Wt.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(D.RemoteMute,(t,r)=>{const i=this.trackPublications.get(t);!i||!i.track||(r?i.mute():i.unmute())}),this.engine.on(D.Connected,this.handleReconnected).on(D.SignalRestarted,this.handleReconnected).on(D.SignalResumed,this.handleReconnected).on(D.Restarting,this.handleReconnecting).on(D.Resuming,this.handleReconnecting).on(D.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(D.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(D.Disconnected,this.handleDisconnected).on(D.SignalRequestResponse,this.handleSignalRequestResponse).on(D.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return S(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return S(this,arguments,void 0,function(t){var r=this;let{metadata:i,name:A,attributes:s}=t;return function*(){return new Promise((o,a)=>S(r,void 0,void 0,function*(){var c,u;try{let l=!1;const d=yield this.engine.client.sendUpdateLocalMetadata((c=i??this.metadata)!==null&&c!==void 0?c:"",(u=A??this.name)!==null&&u!==void 0?u:"",s),h=performance.now();for(this.pendingSignalRequests.set(d,{resolve:o,reject:f=>{a(f),l=!0},values:{name:A,metadata:i,attributes:s}});performance.now()-h<5e3&&!l;){if((!A||this.name===A)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every(f=>{let[p,g]=f;return this.attributes[p]===g||g===""&&!this.attributes[p]}))){this.pendingSignalRequests.delete(d),o();return}yield Nt(50)}a(new Wv("Request to update local metadata timed out","TimeoutError"))}catch(l){l instanceof Error&&a(l)}}))}()})}setCameraEnabled(e,t,r){return this.setTrackEnabled(R.Source.Camera,e,t,r)}setMicrophoneEnabled(e,t,r){return this.setTrackEnabled(R.Source.Microphone,e,t,r)}setScreenShareEnabled(e,t,r){return this.setTrackEnabled(R.Source.ScreenShare,e,t,r)}setPermissions(e){const t=this.permissions,r=super.setPermissions(e);return r&&t&&this.emit(K.ParticipantPermissionsChanged,t),r}setE2EEEnabled(e){return S(this,void 0,void 0,function*(){this.encryptionType=e?Wt.GCM:Wt.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,r,i){return S(this,void 0,void 0,function*(){var A,s;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let a;if(this.pendingPublishing.has(e)){const c=yield this.waitForPendingPublicationOfSource(e);return c||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield c==null?void 0:c.unmute(),c}this.pendingPublishing.add(e);try{switch(e){case R.Source.Camera:a=yield this.createTracks({video:(A=r)!==null&&A!==void 0?A:!0});break;case R.Source.Microphone:a=yield this.createTracks({audio:(s=r)!==null&&s!==void 0?s:!0});break;case R.Source.ScreenShare:a=yield this.createScreenTracks(Object.assign({},r));break;default:throw new Dn(e)}}catch(c){throw a==null||a.forEach(u=>{u.stop()}),c instanceof Error&&this.emit(K.MediaDevicesError,c),this.pendingPublishing.delete(e),c}try{const c=[];for(const l of a)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),_e(l))),c.push(this.publishTrack(l,i));[o]=yield Promise.all(c)}catch(c){throw a==null||a.forEach(u=>{u.stop()}),c}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===R.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const a=this.getTrackPublication(R.Source.ScreenShareAudio);a&&a.track&&this.unpublishTrack(a.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return S(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(R.Source.Camera)||this.pendingPublishing.has(R.Source.Microphone))){this.pendingPublishing.add(R.Source.Camera),this.pendingPublishing.add(R.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(R.Source.Camera),this.pendingPublishing.delete(R.Source.Microphone)}}})}createTracks(e){return S(this,void 0,void 0,function*(){var t,r;e??(e={});const i=i0(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(r=this.roomOptions)===null||r===void 0?void 0:r.videoCaptureDefaults);try{return(yield la(i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Nn(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=R.Source.Microphone,this.emit(K.AudioStreamAcquired)),Pi(o)&&(this.cameraError=void 0,o.source=R.Source.Camera),o))}catch(A){throw A instanceof Error&&(e.audio&&(this.microphoneError=A),e.video&&(this.cameraError=A)),A}})}createScreenTracks(e){return S(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Cl("getDisplayMedia not supported");e.resolution===void 0&&!MF()&&(e.resolution=Il.h1080fps30.resolution);const t=XF(e),r=yield navigator.mediaDevices.getDisplayMedia(t),i=r.getVideoTracks();if(i.length===0)throw new Dn("no video track found");const A=new ua(i[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});A.source=R.Source.ScreenShare,e.contentHint&&(A.mediaStreamTrack.contentHint=e.contentHint);const s=[A];if(r.getAudioTracks().length>0){this.emit(K.AudioStreamAcquired);const o=new aa(r.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=R.Source.ScreenShareAudio,s.push(o)}return s})}publishTrack(e,t){return S(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,a,c,u;Jr(r)&&r.setAudioContext(A.audioContext),yield(o=A.reconnectFuture)===null||o===void 0?void 0:o.promise,A.republishPromise&&!s&&(yield A.republishPromise),Ri(r)&&A.pendingPublishPromises.has(r)&&(yield A.pendingPublishPromises.get(r));let l;if(r instanceof MediaStreamTrack)l=r.getConstraints();else{l=r.constraints;let v;switch(r.source){case R.Source.Microphone:v="audioinput";break;case R.Source.Camera:v="videoinput"}v&&A.activeDeviceMap.has(v)&&(l=Object.assign(Object.assign({},l),{deviceId:A.activeDeviceMap.get(v)}))}if(r instanceof MediaStreamTrack)switch(r.kind){case"audio":r=new aa(r,l,!0,A.audioContext,{loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});break;case"video":r=new ua(r,l,!0,{loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});break;default:throw new Dn("unsupported MediaStreamTrack kind ".concat(r.kind))}else r.updateLoggerOptions({loggerName:A.roomOptions.loggerName,loggerContextCb:()=>A.logContext});let d;if(A.trackPublications.forEach(v=>{v.track&&v.track===r&&(d=v)}),d)return A.log.warn("track has already been published, skipping",Object.assign(Object.assign({},A.logContext),_e(d))),d;const h="channelCount"in r.mediaStreamTrack.getSettings()&&r.mediaStreamTrack.getSettings().channelCount===2||r.mediaStreamTrack.getConstraints().channelCount===2,f=(a=i==null?void 0:i.forceStereo)!==null&&a!==void 0?a:h;f&&(i||(i={}),i.dtx===void 0&&A.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},A.logContext),_e(r))),i.red===void 0&&A.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(c=i.dtx)!==null&&c!==void 0||(i.dtx=!1),(u=i.red)!==null&&u!==void 0||(i.red=!1));const p=Object.assign(Object.assign({},A.roomOptions.publishDefaults),i);!LF()&&A.roomOptions.e2ee&&(A.log.info("End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2",Object.assign({},A.logContext)),p.simulcast=!1),p.source&&(r.source=p.source);const g=new Promise((v,y)=>S(A,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Oe.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:_e(r)}));const B=()=>S(this,void 0,void 0,function*(){try{const b=yield this.publish(r,p,f);v(b)}catch(b){y(b)}});setTimeout(()=>{this.engine.off(D.SignalConnected,B),y(new Sl("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(D.SignalConnected,B),this.engine.on(D.Closing,()=>{this.engine.off(D.SignalConnected,B),y(new Sl("publishing rejected as engine closed",499))})}else try{const B=yield this.publish(r,p,f);v(B)}catch(B){y(B)}}catch(B){y(B)}}));A.pendingPublishPromises.set(r,g);try{return yield g}catch(v){throw v}finally{A.pendingPublishPromises.delete(r)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),_e(e))),!1;const{canPublish:t,canPublishSources:r}=this.permissions;return t&&(r.length===0||r.map(i=>ex(i)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),_e(e))),!1)}publish(e,t,r){return S(this,void 0,void 0,function*(){var i,A,s,o,a,c,u,l,d,h;if(!this.hasPermissionsToPublish(e))throw new Sl("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(w=>Ri(e)&&w.source===e.source)&&e.source!==R.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),_e(e))),t.stopMicTrackOnMute&&Nn(e)&&(e.stopOnMute=!0),e.source===R.Source.ScreenShare&&Qi()&&(t.simulcast=!1),t.videoCodec==="av1"&&!RF()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!PF()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Yl),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(w=>t.videoCodec===Aa(w.mime))||(t.videoCodec=Aa(this.enabledPublishVideoCodecs[0].mime)));const p=t.videoCodec;e.on(L.Muted,this.onTrackMuted),e.on(L.Unmuted,this.onTrackUnmuted),e.on(L.Ended,this.handleTrackEnded),e.on(L.UpstreamPaused,this.onTrackUpstreamPaused),e.on(L.UpstreamResumed,this.onTrackUpstreamResumed),e.on(L.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const g=new ol({cid:e.mediaStreamTrack.id,name:t.name,type:R.kindToProto(e.kind),muted:e.isMuted,source:R.sourceToProto(e.source),disableDtx:!(!((i=t.dtx)!==null&&i!==void 0)||i),encryption:this.encryptionType,stereo:r,disableRed:this.isE2EEEnabled||!(!((A=t.red)!==null&&A!==void 0)||A),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy});let v;if(e.kind===R.Kind.Video){let w={width:0,height:0};try{w=yield e.waitForDimensions()}catch{const k=(o=(s=this.roomOptions.videoCaptureDefaults)===null||s===void 0?void 0:s.resolution)!==null&&o!==void 0?o:HA.h720.resolution;w={width:k.width,height:k.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),_e(e)),{dims:w}))}g.width=w.width,g.height=w.height,gr(e)&&(KA(p)&&(e.source===R.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),_e(e))))),t.scalabilityMode=(a=t.scalabilityMode)!==null&&a!==void 0?a:"L3T3_KEY"),g.simulcastCodecs=[new sl({codec:p,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Yl}),t.backupCodec&&p!==t.backupCodec.codec&&g.encryption===Wt.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),g.simulcastCodecs.push(new sl({codec:t.backupCodec.codec,cid:""})))),v=nd(e.source===R.Source.ScreenShare,g.width,g.height,t),g.layers=E0(g.width,g.height,v,KA(t.videoCodec))}else e.kind===R.Kind.Audio&&(v=[{maxBitrate:(c=t.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(l=(u=t.audioPreset)===null||u===void 0?void 0:u.priority)!==null&&l!==void 0?l:"high",networkPriority:(h=(d=t.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&h!==void 0?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new lt("cannot publish track when not connected");const y=()=>S(this,void 0,void 0,function*(){var w,_,k;if(!this.engine.pcManager)throw new lt("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,v),gr(e)&&((w=t.degradationPreference)!==null&&w!==void 0||(t.degradationPreference=Tx(e)),e.setDegradationPreference(t.degradationPreference)),v)if(Qi()&&e.kind===R.Kind.Audio){let T;for(const x of this.engine.pcManager.publisher.getTransceivers())if(x.sender===e.sender){T=x;break}T&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:T,codec:"opus",maxbr:!((_=v[0])===null||_===void 0)&&_.maxBitrate?v[0].maxBitrate/1e3:0})}else e.codec&&KA(e.codec)&&(!((k=v[0])===null||k===void 0)&&k.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:g.cid,codec:e.codec,maxbr:v[0].maxBitrate/1e3});yield this.engine.negotiate()});let B;if(this.enabledPublishVideoCodecs.length>0)B=(yield Promise.all([this.engine.addTrack(g),y()]))[0];else{B=yield this.engine.addTrack(g);let w;if(B.codecs.forEach(_=>{w===void 0&&(w=_.mimeType)}),w&&e.kind===R.Kind.Video){const _=Aa(w);_!==p&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),_e(e)),{codec:_})),t.videoCodec=_,v=nd(e.source===R.Source.ScreenShare,g.width,g.height,t))}yield y()}const b=new ad(e.kind,B,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return b.options=t,e.sid=B.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:v,trackInfo:B})),gr(e)?e.startMonitor(this.engine.client):Jr(e)&&e.startMonitor(),this.addTrackPublication(b),this.emit(K.LocalTrackPublished,b),b})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,r){return S(this,void 0,void 0,function*(){var i;if(this.encryptionType!==Wt.NONE)return;let A;if(this.trackPublications.forEach(h=>{h.track&&h.track===e&&(A=h)}),!A)throw new Dn("track is not published");if(!gr(e))throw new Dn("track is not a video track");const s=Object.assign(Object.assign({},(i=this.roomOptions)===null||i===void 0?void 0:i.publishDefaults),r),o=kx(e,t,s);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),_e(e)));return}const a=e.addSimulcastTrack(t,o);if(!a)return;const c=new ol({cid:a.mediaStreamTrack.id,type:R.kindToProto(e.kind),muted:e.isMuted,source:R.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=E0(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new lt("cannot publish track when not connected");const u=()=>S(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,s,o),yield this.engine.negotiate()}),d=(yield Promise.all([this.engine.addTrack(c),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))})}unpublishTrack(e,t){return S(this,void 0,void 0,function*(){var r,i;if(Ri(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),_e(e))),yield c)}const A=this.getPublicationForTrack(e),s=A?_e(A):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),s)),!A||!A.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),s));return}e=A.track,e.off(L.Muted,this.onTrackMuted),e.off(L.Unmuted,this.onTrackUnmuted),e.off(L.Ended,this.handleTrackEnded),e.off(L.UpstreamPaused,this.onTrackUpstreamPaused),e.off(L.UpstreamResumed,this.onTrackUpstreamResumed),e.off(L.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(i=(r=this.roomOptions)===null||r===void 0?void 0:r.stopLocalTrackOnUnpublish)!==null&&i!==void 0?i:!0),t?e.stop():e.stopMonitor();let o=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Ye.FAILED&&a)try{for(const c of this.engine.pcManager.publisher.getTransceivers())c.sender===a&&(c.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),gr(e)){for(const[,c]of e.simulcastCodecs)c.sender&&(this.engine.removeTrack(c.sender)&&(o=!0),c.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),s),{error:c}))}switch(this.trackPublications.delete(A.trackSid),A.kind){case R.Kind.Audio:this.audioTrackPublications.delete(A.trackSid);break;case R.Kind.Video:this.videoTrackPublications.delete(A.trackSid);break}return this.emit(K.LocalTrackUnpublished,A),A.setTrack(void 0),o&&(yield this.engine.negotiate()),A})}unpublishTracks(e){return S(this,void 0,void 0,function*(){return(yield Promise.all(e.map(r=>this.unpublishTrack(r)))).filter(r=>!!r)})}republishAllTracks(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){r.republishPromise&&(yield r.republishPromise),r.republishPromise=new Promise((A,s)=>S(r,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(a=>{a.track&&(t&&(a.options=Object.assign(Object.assign({},a.options),t)),o.push(a))}),yield Promise.all(o.map(a=>S(this,void 0,void 0,function*(){const c=a.track;yield this.unpublishTrack(c,!1),i&&!c.isMuted&&c.source!==R.Source.ScreenShare&&c.source!==R.Source.ScreenShareAudio&&(Jr(c)||gr(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:a.trackSid})),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,a.options,!0)}))),A()}catch(o){s(o)}finally{this.republishPromise=void 0}})),yield r.republishPromise}()})}publishData(e){return S(this,arguments,void 0,function(t){var r=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const A=i.reliable?pe.RELIABLE:pe.LOSSY,s=i.destinationIdentities,o=i.topic,a=new Dt({kind:A,value:{case:"user",value:new Fm({participantIdentity:r.identity,payload:t,destinationIdentities:s,topic:o})}});yield r.engine.sendDataPacket(a,A)}()})}publishDtmf(e,t){return S(this,void 0,void 0,function*(){const r=new Dt({kind:pe.RELIABLE,value:{case:"sipDtmf",value:new xm({code:e,digit:t})}});yield this.engine.sendDataPacket(r,pe.RELIABLE)})}sendChatMessage(e,t){return S(this,void 0,void 0,function*(){const r={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},i=new Dt({value:{case:"chatMessage",value:new el(Object.assign(Object.assign({},r),{timestamp:Ke.parse(r.timestamp)}))}});return yield this.engine.sendDataPacket(i,pe.RELIABLE),this.emit(K.ChatMessage,r),r})}editChatMessage(e,t){return S(this,void 0,void 0,function*(){const r=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),i=new Dt({value:{case:"chatMessage",value:new el(Object.assign(Object.assign({},r),{timestamp:Ke.parse(r.timestamp),editTimestamp:Ke.parse(r.editTimestamp)}))}});return yield this.engine.sendDataPacket(i,pe.RELIABLE),this.emit(K.ChatMessage,r),r})}sendText(e,t){return S(this,void 0,void 0,function*(){var r;const i=crypto.randomUUID(),s=new TextEncoder().encode(e).byteLength,o=(r=t==null?void 0:t.attachments)===null||r===void 0?void 0:r.map(()=>crypto.randomUUID()),a=new Array(o?o.length+1:1).fill(0),c=(l,d)=>{var h;a[d]=l;const f=a.reduce((p,g)=>p+g,0);(h=t==null?void 0:t.onProgress)===null||h===void 0||h.call(t,f)},u=yield this.streamText({streamId:i,totalSize:s,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:o,attributes:t==null?void 0:t.attributes});return yield u.write(e),c(1,0),yield u.close(),t!=null&&t.attachments&&o&&(yield Promise.all(t.attachments.map((l,d)=>S(this,void 0,void 0,function*(){return this._sendFile(o[d],l,{topic:t.topic,mimeType:l.type,onProgress:h=>{c(h,d+1)}})})))),u.info})}streamText(e){return S(this,void 0,void 0,function*(){var t,r;const i=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),A={id:i,mimeType:"text/plain",timestamp:Date.now(),topic:(r=e==null?void 0:e.topic)!==null&&r!==void 0?r:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},s=new nl({streamId:i,mimeType:A.mimeType,topic:A.topic,timestamp:qr(A.timestamp),totalLength:qr(e==null?void 0:e.totalSize),attributes:A.attributes,contentHeader:{case:"textHeader",value:new Vm({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?tl.UPDATE:tl.CREATE})}}),o=e==null?void 0:e.destinationIdentities,a=new Dt({destinationIdentities:o,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(a,pe.RELIABLE);let c=0;const u=this,l=new WritableStream({write(f){return S(this,void 0,void 0,function*(){for(const p of JF(f,R0)){yield u.engine.waitForBufferStatusLow(pe.RELIABLE);const g=new rl({content:p,streamId:i,chunkIndex:qr(c)}),v=new Dt({destinationIdentities:o,value:{case:"streamChunk",value:g}});yield u.engine.sendDataPacket(v,pe.RELIABLE),c+=1}})},close(){return S(this,void 0,void 0,function*(){const f=new il({streamId:i}),p=new Dt({destinationIdentities:o,value:{case:"streamTrailer",value:f}});yield u.engine.sendDataPacket(p,pe.RELIABLE)})},abort(f){console.log("Sink error:",f)}});let d=()=>S(this,void 0,void 0,function*(){yield h.close()});u.engine.once(D.Closing,d);const h=new Lx(l,A,()=>this.engine.off(D.Closing,d));return h})}sendFile(e,t){return S(this,void 0,void 0,function*(){const r=crypto.randomUUID();return yield this._sendFile(r,e,t),{id:r}})}_sendFile(e,t,r){return S(this,void 0,void 0,function*(){var i;const A=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(i=r==null?void 0:r.mimeType)!==null&&i!==void 0?i:t.type,topic:r==null?void 0:r.topic,destinationIdentities:r==null?void 0:r.destinationIdentities}),s=t.stream().getReader();for(;;){const{done:o,value:a}=yield s.read();if(o)break;yield A.write(a)}return yield A.close(),A.info})}streamBytes(e){return S(this,void 0,void 0,function*(){var t,r,i,A,s;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a=e==null?void 0:e.destinationIdentities,c={id:o,mimeType:(r=e==null?void 0:e.mimeType)!==null&&r!==void 0?r:"application/octet-stream",topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(A=e==null?void 0:e.name)!==null&&A!==void 0?A:"unknown"},u=new nl({totalLength:qr((s=c.size)!==null&&s!==void 0?s:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:qr(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Gm({name:c.name})}}),l=new Dt({destinationIdentities:a,value:{case:"streamHeader",value:u}});yield this.engine.sendDataPacket(l,pe.RELIABLE);let d=0;const h=new Mt,f=this.engine,p=this.log,g=new WritableStream({write(y){return S(this,void 0,void 0,function*(){const B=yield h.lock();let b=0;try{for(;b<y.byteLength;){const w=y.slice(b,b+R0);yield f.waitForBufferStatusLow(pe.RELIABLE);const _=new Dt({destinationIdentities:a,value:{case:"streamChunk",value:new rl({content:w,streamId:o,chunkIndex:qr(d)})}});yield f.sendDataPacket(_,pe.RELIABLE),d+=1,b+=w.byteLength}}finally{B()}})},close(){return S(this,void 0,void 0,function*(){const y=new il({streamId:o}),B=new Dt({destinationIdentities:a,value:{case:"streamTrailer",value:y}});yield f.sendDataPacket(B,pe.RELIABLE)})},abort(y){p.error("Sink error:",y)}});return new Dx(g,c)})}performRpc(e){return S(this,arguments,void 0,function(t){var r=this;let{destinationIdentity:i,method:A,payload:s,responseTimeout:o=1e4}=t;return function*(){return new Promise((c,u)=>S(r,void 0,void 0,function*(){var l,d,h,f;if($l(s)>w0){u(Ze.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((d=(l=this.engine.latestJoinResponse)===null||l===void 0?void 0:l.serverInfo)===null||d===void 0)&&d.version&&Wr((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){u(Ze.builtIn("UNSUPPORTED_SERVER"));return}const p=crypto.randomUUID();yield this.publishRpcRequest(i,p,A,s,o-2e3);const g=setTimeout(()=>{this.pendingAcks.delete(p),u(Ze.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(p),clearTimeout(v)},2e3);this.pendingAcks.set(p,{resolve:()=>{clearTimeout(g)},participantIdentity:i});const v=setTimeout(()=>{this.pendingResponses.delete(p),u(Ze.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(p,{resolve:(y,B)=>{clearTimeout(v),this.pendingAcks.has(p)&&(console.warn("RPC response received before ack",p),this.pendingAcks.delete(p),clearTimeout(g)),B?u(B):c(y??"")},participantIdentity:i})}))}()})}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,r){const i=this.pendingResponses.get(e);i?(i.resolve(t,r),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,r,i,A){return S(this,void 0,void 0,function*(){const s=new Dt({destinationIdentities:[e],kind:pe.RELIABLE,value:{case:"rpcRequest",value:new Qm({id:t,method:r,payload:i,responseTimeoutMs:A,version:1})}});yield this.engine.sendDataPacket(s,pe.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:r}]of this.pendingAcks)r===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:r,resolve:i}]of this.pendingResponses)r===e&&(i(null,Ze.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var r,i;const A=this.trackPublications.get(t.sid);if(A){const s=A.isMuted||((i=(r=A.track)===null||r===void 0?void 0:r.isUpstreamPaused)!==null&&i!==void 0?i:!1);s!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),_e(A)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(t.sid,s))}}),!0):!1}getPublicationForTrack(e){let t;return this.trackPublications.forEach(r=>{const i=r.track;i&&(e instanceof MediaStreamTrack?(Jr(i)||gr(i))&&i.mediaStreamTrack===e&&(t=r):e===i&&(t=r))}),t}waitForPendingPublicationOfSource(e){return S(this,void 0,void 0,function*(){const r=Date.now();for(;Date.now()<r+1e4;){const i=Array.from(this.pendingPublishPromises.entries()).find(A=>{let[s]=A;return s.source===e});if(i)return i[1];yield Nt(20)}})}}class Jx extends Hn{constructor(e,t,r,i){super(e,t.sid,t.name,i),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Yt.HIGH,this.handleEnded=A=>{this.setTrack(void 0),this.emit(L.Ended,A)},this.handleVisibilityChange=A=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(A),this.logContext),this.disabled=!A,this.emitTrackUpdate()},this.handleVideoDimensionsChange=A=>{this.log.debug("adaptivestream video dimensions ".concat(A.width,"x").concat(A.height),this.logContext),this.videoDimensions=A,this.emitTrackUpdate()},this.subscribed=r,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,r=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const i=new Go({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Mm({participantSid:"",trackSids:[this.trackSid]})]});this.emit(L.UpdateSubscription,i),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(r)}get subscriptionStatus(){return this.subscribed===!1?Hn.SubscriptionStatus.Unsubscribed:super.isSubscribed?Hn.SubscriptionStatus.Subscribed:Hn.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Hn.PermissionStatus.Allowed:Hn.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,r;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((r=this.videoDimensions)===null||r===void 0?void 0:r.height)===e.height||(Hl(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Hl(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,r=this.permissionStatus,i=this.track;i!==e&&(i&&(i.off(L.VideoDimensionsChanged,this.handleVideoDimensionsChange),i.off(L.VisibilityChanged,this.handleVisibilityChange),i.off(L.Ended,this.handleEnded),i.detach(),i.stopMonitor(),this.emit(L.Unsubscribed,i)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(L.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(L.VisibilityChanged,this.handleVisibilityChange),e.on(L.Ended,this.handleEnded),this.emit(L.Subscribed,e)),this.emitPermissionUpdateIfChanged(r),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,r=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(r),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(L.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?L.Muted:L.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(L.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(L.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===R.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Hl(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Wm({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=Yt.HIGH,this.emit(L.UpdateSettings,e)}}class da extends Q0{static fromParticipantInfo(e,t,r){return new da(e,t.sid,t.identity,t.name,t.metadata,t.attributes,r,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,r,i,A,s,o){let a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Vo.STANDARD;super(t,r||"",i,A,s,o,a),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(L.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),_e(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(L.UpdateSubscription,t=>{t.participantTracks.forEach(r=>{r.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(L.SubscriptionPermissionChanged,t=>{this.emit(K.TrackSubscriptionPermissionChanged,e,t)}),e.on(L.SubscriptionStatusChanged,t=>{this.emit(K.TrackSubscriptionStatusChanged,e,t)}),e.on(L.Subscribed,t=>{this.emit(K.TrackSubscribed,t,e)}),e.on(L.Unsubscribed,t=>{this.emit(K.TrackUnsubscribed,t,e)}),e.on(L.SubscriptionFailed,t=>{this.emit(K.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:R.Source.Microphone;this.volumeMap.set(t,e);const r=this.getTrackPublication(t);r&&r.track&&r.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:R.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,r,i,A,s){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(u=>{!o&&e.kind===u.kind.toString()&&(o=u)}),!o){if(s===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(K.TrackSubscriptionFailed,t);return}s===void 0&&(s=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,r,i,A,s-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),_e(o))),this.emit(K.TrackSubscriptionFailed,t);return}const a=e.kind==="video";let c;return a?c=new Hx(e,t,i,A):c=new Nx(e,t,i,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(r),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&Nl(c)&&Nn(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,r=new Map;return e.tracks.forEach(i=>{var A,s;let o=this.getTrackPublicationBySid(i.sid);if(o)o.updateInfo(i);else{const a=R.kindFromProto(i.type);if(!a)return;o=new Jx(a,i,(A=this.signalClient.connectOptions)===null||A===void 0?void 0:A.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(s=this.loggerOptions)===null||s===void 0?void 0:s.loggerName}),o.updateInfo(i),r.set(i.sid,o);const c=Array.from(this.trackPublications.values()).find(u=>u.source===(o==null?void 0:o.source));c&&o.source!==R.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:_e(c),newTrack:_e(o)})),this.addTrackPublication(o)}t.set(i.sid,o)}),this.trackPublications.forEach(i=>{t.has(i.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),_e(i))),this.unpublishTrack(i.trackSid,!0))}),r.forEach(i=>{this.emit(K.TrackPublished,i)}),!0}unpublishTrack(e,t){const r=this.trackPublications.get(e);if(!r)return;const{track:i}=r;switch(i&&(i.stop(),r.setTrack(void 0)),this.trackPublications.delete(e),r.kind){case R.Kind.Audio:this.audioTrackPublications.delete(e);break;case R.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(K.TrackUnpublished,r)}setAudioOutput(e){return S(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(r=>{var i;Nn(r.track)&&Nl(r.track)&&t.push(r.track.setSinkId((i=e.deviceId)!==null&&i!==void 0?i:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:r})),super.emit(e,...r)}}var fe;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(fe||(fe={}));const zx=4*1e3;class Li extends Sn.EventEmitter{constructor(e){var t,r,i,A;if(super(),t=this,this.state=fe.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ue,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(s,o,a)=>S(this,void 0,void 0,function*(){var c;if(!OF())throw kn()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const u=yield this.disconnectLock.lock();if(this.state===fe.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),u(),Promise.resolve();if(this.connectFuture)return u(),this.connectFuture.promise;this.setAndEmitConnectionState(fe.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==s&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Rl(new URL(s))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Ad(s,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(h=>{var f;(f=this.regionUrlProvider)===null||f===void 0||f.setServerReportedRegions(h)}).catch(h=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:h}))}));const l=(h,f,p)=>S(this,void 0,void 0,function*(){var g,v;this.abortController&&this.abortController.abort();const y=new AbortController;this.abortController=y,u==null||u();try{yield this.attemptConnection(p??s,o,a,y),this.abortController=void 0,h()}catch(B){if(this.regionUrlProvider&&B instanceof Fe&&B.reason!==de.Cancelled&&B.reason!==de.NotAllowed){let b=null;try{b=yield this.regionUrlProvider.getNextBestRegionUrl((g=this.abortController)===null||g===void 0?void 0:g.signal)}catch(w){if(w instanceof Fe&&(w.status===401||w.reason===de.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),f(w);return}}b&&!(!((v=this.abortController)===null||v===void 0)&&v.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(B.message,". Retrying with another region: ").concat(b),this.logContext),this.recreateEngine(),yield l(h,f,b)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,r0(B)),f(B))}else{let b=sn.UNKNOWN_REASON;B instanceof Fe&&(b=r0(B)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,b),f(B)}}}),d=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ll((h,f)=>{l(h,f,d)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(s,o,a,c,u,l)=>S(this,void 0,void 0,function*(){var d,h,f;const p=yield a.join(s,o,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof u.adaptiveStream=="object"?!0:u.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},l.signal);let g=p.serverInfo;if(g||(g={version:p.serverVersion,region:p.serverRegion}),this.serverInfo=g,this.log.debug("connected to Livekit Server ".concat(Object.entries(g).map(v=>{let[y,B]=v;return"".concat(y,": ").concat(B)}).join(", ")),{room:(d=p.room)===null||d===void 0?void 0:d.name,roomSid:(h=p.room)===null||h===void 0?void 0:h.sid,identity:(f=p.participant)===null||f===void 0?void 0:f.identity}),!g.version)throw new bF("unknown server version");return g.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),u.dynacast=!1),p}),this.applyJoinResponse=s=>{const o=s.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(s.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(s.sifTrailer)}catch(a){this.log.error(a instanceof Error?a.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:a}))}this.handleParticipantUpdates([o,...s.otherParticipants]),s.room&&this.handleRoomUpdate(s.room)},this.attemptConnection=(s,o,a,c)=>S(this,void 0,void 0,function*(){var u,l;this.state===fe.Reconnecting||this.isResuming||!((u=this.engine)===null||u===void 0)&&u.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((l=this.regionUrlProvider)===null||l===void 0)&&l.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Zl),a),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const d=yield this.connectSignal(s,o,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(d),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected)}catch(d){yield this.engine.close(),this.recreateEngine();const h=new Fe("could not establish signal connection",de.ServerUnreachable);throw d instanceof Error&&(h.message="".concat(h.message,": ").concat(d.message)),d instanceof Fe&&(h.reason=d.reason,h.status=d.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:d})),h}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new Fe("Connection attempt aborted",de.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(d){throw yield this.engine.close(),this.recreateEngine(),d}Ht()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ht()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(fe.Connected),this.emit(O.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];return S(t,[...o],void 0,function(){var c=this;let u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var l,d,h,f;const p=yield c.disconnectLock.lock();try{if(c.state===fe.Disconnected){c.log.debug("already disconnected",c.logContext);return}c.log.info("disconnect from room",Object.assign({},c.logContext)),(c.state===fe.Connecting||c.state===fe.Reconnecting||c.isResuming)&&(c.log.warn("abort connection attempt",c.logContext),(l=c.abortController)===null||l===void 0||l.abort(),(h=(d=c.connectFuture)===null||d===void 0?void 0:d.reject)===null||h===void 0||h.call(d,new Fe("Client initiated disconnect",de.Cancelled)),c.connectFuture=void 0),!((f=c.engine)===null||f===void 0)&&f.client.isDisconnected||(yield c.engine.client.sendLeave()),c.engine&&(yield c.engine.close()),c.handleDisconnect(u,sn.CLIENT_INITIATED),c.engine=void 0}finally{p()}}()})},this.onPageLeave=()=>S(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>S(this,void 0,void 0,function*(){const s=[],o=un();if(o&&o.os==="iOS"){const a="livekit-dummy-audio-el";let c=document.getElementById(a);if(!c){c=document.createElement("audio"),c.id=a,c.autoplay=!0,c.hidden=!0;const u=Ml();u.enabled=!0;const l=new MediaStream([u]);c.srcObject=l,document.addEventListener("visibilitychange",()=>{c&&(c.srcObject=document.hidden?null:l,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(c),this.once(O.Disconnected,()=>{c==null||c.remove(),c=null})}s.push(c)}this.remoteParticipants.forEach(a=>{a.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(u=>{s.push(u)})})});try{yield Promise.all([this.acquireAudioContext(),...s.map(a=>(a.muted=!1,a.play()))]),this.handleAudioPlaybackStarted()}catch(a){throw this.handleAudioPlaybackFailed(a),a}}),this.startVideo=()=>S(this,void 0,void 0,function*(){const s=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(a=>{var c;(c=a.track)===null||c===void 0||c.attachedElements.forEach(u=>{s.includes(u)||s.push(u)})});yield Promise.all(s.map(o=>o.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(o=>{o.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const s of this.remoteParticipants.values())this.handleParticipantDisconnected(s.identity,s);this.setAndEmitConnectionState(fe.Reconnecting)&&this.emit(O.Reconnecting)},this.handleSignalRestarted=s=>S(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(s.serverRegion),Object.assign(Object.assign({},this.logContext),{region:s.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(s);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(o){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:o}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:s.serverRegion}))}catch{return}this.setAndEmitConnectionState(fe.Connected),this.emit(O.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=s=>{s.forEach(o=>{var a;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(a=this.sidToIdentity.get(o.sid))!==null&&a!==void 0?a:"");let c=this.remoteParticipants.get(o.identity);o.state===Ei.DISCONNECTED?this.handleParticipantDisconnected(o.identity,c):c=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=s=>{const o=[],a={};s.forEach(c=>{if(a[c.sid]=!0,c.sid===this.localParticipant.sid)this.localParticipant.audioLevel=c.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const u=this.getRemoteParticipantBySid(c.sid);u&&(u.audioLevel=c.level,u.setIsSpeaking(!0),o.push(u))}}),a[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{a[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(O.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=s=>{const o=new Map;this.activeSpeakers.forEach(c=>{const u=this.remoteParticipants.get(c.identity);u&&u.sid!==c.sid||o.set(c.sid,c)}),s.forEach(c=>{let u=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(u=this.localParticipant),u&&(u.audioLevel=c.level,u.setIsSpeaking(c.active),c.active?o.set(c.sid,u):o.delete(c.sid))});const a=Array.from(o.values());a.sort((c,u)=>u.audioLevel-c.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(O.ActiveSpeakersChanged,a)},this.handleStreamStateUpdate=s=>{s.streamStates.forEach(o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);if(!c||!c.track)return;const u=R.streamStateFromProto(o.state);u!==c.track.streamState&&(c.track.streamState=u,a.emit(K.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(O.TrackStreamStateChanged,c,c.track.streamState,a))})},this.handleSubscriptionPermissionUpdate=s=>{const o=this.getRemoteParticipantBySid(s.participantSid);if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setAllowed(s.allowed)},this.handleSubscriptionError=s=>{const o=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(s.trackSid));if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setSubscriptionError(s.err)},this.handleDataPacket=s=>{const o=this.remoteParticipants.get(s.participantIdentity);if(s.value.case==="user")this.handleUserPacket(o,s.value.value,s.kind);else if(s.value.case==="transcription")this.handleTranscription(o,s.value.value);else if(s.value.case==="sipDtmf")this.handleSipDtmf(o,s.value.value);else if(s.value.case==="chatMessage")this.handleChatMessage(o,s.value.value);else if(s.value.case==="metrics")this.handleMetrics(s.value.value,o);else if(s.value.case==="streamHeader")this.handleStreamHeader(s.value.value,s.participantIdentity);else if(s.value.case==="streamChunk")this.handleStreamChunk(s.value.value);else if(s.value.case==="streamTrailer")this.handleStreamTrailer(s.value.value);else if(s.value.case==="rpcRequest"){const a=s.value.value;this.handleIncomingRpcRequest(s.participantIdentity,a.id,a.method,a.payload,a.responseTimeoutMs,a.version)}},this.handleUserPacket=(s,o,a)=>{this.emit(O.DataReceived,o.payload,s,a,o.topic),s==null||s.emit(K.DataReceived,o.payload,a)},this.handleSipDtmf=(s,o)=>{this.emit(O.SipDTMFReceived,o,s),s==null||s.emit(K.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(s,o)=>{const a=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),c=a==null?void 0:a.trackPublications.get(o.trackId),u=GF(o,this.transcriptionReceivedTimes);c==null||c.emit(L.TranscriptionReceived,u),a==null||a.emit(K.TranscriptionReceived,u,c),this.emit(O.TranscriptionReceived,u,a,c)},this.handleChatMessage=(s,o)=>{const a=jF(o);this.emit(O.ChatMessage,a,s)},this.handleMetrics=(s,o)=>{this.emit(O.MetricsReceived,s,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(O.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=s=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:s})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(O.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(O.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(O.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>S(this,void 0,void 0,function*(){var s,o,a;const c=ft.getInstance().previousDevices,u=yield ft.getInstance().getDevices(void 0,!1),l=un();if((l==null?void 0:l.name)==="Chrome"&&l.os!=="iOS")for(let h of u){const f=c.find(p=>p.deviceId===h.deviceId);f&&f.label!==""&&f.kind===h.kind&&f.label!==h.label&&this.getActiveDevice(h.kind)==="default"&&this.emit(O.ActiveDeviceChanged,h.kind,h.deviceId)}const d=["audiooutput","audioinput","videoinput"];for(let h of d){const f=zF(h),p=this.localParticipant.getTrackPublication(f);if(p&&(!((s=p.track)===null||s===void 0)&&s.isUserProvided))continue;const g=u.filter(y=>y.kind===h),v=this.getActiveDevice(h);if(v===((o=c.filter(y=>y.kind===h)[0])===null||o===void 0?void 0:o.deviceId)&&g.length>0&&((a=g[0])===null||a===void 0?void 0:a.deviceId)!==v){yield this.switchActiveDevice(h,g[0].deviceId);continue}h==="audioinput"&&!pr()||h==="videoinput"||g.length>0&&!g.find(y=>y.deviceId===this.getActiveDevice(h))&&(yield this.switchActiveDevice(h,g[0].deviceId))}this.emit(O.MediaDevicesChanged)}),this.handleRoomUpdate=s=>{const o=this.roomInfo;this.roomInfo=s,o&&o.metadata!==s.metadata&&this.emitWhenConnected(O.RoomMetadataChanged,s.metadata),(o==null?void 0:o.activeRecording)!==s.activeRecording&&this.emitWhenConnected(O.RecordingStatusChanged,s.activeRecording)},this.handleConnectionQualityUpdate=s=>{s.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const a=this.getRemoteParticipantBySid(o.participantSid);a&&a.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=s=>{this.emit(O.ParticipantMetadataChanged,s,this.localParticipant)},this.onLocalParticipantNameChanged=s=>{this.emit(O.ParticipantNameChanged,s,this.localParticipant)},this.onLocalAttributesChanged=s=>{this.emit(O.ParticipantAttributesChanged,s,this.localParticipant)},this.onLocalTrackMuted=s=>{this.emit(O.TrackMuted,s,this.localParticipant)},this.onLocalTrackUnmuted=s=>{this.emit(O.TrackUnmuted,s,this.localParticipant)},this.onTrackProcessorUpdate=s=>{var o;(o=s==null?void 0:s.onPublish)===null||o===void 0||o.call(s,this)},this.onLocalTrackPublished=s=>S(this,void 0,void 0,function*(){var o,a,c,u,l,d;(o=s.track)===null||o===void 0||o.on(L.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.on(L.Restarted,this.onLocalTrackRestarted),(l=(u=(c=s.track)===null||c===void 0?void 0:c.getProcessor())===null||u===void 0?void 0:u.onPublish)===null||l===void 0||l.call(u,this),this.emit(O.LocalTrackPublished,s,this.localParticipant),Jr(s.track)&&(yield s.track.checkForSilence())&&this.emit(O.LocalAudioSilenceDetected,s);const h=yield(d=s.track)===null||d===void 0?void 0:d.getDeviceId(!1),f=o0(s.source);f&&h&&h!==this.localParticipant.activeDeviceMap.get(f)&&(this.localParticipant.activeDeviceMap.set(f,h),this.emit(O.ActiveDeviceChanged,f,h))}),this.onLocalTrackUnpublished=s=>{var o,a;(o=s.track)===null||o===void 0||o.off(L.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.off(L.Restarted,this.onLocalTrackRestarted),this.emit(O.LocalTrackUnpublished,s,this.localParticipant)},this.onLocalTrackRestarted=s=>S(this,void 0,void 0,function*(){const o=yield s.getDeviceId(!1),a=o0(s.source);a&&o&&o!==this.localParticipant.activeDeviceMap.get(a)&&(this.log.debug("local track restarted, setting ".concat(a," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(a,o),this.emit(O.ActiveDeviceChanged,a,o))}),this.onLocalConnectionQualityChanged=s=>{this.emit(O.ConnectionQualityChanged,s,this.localParticipant)},this.onMediaDevicesError=s=>{this.emit(O.MediaDevicesError,s)},this.onLocalParticipantPermissionsChanged=s=>{this.emit(O.ParticipantPermissionsChanged,s,this.localParticipant)},this.onLocalChatMessageSent=s=>{this.emit(O.ChatMessage,s,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},gx),e),this.log=Ln((r=this.options.loggerName)!==null&&r!==void 0?r:cn.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},v0),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},y0),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},fx),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Mt,this.localParticipant=new qx("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",fr(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",fr(this.options.audioCaptureDefaults.deviceId)),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&this.switchActiveDevice("audiooutput",fr(this.options.audioOutput.deviceId)).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),Ht()){const s=new AbortController;(A=navigator.mediaDevices)===null||A===void 0||A.addEventListener("devicechange",this.handleDeviceChange,{signal:s.signal}),Li.cleanupRegistry&&Li.cleanupRegistry.register(this,()=>{s.abort()})}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t,r,i,A,s){return S(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),s!==1){yield this.engine.publishRpcResponse(e,t,null,Ze.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(r);if(!o){yield this.engine.publishRpcResponse(e,t,null,Ze.builtIn("UNSUPPORTED_METHOD"));return}let a=null,c=null;try{const u=yield o({requestId:t,callerIdentity:e,payload:i,responseTimeout:A});$l(u)>w0?(a=Ze.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(r))):c=u}catch(u){u instanceof Ze?a=u:(console.warn("Uncaught error returned by RPC handler for ".concat(r,". Returning APPLICATION_ERROR instead."),u),a=Ze.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,c,a)})}setE2EEEnabled(e){return S(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([this.localParticipant.setE2EEEnabled(e)]),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity);else throw Error("e2ee not configured, please set e2ee settings within the room options")})}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new tx(this.options.e2ee),this.e2eeManager.on(dr.ParticipantEncryptionStatusChanged,(t,r)=>{qF(r)&&(this.isE2EEEnabled=t),this.emit(O.ParticipantEncryptionStatusChanged,t,r)}),this.e2eeManager.on(dr.EncryptionError,t=>this.emit(O.EncryptionError,t)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&t!==void 0?t:!1}getSid(){return S(this,void 0,void 0,function*(){return this.state===fe.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const r=i=>{i.sid!==""&&(this.engine.off(D.RoomUpdate,r),e(i.sid))};this.engine.on(D.RoomUpdate,r),this.once(O.Disconnected,()=>{this.engine.off(D.RoomUpdate,r),t("Room disconnected before room server id was available")})})})}get name(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&t!==void 0?t:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&t!==void 0?t:0}get numPublishers(){var e,t;return(t=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&t!==void 0?t:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new xx(this.options),this.engine.on(D.ParticipantUpdate,this.handleParticipantUpdates).on(D.RoomUpdate,this.handleRoomUpdate).on(D.SpeakersChanged,this.handleSpeakersChanged).on(D.StreamStateChanged,this.handleStreamStateUpdate).on(D.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(D.SubscriptionError,this.handleSubscriptionError).on(D.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(D.MediaTrackAdded,(e,t,r)=>{this.onTrackAdded(e,t,r)}).on(D.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(D.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(D.DataPacketReceived,this.handleDataPacket).on(D.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(fe.SignalReconnecting)&&this.emit(O.SignalReconnecting)}).on(D.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(fe.Connected)&&this.emit(O.Reconnected)}).on(D.SignalResumed,()=>{this.bufferedEvents=[],(this.state===fe.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(D.Restarting,this.handleRestarting).on(D.SignalRestarted,this.handleSignalRestarted).on(D.Offline,()=>{this.setAndEmitConnectionState(fe.Reconnecting)&&this.emit(O.Reconnecting)}).on(D.DCBufferStatusChanged,(e,t)=>{this.emit(O.DCBufferStatusChanged,e,t)}).on(D.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(r=>{let{trackSid:i}=r;return i===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(K.LocalTrackSubscribed,t),this.emitWhenConnected(O.LocalTrackSubscribed,t,this.localParticipant)}).on(D.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,r)=>{this.handleParticipantDisconnected(r,t)}),this.emit(O.Moved,e.room.name,e.token),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return ft.getInstance().getDevices(e,t)}prepareConnection(e,t){return S(this,void 0,void 0,function*(){if(this.state===fe.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Rl(new URL(e))&&t){this.regionUrlProvider=new Ad(e,t);const r=yield this.regionUrlProvider.getNextBestRegionUrl();r&&this.state===fe.Disconnected&&(this.regionUrl=r,yield fetch(Dl(r),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(r),this.logContext))}else yield fetch(Dl(e),{method:"HEAD"})}catch(r){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:r}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return S(this,void 0,void 0,function*(){let r=()=>{},i;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new _n({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new _n({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new _n({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new _n({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":r=()=>S(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new _n({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":r=()=>S(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new _n({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":i=new _n({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),r=()=>S(this,void 0,void 0,function*(){const A=this.engine.client.onLeave;A&&A(new jo({reason:sn.CLIENT_INITIATED,action:Ti.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");i=new _n({scenario:{case:"subscriberBandwidth",value:qr(t)}});break;case"leave-full-reconnect":i=new _n({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield r())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return S(this,arguments,void 0,function(r,i){var A=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,a,c,u,l,d,h,f;let p=!0,g=!1;const v=s?{exact:i}:i;if(r==="audioinput"){g=A.localParticipant.audioTrackPublications.size===0;const y=(o=A.getActiveDevice(r))!==null&&o!==void 0?o:A.options.audioCaptureDefaults.deviceId;A.options.audioCaptureDefaults.deviceId=v;const B=Array.from(A.localParticipant.audioTrackPublications.values()).filter(b=>b.source===R.Source.Microphone);try{p=(yield Promise.all(B.map(b=>{var w;return(w=b.audioTrack)===null||w===void 0?void 0:w.setDeviceId(v)}))).every(b=>b===!0)}catch(b){throw A.options.audioCaptureDefaults.deviceId=y,b}}else if(r==="videoinput"){g=A.localParticipant.videoTrackPublications.size===0;const y=(a=A.getActiveDevice(r))!==null&&a!==void 0?a:A.options.videoCaptureDefaults.deviceId;A.options.videoCaptureDefaults.deviceId=v;const B=Array.from(A.localParticipant.videoTrackPublications.values()).filter(b=>b.source===R.Source.Camera);try{p=(yield Promise.all(B.map(b=>{var w;return(w=b.videoTrack)===null||w===void 0?void 0:w.setDeviceId(v)}))).every(b=>b===!0)}catch(b){throw A.options.videoCaptureDefaults.deviceId=y,b}}else if(r==="audiooutput"){if(!Ql()&&!A.options.webAudioMix||A.options.webAudioMix&&A.audioContext&&!("setSinkId"in A.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");A.options.webAudioMix&&(i=(c=yield ft.getInstance().normalizeDeviceId("audiooutput",i))!==null&&c!==void 0?c:""),(u=(f=A.options).audioOutput)!==null&&u!==void 0||(f.audioOutput={});const y=(l=A.getActiveDevice(r))!==null&&l!==void 0?l:A.options.audioOutput.deviceId;A.options.audioOutput.deviceId=i;try{A.options.webAudioMix&&((d=A.audioContext)===null||d===void 0||d.setSinkId(i)),yield Promise.all(Array.from(A.remoteParticipants.values()).map(B=>B.setAudioOutput({deviceId:i})))}catch(B){throw A.options.audioOutput.deviceId=y,B}}return(g||r==="audiooutput")&&(A.localParticipant.activeDeviceMap.set(r,r==="audiooutput"&&((h=A.options.audioOutput)===null||h===void 0?void 0:h.deviceId)||i),A.emit(O.ActiveDeviceChanged,r,i)),p}()})}setupLocalParticipantEvents(){this.localParticipant.on(K.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(K.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(K.AttributesChanged,this.onLocalAttributesChanged).on(K.TrackMuted,this.onLocalTrackMuted).on(K.TrackUnmuted,this.onLocalTrackUnmuted).on(K.LocalTrackPublished,this.onLocalTrackPublished).on(K.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(K.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(K.MediaDevicesError,this.onMediaDevicesError).on(K.AudioStreamAcquired,this.startAudio).on(K.ChatMessage,this.onLocalChatMessageSent).on(K.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,r){if(this.state===fe.Connecting||this.state===fe.Reconnecting){const u=()=>{this.onTrackAdded(e,t,r),l()},l=()=>{this.off(O.Reconnected,u),this.off(O.Connected,u),this.off(O.Disconnected,l)};this.once(O.Reconnected,u),this.once(O.Connected,u),this.once(O.Disconnected,l);return}if(this.state===fe.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const i=QF(t.id),A=i[0];let s=i[1],o=e.id;if(s&&s.startsWith("TR")&&(o=s),A===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const a=Array.from(this.remoteParticipants.values()).find(u=>u.sid===A);if(!a){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(A),this.logContext);return}let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={}),a.addSubscribedMediaTrack(e,o,t,r,c)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==fe.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(i=>{i.trackPublications.forEach(A=>{i.unpublishTrack(A.trackSid)})}),this.localParticipant.trackPublications.forEach(i=>{var A,s,o;i.track&&this.localParticipant.unpublishTrack(i.track,e),e?((A=i.track)===null||A===void 0||A.detach(),(s=i.track)===null||s===void 0||s.stop()):(o=i.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(K.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(K.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(K.AttributesChanged,this.onLocalAttributesChanged).off(K.TrackMuted,this.onLocalTrackMuted).off(K.TrackUnmuted,this.onLocalTrackUnmuted).off(K.LocalTrackPublished,this.onLocalTrackPublished).off(K.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(K.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(K.MediaDevicesError,this.onMediaDevicesError).off(K.AudioStreamAcquired,this.startAudio).off(K.ChatMessage,this.onLocalChatMessageSent).off(K.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),Ht()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(r=navigator.mediaDevices)===null||r===void 0||r.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(fe.Disconnected),this.emit(O.Disconnected,t)}}}handleParticipantDisconnected(e,t){var r;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(i=>{t.unpublishTrack(i.trackSid,!0)}),this.emit(O.ParticipantDisconnected,t),t.setDisconnected(),(r=this.localParticipant)===null||r===void 0||r.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return S(this,void 0,void 0,function*(){var r;if(e.contentHeader.case==="byteHeader"){const i=this.byteStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let A;const s={id:e.streamId,name:(r=e.contentHeader.value.name)!==null&&r!==void 0?r:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:ia(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{A=a,this.byteStreamControllers.set(e.streamId,{info:s,controller:A,startTime:Date.now()})}});i(new Ox(s,o,ia(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){const i=this.textStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let A;const s={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{A=a,this.textStreamControllers.set(e.streamId,{info:s,controller:A,startTime:Date.now()})}});i(new Mx(s,o,ia(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const r=this.textStreamControllers.get(e.streamId);r&&e.content.length>0&&r.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const r=this.byteStreamControllers.get(e.streamId);r&&(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return S(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=s0())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(i=>i.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Nt(200)])}catch(i){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:i}))}const r=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";r!==this.canPlaybackAudio&&(this.audioEnabled=r,this.emit(O.AudioPlaybackStatusChanged,r))})}createParticipant(e,t){var r;let i;return t?i=da.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):i=new da(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),!((r=this.options.audioOutput)===null||r===void 0)&&r.deviceId&&i.setAudioOutput(this.options.audioOutput).catch(A=>this.log.warn("Could not set audio output: ".concat(A.message),this.logContext)),i}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}const r=this.createParticipant(e,t);return this.remoteParticipants.set(e,r),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(O.ParticipantConnected,r),r.on(K.TrackPublished,i=>{this.emitWhenConnected(O.TrackPublished,i,r)}).on(K.TrackSubscribed,(i,A)=>{i.kind===R.Kind.Audio?(i.on(L.AudioPlaybackStarted,this.handleAudioPlaybackStarted),i.on(L.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):i.kind===R.Kind.Video&&(i.on(L.VideoPlaybackFailed,this.handleVideoPlaybackFailed),i.on(L.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(O.TrackSubscribed,i,A,r)}).on(K.TrackUnpublished,i=>{this.emit(O.TrackUnpublished,i,r)}).on(K.TrackUnsubscribed,(i,A)=>{this.emit(O.TrackUnsubscribed,i,A,r)}).on(K.TrackMuted,i=>{this.emitWhenConnected(O.TrackMuted,i,r)}).on(K.TrackUnmuted,i=>{this.emitWhenConnected(O.TrackUnmuted,i,r)}).on(K.ParticipantMetadataChanged,i=>{this.emitWhenConnected(O.ParticipantMetadataChanged,i,r)}).on(K.ParticipantNameChanged,i=>{this.emitWhenConnected(O.ParticipantNameChanged,i,r)}).on(K.AttributesChanged,i=>{this.emitWhenConnected(O.ParticipantAttributesChanged,i,r)}).on(K.ConnectionQualityChanged,i=>{this.emitWhenConnected(O.ConnectionQualityChanged,i,r)}).on(K.ParticipantPermissionsChanged,i=>{this.emitWhenConnected(O.ParticipantPermissionsChanged,i,r)}).on(K.TrackSubscriptionStatusChanged,(i,A)=>{this.emitWhenConnected(O.TrackSubscriptionStatusChanged,i,A,r)}).on(K.TrackSubscriptionFailed,(i,A)=>{this.emit(O.TrackSubscriptionFailed,i,r,A)}).on(K.TrackSubscriptionPermissionChanged,(i,A)=>{this.emitWhenConnected(O.TrackSubscriptionPermissionChanged,i,A,r)}).on(K.Active,()=>{this.emitWhenConnected(O.ParticipantActive,r)}),t&&r.updateInfo(t),r}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((r,i)=>(r.push(...i.getTrackPublications()),r),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&WF(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=wt.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,sn.STATE_MISMATCH))):e=0},zx)}clearConnectionReconcile(){this.connectionReconcileInterval&&wt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(O.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,r]=e;this.emit(t,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];if(this.state===fe.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,r]);else if(this.state===fe.Connected)return this.emit(e,...r);return!1}simulateParticipants(e){return S(this,void 0,void 0,function*(){var t,r;const i=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),A=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new Ho({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Ke.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Kr({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(O.SignalConnected),this.emit(O.Connected),this.setAndEmitConnectionState(fe.Connected),i.video){const s=new ad(R.Kind.Video,new Ui({source:at.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:An.AUDIO,name:"video-dummy"}),new ua(i.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:n0(160*((t=A.aspectRatios[0])!==null&&t!==void 0?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(K.LocalTrackPublished,s)}if(i.audio){const s=new ad(R.Kind.Audio,new Ui({source:at.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:An.AUDIO}),new aa(i.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ml(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(K.LocalTrackPublished,s)}for(let s=0;s<A.count-1;s+=1){let o=new Kr({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(s),state:Ei.ACTIVE,tracks:[],joinedAt:Ke.parse(Date.now())});const a=this.getOrCreateParticipant(o.identity,o);if(A.video){const c=n0(160*((r=A.aspectRatios[s%A.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),u=new Ui({source:at.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:An.AUDIO});a.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}if(A.audio){const c=Ml(),u=new Ui({source:at.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:An.AUDIO});a.addSubscribedMediaTrack(c,u.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,u]}a.updateInfo(o)}})}emit(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];if(e!==O.ActiveSpeakersChanged&&e!==O.TranscriptionReceived){const A=P0(r).filter(s=>s!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:A}))}return super.emit(e,...r)}}Li.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function P0(n){return n.map(e=>{if(e)return Array.isArray(e)?P0(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var hn;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(hn||(hn={}));class yr extends Sn.EventEmitter{constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=hn.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Li(r.roomOptions),this.connectOptions=r.connectOptions,this.options=r}run(e){return S(this,void 0,void 0,function*(){if(this.status!==hn.IDLE)throw Error("check is running already");this.setStatus(hn.RUNNING);try{yield this.perform()}catch(t){t instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(t.message):this.appendError(t.message))}return yield this.disconnect(),yield new Promise(t=>setTimeout(t,500)),this.status!==hn.SKIPPED&&this.setStatus(this.isSuccess()?hn.SUCCESS:hn.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return S(this,void 0,void 0,function*(){return this.room.state===fe.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return S(this,void 0,void 0,function*(){this.room&&this.room.state!==fe.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(hn.SKIPPED)}switchProtocol(e){return S(this,void 0,void 0,function*(){let t=!1,r=!1;if(this.room.on(O.Reconnecting,()=>{t=!0}),this.room.once(O.Reconnected,()=>{r=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(A=>setTimeout(A,1e3)),!t)return;const i=Date.now()+1e4;for(;Date.now()<i;){if(r)return;yield Nt(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Xx extends yr{get description(){return"Cloud regions"}perform(){return S(this,void 0,void 0,function*(){const e=new Ad(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],r=new Set;for(let A=0;A<3;A++){const s=yield e.getNextBestRegionUrl();if(!s)break;if(r.has(s))continue;r.add(s);const o=yield this.checkCloudRegion(s);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((A,s)=>(A.duration-s.duration)*.5+(A.rtt-s.rtt)*.5);const i=t[0];this.bestStats=i,this.appendMessage("best Cloud region: ".concat(i.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return S(this,void 0,void 0,function*(){var t,r;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const i=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!i)throw new Error("Region not found");const A=yield this.room.localParticipant.streamText({topic:"test"}),s=1e3,a=1e6/s,c="A".repeat(s),u=Date.now();for(let f=0;f<a;f++)yield A.write(c);yield A.close();const l=Date.now(),d=yield(r=this.room.engine.pcManager)===null||r===void 0?void 0:r.publisher.getStats(),h={region:i,rtt:1e4,duration:l-u};return d==null||d.forEach(f=>{f.type==="candidate-pair"&&f.nominated&&(h.rtt=f.currentRoundTripTime*1e3)}),yield this.disconnect(),h})}}const cd=1e4;class Yx extends yr{get description(){return"Connection via UDP vs TCP"}perform(){return S(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const r=this.bestStats;this.appendMessage("upstream bitrate: ".concat((r.bitrateTotal/r.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((r.rttTotal/r.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((r.jitterTotal/r.count*1e3).toFixed(2)," ms")),r.packetsLost>0&&this.appendWarning("packets lost: ".concat((r.packetsLost/r.packetsSent*100).toFixed(2),"%")),r.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((r.qualityLimitationDurations.bandwidth/(cd/1e3)*100).toFixed(2),"%")),r.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((r.qualityLimitationDurations.cpu/(cd/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return S(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const r=t.getContext("2d");if(!r)throw new Error("Could not get canvas context");let i=0;const A=()=>{i=(i+1)%360,r.fillStyle="hsl(".concat(i,", 100%, 50%)"),r.fillRect(0,0,t.width,t.height),requestAnimationFrame(A)};A();const o=t.captureStream(30).getVideoTracks()[0],c=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,u={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},l=setInterval(()=>S(this,void 0,void 0,function*(){const d=yield c.getRTCStatsReport();d==null||d.forEach(h=>{h.type==="outbound-rtp"?(u.packetsSent=h.packetsSent,u.qualityLimitationDurations=h.qualityLimitationDurations,u.bitrateTotal+=h.targetBitrate,u.count++):h.type==="remote-inbound-rtp"&&(u.packetsLost=h.packetsLost,u.rttTotal+=h.roundTripTime,u.jitterTotal+=h.jitter)})}),1e3);return yield new Promise(d=>setTimeout(d,cd)),clearInterval(l),o.stop(),t.remove(),yield this.disconnect(),u})}}class Zx extends yr{get description(){return"Can publish audio"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect(),r=yield Gx();if(yield A0(r,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(r),yield new Promise(o=>setTimeout(o,3e3));const A=yield(e=r.sender)===null||e===void 0?void 0:e.getStats();if(!A)throw new Error("Could not get RTCStats");let s=0;if(A.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(s=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," audio packets"))})}}class $x extends yr{get description(){return"Can publish video"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect(),r=yield Vx();yield this.checkForVideo(r.mediaStreamTrack),t.localParticipant.publishTrack(r),yield new Promise(s=>setTimeout(s,5e3));const i=yield(e=r.sender)===null||e===void 0?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let A=0;if(i.forEach(s=>{s.type==="outbound-rtp"&&(s.kind==="video"||!s.kind&&s.mediaType==="video")&&(A+=s.packetsSent)}),A===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(A," video packets"))})}checkForVideo(e){return S(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const r=document.createElement("video");r.srcObject=t,r.muted=!0,yield new Promise(i=>{r.onplay=()=>{setTimeout(()=>{var A,s,o,a;const c=document.createElement("canvas"),u=e.getSettings(),l=(s=(A=u.width)!==null&&A!==void 0?A:r.videoWidth)!==null&&s!==void 0?s:1280,d=(a=(o=u.height)!==null&&o!==void 0?o:r.videoHeight)!==null&&a!==void 0?a:720;c.width=l,c.height=d;const h=c.getContext("2d");h.drawImage(r,0,0);const p=h.getImageData(0,0,c.width,c.height).data;let g=!0;for(let v=0;v<p.length;v+=4)if(p[v]!==0||p[v+1]!==0||p[v+2]!==0){g=!1;break}g?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),i()},1e3)},r.play()}),r.remove()})}}class eQ extends yr{get description(){return"Resuming connection after interruption"}perform(){return S(this,void 0,void 0,function*(){var e;const t=yield this.connect();let r=!1,i=!1,A;const s=new Promise(c=>{setTimeout(c,5e3),A=c}),o=()=>{r=!0};t.on(O.SignalReconnecting,o).on(O.Reconnecting,o).on(O.Reconnected,()=>{i=!0,A(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const a=t.engine.client.onClose;if(a&&a(""),yield s,r){if(!i||t.state!==fe.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class tQ extends yr{get description(){return"Can connect via TURN"}perform(){return S(this,void 0,void 0,function*(){var e,t;const r=new jl,i=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let A=!1,s=!1,o=!1;for(let a of i.iceServers)for(let c of a.urls)c.startsWith("turn:")?(s=!0,o=!0):c.startsWith("turns:")&&(s=!0,o=!0,A=!0),c.startsWith("stun:")&&(o=!0);o?s&&!A&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield r.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(a=>setTimeout(a,0)))})}}class nQ extends yr{get description(){return"Establishing WebRTC connection"}perform(){return S(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(O.SignalConnected,()=>{const r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,A)=>{if(i.candidate){const s=new RTCIceCandidate(i);let o="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(rQ(s.address)?o+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,o+=" (passive)"):s.protocol==="udp"&&(t=!0)),this.appendMessage(o)}r&&r(i,A)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=i=>{i instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(i.errorCode," ").concat(i.errorText," ").concat(i.url))})});try{yield this.connect(),ue.info("now the room is connected")}catch(r){throw this.appendWarning("ports need to be open on firewall in order to connect."),r}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function rQ(n){const e=n.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class iQ extends yr{get description(){return"Connecting to signal connection via WebSocket"}perform(){return S(this,void 0,void 0,function*(){var e,t,r;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new jl;const A=yield i.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(A.serverVersion,".")),((e=A.serverInfo)===null||e===void 0?void 0:e.edition)===Lm.Cloud&&(!((t=A.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((r=A.serverInfo)===null||r===void 0?void 0:r.region)),yield i.close()})}}class Q4 extends Sn.EventEmitter{constructor(e,t){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=r}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:hn.IDLE,name:"",description:""}),e}updateCheck(e,t){this.checkResults.set(e,t),this.emit("checkUpdate",e,t)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==hn.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return S(this,void 0,void 0,function*(){const t=this.getNextCheckId(),r=new e(this.url,this.token,this.options),i=s=>{this.updateCheck(t,s)};r.on("update",i);const A=yield r.run();return r.off("update",i),A})}checkWebsocket(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(iQ)})}checkWebRTC(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(nQ)})}checkTURN(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(tQ)})}checkReconnect(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(eQ)})}checkPublishAudio(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Zx)})}checkPublishVideo(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck($x)})}checkConnectionProtocol(){return S(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Yx);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return S(this,void 0,void 0,function*(){return this.createAndRunCheck(Xx)})}}const AQ=/\{[^{}]+\}/g;function sQ(){return Math.random().toString(36).slice(2,11)}function oQ(n){let{baseUrl:e="",Request:t=globalThis.Request,fetch:r=globalThis.fetch,querySerializer:i,bodySerializer:A,headers:s,...o}={...n};e=D0(e);const a=[];async function c(u,l){const{baseUrl:d,fetch:h=r,Request:f=t,headers:p,params:g={},parseAs:v="json",querySerializer:y,bodySerializer:B=A??cQ,body:b,...w}=l||{};d&&(e=D0(d));let _=typeof i=="function"?i:L0(i);y&&(_=typeof y=="function"?y:L0({...typeof i=="object"?i:{},...y}));const k=b===void 0?void 0:B(b),T=k===void 0||k instanceof FormData?{}:{"Content-Type":"application/json"},x={redirect:"follow",...o,...w,body:k,headers:lQ(T,s,p,g.header)};let P,E,F=new t(uQ(u,{baseUrl:e,params:g,querySerializer:_}),x);for(const N in w)N in F||(F[N]=w[N]);if(a.length){P=sQ(),E=Object.freeze({baseUrl:e,fetch:h,parseAs:v,querySerializer:_,bodySerializer:B});for(const N of a)if(N&&typeof N=="object"&&typeof N.onRequest=="function"){const q=await N.onRequest({request:F,schemaPath:u,params:g,options:E,id:P});if(q){if(!(q instanceof t))throw new Error("onRequest: must return new Request() when modifying the request");F=q}}}let M=await h(F);if(a.length)for(let N=a.length-1;N>=0;N--){const q=a[N];if(q&&typeof q=="object"&&typeof q.onResponse=="function"){const ve=await q.onResponse({request:F,response:M,schemaPath:u,params:g,options:E,id:P});if(ve){if(!(ve instanceof Response))throw new Error("onResponse: must return new Response() when modifying the response");M=ve}}}if(M.status===204||M.headers.get("Content-Length")==="0")return M.ok?{data:{},response:M}:{error:{},response:M};if(M.ok)return v==="stream"?{data:M.body,response:M}:{data:await M[v](),response:M};let J=await M.text();try{J=JSON.parse(J)}catch{}return{error:J,response:M}}return{GET(u,l){return c(u,{...l,method:"GET"})},PUT(u,l){return c(u,{...l,method:"PUT"})},POST(u,l){return c(u,{...l,method:"POST"})},DELETE(u,l){return c(u,{...l,method:"DELETE"})},OPTIONS(u,l){return c(u,{...l,method:"OPTIONS"})},HEAD(u,l){return c(u,{...l,method:"HEAD"})},PATCH(u,l){return c(u,{...l,method:"PATCH"})},TRACE(u,l){return c(u,{...l,method:"TRACE"})},use(...u){for(const l of u)if(l){if(typeof l!="object"||!("onRequest"in l||"onResponse"in l))throw new Error("Middleware must be an object with one of `onRequest()` or `onResponse()`");a.push(l)}},eject(...u){for(const l of u){const d=a.indexOf(l);d!==-1&&a.splice(d,1)}}}}function ha(n,e,t){if(e==null)return"";if(typeof e=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${n}=${(t==null?void 0:t.allowReserved)===!0?e:encodeURIComponent(e)}`}function O0(n,e,t){if(!e||typeof e!="object")return"";const r=[],i={simple:",",label:".",matrix:";"}[t.style]||"&";if(t.style!=="deepObject"&&t.explode===!1){for(const o in e)r.push(o,t.allowReserved===!0?e[o]:encodeURIComponent(e[o]));const s=r.join(",");switch(t.style){case"form":return`${n}=${s}`;case"label":return`.${s}`;case"matrix":return`;${n}=${s}`;default:return s}}for(const s in e){const o=t.style==="deepObject"?`${n}[${s}]`:s;r.push(ha(o,e[s],t))}const A=r.join(i);return t.style==="label"||t.style==="matrix"?`${i}${A}`:A}function M0(n,e,t){if(!Array.isArray(e))return"";if(t.explode===!1){const A={form:",",spaceDelimited:"%20",pipeDelimited:"|"}[t.style]||",",s=(t.allowReserved===!0?e:e.map(o=>encodeURIComponent(o))).join(A);switch(t.style){case"simple":return s;case"label":return`.${s}`;case"matrix":return`;${n}=${s}`;default:return`${n}=${s}`}}const r={simple:",",label:".",matrix:";"}[t.style]||"&",i=[];for(const A of e)t.style==="simple"||t.style==="label"?i.push(t.allowReserved===!0?A:encodeURIComponent(A)):i.push(ha(n,A,t));return t.style==="label"||t.style==="matrix"?`${r}${i.join(r)}`:i.join(r)}function L0(n){return function(t){const r=[];if(t&&typeof t=="object")for(const i in t){const A=t[i];if(A!=null){if(Array.isArray(A)){if(A.length===0)continue;r.push(M0(i,A,{style:"form",explode:!0,...n==null?void 0:n.array,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}if(typeof A=="object"){r.push(O0(i,A,{style:"deepObject",explode:!0,...n==null?void 0:n.object,allowReserved:(n==null?void 0:n.allowReserved)||!1}));continue}r.push(ha(i,A,n))}}return r.join("&")}}function aQ(n,e){let t=n;for(const r of n.match(AQ)??[]){let i=r.substring(1,r.length-1),A=!1,s="simple";if(i.endsWith("*")&&(A=!0,i=i.substring(0,i.length-1)),i.startsWith(".")?(s="label",i=i.substring(1)):i.startsWith(";")&&(s="matrix",i=i.substring(1)),!e||e[i]===void 0||e[i]===null)continue;const o=e[i];if(Array.isArray(o)){t=t.replace(r,M0(i,o,{style:s,explode:A}));continue}if(typeof o=="object"){t=t.replace(r,O0(i,o,{style:s,explode:A}));continue}if(s==="matrix"){t=t.replace(r,`;${ha(i,o)}`);continue}t=t.replace(r,s==="label"?`.${encodeURIComponent(o)}`:encodeURIComponent(o))}return t}function cQ(n){return n instanceof FormData?n:JSON.stringify(n)}function uQ(n,e){var i;let t=`${e.baseUrl}${n}`;(i=e.params)!=null&&i.path&&(t=aQ(t,e.params.path));let r=e.querySerializer(e.params.query??{});return r.startsWith("?")&&(r=r.substring(1)),r&&(t+=`?${r}`),t}function lQ(...n){const e=new Headers;for(const t of n){if(!t||typeof t!="object")continue;const r=t instanceof Headers?t.entries():Object.entries(t);for(const[i,A]of r)if(A===null)e.delete(i);else if(Array.isArray(A))for(const s of A)e.append(i,s);else A!==void 0&&e.set(i,A)}return e}function D0(n){return n.endsWith("/")?n.substring(0,n.length-1):n}const N0="Onboardee-Session-Token",H0="OnboardeeSessionToken";class K0{constructor(e){this.client=oQ({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch}),this.client.use({onRequest({request:t}){if(window.localStorage){const r=window.localStorage.getItem(H0);r&&t.headers.set(N0,r)}return t},onResponse({response:t}){const r=t.headers.get(N0);return r&&window.localStorage&&window.localStorage.setItem(H0,r),t}})}setAuthToken(e){this.client.use({onRequest({request:t}){return t.headers.set("Authorization",`Bearer ${e}`),t}})}setApiToken(e){this.client.use({onRequest({request:t}){return t.headers.set("Authorization",`Token ${e}`),t}})}async getAuthUrl(e){return await this.client.GET("/api/auth/{type}",{params:{path:{type:e}}})}async getConnectUrl(e){return await this.client.GET("/api/connect/{type}",{params:{path:{type:e}}})}async logout(){return await this.client.POST("/api/logout")}async getCurrentUser(){return await this.client.GET("/api/me")}async clientInitialise(e,t={}){return await this.client.POST("/api/client/{appToken}/initialise",{params:{path:{appToken:e}},body:t})}async clientStartSession(e,t){return await this.client.POST("/api/client/{appToken}/start-session",{params:{path:{appToken:e}},body:t})}async createPresignedUploadUrl(e){return await this.client.POST("/api/files",{body:e})}async createKnowledgeBlock(e){return await this.client.POST("/api/knowledge",{body:e})}async listOnboardees(){return await this.client.GET("/api/onboardees")}async getOnboardee(e){return await this.client.GET("/api/onboardees/{id}",{params:{path:{id:e}}})}async getOnboardeeWidgetConfig(e,t){return await this.client.GET("/api/onboardees/{id}/config",{params:{path:{id:e}},signal:t})}async listPlans(e){return await this.client.GET("/api/plans",{params:{query:{...e&&{client_type:e}}}})}async listPlansWithStatus(){return await this.client.GET("/api/plans-with-status")}async listProducts(){return await this.client.GET("/api/products")}async getProduct(e){return await this.client.GET("/api/products/{id}",{params:{path:{id:e}}})}async getProductAnalytics(e,t,r,i){return await this.client.GET("/api/products/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...r&&{end_date:r},...i&&{course_id:i}}}})}async createProduct(e){return await this.client.POST("/api/products",{body:e})}async updateProduct(e,t){return await this.client.PATCH("/api/products/{id}",{params:{path:{id:e}},body:t})}async getProductNavigationIndex(e){return await this.client.GET("/api/products/{id}/navigation-index",{params:{path:{id:e}}})}async replaceProductNavigationIndex(e,t){return await this.client.PUT("/api/products/{id}/navigation-index",{params:{path:{id:e}},body:t})}async listProductKnowledgeBlocks(e){return await this.client.GET("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createProductKnowledgeBlock(e,t){return await this.client.POST("/api/products/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async searchProductKnowledgeBlocks(e,t,r){return await this.client.GET("/api/products/{id}/knowledge-blocks/search",{params:{path:{id:e},query:{q:t,...r&&{limit:r.toString()}}}})}async updateProductKnowledgeBlock(e,t,r){return await this.client.PATCH("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deleteProductKnowledgeBlock(e,t){return await this.client.DELETE("/api/products/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async createPlan(e){return await this.client.POST("/api/plans",{body:e})}async getPlan(e){return await this.client.GET("/api/plans/{id}",{params:{path:{id:e}}})}async getAdminPlan(e){return await this.client.GET("/api/admin/plans/{id}",{params:{path:{id:e}}})}async getPlanAnalytics(e,t,r){return await this.client.GET("/api/plans/{id}/analytics",{params:{path:{id:e},query:{...t&&{start_date:t},...r&&{end_date:r}}}})}async replacePlan(e,t){return await this.client.PUT("/api/plans/{id}",{params:{path:{id:e}},body:t})}async updatePlan(e,t){return await this.client.PATCH("/api/plans/{id}",{params:{path:{id:e}},body:t})}async getPlanVideoUrl(e){return await this.client.GET("/api/plans/{id}/video-url",{params:{path:{id:e}}})}async getPlanVideoMetadata(e){return await this.client.GET("/api/plans/{id}/video-metadata",{params:{path:{id:e}}})}async deletePlan(e){return await this.client.DELETE("/api/admin/plans/{id}",{params:{path:{id:e}}})}async publishPlanRevision(e,t){return await this.client.POST("/api/plans/{id}/publish",{params:{path:{id:e}},body:t})}async listPlanRevisions(e){return await this.client.GET("/api/plans/{id}/revisions",{params:{path:{id:e}}})}async listPlanKnowledgeBlocks(e){return await this.client.GET("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}}})}async createPlanKnowledgeBlock(e,t){return await this.client.POST("/api/plans/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async updatePlanKnowledgeBlock(e,t,r){return await this.client.PUT("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deletePlanKnowledgeBlock(e,t){return await this.client.DELETE("/api/plans/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async getPlanNavigationIndex(e){return await this.client.GET("/api/plans/{id}/navigation-index",{params:{path:{id:e}}})}async replacePlanNavigationIndex(e,t){return await this.client.POST("/api/plans/{id}/navigation-index",{params:{path:{id:e}},body:t})}async getRevisionNavigationIndex(e){return await this.client.GET("/api/revisions/{id}/navigation-index",{params:{path:{id:e}}})}async replaceRevisionNavigationIndex(e,t){return await this.client.PUT("/api/revisions/{id}/navigation-index",{params:{path:{id:e}},body:t})}async getPlanFAQ(e){return await this.client.GET("/api/plans/{id}/faq",{params:{path:{id:e}}})}async getRevisionFAQ(e){return await this.client.GET("/api/revisions/{id}/faq",{params:{path:{id:e}}})}async replaceRevisionFAQ(e,t){return await this.client.PUT("/api/revisions/{id}/faq",{params:{path:{id:e}},body:t})}async listRevisionKnowledgeBlocks(e){return await this.client.GET("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}}})}async getRevisionSteps(e){return await this.client.GET("/api/revisions/{id}/steps",{params:{path:{id:e}}})}async replaceRevisionKnowledgeBlocks(e,t){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async createRevisionKnowledgeBlock(e,t){return await this.client.POST("/api/revisions/{id}/knowledge-blocks",{params:{path:{id:e}},body:t})}async updateRevisionKnowledgeBlock(e,t,r){return await this.client.PUT("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}},body:r})}async deleteRevisionKnowledgeBlock(e,t){return await this.client.DELETE("/api/revisions/{id}/knowledge-blocks/{blockId}",{params:{path:{id:e,blockId:t}}})}async listSessions(e,t){const r={token:e};return t!=null&&t.productId&&(r.product_id=t.productId),t!=null&&t.startDate&&(r.start_date=t.startDate),t!=null&&t.endDate&&(r.end_date=t.endDate),await this.client.GET("/api/sessions",{params:{query:r}})}async createSession(e){return await this.client.POST("/api/sessions",{body:e})}async getSession(e){return await this.client.GET("/api/sessions/{id}",{params:{path:{id:e}}})}async startSession(e,t){return await this.client.GET("/api/sessions/{id}/start-session",{params:{path:{id:e},query:{token:t}}})}async getSessionRecording(e){return await this.client.GET("/api/sessions/{id}/recording",{params:{path:{id:e}}})}async getSessionSummary(e){return await this.client.GET("/api/sessions/{id}/summary",{params:{path:{id:e}}})}async getSessionProductUrl(e){return await this.client.GET("/api/sessions/{id}/product-url",{params:{path:{id:e}}})}async updateSession(e,t){return await this.client.PATCH("/api/sessions/{id}",{params:{path:{id:e}},body:t})}async listUserSessions(e){const t={};return e!=null&&e.productId&&(t.product_id=e.productId),e!=null&&e.courseId&&(t.course_id=e.courseId),e!=null&&e.startDate&&(t.start_date=e.startDate),e!=null&&e.endDate&&(t.end_date=e.endDate),e!=null&&e.page&&(t.page=e.page),e!=null&&e.limit&&(t.limit=e.limit),e!=null&&e.courseName&&(t.course_name=e.courseName),e!=null&&e.userName&&(t.user_name=e.userName),e!=null&&e.company&&(t.company=e.company),e!=null&&e.email&&(t.email=e.email),e!=null&&e.sortBy&&(t.sort_by=e.sortBy),e!=null&&e.sortOrder&&(t.sort_order=e.sortOrder),await this.client.GET("/api/user-sessions",{params:Object.keys(t).length>0?{query:t}:void 0})}async listUserSessionsAggregate(e){const t={};return e!=null&&e.productId&&(t.product_id=e.productId),e!=null&&e.courseId&&(t.course_id=e.courseId),e!=null&&e.startDate&&(t.start_date=e.startDate),e!=null&&e.endDate&&(t.end_date=e.endDate),await this.client.GET("/api/user-sessions-aggregate",{params:Object.keys(t).length>0?{query:t}:void 0})}async getJoinToken(e,{clientType:t,user:r}={}){return await this.client.GET("/api/join-token",{params:{query:{token:e,...t&&{client_type:t},...r&&{user:encodeURIComponent(r)}}}})}async getSessionPlan(e){return await this.client.GET("/api/sessions/{id}/plan",{params:{path:{id:e}}})}async getPlanSDK(e){return await this.client.GET("/api/plans/{uuid}/sdk",{params:{path:{uuid:e}}})}getClient(){return this.client}}const V0="https://app.coragents.ai";class pa extends jc{constructor(e,t,r,i){super(),this.state=null,this.isPaused=!1,this.speakingState=null,this.captureScreen=null,this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.room=null,this.agentAnalyser=null,this.userAnalyser=null,this.appToken=e,this.planId=t,this.clientType=r,this.api=i.api||new K0({baseUrl:V0}),this.identity=i.identity||null,this.roomFactory=i.roomFactory||(A=>new Li(A)),this.captureScreen=i.captureScreen||null}async start(){this.planId,this.setState("connecting"),this.speakingStateChanged("thinking");try{const t=(await this.api.clientStartSession(this.appToken,{client_type:this.clientType,onboarding_plan:this.planId})).data;if(!(t!=null&&t.url)||!(t!=null&&t.token)||!(t!=null&&t.room)||!(t!=null&&t.session_uuid))throw new Error("Invalid room info");this.sessionUuid=t==null?void 0:t.session_uuid,this.roomId=t==null?void 0:t.room,this.joinToken=t==null?void 0:t.token,this.roomUrl=t==null?void 0:t.url,await this.joinRoom(),this.setState("connected"),this.planId,this.sessionUuid}catch(e){console.error("[obi] error starting session",{error:e}),this.setState("error")}}async joinRoom({withMicrophone:e=!1,withStateRecovery:t=!1}={}){this.room=this.roomFactory({adaptiveStream:!0,dynacast:!0}),this.room.on(O.Disconnected,r=>{if(!this.room)return;let i=null;switch(r){case 12:i="invalid-room";break}this.shutdown(i)}),this.room.on(O.TrackSubscribed,r=>{r.kind==="audio"&&(r.attach(),r.source===R.Source.Microphone&&(this.agentAnalyser&&this.agentAnalyser.disconnect(),this.agentAnalyser=this.createFFT(r.mediaStream)))}),this.room.on(O.LocalTrackPublished,r=>{r.kind==="audio"&&(this.userAnalyser&&this.userAnalyser.disconnect(),this.userAnalyser=this.createFFT(r.audioTrack.mediaStream))}),this.room.on(O.ParticipantAttributesChanged,r=>{if(!r["lk.agent.state"])return;const i=r["lk.agent.state"];switch(i){case"speaking":this.speakingStateChanged("speaking");break;case"listening":this.state!=="connected"&&this.speakingStateChanged("listening");break;case"thinking":this.speakingStateChanged("thinking");break;default:console.warn("[obi] unknown speaking state",i)}}),this.room.on(O.DataReceived,async r=>{try{const i=new TextDecoder().decode(r),A=JSON.parse(i);switch(A.status||A.request||A.type){case"course_progress":typeof A.current_step=="number"&&typeof A.total_steps=="number"&&Array.isArray(A.step_names)&&this.emit("courseProgress",{currentStep:Math.max(1,A.current_step),totalSteps:Math.max(1,A.total_steps),stepNames:A.step_names});break;case"using_tool":this.speakingStateChanged("busy");break;case"using_tool_ended":this.speakingStateChanged("speaking");break;case"prompt_user":this.setState("volume-check");break;case"mic_check":this.setState("mic-check");break;case"share_mic":this.setState("mic-share");break;case"share_screen":this.setState("screen-share");break;case"navigate":this.setState("navigate");break;default:console.warn("[obi] unknown data received",A)}}catch(i){console.error("[obi] error parsing data",i)}}),this.room.localParticipant.registerRpcMethod("mic_check",async r=>(this.sessionUuid,await this.checkMicrophone()?"ok":"error")),this.room.localParticipant.registerRpcMethod("screen_capture",async r=>{if(!this.captureScreen)return console.error("[obi] no captureScreen function provided"),"error";let i=null,A=null;try{i=await this.captureScreen()}catch(s){i=null,s=s}if(!i||A)return console.error("[obi] error capturing screen",{error:A}),"error";try{return await this.room.localParticipant.sendFile(new File([i],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),"ok"}catch(s){return console.error("[obi] error sending screen capture",{error:s}),"error"}}),await this.room.connect(this.roomUrl,this.joinToken);for(let r=0;r<9&&!(this.room.state===fe.Connected&&this.room.remoteParticipants.size>=1);r++)await new Promise(i=>setTimeout(i,1e3));if(!(this.room.state===fe.Connected&&this.room.remoteParticipants.size>=1)){console.error("[obi] room not connected",{state:this.room.state,numParticipants:this.room.remoteParticipants.size}),this.shutdown("invalid-room");return}if(e&&await this.room.localParticipant.setMicrophoneEnabled(!0),t){let r=!1;for(const i of this.room.remoteParticipants.values())i.isSpeaking&&(r=!0);r?this.speakingState="speaking":this.speakingState="listening"}}async continue(){this.sessionUuid,this.speakingStateChanged("thinking"),await this.sendData({request:"prompt_user",success:!0})}async checkMicrophone(){let e=!1;try{e=(await navigator.permissions.query({name:"microphone"})).state==="granted"}catch(t){console.error("[obi] error checking microphone permission:",t)}return e?(this.sessionUuid,await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0):this.sessionUuid,e&&this.clientType==="sdk"&&this.setState("in-progress"),this.emit("micCheckComplete",e),e}async shareMicrophone(){this.sessionUuid,this.speakingStateChanged("thinking");let e=null,t=null;try{e=await this.room.localParticipant.setMicrophoneEnabled(!0),this.isMicShared=!0}catch(r){r=r,this.isMicShared=!1}e?this.sessionUuid:console.error("[obi] failed to share microphone",{error:t}),await this.sendData({request:"share_mic",success:!!e}),this.clientType==="sdk"&&this.setState("in-progress")}async shareMicrophoneFailed(){this.isMicShared=!1,await this.sendData({request:"share_mic",success:!1}),this.clientType==="sdk"&&this.setState("in-progress")}async shareScreen(){this.sessionUuid,this.speakingStateChanged("thinking"),await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),await this.sendData({request:"share_screen",success:!0}),this.setState("navigate")}async pause(){this.muteMicrophone(),this.isPaused=!0,this.emit("paused"),await this.sendData({request:"pause"}),console.log("[obi] paused session",{sessionUuid:this.sessionUuid})}async unpause(){this.unmuteMicrophone(),this.isPaused=!1,this.emit("unpaused"),await this.sendData({request:"unpause"}),console.log("[obi] unpaused session",{sessionUuid:this.sessionUuid})}muteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var t,r;e.handleMuted(),(r=(t=e.track)==null?void 0:t.mediaStream)==null||r.getTracks().forEach(i=>i.enabled=!1)})}unmuteMicrophone(){this.sessionUuid,this.room.localParticipant.getTrackPublications().forEach(e=>{var t,r;e.handleUnmuted(),(r=(t=e.track)==null?void 0:t.mediaStream)==null||r.getTracks().forEach(i=>i.enabled=!0)})}async stop(){this.emit("stopped"),await this.shutdown()}async shutdown(e=null){if(this.room){this.sessionUuid;const t=this.room;this.room=null,await t.disconnect(),this.sessionUuid}this.sessionUuid=null,this.roomId=null,this.joinToken=null,this.roomUrl=null,this.emit("shutdown",e)}async say(e){this.speakingStateChanged("thinking"),this.isPaused&&await this.unpause(),await this.sendData({request:"say",message:e})}serialise(){return JSON.stringify({state:this.state,speakingState:this.speakingState,appToken:this.appToken,planId:this.planId,clientType:this.clientType,isPaused:this.isPaused,identity:this.identity,sessionUuid:this.sessionUuid,roomId:this.roomId,joinToken:this.joinToken,roomUrl:this.roomUrl})}audioSpectrum(){return this.speakingState==="speaking"&&this.agentAnalyser?this.normaliseSpectrum(this.agentAnalyser):this.speakingState==="listening"&&this.userAnalyser?this.normaliseSpectrum(this.userAnalyser):null}normaliseSpectrum(e){const r=e.context.sampleRate/2/e.frequencyBinCount,i=new Uint8Array(e.frequencyBinCount);e.getByteFrequencyData(i);const A=[],s=50,o=5e3,a=8,c=Math.pow(o/s,1/a);for(let u=0;u<a;u++){const l=s*Math.pow(c,u),d=s*Math.pow(c,u+1),h=Math.floor(l/r),f=Math.floor(d/r),p=Math.min(f,i.length),g=Math.min(h,p);if(g<p){const v=i.slice(g,p).reduce((y,B)=>y+B,0)/(p-g)/255;A.push(v)}else A.push(0)}return A}setState(e){this.state;const t=this.state;this.state=e,this.emit("stateChanged",e,t)}static deserialise(e,t,r,i={}){const A=JSON.parse(e),s=new pa(t,A.planId,r,i);return s.state=A.state,s.speakingState=A.speakingState,s.identity=A.identity||null,s.isPaused=A.isPaused||!1,s.sessionUuid=A.sessionUuid||null,s.roomId=A.roomId||null,s.joinToken=A.joinToken||null,s.roomUrl=A.roomUrl||null,s}speakingStateChanged(e){this.speakingState;const t=this.speakingState;this.speakingState=e,this.emit("speakingStateChanged",e,t)}async sendData(e){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0})}createFFT(e){const t=new AudioContext,r=t.createAnalyser();return t.createMediaStreamSource(e).connect(r),r.fftSize=2048,r.smoothingTimeConstant=.6,r}}class fa extends jc{constructor(e,t,r={}){super(),this.state="loading",this.error=null,this.identity=null,this.product=null,this.plans=[],this.planIsCompleted=[],this.selectedPlan=null,this.selectedPlanUuid=null,this.showWidget=!1,this.session=null,this.captureScreen=null,this.appToken=e,this.clientType=t,this.api=r.api||new K0({baseUrl:r.apiBaseUrl||V0}),this.sessionFactory=r.sessionFactory||((i,A,s,o)=>new pa(i,A,s,o)),this.captureScreen=r.captureScreen||null}async initialise(e={}){var t,r,i,A,s,o;if(!this.appToken)throw new Error("App token is required");this.setState("loading");try{const a=await this.api.clientInitialise(this.appToken,{identity:e.identity,client_type:this.clientType});if(this.identity=e.identity||null,this.product=((t=a.data)==null?void 0:t.product)||null,this.plans=((r=a.data)==null?void 0:r.onboarding_plans)||[],this.selectedPlan=((i=a.data)==null?void 0:i.selected_plan)||null,this.planIsCompleted=((A=a.data)==null?void 0:A.plan_is_completed)||[],this.showWidget=((s=a.data)==null?void 0:s.show_widget)||!1,e.planUuid){let c=null;try{const u=await this.api.getPlanSDK(e.planUuid);u.data&&(c=u.data)}catch(u){try{const l=await this.api.getSessionPlan(e.planUuid);(o=l.data)!=null&&o.plan_uuid&&(c={uuid:l.data.plan_uuid})}catch(l){console.error("[obi] error getting plan via both endpoints",{planErr:u,sessionErr:l})}}c?(this.selectedPlan=c,this.selectedPlanUuid=e.planUuid):console.warn("[obi] plan not found",{planUuid:e.planUuid})}this.identity,this.product,this.plans,this.selectedPlan,this.showWidget}catch(a){throw this.error=a instanceof Error?a:new Error(String(a)),this.setState("error"),a}finally{this.setState("ready")}}selectPlan(e){this.selectedPlan=e,this.selectedPlanUuid=(e==null?void 0:e.uuid)||null,this.emit("planSelected",e)}async startSession(e,t){return await this._stopSession(),this.session=this.sessionFactory(this.appToken,e,this.clientType,{api:this.api,identity:this.identity,captureScreen:this.captureScreen}),this.prepareSession(t),this.session.start().then(()=>{this.emit("sessionStarted",this.session)}).catch(r=>{this.session=null,console.error("[obi] error starting session",r)}),this.session}async resumeSession(e){var t,r;return this.state,(t=this.session)==null||t.state,(r=this.session)==null||r.speakingState,this.session.captureScreen=this.captureScreen,this.prepareSession(e),this.session.joinRoom({withMicrophone:!0,withStateRecovery:!0}).then(()=>{this.emit("sessionResumed",this.session)}).catch(i=>{console.error("[obi] error joining room",{error:i}),i instanceof Error&&i.message==="Room is not connected"&&this.session.stop()}),this.session}prepareSession(e){if(!this.session)throw new Error("No session to prepare");return e(this.session),this.session.on("stopped",()=>{this.emit("sessionStopped")}),this.session.on("shutdown",t=>{var r,i;(i=(r=this.session)==null?void 0:r.removeAllListeners)==null||i.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,plans:this.plans,selectedPlan:this.selectedPlan,selectedPlanUuid:this.selectedPlanUuid,showWidget:this.showWidget,session:(e=this.session)==null?void 0:e.serialise(),serialisedAt:new Date().toISOString()})}static deserialise(e,t,r,i={}){const A=JSON.parse(e);if(A.serialisedAt){const o=new Date(A.serialisedAt);if(new Date().getTime()-o.getTime()>1e3*20)throw new Error("Client was serialised more than 20 seconds ago, assuming it's dead.")}else throw new Error("Client was not serialised, assuming it's dead.");const s=new fa(t,r,i);return s.state=A.state,s.identity=A.identity||null,s.product=A.product||null,s.plans=A.plans||[],s.selectedPlan=A.selectedPlan||null,s.selectedPlanUuid=A.selectedPlanUuid||null,s.showWidget=A.showWidget||!1,A.session&&(s.session=pa.deserialise(A.session,t,r,{api:s.api})),s}setState(e){const t=this.state;this.state=e,this.emit("stateChanged",e,t)}trackEvent(e,t={}){var r,i,A;this.emit("trackEvent",e,{...t,clientType:this.clientType,planId:(r=this.selectedPlan)==null?void 0:r.uuid,productId:(i=this.product)==null?void 0:i.uuid,sessionId:(A=this.session)==null?void 0:A.sessionUuid})}}var ga,ee,G0,zr,j0,W0,q0,J0,ud,ld,dd,z0,WA={},X0=[],dQ=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,qA=Array.isArray;function Kn(n,e){for(var t in e)n[t]=e[t];return n}function hd(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function pd(n,e,t){var r,i,A,s={};for(A in e)A=="key"?r=e[A]:A=="ref"?i=e[A]:s[A]=e[A];if(arguments.length>2&&(s.children=arguments.length>3?ga.call(arguments,2):t),typeof n=="function"&&n.defaultProps!=null)for(A in n.defaultProps)s[A]==null&&(s[A]=n.defaultProps[A]);return ma(n,s,r,i,null)}function ma(n,e,t,r,i){var A={type:n,props:e,key:t,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++G0,__i:-1,__u:0};return i==null&&ee.vnode!=null&&ee.vnode(A),A}function St(n){return n.children}function Vn(n,e){this.props=n,this.context=e}function Di(n,e){if(e==null)return n.__?Di(n.__,n.__i+1):null;for(var t;e<n.__k.length;e++)if((t=n.__k[e])!=null&&t.__e!=null)return t.__e;return typeof n.type=="function"?Di(n):null}function Y0(n){var e,t;if((n=n.__)!=null&&n.__c!=null){for(n.__e=n.__c.base=null,e=0;e<n.__k.length;e++)if((t=n.__k[e])!=null&&t.__e!=null){n.__e=n.__c.base=t.__e;break}return Y0(n)}}function fd(n){(!n.__d&&(n.__d=!0)&&zr.push(n)&&!va.__r++||j0!=ee.debounceRendering)&&((j0=ee.debounceRendering)||W0)(va)}function va(){for(var n,e,t,r,i,A,s,o=1;zr.length;)zr.length>o&&zr.sort(q0),n=zr.shift(),o=zr.length,n.__d&&(t=void 0,i=(r=(e=n).__v).__e,A=[],s=[],e.__P&&((t=Kn({},r)).__v=r.__v+1,ee.vnode&&ee.vnode(t),gd(e.__P,t,r,e.__n,e.__P.namespaceURI,32&r.__u?[i]:null,A,i??Di(r),!!(32&r.__u),s),t.__v=r.__v,t.__.__k[t.__i]=t,ny(A,t,s),t.__e!=i&&Y0(t)));va.__r=0}function Z0(n,e,t,r,i,A,s,o,a,c,u){var l,d,h,f,p,g,v=r&&r.__k||X0,y=e.length;for(a=hQ(t,e,v,a,y),l=0;l<y;l++)(h=t.__k[l])!=null&&(d=h.__i==-1?WA:v[h.__i]||WA,h.__i=l,g=gd(n,h,d,i,A,s,o,a,c,u),f=h.__e,h.ref&&d.ref!=h.ref&&(d.ref&&md(d.ref,null,h),u.push(h.ref,h.__c||f,h)),p==null&&f!=null&&(p=f),4&h.__u||d.__k===h.__k?a=$0(h,a,n):typeof h.type=="function"&&g!==void 0?a=g:f&&(a=f.nextSibling),h.__u&=-7);return t.__e=p,a}function hQ(n,e,t,r,i){var A,s,o,a,c,u=t.length,l=u,d=0;for(n.__k=new Array(i),A=0;A<i;A++)(s=e[A])!=null&&typeof s!="boolean"&&typeof s!="function"?(a=A+d,(s=n.__k[A]=typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?ma(null,s,null,null,null):qA(s)?ma(St,{children:s},null,null,null):s.constructor==null&&s.__b>0?ma(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):s).__=n,s.__b=n.__b+1,o=null,(c=s.__i=pQ(s,t,a,l))!=-1&&(l--,(o=t[c])&&(o.__u|=2)),o==null||o.__v==null?(c==-1&&(i>u?d--:i<u&&d++),typeof s.type!="function"&&(s.__u|=4)):c!=a&&(c==a-1?d--:c==a+1?d++:(c>a?d--:d++,s.__u|=4))):n.__k[A]=null;if(l)for(A=0;A<u;A++)(o=t[A])!=null&&!(2&o.__u)&&(o.__e==r&&(r=Di(o)),iy(o,o));return r}function $0(n,e,t){var r,i;if(typeof n.type=="function"){for(r=n.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=n,e=$0(r[i],e,t));return e}n.__e!=e&&(e&&n.type&&!t.contains(e)&&(e=Di(n)),t.insertBefore(n.__e,e||null),e=n.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ya(n,e){return e=e||[],n==null||typeof n=="boolean"||(qA(n)?n.some(function(t){ya(t,e)}):e.push(n)),e}function pQ(n,e,t,r){var i,A,s=n.key,o=n.type,a=e[t];if(a===null&&n.key==null||a&&s==a.key&&o==a.type&&!(2&a.__u))return t;if(r>(a!=null&&!(2&a.__u)?1:0))for(i=t-1,A=t+1;i>=0||A<e.length;){if(i>=0){if((a=e[i])&&!(2&a.__u)&&s==a.key&&o==a.type)return i;i--}if(A<e.length){if((a=e[A])&&!(2&a.__u)&&s==a.key&&o==a.type)return A;A++}}return-1}function ey(n,e,t){e[0]=="-"?n.setProperty(e,t??""):n[e]=t==null?"":typeof t!="number"||dQ.test(e)?t:t+"px"}function wa(n,e,t,r,i){var A;e:if(e=="style")if(typeof t=="string")n.style.cssText=t;else{if(typeof r=="string"&&(n.style.cssText=r=""),r)for(e in r)t&&e in t||ey(n.style,e,"");if(t)for(e in t)r&&t[e]==r[e]||ey(n.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")A=e!=(e=e.replace(J0,"$1")),e=e.toLowerCase()in n||e=="onFocusOut"||e=="onFocusIn"?e.toLowerCase().slice(2):e.slice(2),n.l||(n.l={}),n.l[e+A]=t,t?r?t.u=r.u:(t.u=ud,n.addEventListener(e,A?dd:ld,A)):n.removeEventListener(e,A?dd:ld,A);else{if(i=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in n)try{n[e]=t??"";break e}catch{}typeof t=="function"||(t==null||t===!1&&e[4]!="-"?n.removeAttribute(e):n.setAttribute(e,e=="popover"&&t==1?"":t))}}function ty(n){return function(e){if(this.l){var t=this.l[e.type+n];if(e.t==null)e.t=ud++;else if(e.t<t.u)return;return t(ee.event?ee.event(e):e)}}}function gd(n,e,t,r,i,A,s,o,a,c){var u,l,d,h,f,p,g,v,y,B,b,w,_,k,T,x,P,E=e.type;if(e.constructor!=null)return null;128&t.__u&&(a=!!(32&t.__u),A=[o=e.__e=t.__e]),(u=ee.__b)&&u(e);e:if(typeof E=="function")try{if(v=e.props,y="prototype"in E&&E.prototype.render,B=(u=E.contextType)&&r[u.__c],b=u?B?B.props.value:u.__:r,t.__c?g=(l=e.__c=t.__c).__=l.__E:(y?e.__c=l=new E(v,b):(e.__c=l=new Vn(v,b),l.constructor=E,l.render=gQ),B&&B.sub(l),l.props=v,l.state||(l.state={}),l.context=b,l.__n=r,d=l.__d=!0,l.__h=[],l._sb=[]),y&&l.__s==null&&(l.__s=l.state),y&&E.getDerivedStateFromProps!=null&&(l.__s==l.state&&(l.__s=Kn({},l.__s)),Kn(l.__s,E.getDerivedStateFromProps(v,l.__s))),h=l.props,f=l.state,l.__v=e,d)y&&E.getDerivedStateFromProps==null&&l.componentWillMount!=null&&l.componentWillMount(),y&&l.componentDidMount!=null&&l.__h.push(l.componentDidMount);else{if(y&&E.getDerivedStateFromProps==null&&v!==h&&l.componentWillReceiveProps!=null&&l.componentWillReceiveProps(v,b),!l.__e&&l.shouldComponentUpdate!=null&&l.shouldComponentUpdate(v,l.__s,b)===!1||e.__v==t.__v){for(e.__v!=t.__v&&(l.props=v,l.state=l.__s,l.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.some(function(F){F&&(F.__=e)}),w=0;w<l._sb.length;w++)l.__h.push(l._sb[w]);l._sb=[],l.__h.length&&s.push(l);break e}l.componentWillUpdate!=null&&l.componentWillUpdate(v,l.__s,b),y&&l.componentDidUpdate!=null&&l.__h.push(function(){l.componentDidUpdate(h,f,p)})}if(l.context=b,l.props=v,l.__P=n,l.__e=!1,_=ee.__r,k=0,y){for(l.state=l.__s,l.__d=!1,_&&_(e),u=l.render(l.props,l.state,l.context),T=0;T<l._sb.length;T++)l.__h.push(l._sb[T]);l._sb=[]}else do l.__d=!1,_&&_(e),u=l.render(l.props,l.state,l.context),l.state=l.__s;while(l.__d&&++k<25);l.state=l.__s,l.getChildContext!=null&&(r=Kn(Kn({},r),l.getChildContext())),y&&!d&&l.getSnapshotBeforeUpdate!=null&&(p=l.getSnapshotBeforeUpdate(h,f)),x=u,u!=null&&u.type===St&&u.key==null&&(x=ry(u.props.children)),o=Z0(n,qA(x)?x:[x],e,t,r,i,A,s,o,a,c),l.base=e.__e,e.__u&=-161,l.__h.length&&s.push(l),g&&(l.__E=l.__=null)}catch(F){if(e.__v=null,a||A!=null)if(F.then){for(e.__u|=a?160:128;o&&o.nodeType==8&&o.nextSibling;)o=o.nextSibling;A[A.indexOf(o)]=null,e.__e=o}else for(P=A.length;P--;)hd(A[P]);else e.__e=t.__e,e.__k=t.__k;ee.__e(F,e,t)}else A==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):o=e.__e=fQ(t.__e,e,t,r,i,A,s,a,c);return(u=ee.diffed)&&u(e),128&e.__u?void 0:o}function ny(n,e,t){for(var r=0;r<t.length;r++)md(t[r],t[++r],t[++r]);ee.__c&&ee.__c(e,n),n.some(function(i){try{n=i.__h,i.__h=[],n.some(function(A){A.call(i)})}catch(A){ee.__e(A,i.__v)}})}function ry(n){return typeof n!="object"||n==null||n.__b&&n.__b>0?n:qA(n)?n.map(ry):Kn({},n)}function fQ(n,e,t,r,i,A,s,o,a){var c,u,l,d,h,f,p,g=t.props,v=e.props,y=e.type;if(y=="svg"?i="http://www.w3.org/2000/svg":y=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),A!=null){for(c=0;c<A.length;c++)if((h=A[c])&&"setAttribute"in h==!!y&&(y?h.localName==y:h.nodeType==3)){n=h,A[c]=null;break}}if(n==null){if(y==null)return document.createTextNode(v);n=document.createElementNS(i,y,v.is&&v),o&&(ee.__m&&ee.__m(e,A),o=!1),A=null}if(y==null)g===v||o&&n.data==v||(n.data=v);else{if(A=A&&ga.call(n.childNodes),g=t.props||WA,!o&&A!=null)for(g={},c=0;c<n.attributes.length;c++)g[(h=n.attributes[c]).name]=h.value;for(c in g)if(h=g[c],c!="children"){if(c=="dangerouslySetInnerHTML")l=h;else if(!(c in v)){if(c=="value"&&"defaultValue"in v||c=="checked"&&"defaultChecked"in v)continue;wa(n,c,null,h,i)}}for(c in v)h=v[c],c=="children"?d=h:c=="dangerouslySetInnerHTML"?u=h:c=="value"?f=h:c=="checked"?p=h:o&&typeof h!="function"||g[c]===h||wa(n,c,h,g[c],i);if(u)o||l&&(u.__html==l.__html||u.__html==n.innerHTML)||(n.innerHTML=u.__html),e.__k=[];else if(l&&(n.innerHTML=""),Z0(e.type=="template"?n.content:n,qA(d)?d:[d],e,t,r,y=="foreignObject"?"http://www.w3.org/1999/xhtml":i,A,s,A?A[0]:t.__k&&Di(t,0),o,a),A!=null)for(c=A.length;c--;)hd(A[c]);o||(c="value",y=="progress"&&f==null?n.removeAttribute("value"):f!=null&&(f!==n[c]||y=="progress"&&!f||y=="option"&&f!=g[c])&&wa(n,c,f,g[c],i),c="checked",p!=null&&p!=n[c]&&wa(n,c,p,g[c],i))}return n}function md(n,e,t){try{if(typeof n=="function"){var r=typeof n.__u=="function";r&&n.__u(),r&&e==null||(n.__u=n(e))}else n.current=e}catch(i){ee.__e(i,t)}}function iy(n,e,t){var r,i;if(ee.unmount&&ee.unmount(n),(r=n.ref)&&(r.current&&r.current!=n.__e||md(r,null,e)),(r=n.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(A){ee.__e(A,e)}r.base=r.__P=null}if(r=n.__k)for(i=0;i<r.length;i++)r[i]&&iy(r[i],e,t||typeof n.type!="function");t||hd(n.__e),n.__c=n.__=n.__e=void 0}function gQ(n,e,t){return this.constructor(n,t)}function mQ(n,e,t){var r,i,A,s;e==document&&(e=document.documentElement),ee.__&&ee.__(n,e),i=(r=typeof t=="function")?null:t&&t.__k||e.__k,A=[],s=[],gd(e,n=(!r&&t||e).__k=pd(St,null,[n]),i||WA,WA,e.namespaceURI,!r&&t?[t]:i?null:e.firstChild?ga.call(e.childNodes):null,A,!r&&t?t:i?i.__e:e.firstChild,r,s),ny(A,n,s)}function Ay(n){function e(t){var r,i;return this.getChildContext||(r=new Set,(i={})[e.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(A){this.props.value!=A.value&&r.forEach(function(s){s.__e=!0,fd(s)})},this.sub=function(A){r.add(A);var s=A.componentWillUnmount;A.componentWillUnmount=function(){r&&r.delete(A),s&&s.call(A)}}),t.children}return e.__c="__cC"+z0++,e.__=n,e.Provider=e.__l=(e.Consumer=function(t,r){return t.children(r)}).contextType=e,e}ga=X0.slice,ee={__e:function(n,e,t,r){for(var i,A,s;e=e.__;)if((i=e.__c)&&!i.__)try{if((A=i.constructor)&&A.getDerivedStateFromError!=null&&(i.setState(A.getDerivedStateFromError(n)),s=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(n,r||{}),s=i.__d),s)return i.__E=i}catch(o){n=o}throw n}},G0=0,Vn.prototype.setState=function(n,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Kn({},this.state),typeof n=="function"&&(n=n(Kn({},t),this.props)),n&&Kn(t,n),n!=null&&this.__v&&(e&&this._sb.push(e),fd(this))},Vn.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),fd(this))},Vn.prototype.render=St,zr=[],W0=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,q0=function(n,e){return n.__v.__b-e.__v.__b},va.__r=0,J0=/(PointerCapture)$|Capture$/i,ud=0,ld=ty(!1),dd=ty(!0),z0=0;var vQ=0;function C(n,e,t,r,i,A){e||(e={});var s,o,a=e;if("ref"in a)for(o in a={},e)o=="ref"?s=e[o]:a[o]=e[o];var c={type:n,props:a,key:t,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--vQ,__i:-1,__u:0,__source:i,__self:A};if(typeof n=="function"&&(s=n.defaultProps))for(o in s)a[o]===void 0&&(a[o]=s[o]);return ee.vnode&&ee.vnode(c),c}var Xr,Ve,vd,sy,JA=0,oy=[],it=ee,ay=it.__b,cy=it.__r,uy=it.diffed,ly=it.__c,dy=it.unmount,hy=it.__;function zA(n,e){it.__h&&it.__h(Ve,n,JA||e),JA=0;var t=Ve.__H||(Ve.__H={__:[],__h:[]});return n>=t.__.length&&t.__.push({}),t.__[n]}function ge(n){return JA=1,yQ(gy,n)}function yQ(n,e,t){var r=zA(Xr++,2);if(r.t=n,!r.__c&&(r.__=[t?t(e):gy(void 0,e),function(o){var a=r.__N?r.__N[0]:r.__[0],c=r.t(a,o);a!==c&&(r.__N=[c,r.__[1]],r.__c.setState({}))}],r.__c=Ve,!Ve.__f)){var i=function(o,a,c){if(!r.__c.__H)return!0;var u=r.__c.__H.__.filter(function(d){return!!d.__c});if(u.every(function(d){return!d.__N}))return!A||A.call(this,o,a,c);var l=r.__c.props!==o;return u.forEach(function(d){if(d.__N){var h=d.__[0];d.__=d.__N,d.__N=void 0,h!==d.__[0]&&(l=!0)}}),A&&A.call(this,o,a,c)||l};Ve.__f=!0;var A=Ve.shouldComponentUpdate,s=Ve.componentWillUpdate;Ve.componentWillUpdate=function(o,a,c){if(this.__e){var u=A;A=void 0,i(o,a,c),A=u}s&&s.call(this,o,a,c)},Ve.shouldComponentUpdate=i}return r.__N||r.__}function Kt(n,e){var t=zA(Xr++,3);!it.__s&&Bd(t.__H,e)&&(t.__=n,t.u=e,Ve.__H.__h.push(t))}function yd(n,e){var t=zA(Xr++,4);!it.__s&&Bd(t.__H,e)&&(t.__=n,t.u=e,Ve.__h.push(t))}function En(n){return JA=5,wd(function(){return{current:n}},[])}function wd(n,e){var t=zA(Xr++,7);return Bd(t.__H,e)&&(t.__=n(),t.__H=e,t.__h=n),t.__}function wQ(n,e){return JA=8,wd(function(){return n},e)}function py(n){var e=Ve.context[n.__c],t=zA(Xr++,9);return t.c=n,e?(t.__==null&&(t.__=!0,e.sub(Ve)),e.props.value):n.__}function bQ(){for(var n;n=oy.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(ba),n.__H.__h.forEach(bd),n.__H.__h=[]}catch(e){n.__H.__h=[],it.__e(e,n.__v)}}it.__b=function(n){Ve=null,ay&&ay(n)},it.__=function(n,e){n&&e.__k&&e.__k.__m&&(n.__m=e.__k.__m),hy&&hy(n,e)},it.__r=function(n){cy&&cy(n),Xr=0;var e=(Ve=n.__c).__H;e&&(vd===Ve?(e.__h=[],Ve.__h=[],e.__.forEach(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.forEach(ba),e.__h.forEach(bd),e.__h=[],Xr=0)),vd=Ve},it.diffed=function(n){uy&&uy(n);var e=n.__c;e&&e.__H&&(e.__H.__h.length&&(oy.push(e)!==1&&sy===it.requestAnimationFrame||((sy=it.requestAnimationFrame)||BQ)(bQ)),e.__H.__.forEach(function(t){t.u&&(t.__H=t.u),t.u=void 0})),vd=Ve=null},it.__c=function(n,e){e.some(function(t){try{t.__h.forEach(ba),t.__h=t.__h.filter(function(r){return!r.__||bd(r)})}catch(r){e.some(function(i){i.__h&&(i.__h=[])}),e=[],it.__e(r,t.__v)}}),ly&&ly(n,e)},it.unmount=function(n){dy&&dy(n);var e,t=n.__c;t&&t.__H&&(t.__H.__.forEach(function(r){try{ba(r)}catch(i){e=i}}),t.__H=void 0,e&&it.__e(e,t.__v))};var fy=typeof requestAnimationFrame=="function";function BQ(n){var e,t=function(){clearTimeout(r),fy&&cancelAnimationFrame(e),setTimeout(n)},r=setTimeout(t,100);fy&&(e=requestAnimationFrame(t))}function ba(n){var e=Ve,t=n.__c;typeof t=="function"&&(n.__c=void 0,t()),Ve=e}function bd(n){var e=Ve;n.__c=n.__(),Ve=e}function Bd(n,e){return!n||n.length!==e.length||e.some(function(t,r){return t!==n[r]})}function gy(n,e){return typeof e=="function"?e(n):e}function CQ({size:n=24,color:e="#000"}){return C("svg",{xmlns:"http://www.w3.org/2000/svg",width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:e,"stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",class:"lucide lucide-x-icon lucide-x",children:[C("path",{d:"M18 6 6 18"}),C("path",{d:"m6 6 12 12"})]})}function my({onClose:n}){return C("button",{class:"obi-button obi-close-button",onClick:n,"aria-label":"Close",type:"button",children:C(CQ,{})})}function vy({open:n=!1,children:e,onClose:t,size:r="medium"}){const i=En(null),A=En(null);Kt(()=>{const c=i.current;c&&(n&&!c.open?c.showModal():!n&&c.open&&(A.current="programmatic",c.close()))},[n]);const s=c=>{const u=i.current;c.target===u&&(A.current="user-initiated",u==null||u.close())},o=c=>{c.preventDefault(),A.current||(A.current="user-initiated");const u=A.current;A.current=null,t==null||t(u)},a=()=>{var c;A.current="user-initiated",(c=i.current)==null||c.close()};return Kt(()=>{const c=i.current;if(c)return c.addEventListener("click",s),c.addEventListener("close",o),()=>{c.removeEventListener("click",s),c.removeEventListener("close",o)}},[t]),C("dialog",{ref:i,className:`modal-${r}`,children:[C(my,{onClose:a}),C("div",{class:"modal-content",children:n?typeof e=="function"?e():e:null})]})}function Cd(n){const{children:e,className:t="",...r}=n;return C("div",{className:`${t} obi-panel`,...r,children:e})}function _d({className:n="",isActive:e=!1,speakingStatus:t,onClick:r,onMouseEnter:i,onMouseLeave:A,children:s}){let o=`obi-pill container ${e&&"active"}`;return t==="user-speaking"&&(o+=" user-speaking"),t==="busy"&&(o+=" busy"),C("div",{className:o,onMouseEnter:i,onMouseLeave:A,children:C("div",{className:`obi-pill pill ${n}`,onClick:r,children:s})})}function yy({className:n="",active:e,speakingStatus:t,onClick:r,onMouseEnter:i,onMouseLeave:A,children:s,...o}){const a=`obi-pill2 container ${e?"active":""} ${t==="user-speaking"?"user-speaking":""} ${n}`;return C("div",{className:a,...o,children:C("div",{className:"pill",onClick:r,onMouseEnter:i,onMouseLeave:A,children:s})})}function Yr({type:n,size:e=24}){return C("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",children:_Q(n)})}function _Q(n){switch(n){case"pause":return C(St,{children:[C("rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}),C("rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"})]});case"play":return C(St,{children:C("path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"})});case"close":return C(St,{children:[C("path",{d:"M18 6 6 18"}),C("path",{d:"m6 6 12 12"})]});case"message":return C(St,{children:C("path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"})});case"minimize":return C(St,{children:[C("path",{d:"m14 10 7-7"}),C("path",{d:"M20 10h-6V4"}),C("path",{d:"m3 21 7-7"}),C("path",{d:"M4 14h6v6"})]});case"voice":return C(St,{children:[C("path",{d:"M2 10v3"}),C("path",{d:"M6 6v11"}),C("path",{d:"M10 3v18"}),C("path",{d:"M14 8v7"}),C("path",{d:"M18 5v13"}),C("path",{d:"M22 10v3"})]});case"open":return C(St,{children:[C("path",{d:"M12 7v14"}),C("path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"})]})}}const Sd=Ay(null);function SQ({children:n}){const e=py(Sd);if(!e)throw new Error("PopoutTarget must be used within a Popout component");const{controlledOpen:t,isOpen:r,setIsOpen:i,setAnimating:A,targetRef:s,trigger:o,onChange:a,delayMs:c}=e,u=En(null),l=wy(s,A),[d,h]=ge(!1);Kt(()=>{t!==void 0&&t!==d&&(t?p():g()),h(t)},[t]),Kt(()=>()=>{u.current&&clearTimeout(u.current)},[]);function f(){u.current&&(clearTimeout(u.current),u.current=null)}function p(){f(),c>0?u.current=setTimeout(()=>{a==null||a(!0),i(!0),u.current=null},c):(a==null||a(!0),i(!0))}function g(){f(),a==null||a(!1),i(!1)}const v=()=>{o==="click"&&(r?g():p())};function y(){o==="hover"&&p()}function B(){o==="hover"&&g()}return C("div",{ref:l,class:"target",onClick:v,onMouseEnter:y,onMouseLeave:B,children:n})}function kQ({children:n}){const e=py(Sd);if(!e)throw new Error("PopoutContent must be used within a Popout component");const{isOpen:t,animating:r,setAnimating:i,targetRef:A,contentRef:s}=e,o=wy(s,i);return yd(()=>{if(t&&!r&&A.current&&s.current){const a=s.current;if(!a)return;const c=A.current;if(!c)return;const u=a.getBoundingClientRect(),l=c.getBoundingClientRect(),d=l.right-l.left;a.style.top=`${u.top-u.bottom-(8+e.offset)}px`,a.style.left=`${-(u.right-u.left-d)/2}px`}},[t,r]),t?C("div",{ref:o,class:"content",style:{opacity:r?0:1},children:n}):null}function Vt({trigger:n="click",open:e,onChange:t,children:r,delayMs:i=0,offset:A=0,className:s=""}){const[o,a]=ge(!1),[c,u]=ge(!1),l=En(null),d=En(null),h={controlledOpen:e,isOpen:o,setIsOpen:a,animating:c,setAnimating:u,targetRef:l,contentRef:d,trigger:n,onChange:t,delayMs:i,offset:A};return C(Sd.Provider,{value:h,children:C("div",{class:`obi-popout ${s}`,children:r})})}Vt.Target=SQ,Vt.Content=kQ;function wy(n,e){const t=En(null),r=En(null),i=En(!0),A=wQ(s=>{if(n.current=s,!s){r.current&&(r.current.disconnect(),r.current=null),i.current=!0;return}function o(){if(i.current){i.current=!1;return}t.current?clearTimeout(t.current):e(!0),t.current=setTimeout(()=>{e(!1),t.current=null},200)}r.current=new ResizeObserver(o),r.current.observe(s,{box:"border-box"})},[]);return Kt(()=>()=>{r.current&&(r.current.disconnect(),r.current=null)},[]),A}function pn({className:n,onClick:e,type:t,disabled:r,title:i}){const A={cancel:C(Yr,{type:"close",size:16}),pause:C(Yr,{type:"pause",size:16}),play:C(Yr,{type:"play",size:16}),message:C(Yr,{type:"message",size:16}),minimize:C(Yr,{type:"minimize",size:16}),voice:C(Yr,{type:"voice",size:16}),open:C(Yr,{type:"open",size:16})}[t],s={cancel:"",pause:"",play:"",message:"",minimize:"",voice:"",open:""}[t],o=C("button",{class:`obi-button obi-round-button ${s} ${n}`,onClick:r?void 0:e,disabled:r,children:A});return i?C(Vt,{className:"obi-round-button-popout",trigger:"hover",delayMs:200,offset:9,children:[C(Vt.Target,{children:o}),C(Vt.Content,{children:C("div",{className:"obi-round-button-title",children:i})})]}):o}const by=8,Ba=8,EQ=50,UQ=.7,Ni=3;function By({getBands:n,color:e="white"}){const t=En(null);return Kt(()=>{if(!n)return;const r=setInterval(()=>{try{const i=n();if(!t.current)return;const A=t.current.querySelectorAll(".bar"),s=i&&i.length>0?i.slice(0,Ba).map(o=>{const a=Math.abs(o);return Math.min(a/UQ*by,by)||Ni}):Array(Ba).fill(Ni);for(;s.length<Ba;)s.push(Ni);s.forEach((o,a)=>{if(o<Ni&&(o=Ni),A[a]){const c=o*2;A[a].style.height=`${c}px`,A[a].style.display=o>0?"block":"none"}})}catch(i){console.warn("Error updating equaliser:",i)}},EQ);return()=>{clearInterval(r)}},[n]),C("div",{className:"obi-equaliser",ref:t,children:Array.from({length:Ba},(r,i)=>C("div",{className:"column",children:C("div",{className:"bar",style:{height:`${Ni}px`,backgroundColor:e,display:"block"}})},i))})}function XA({className:n,children:e,onClick:t}){return t?C("button",{class:`obi-button obi-message ${n} clickable`,onClick:t,children:e}):C("div",{class:`obi-message ${n}`,children:e})}const TQ=8;function Cy({color:n="white"}){return C("div",{className:"obi-loading-dots",children:Array.from({length:TQ},(e,t)=>C("div",{className:"column",children:[C("div",{className:"bar",style:{backgroundColor:n,animationDelay:`${t*.15}s`}}),C("div",{className:"dot",style:{backgroundColor:n}})]},t))})}function IQ({onContinue:n,onWrapUp:e}){return C(Cd,{className:"obi-exit-survey",children:C(xQ,{onContinue:n,onWrapUp:()=>{e()}})})}function FQ({onOtherSelect:n,onReasonSelect:e,onClose:t}){const[r,i]=ge("reason"),A=s=>{s==="other"?(n(),i("other-reason")):e(s)};return C(Cd,{className:`obi-exit-survey ${r==="reason"?"obi-exit-survey-reason":""}`,children:r==="reason"?C(QQ,{onReasonSelect:A}):C(RQ,{onReasonSelect:A,onClose:t})})}function xQ({onContinue:n,onWrapUp:e}){return C("div",{className:"obi-exit-survey-container",children:[C("h2",{className:"obi-exit-survey-title",children:"Wrapping up early?"}),C("div",{className:"obi-exit-survey-options",children:[C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-continue",onClick:n,type:"button",children:"No, let's continue"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:e,type:"button",children:"Yes, let's wrap up"})]})]})}function QQ({onReasonSelect:n}){return C("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[C("div",{className:"obi-exit-survey-header",children:C("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Quick feedback?"})}),C("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("do-later"),type:"button",children:"Will do later"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("cant-talk"),type:"button",children:"Can't talk right now"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("prefer-written"),type:"button",children:"Prefer written instructions"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("technical-issues"),type:"button",children:"Experienced technical issues"}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-reason-button",onClick:()=>n("other"),type:"button",children:"Other"})]})]})}function RQ({onReasonSelect:n,onClose:e}){const[t,r]=ge("");return C("div",{className:"obi-exit-survey-container obi-exit-survey-reason-container",children:[C("div",{className:"obi-exit-survey-header",children:[C(my,{onClose:e}),C("h2",{className:"obi-exit-survey-title obi-exit-survey-reason-title",children:"Tell us more"})]}),C("div",{className:"obi-exit-survey-options obi-exit-survey-reason-options",children:[C("textarea",{className:"obi-exit-survey-button obi-exit-survey-reason-button",placeholder:"What's on your mind?",value:t,onChange:i=>r(i.target.value)}),C("button",{className:"obi-button obi-exit-survey-button obi-exit-survey-button-wrap-up",onClick:()=>n("other-feedback",t),type:"button",children:"Send feedback"})]})]})}function PQ(n,e){for(var t in e)n[t]=e[t];return n}function _y(n,e){for(var t in n)if(t!=="__source"&&!(t in e))return!0;for(var r in e)if(r!=="__source"&&n[r]!==e[r])return!0;return!1}function Sy(n,e){this.props=n,this.context=e}(Sy.prototype=new Vn).isPureReactComponent=!0,Sy.prototype.shouldComponentUpdate=function(n,e){return _y(this.props,n)||_y(this.state,e)};var ky=ee.__b;ee.__b=function(n){n.type&&n.type.__f&&n.ref&&(n.props.ref=n.ref,n.ref=null),ky&&ky(n)};var OQ=ee.__e;ee.__e=function(n,e,t,r){if(n.then){for(var i,A=e;A=A.__;)if((i=A.__c)&&i.__c)return e.__e==null&&(e.__e=t.__e,e.__k=t.__k),i.__c(n,e)}OQ(n,e,t,r)};var Ey=ee.unmount;function Uy(n,e,t){return n&&(n.__c&&n.__c.__H&&(n.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),n.__c.__H=null),(n=PQ({},n)).__c!=null&&(n.__c.__P===t&&(n.__c.__P=e),n.__c.__e=!0,n.__c=null),n.__k=n.__k&&n.__k.map(function(r){return Uy(r,e,t)})),n}function Ty(n,e,t){return n&&t&&(n.__v=null,n.__k=n.__k&&n.__k.map(function(r){return Ty(r,e,t)}),n.__c&&n.__c.__P===e&&(n.__e&&t.appendChild(n.__e),n.__c.__e=!0,n.__c.__P=t)),n}function kd(){this.__u=0,this.o=null,this.__b=null}function Iy(n){var e=n.__.__c;return e&&e.__a&&e.__a(n)}function Ca(){this.i=null,this.l=null}ee.unmount=function(n){var e=n.__c;e&&e.__R&&e.__R(),e&&32&n.__u&&(n.type=null),Ey&&Ey(n)},(kd.prototype=new Vn).__c=function(n,e){var t=e.__c,r=this;r.o==null&&(r.o=[]),r.o.push(t);var i=Iy(r.__v),A=!1,s=function(){A||(A=!0,t.__R=null,i?i(o):o())};t.__R=s;var o=function(){if(!--r.__u){if(r.state.__a){var a=r.state.__a;r.__v.__k[0]=Ty(a,a.__c.__P,a.__c.__O)}var c;for(r.setState({__a:r.__b=null});c=r.o.pop();)c.forceUpdate()}};r.__u++||32&e.__u||r.setState({__a:r.__b=r.__v.__k[0]}),n.then(s,s)},kd.prototype.componentWillUnmount=function(){this.o=[]},kd.prototype.render=function(n,e){if(this.__b){if(this.__v.__k){var t=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=Uy(this.__b,t,r.__O=r.__P)}this.__b=null}var i=e.__a&&pd(St,null,n.fallback);return i&&(i.__u&=-33),[pd(St,null,e.__a?null:n.children),i]};var Fy=function(n,e,t){if(++t[1]===t[0]&&n.l.delete(e),n.props.revealOrder&&(n.props.revealOrder[0]!=="t"||!n.l.size))for(t=n.i;t;){for(;t.length>3;)t.pop()();if(t[1]<t[0])break;n.i=t=t[2]}};(Ca.prototype=new Vn).__a=function(n){var e=this,t=Iy(e.__v),r=e.l.get(n);return r[0]++,function(i){var A=function(){e.props.revealOrder?(r.push(i),Fy(e,n,r)):i()};t?t(A):A()}},Ca.prototype.render=function(n){this.i=null,this.l=new Map;var e=ya(n.children);n.revealOrder&&n.revealOrder[0]==="b"&&e.reverse();for(var t=e.length;t--;)this.l.set(e[t],this.i=[1,0,this.i]);return n.children},Ca.prototype.componentDidUpdate=Ca.prototype.componentDidMount=function(){var n=this;this.l.forEach(function(e,t){Fy(n,t,e)})};var MQ=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,LQ=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,DQ=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,NQ=/[A-Z0-9]/g,HQ=typeof document<"u",KQ=function(n){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(n)};Vn.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(n){Object.defineProperty(Vn.prototype,n,{configurable:!0,get:function(){return this["UNSAFE_"+n]},set:function(e){Object.defineProperty(this,n,{configurable:!0,writable:!0,value:e})}})});var xy=ee.event;function VQ(){}function GQ(){return this.cancelBubble}function jQ(){return this.defaultPrevented}ee.event=function(n){return xy&&(n=xy(n)),n.persist=VQ,n.isPropagationStopped=GQ,n.isDefaultPrevented=jQ,n.nativeEvent=n};var WQ={enumerable:!1,configurable:!0,get:function(){return this.class}},Qy=ee.vnode;ee.vnode=function(n){typeof n.type=="string"&&function(e){var t=e.props,r=e.type,i={},A=r.indexOf("-")===-1;for(var s in t){var o=t[s];if(!(s==="value"&&"defaultValue"in t&&o==null||HQ&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var a=s.toLowerCase();s==="defaultValue"&&"value"in t&&t.value==null?s="value":s==="download"&&o===!0?o="":a==="translate"&&o==="no"?o=!1:a[0]==="o"&&a[1]==="n"?a==="ondoubleclick"?s="ondblclick":a!=="onchange"||r!=="input"&&r!=="textarea"||KQ(t.type)?a==="onfocus"?s="onfocusin":a==="onblur"?s="onfocusout":DQ.test(s)&&(s=a):a=s="oninput":A&&LQ.test(s)?s=s.replace(NQ,"-$&").toLowerCase():o===null&&(o=void 0),a==="oninput"&&i[s=a]&&(s="oninputCapture"),i[s]=o}}r=="select"&&i.multiple&&Array.isArray(i.value)&&(i.value=ya(t.children).forEach(function(c){c.props.selected=i.value.indexOf(c.props.value)!=-1})),r=="select"&&i.defaultValue!=null&&(i.value=ya(t.children).forEach(function(c){c.props.selected=i.multiple?i.defaultValue.indexOf(c.props.value)!=-1:i.defaultValue==c.props.value})),t.class&&!t.className?(i.class=t.class,Object.defineProperty(i,"className",WQ)):(t.className&&!t.class||t.class&&t.className)&&(i.class=i.className=t.className),e.props=i}(n),n.$$typeof=MQ,Qy&&Qy(n)};var Ry=ee.__r;ee.__r=function(n){Ry&&Ry(n),n.__c};var Py=ee.diffed;ee.diffed=function(n){Py&&Py(n);var e=n.props,t=n.__e;t!=null&&n.type==="textarea"&&"value"in e&&e.value!==t.value&&(t.value=e.value==null?"":e.value)};function qQ(n){const{placeholder:e="Type your message...",value:t,defaultValue:r,onChange:i,onSend:A,onCancel:s,onExpand:o,isLoading:a=!1,disabled:c=!1,maxLength:u=500,children:l}=n,[d,h]=ge(t||r||""),[f,p]=ge((t||r||"").length>24),g=En(null);yd(()=>{f&&(o==null||o(!0))},[]);const v=t!==void 0?t:d,y=w=>{const _=w.currentTarget.value;t===void 0&&h(_),i==null||i(_)},B=w=>{w.key==="Escape"&&(h(t||r||""),p(!1),s==null||s()),w.key==="Enter"&&!w.shiftKey&&v.trim()&&(w.preventDefault(),h(t||r||""),p(!1),b()),(v||"").length>=24&&!f&&(p(!0),o==null||o(!0))};Kt(()=>{g.current&&g.current.focus()},[g.current]);const b=()=>{!v.trim()||a||c||(A==null||A(v.trim()),t===void 0&&h(""))};return C("div",{className:`obi-message-input ${f?"expanded":""}`,children:[C("div",{className:"container",children:C("textarea",{ref:g,className:"field",placeholder:e,value:v,onInput:y,onKeyDown:B,disabled:c||a,maxLength:u,rows:1})}),C("div",{className:"button-container",children:[f&&C("div",{children:l}),C("button",{className:"obi-button send",onClick:b,disabled:!v.trim()||a||c,type:"button",children:C("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:C("path",{d:"M6.00016 10.6673V1.33398M6.00016 1.33398L1.3335 6.00065M6.00016 1.33398L10.6668 6.00065",stroke:"#F3F3F3","stroke-width":"1.6","stroke-linecap":"round","stroke-linejoin":"round"})})})]})]})}function JQ(n){const{currentStep:e,totalSteps:t,stepNames:r,className:i}=n,A=Array.from({length:t},(a,c)=>({isCompleted:c<e,stepNumber:c+1})),s=r[e-1]||`Step ${e}`,o=`${e}/${t} \u2022 ${s}`;return C("div",{class:`obi-course-progress ${i||""}`,children:[C("div",{class:"obi-course-progress-steps",children:A.map((a,c)=>C("div",{class:"obi-course-progress-container",children:C("div",{class:`obi-course-progress-step ${a.isCompleted?"completed":""}`})},c))}),C("div",{class:"obi-course-progress-description",children:o})]})}function Ed({className:n="",size:e=64}){return C("svg",{width:e,height:e,viewBox:"0 0 256 256",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:n,children:C("path",{d:"M158.803 0L160.352 0.0399439C176.267 0.844061 188.922 13.9634 188.922 30.0311C188.922 46.6174 175.438 60.0653 158.803 60.0656H99.0263L98.9061 60.0722C78.8071 61.4795 62.6269 77.004 60.2644 96.7673L60.241 96.9704V158.93L60.2644 159.13C62.7406 179.86 80.4234 195.934 101.881 195.935H153.842C176.993 195.935 195.759 177.223 195.759 154.14V96.9138L195.799 95.3693C196.606 79.5009 209.766 66.8827 225.881 66.8827C242.515 66.8834 256 80.328 256 96.9138V159.086L255.963 160.564C255.225 175.748 243.176 187.971 228.038 189.038V189.214C207.121 190.591 190.4 207.263 189.019 228.119H188.842C187.738 243.7 174.712 256 158.803 256H96.4491C79.8147 256 66.3309 242.555 66.3302 225.969C66.3302 225.673 66.3349 225.375 66.3436 225.077H66.3503H66.3035C63.3344 206.008 47.4427 190.589 27.8321 189.231L27.8354 189.031C12.2702 187.868 0.000167669 174.905 0 159.086V96.9138L0.0367222 95.4192C0.791087 80.0787 13.0909 67.7634 28.453 66.9293C47.7697 65.3039 63.3522 50.3234 66.2969 31.4658L66.3469 31.1595L66.3369 30.85C66.3301 30.5933 66.3302 30.3238 66.3302 30.0311C66.3309 13.4454 79.8148 0.000165137 96.4491 0H158.803Z",fill:"currentColor"})})}function zQ({children:n}){const e={container:{position:"relative",width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},logo:{display:"flex",width:"120px",height:"120px",justifyContent:"center",alignItems:"center",aspectRatio:"1/1",borderRadius:"8px",color:"#FFFFFF",position:"relative",overflow:"hidden",background:"var(--obi-color-primary)",boxShadow:`
43
43
  0 0 20px color-mix(in srgb, var(--obi-color-primary) 20%, transparent),
44
44
  0 0 40px color-mix(in srgb, var(--obi-color-primary) 15%, transparent),
45
45
  0 0 60px color-mix(in srgb, var(--obi-color-primary) 8%, transparent)
@@ -120,6 +120,6 @@ or you can use record.mirror to access the mirror instance during recording.`,tB
120
120
  `+d+"]":"["+h.join(",")+"]",s=d,u}for(c in f)Uc.call(f,c)&&(u=r(c,f),u&&h.push(t(c)+(s?": ":":")+u));return u=h.length===0?"{}":s?"{"+h.join(",")+d+"}":"{"+h.join(",")+"}",s=d,u}};return r("",{"":e})}}(),m.JSONDecode=function(){var n,e,t={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
121
121
  `,r:"\r",t:" "},r,i=function(h){var f=new SyntaxError(h);throw f.at=n,f.text=r,f},A=function(h){return h&&h!==e&&i("Expected '"+h+"' instead of '"+e+"'"),e=r.charAt(n),n+=1,e},s=function(){var h,f="";for(e==="-"&&(f="-",A("-"));e>="0"&&e<="9";)f+=e,A();if(e===".")for(f+=".";A()&&e>="0"&&e<="9";)f+=e;if(e==="e"||e==="E")for(f+=e,A(),(e==="-"||e==="+")&&(f+=e,A());e>="0"&&e<="9";)f+=e,A();if(h=+f,!isFinite(h))i("Bad number");else return h},o=function(){var h,f,p="",g;if(e==='"')for(;A();){if(e==='"')return A(),p;if(e==="\\")if(A(),e==="u"){for(g=0,f=0;f<4&&(h=parseInt(A(),16),!!isFinite(h));f+=1)g=g*16+h;p+=String.fromCharCode(g)}else if(typeof t[e]=="string")p+=t[e];else break;else p+=e}i("Bad string")},a=function(){for(;e&&e<=" ";)A()},c=function(){switch(e){case"t":return A("t"),A("r"),A("u"),A("e"),!0;case"f":return A("f"),A("a"),A("l"),A("s"),A("e"),!1;case"n":return A("n"),A("u"),A("l"),A("l"),null}i('Unexpected "'+e+'"')},u,l=function(){var h=[];if(e==="["){if(A("["),a(),e==="]")return A("]"),h;for(;e;){if(h.push(u()),a(),e==="]")return A("]"),h;A(","),a()}}i("Bad array")},d=function(){var h,f={};if(e==="{"){if(A("{"),a(),e==="}")return A("}"),f;for(;e;){if(h=o(),a(),A(":"),Object.hasOwnProperty.call(f,h)&&i('Duplicate key "'+h+'"'),f[h]=u(),a(),e==="}")return A("}"),f;A(","),a()}}i("Bad object")};return u=function(){switch(a(),e){case"{":return d();case"[":return l();case'"':return o();case"-":return s();default:return e>="0"&&e<="9"?s():c()}},function(h){var f;return r=h,n=0,e=" ",f=u(),a(),e&&i("Syntax error"),f}}(),m.base64Encode=function(n){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t,r,i,A,s,o,a,c,u=0,l=0,d="",h=[];if(!n)return n;n=m.utf8Encode(n);do t=n.charCodeAt(u++),r=n.charCodeAt(u++),i=n.charCodeAt(u++),c=t<<16|r<<8|i,A=c>>18&63,s=c>>12&63,o=c>>6&63,a=c&63,h[l++]=e.charAt(A)+e.charAt(s)+e.charAt(o)+e.charAt(a);while(u<n.length);switch(d=h.join(""),n.length%3){case 1:d=d.slice(0,-2)+"==";break;case 2:d=d.slice(0,-1)+"=";break}return d},m.utf8Encode=function(n){n=(n+"").replace(/\r\n/g,`
122
122
  `).replace(/\r/g,`
123
- `);var e="",t,r,i=0,A;for(t=r=0,i=n.length,A=0;A<i;A++){var s=n.charCodeAt(A),o=null;s<128?r++:s>127&&s<2048?o=String.fromCharCode(s>>6|192,s&63|128):o=String.fromCharCode(s>>12|224,s>>6&63|128,s&63|128),o!==null&&(r>t&&(e+=n.substring(t,r)),e+=o,t=r=A+1)}return r>t&&(e+=n.substring(t,n.length)),e},m.UUID=function(){try{return V.crypto.randomUUID()}catch{for(var n=new Array(36),e=0;e<36;e++)n[e]=Math.floor(Math.random()*16);return n[14]=4,n[19]=n[19]&=-5,n[19]=n[19]|=8,n[8]=n[13]=n[18]=n[23]="-",m.map(n,function(t){return t.toString(16)}).join("")}};var GB=["ahrefsbot","ahrefssiteaudit","amazonbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","facebookexternal","petalbot","pinterest","screaming frog","yahoo! slurp","yandex","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleweblight","mediapartners-google","storebot-google"];m.isBlockedUA=function(n){var e;for(n=n.toLowerCase(),e=0;e<GB.length;e++)if(n.indexOf(GB[e])!==-1)return!0;return!1},m.HTTPBuildQuery=function(n,e){var t,r,i=[];return m.isUndefined(e)&&(e="&"),m.each(n,function(A,s){t=encodeURIComponent(A.toString()),r=encodeURIComponent(s),i[i.length]=r+"="+t}),i.join(e)},m.getQueryParam=function(n,e){e=e.replace(/[[]/g,"\\[").replace(/[\]]/g,"\\]");var t="[\\?&]"+e+"=([^&#]*)",r=new RegExp(t),i=r.exec(n);if(i===null||i&&typeof i[1]!="string"&&i[1].length)return"";var A=i[1];try{A=decodeURIComponent(A)}catch{we.error("Skipping decoding for malformed query param: "+A)}return A.replace(/\+/g," ")},m.cookie={get:function(n){for(var e=n+"=",t=ye.cookie.split(";"),r=0;r<t.length;r++){for(var i=t[r];i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return decodeURIComponent(i.substring(e.length,i.length))}return null},parse:function(n){var e;try{e=m.JSONDecode(m.cookie.get(n))||{}}catch{}return e},set_seconds:function(n,e,t,r,i,A,s){var o="",a="",c="";if(s)o="; domain="+s;else if(r){var u=qB(ye.location.hostname);o=u?"; domain=."+u:""}if(t){var l=new Date;l.setTime(l.getTime()+t*1e3),a="; expires="+l.toGMTString()}A&&(i=!0,c="; SameSite=None"),i&&(c+="; secure"),ye.cookie=n+"="+encodeURIComponent(e)+a+"; path=/"+o+c},set:function(n,e,t,r,i,A,s){var o="",a="",c="";if(s)o="; domain="+s;else if(r){var u=qB(ye.location.hostname);o=u?"; domain=."+u:""}if(t){var l=new Date;l.setTime(l.getTime()+t*24*60*60*1e3),a="; expires="+l.toGMTString()}A&&(i=!0,c="; SameSite=None"),i&&(c+="; secure");var d=n+"="+encodeURIComponent(e)+a+"; path=/"+o+c;return ye.cookie=d,d},remove:function(n,e,t){m.cookie.set(n,"",-1,e,!1,!1,t)}};var jB=function(n){var e=!0;try{var t="__mplss_"+op(8),r="xyz";n.setItem(t,r),n.getItem(t)!==r&&(e=!1),n.removeItem(t)}catch{e=!1}return e},Ap=null,Cs=function(n,e){return Ap!==null&&!e?Ap:Ap=jB(n||V.localStorage)},sp=null,XL=function(n,e){return sp!==null&&!e?sp:sp=jB(n||V.sessionStorage)};function WB(n,e,t){var r=function(i){we.error(e+" error: "+i)};return{is_supported:function(i){var A=t(n,i);return A||we.error(e+" unsupported"),A},error:r,get:function(i){try{return n.getItem(i)}catch(A){r(A)}return null},parse:function(i){try{return m.JSONDecode(n.getItem(i))||{}}catch{}return null},set:function(i,A){try{n.setItem(i,A)}catch(s){r(s)}},remove:function(i){try{n.removeItem(i)}catch(A){r(A)}}}}m.localStorage=WB(V.localStorage,"localStorage",Cs),m.sessionStorage=WB(V.sessionStorage,"sessionStorage",XL),m.register_event=function(){var n=function(r,i,A,s,o){if(!r){we.error("No valid element provided to register_event");return}if(r.addEventListener&&!s)r.addEventListener(i,A,!!o);else{var a="on"+i,c=r[a];r[a]=e(r,A,c)}};function e(r,i,A){var s=function(o){if(o=o||t(V.event),!!o){var a=!0,c,u;return m.isFunction(A)&&(c=A(o)),u=i.call(r,o),(c===!1||u===!1)&&(a=!1),a}};return s}function t(r){return r&&(r.preventDefault=t.preventDefault,r.stopPropagation=t.stopPropagation),r}return t.preventDefault=function(){this.returnValue=!1},t.stopPropagation=function(){this.cancelBubble=!0},n}();var YL=new RegExp('^(\\w*)\\[(\\w+)([=~\\|\\^\\$\\*]?)=?"?([^\\]"]*)"?\\]$');m.dom_query=function(){function n(i){return i.all?i.all:i.getElementsByTagName("*")}var e=/[\t\r\n]/g;function t(i,A){var s=" "+A+" ";return(" "+i.className+" ").replace(e," ").indexOf(s)>=0}function r(i){if(!ye.getElementsByTagName)return[];var A=i.split(" "),s,o,a,c,u,l,d,h,f,p,g=[ye];for(l=0;l<A.length;l++){if(s=A[l].replace(/^\s+/,"").replace(/\s+$/,""),s.indexOf("#")>-1){o=s.split("#"),a=o[0];var v=o[1],y=ye.getElementById(v);if(!y||a&&y.nodeName.toLowerCase()!=a)return[];g=[y];continue}if(s.indexOf(".")>-1){o=s.split("."),a=o[0];var B=o[1];for(a||(a="*"),c=[],u=0,d=0;d<g.length;d++)for(a=="*"?f=n(g[d]):f=g[d].getElementsByTagName(a),h=0;h<f.length;h++)c[u++]=f[h];for(g=[],p=0,d=0;d<c.length;d++)c[d].className&&m.isString(c[d].className)&&t(c[d],B)&&(g[p++]=c[d]);continue}var b=s.match(YL);if(b){a=b[1];var w=b[2],_=b[3],k=b[4];for(a||(a="*"),c=[],u=0,d=0;d<g.length;d++)for(a=="*"?f=n(g[d]):f=g[d].getElementsByTagName(a),h=0;h<f.length;h++)c[u++]=f[h];g=[],p=0;var T;switch(_){case"=":T=function(x){return x.getAttribute(w)==k};break;case"~":T=function(x){return x.getAttribute(w).match(new RegExp("\\b"+k+"\\b"))};break;case"|":T=function(x){return x.getAttribute(w).match(new RegExp("^"+k+"-?"))};break;case"^":T=function(x){return x.getAttribute(w).indexOf(k)===0};break;case"$":T=function(x){return x.getAttribute(w).lastIndexOf(k)==x.getAttribute(w).length-k.length};break;case"*":T=function(x){return x.getAttribute(w).indexOf(k)>-1};break;default:T=function(x){return x.getAttribute(w)}}for(g=[],p=0,d=0;d<c.length;d++)T(c[d])&&(g[p++]=c[d]);continue}for(a=s,c=[],u=0,d=0;d<g.length;d++)for(f=g[d].getElementsByTagName(a),h=0;h<f.length;h++)c[u++]=f[h];g=c}return g}return function(i){return m.isElement(i)?[i]:m.isObject(i)&&!m.isUndefined(i.length)?i:r.call(this,i)}}();var ZL=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","utm_id","utm_source_platform","utm_campaign_id","utm_creative_format","utm_marketing_tactic"],$L=["dclid","fbclid","gclid","ko_click_id","li_fat_id","msclkid","sccid","ttclid","twclid","wbraid"];m.info={campaignParams:function(n){var e="",t={};return m.each(ZL,function(r){e=m.getQueryParam(ye.URL,r),e.length?t[r]=e:n!==void 0&&(t[r]=n)}),t},clickParams:function(){var n="",e={};return m.each($L,function(t){n=m.getQueryParam(ye.URL,t),n.length&&(e[t]=n)}),e},marketingParams:function(){return m.extend(m.info.campaignParams(),m.info.clickParams())},searchEngine:function(n){return n.search("https?://(.*)google.([^/?]*)")===0?"google":n.search("https?://(.*)bing.com")===0?"bing":n.search("https?://(.*)yahoo.com")===0?"yahoo":n.search("https?://(.*)duckduckgo.com")===0?"duckduckgo":null},searchInfo:function(n){var e=m.info.searchEngine(n),t=e!="yahoo"?"q":"p",r={};if(e!==null){r.$search_engine=e;var i=m.getQueryParam(n,t);i.length&&(r.mp_keyword=i)}return r},browser:function(n,e,t){return e=e||"",t||m.includes(n," OPR/")?m.includes(n,"Mini")?"Opera Mini":"Opera":/(BlackBerry|PlayBook|BB10)/i.test(n)?"BlackBerry":m.includes(n,"IEMobile")||m.includes(n,"WPDesktop")?"Internet Explorer Mobile":m.includes(n,"SamsungBrowser/")?"Samsung Internet":m.includes(n,"Edge")||m.includes(n,"Edg/")?"Microsoft Edge":m.includes(n,"FBIOS")?"Facebook Mobile":m.includes(n,"Whale/")?"Whale Browser":m.includes(n,"Chrome")?"Chrome":m.includes(n,"CriOS")?"Chrome iOS":m.includes(n,"UCWEB")||m.includes(n,"UCBrowser")?"UC Browser":m.includes(n,"FxiOS")?"Firefox iOS":m.includes(e,"Apple")?m.includes(n,"Mobile")?"Mobile Safari":"Safari":m.includes(n,"Android")?"Android Mobile":m.includes(n,"Konqueror")?"Konqueror":m.includes(n,"Firefox")?"Firefox":m.includes(n,"MSIE")||m.includes(n,"Trident/")?"Internet Explorer":m.includes(n,"Gecko")?"Mozilla":""},browserVersion:function(n,e,t){var r=m.info.browser(n,e,t),i={"Internet Explorer Mobile":/rv:(\d+(\.\d+)?)/,"Microsoft Edge":/Edge?\/(\d+(\.\d+)?)/,Chrome:/Chrome\/(\d+(\.\d+)?)/,"Chrome iOS":/CriOS\/(\d+(\.\d+)?)/,"UC Browser":/(UCBrowser|UCWEB)\/(\d+(\.\d+)?)/,Safari:/Version\/(\d+(\.\d+)?)/,"Mobile Safari":/Version\/(\d+(\.\d+)?)/,Opera:/(Opera|OPR)\/(\d+(\.\d+)?)/,Firefox:/Firefox\/(\d+(\.\d+)?)/,"Firefox iOS":/FxiOS\/(\d+(\.\d+)?)/,Konqueror:/Konqueror:(\d+(\.\d+)?)/,BlackBerry:/BlackBerry (\d+(\.\d+)?)/,"Android Mobile":/android\s(\d+(\.\d+)?)/,"Samsung Internet":/SamsungBrowser\/(\d+(\.\d+)?)/,"Internet Explorer":/(rv:|MSIE )(\d+(\.\d+)?)/,Mozilla:/rv:(\d+(\.\d+)?)/,"Whale Browser":/Whale\/(\d+(\.\d+)?)/},A=i[r];if(A===void 0)return null;var s=n.match(A);return s?parseFloat(s[s.length-2]):null},os:function(){var n=qn;return/Windows/i.test(n)?/Phone/.test(n)||/WPDesktop/.test(n)?"Windows Phone":"Windows":/(iPhone|iPad|iPod)/.test(n)?"iOS":/Android/.test(n)?"Android":/(BlackBerry|PlayBook|BB10)/i.test(n)?"BlackBerry":/Mac/i.test(n)?"Mac OS X":/Linux/.test(n)?"Linux":/CrOS/.test(n)?"Chrome OS":""},device:function(n){return/Windows Phone/i.test(n)||/WPDesktop/.test(n)?"Windows Phone":/iPad/.test(n)?"iPad":/iPod/.test(n)?"iPod Touch":/iPhone/.test(n)?"iPhone":/(BlackBerry|PlayBook|BB10)/i.test(n)?"BlackBerry":/Android/.test(n)?"Android":""},referringDomain:function(n){var e=n.split("/");return e.length>=3?e[2]:""},currentUrl:function(){return V.location.href},properties:function(n){return typeof n!="object"&&(n={}),m.extend(m.strip_empty_properties({$os:m.info.os(),$browser:m.info.browser(qn,Ur.vendor,Tc),$referrer:ye.referrer,$referring_domain:m.info.referringDomain(ye.referrer),$device:m.info.device(qn)}),{$current_url:m.info.currentUrl(),$browser_version:m.info.browserVersion(qn,Ur.vendor,Tc),$screen_height:DB.height,$screen_width:DB.width,mp_lib:"web",$lib_version:gn.LIB_VERSION,$insert_id:op(),time:m.timestamp()/1e3},m.strip_empty_properties(n))},people_properties:function(){return m.extend(m.strip_empty_properties({$os:m.info.os(),$browser:m.info.browser(qn,Ur.vendor,Tc)}),{$browser_version:m.info.browserVersion(qn,Ur.vendor,Tc)})},mpPageViewProperties:function(){return m.strip_empty_properties({current_page_title:ye.title,current_domain:V.location.hostname,current_url_path:V.location.pathname,current_url_protocol:V.location.protocol,current_url_search:V.location.search})}};var eD=function(n,e){var t=null,r=[];return function(i){var A=this;return r.push(i),t||(t=new be(function(s){setTimeout(function(){var o=n.apply(A,[r]);t=null,r=[],s(o)},e)})),t}},op=function(n){var e=Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10);return n?e.substring(0,n):e},tD=/[a-z0-9][a-z0-9-]*\.[a-z]+$/i,nD=/[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i,qB=function(n){var e=nD,t=n.split("."),r=t[t.length-1];(r.length>4||r==="com"||r==="org")&&(e=tD);var i=n.match(e);return i?i[0]:""},rD=function(){var n=V.navigator.onLine;return m.isUndefined(n)||n},Tr=function(){},tA=null,Ic=null;typeof JSON<"u"&&(tA=JSON.stringify,Ic=JSON.parse),tA=tA||m.JSONEncode,Ic=Ic||m.JSONDecode,m.info=m.info,m.info.browser=m.info.browser,m.info.browserVersion=m.info.browserVersion,m.info.device=m.info.device,m.info.properties=m.info.properties,m.isBlockedUA=m.isBlockedUA,m.isEmptyObject=m.isEmptyObject,m.isObject=m.isObject,m.JSONDecode=m.JSONDecode,m.JSONEncode=m.JSONEncode,m.toArray=m.toArray,m.NPO=Er;var iD="mixpanelBrowserDb",JB="mixpanelRecordingEvents",ap="mixpanelRecordingRegistry",AD=1,sD=[JB,ap],In=function(n){this.dbPromise=null,this.storeName=n};In.prototype._openDb=function(){return new be(function(n,e){var t=V.indexedDB.open(iD,AD);t.onerror=function(){e(t.error)},t.onsuccess=function(){n(t.result)},t.onupgradeneeded=function(r){var i=r.target.result;sD.forEach(function(A){i.createObjectStore(A)})}})},In.prototype.init=function(){return V.indexedDB?(this.dbPromise||(this.dbPromise=this._openDb()),this.dbPromise.then(function(n){return n instanceof V.IDBDatabase?be.resolve():be.reject(n)})):be.reject("indexedDB is not supported in this browser")},In.prototype.makeTransaction=function(n,e){var t=this.storeName,r=function(i){return new be(function(A,s){var o=i.transaction(t,n);o.oncomplete=function(){A(o)},o.onabort=o.onerror=function(){s(o.error)},e(o.objectStore(t))})};return this.dbPromise.then(r).catch((function(i){return i&&i.name==="InvalidStateError"?(this.dbPromise=this._openDb(),this.dbPromise.then(r)):be.reject(i)}).bind(this))},In.prototype.setItem=function(n,e){return this.makeTransaction("readwrite",function(t){t.put(e,n)})},In.prototype.getItem=function(n){var e;return this.makeTransaction("readonly",function(t){e=t.get(n)}).then(function(){return e.result})},In.prototype.removeItem=function(n){return this.makeTransaction("readwrite",function(e){e.delete(n)})},In.prototype.getAll=function(){var n;return this.makeTransaction("readonly",function(e){n=e.getAll()}).then(function(){return n.result})};var oD="__mp_opt_in_out_";function aD(n,e){YB(!0,n,e)}function cD(n,e){YB(!1,n,e)}function uD(n,e){return XB(n,e)==="1"}function zB(n,e){if(dD(e))return we.warn('This browser has "Do Not Track" enabled. This will prevent the Mixpanel SDK from sending any data. To ignore the "Do Not Track" browser setting, initialize the Mixpanel instance with the config "ignore_dnt: true"'),!0;var t=XB(n,e)==="0";return t&&we.warn("You are opted out of Mixpanel tracking. This will prevent the Mixpanel SDK from sending any data."),t}function Ir(n){return lp(n,function(e){return this.get_config(e)})}function Fr(n){return lp(n,function(e){return this._get_config(e)})}function nA(n){return lp(n,function(e){return this._get_config(e)})}function lD(n,e){e=e||{},cp(e).remove(up(n,e),!!e.crossSubdomainCookie,e.cookieDomain)}function cp(n){return n=n||{},n.persistenceType==="localStorage"?m.localStorage:m.cookie}function up(n,e){return e=e||{},(e.persistencePrefix||oD)+n}function XB(n,e){return cp(e).get(up(n,e))}function dD(n){if(n&&n.ignoreDnt)return!1;var e=n&&n.window||V,t=e.navigator||{},r=!1;return m.each([t.doNotTrack,t.msDoNotTrack,e.doNotTrack],function(i){m.includes([!0,1,"1","yes"],i)&&(r=!0)}),r}function YB(n,e,t){if(!m.isString(e)||!e.length){we.error("gdpr."+(n?"optIn":"optOut")+" called with an invalid token");return}t=t||{},cp(t).set(up(e,t),n?1:0,m.isNumber(t.cookieExpiration)?t.cookieExpiration:null,!!t.crossSubdomainCookie,!!t.secureCookie,!!t.crossSiteCookie,t.cookieDomain),t.track&&n&&t.track(t.trackEventName||"$opt_in",t.trackProperties,{send_immediately:!0})}function lp(n,e){return function(){var t=!1;try{var r=e.call(this,"token"),i=e.call(this,"ignore_dnt"),A=e.call(this,"opt_out_tracking_persistence_type"),s=e.call(this,"opt_out_tracking_cookie_prefix"),o=e.call(this,"window");r&&(t=zB(r,{ignoreDnt:i,persistenceType:A,persistencePrefix:s,window:o}))}catch(c){we.error("Unexpected error when checking tracking opt-out status: "+c)}if(!t)return n.apply(this,arguments);var a=arguments[arguments.length-1];typeof a=="function"&&a(0)}}var hD=ri("lock"),ZB=function(n,e){e=e||{},this.storageKey=n,this.storage=e.storage||V.localStorage,this.pollIntervalMS=e.pollIntervalMS||100,this.timeoutMS=e.timeoutMS||2e3,this.promiseImpl=e.promiseImpl||be};ZB.prototype.withLock=function(n,e){var t=this.promiseImpl;return new t(m.bind(function(r,i){var A=e||new Date().getTime()+"|"+Math.random(),s=new Date().getTime(),o=this.storageKey,a=this.pollIntervalMS,c=this.timeoutMS,u=this.storage,l=o+":X",d=o+":Y",h=o+":Z",f=function(B){if(new Date().getTime()-s>c){hD.error("Timeout waiting for mutex on "+o+"; clearing lock. ["+A+"]"),u.removeItem(h),u.removeItem(d),v();return}setTimeout(function(){try{B()}catch(b){i(b)}},a*(Math.random()+.1))},p=function(B,b){B()?b():f(function(){p(B,b)})},g=function(){var B=u.getItem(d);return B&&B!==A?!1:(u.setItem(d,A),u.getItem(d)===A?!0:(Cs(u,!0)||i(new Error("localStorage support dropped while acquiring lock")),!1))},v=function(){u.setItem(l,A),p(g,function(){if(u.getItem(l)===A){y();return}f(function(){if(u.getItem(d)!==A){v();return}p(function(){return!u.getItem(h)},y)})})},y=function(){u.setItem(h,"1");var B=function(){u.removeItem(h),u.getItem(d)===A&&u.removeItem(d),u.getItem(l)===A&&u.removeItem(l)};n().then(function(b){B(),r(b)}).catch(function(b){B(),i(b)})};try{if(Cs(u,!0))v();else throw new Error("localStorage support check failed")}catch(B){i(B)}},this))};var _s=function(n){this.storage=n||V.localStorage};_s.prototype.init=function(){return be.resolve()},_s.prototype.setItem=function(n,e){return new be(m.bind(function(t,r){try{this.storage.setItem(n,tA(e))}catch(i){r(i)}t()},this))},_s.prototype.getItem=function(n){return new be(m.bind(function(e,t){var r;try{r=Ic(this.storage.getItem(n))}catch(i){t(i)}e(r)},this))},_s.prototype.removeItem=function(n){return new be(m.bind(function(e,t){try{this.storage.removeItem(n)}catch(r){t(r)}e()},this))};var $B=ri("batch"),Fn=function(n,e){e=e||{},this.storageKey=n,this.usePersistence=e.usePersistence,this.usePersistence&&(this.queueStorage=e.queueStorage||new _s,this.lock=new ZB(n,{storage:e.sharedLockStorage||V.localStorage,timeoutMS:e.sharedLockTimeoutMS})),this.reportError=e.errorReporter||m.bind($B.error,$B),this.pid=e.pid||null,this.memQueue=[],this.initialized=!1,e.enqueueThrottleMs?this.enqueuePersisted=eD(m.bind(this._enqueuePersisted,this),e.enqueueThrottleMs):this.enqueuePersisted=m.bind(function(t){return this._enqueuePersisted([t])},this)};Fn.prototype.ensureInit=function(){return this.initialized?be.resolve():this.queueStorage.init().then(m.bind(function(){this.initialized=!0},this)).catch(m.bind(function(n){this.reportError("Error initializing queue persistence. Disabling persistence",n),this.initialized=!0,this.usePersistence=!1},this))},Fn.prototype.enqueue=function(n,e){var t={id:op(),flushAfter:new Date().getTime()+e*2,payload:n};return this.usePersistence?this.enqueuePersisted(t):(this.memQueue.push(t),be.resolve(!0))},Fn.prototype._enqueuePersisted=function(n){var e=m.bind(function(){return this.ensureInit().then(m.bind(function(){return this.readFromStorage()},this)).then(m.bind(function(t){return this.saveToStorage(t.concat(n))},this)).then(m.bind(function(t){return t&&(this.memQueue=this.memQueue.concat(n)),t},this)).catch(m.bind(function(t){return this.reportError("Error enqueueing items",t,n),!1},this))},this);return this.lock.withLock(e,this.pid).catch(m.bind(function(t){return this.reportError("Error acquiring storage lock",t),!1},this))},Fn.prototype.fillBatch=function(n){var e=this.memQueue.slice(0,n);return this.usePersistence&&e.length<n?this.ensureInit().then(m.bind(function(){return this.readFromStorage()},this)).then(m.bind(function(t){if(t.length){var r={};m.each(e,function(s){r[s.id]=!0});for(var i=0;i<t.length;i++){var A=t[i];if(new Date().getTime()>A.flushAfter&&!r[A.id]&&(A.orphaned=!0,e.push(A),e.length>=n))break}}return e},this)):be.resolve(e)};var eC=function(n,e){var t=[];return m.each(n,function(r){r.id&&!e[r.id]&&t.push(r)}),t};Fn.prototype.removeItemsByID=function(n){var e={};if(m.each(n,function(r){e[r]=!0}),this.memQueue=eC(this.memQueue,e),this.usePersistence){var t=m.bind(function(){return this.ensureInit().then(m.bind(function(){return this.readFromStorage()},this)).then(m.bind(function(r){return r=eC(r,e),this.saveToStorage(r)},this)).then(m.bind(function(){return this.readFromStorage()},this)).then(m.bind(function(r){for(var i=0;i<r.length;i++){var A=r[i];if(A.id&&e[A.id])throw new Error("Item not removed from storage")}return!0},this)).catch(m.bind(function(r){return this.reportError("Error removing items",r,n),!1},this))},this);return this.lock.withLock(t,this.pid).catch(m.bind(function(r){return this.reportError("Error acquiring storage lock",r),Cs(this.lock.storage,!0)?!1:t().then(m.bind(function(i){return i||this.queueStorage.removeItem(this.storageKey).then(function(){return i})},this)).catch(m.bind(function(i){return this.reportError("Error clearing queue",i),!1},this))},this))}else return be.resolve(!0)};var tC=function(n,e){var t=[];return m.each(n,function(r){var i=r.id;if(i in e){var A=e[i];A!==null&&(r.payload=A,t.push(r))}else t.push(r)}),t};Fn.prototype.updatePayloads=function(n){return this.memQueue=tC(this.memQueue,n),this.usePersistence?this.lock.withLock(m.bind(function(){return this.ensureInit().then(m.bind(function(){return this.readFromStorage()},this)).then(m.bind(function(e){return e=tC(e,n),this.saveToStorage(e)},this)).catch(m.bind(function(e){return this.reportError("Error updating items",n,e),!1},this))},this),this.pid).catch(m.bind(function(e){return this.reportError("Error acquiring storage lock",e),!1},this)):be.resolve(!0)},Fn.prototype.readFromStorage=function(){return this.ensureInit().then(m.bind(function(){return this.queueStorage.getItem(this.storageKey)},this)).then(m.bind(function(n){return n&&(m.isArray(n)||(this.reportError("Invalid storage entry:",n),n=null)),n||[]},this)).catch(m.bind(function(n){return this.reportError("Error retrieving queue",n),[]},this))},Fn.prototype.saveToStorage=function(n){return this.ensureInit().then(m.bind(function(){return this.queueStorage.setItem(this.storageKey,n)},this)).then(function(){return!0}).catch(m.bind(function(e){return this.reportError("Error saving queue",e),!1},this))},Fn.prototype.clear=function(){return this.memQueue=[],this.usePersistence?this.ensureInit().then(m.bind(function(){return this.queueStorage.removeItem(this.storageKey)},this)):be.resolve()};var pD=10*60*1e3,Ss=ri("batch"),$t=function(n,e){this.errorReporter=e.errorReporter,this.queue=new Fn(n,{errorReporter:m.bind(this.reportError,this),queueStorage:e.queueStorage,sharedLockStorage:e.sharedLockStorage,sharedLockTimeoutMS:e.sharedLockTimeoutMS,usePersistence:e.usePersistence,enqueueThrottleMs:e.enqueueThrottleMs}),this.libConfig=e.libConfig,this.sendRequest=e.sendRequestFunc,this.beforeSendHook=e.beforeSendHook,this.stopAllBatching=e.stopAllBatchingFunc,this.batchSize=this.libConfig.batch_size,this.flushInterval=this.libConfig.batch_flush_interval_ms,this.stopped=!this.libConfig.batch_autostart,this.consecutiveRemovalFailures=0,this.itemIdsSentSuccessfully={},this.flushOnlyOnInterval=e.flushOnlyOnInterval||!1,this._flushPromise=null};$t.prototype.enqueue=function(n){return this.queue.enqueue(n,this.flushInterval)},$t.prototype.start=function(){return this.stopped=!1,this.consecutiveRemovalFailures=0,this.flush()},$t.prototype.stop=function(){this.stopped=!0,this.timeoutID&&(clearTimeout(this.timeoutID),this.timeoutID=null)},$t.prototype.clear=function(){return this.queue.clear()},$t.prototype.resetBatchSize=function(){this.batchSize=this.libConfig.batch_size},$t.prototype.resetFlush=function(){this.scheduleFlush(this.libConfig.batch_flush_interval_ms)},$t.prototype.scheduleFlush=function(n){this.flushInterval=n,this.stopped||(this.timeoutID=setTimeout(m.bind(function(){this.stopped||(this._flushPromise=this.flush())},this),this.flushInterval))},$t.prototype.sendRequestPromise=function(n,e){return new be(m.bind(function(t){this.sendRequest(n,e,t)},this))},$t.prototype.flush=function(n){if(this.requestInProgress)return Ss.log("Flush: Request already in progress"),be.resolve();this.requestInProgress=!0,n=n||{};var e=this.libConfig.batch_request_timeout_ms,t=new Date().getTime(),r=this.batchSize;return this.queue.fillBatch(r).then(m.bind(function(i){var A=i.length===r,s=[],o={};if(m.each(i,function(l){var d=l.payload;if(this.beforeSendHook&&!l.orphaned&&(d=this.beforeSendHook(d)),d){d.event&&d.properties&&(d.properties=m.extend({},d.properties,{mp_sent_by_lib_version:gn.LIB_VERSION}));var h=!0,f=l.id;f?(this.itemIdsSentSuccessfully[f]||0)>5&&(this.reportError("[dupe] item ID sent too many times, not sending",{item:l,batchSize:i.length,timesSent:this.itemIdsSentSuccessfully[f]}),h=!1):this.reportError("[dupe] found item with no ID",{item:l}),h&&s.push(d)}o[l.id]=d},this),s.length<1)return this.requestInProgress=!1,this.resetFlush(),be.resolve();var a=m.bind(function(){return this.queue.removeItemsByID(m.map(i,function(l){return l.id})).then(m.bind(function(l){return m.each(i,m.bind(function(d){var h=d.id;h?(this.itemIdsSentSuccessfully[h]=this.itemIdsSentSuccessfully[h]||0,this.itemIdsSentSuccessfully[h]++,this.itemIdsSentSuccessfully[h]>5&&this.reportError("[dupe] item ID sent too many times",{item:d,batchSize:i.length,timesSent:this.itemIdsSentSuccessfully[h]})):this.reportError("[dupe] found item with no ID while removing",{item:d})},this)),l?(this.consecutiveRemovalFailures=0,this.flushOnlyOnInterval&&!A?(this.resetFlush(),be.resolve()):this.flush()):(++this.consecutiveRemovalFailures>5?(this.reportError("Too many queue failures; disabling batching system."),this.stopAllBatching()):this.resetFlush(),be.resolve())},this))},this),c=m.bind(function(l){this.requestInProgress=!1;try{if(n.unloading)return this.queue.updatePayloads(o);if(m.isObject(l)&&l.error==="timeout"&&new Date().getTime()-t>=e)return this.reportError("Network timeout; retrying"),this.flush();if(m.isObject(l)&&(l.httpStatusCode>=500||l.httpStatusCode===429||l.httpStatusCode<=0&&!rD()||l.error==="timeout")){var d=this.flushInterval*2;return l.retryAfter&&(d=parseInt(l.retryAfter,10)*1e3||d),d=Math.min(pD,d),this.reportError("Error; retry in "+d+" ms"),this.scheduleFlush(d),be.resolve()}else if(m.isObject(l)&&l.httpStatusCode===413)if(i.length>1){var h=Math.max(1,Math.floor(r/2));return this.batchSize=Math.min(this.batchSize,h,i.length-1),this.reportError("413 response; reducing batch size to "+this.batchSize),this.resetFlush(),be.resolve()}else return this.reportError("Single-event request too large; dropping",i),this.resetBatchSize(),a();else return a()}catch(f){this.reportError("Error handling API response",f),this.resetFlush()}},this),u={method:"POST",verbose:!0,ignore_json_errors:!0,timeout_ms:e};return n.unloading&&(u.transport="sendBeacon"),Ss.log("MIXPANEL REQUEST:",s),this.sendRequestPromise(s,u).then(c)},this)).catch(m.bind(function(i){this.reportError("Error flushing request queue",i),this.resetFlush()},this))},$t.prototype.reportError=function(n,e){if(Ss.error.apply(Ss.error,arguments),this.errorReporter)try{e instanceof Error||(e=new Error(n)),this.errorReporter(n,e)}catch(t){Ss.error(t)}};var dp=function(n){var e=Date.now();return!n||e>n.maxExpires||e>n.idleExpires},fD=250,rA=ri("recorder"),nC=V.CompressionStream,gD={batch_size:1e3,batch_flush_interval_ms:10*1e3,batch_request_timeout_ms:90*1e3,batch_autostart:!0},mD=new Set([X.MouseMove,X.MouseInteraction,X.Scroll,X.ViewportResize,X.Input,X.TouchMove,X.MediaInteraction,X.Drag,X.Selection]);function vD(n){return n.type===le.IncrementalSnapshot&&mD.has(n.data.source)}var Bt=function(n){this._mixpanel=n.mixpanelInstance,this._onIdleTimeout=n.onIdleTimeout||Tr,this._onMaxLengthReached=n.onMaxLengthReached||Tr,this._onBatchSent=n.onBatchSent||Tr,this._rrwebRecord=n.rrwebRecord||null,this._stopRecording=null,this.replayId=n.replayId,this.batchStartUrl=n.batchStartUrl||null,this.replayStartUrl=n.replayStartUrl||null,this.idleExpires=n.idleExpires||null,this.maxExpires=n.maxExpires||null,this.replayStartTime=n.replayStartTime||null,this.seqNo=n.seqNo||0,this.idleTimeoutId=null,this.maxTimeoutId=null,this.recordMaxMs=bs,this.recordMinMs=0;var e=Cs(n.sharedLockStorage,!0);this.batcherKey="__mprec_"+this.getConfig("name")+"_"+this.getConfig("token")+"_"+this.replayId,this.queueStorage=new In(JB),this.batcher=new $t(this.batcherKey,{errorReporter:this.reportError.bind(this),flushOnlyOnInterval:!0,libConfig:gD,sendRequestFunc:this.flushEventsWithOptOut.bind(this),queueStorage:this.queueStorage,sharedLockStorage:n.sharedLockStorage,usePersistence:e,stopAllBatchingFunc:this.stopRecording.bind(this),enqueueThrottleMs:fD,sharedLockTimeoutMS:10*1e3})};Bt.prototype.getUserIdInfo=function(){if(this.finalFlushUserIdInfo)return this.finalFlushUserIdInfo;var n={distinct_id:String(this._mixpanel.get_distinct_id())},e=this._mixpanel.get_property("$device_id");e&&(n.$device_id=e);var t=this._mixpanel.get_property("$user_id");return t&&(n.$user_id=t),n},Bt.prototype.unloadPersistedData=function(){return this.batcher.stop(),this.batcher.flush().then((function(){return this.queueStorage.removeItem(this.batcherKey)}).bind(this))},Bt.prototype.getConfig=function(n){return this._mixpanel.get_config(n)},Bt.prototype.get_config=function(n){return this.getConfig(n)},Bt.prototype.startRecording=function(n){if(this._rrwebRecord===null){this.reportError("rrweb record function not provided. ");return}if(this._stopRecording!==null){rA.log("Recording already in progress, skipping startRecording.");return}this.recordMaxMs=this.getConfig("record_max_ms"),this.recordMaxMs>bs&&(this.recordMaxMs=bs,rA.critical("record_max_ms cannot be greater than "+bs+"ms. Capping value.")),this.maxExpires||(this.maxExpires=new Date().getTime()+this.recordMaxMs),this.recordMinMs=this.getConfig("record_min_ms"),this.recordMinMs>ep&&(this.recordMinMs=ep,rA.critical("record_min_ms cannot be greater than "+ep+"ms. Capping value.")),this.replayStartTime||(this.replayStartTime=new Date().getTime(),this.batchStartUrl=m.info.currentUrl(),this.replayStartUrl=m.info.currentUrl()),n||this.recordMinMs>0?this.batcher.stop():this.batcher.start();var e=(function(){clearTimeout(this.idleTimeoutId);var i=this.getConfig("record_idle_timeout_ms");this.idleTimeoutId=setTimeout(this._onIdleTimeout,i),this.idleExpires=new Date().getTime()+i}).bind(this);e();var t=this.getConfig("record_block_selector");(t===""||t===null)&&(t=void 0);try{this._stopRecording=this._rrwebRecord({emit:(function(i){if(this.idleExpires&&this.idleExpires<i.timestamp){this._onIdleTimeout();return}vD(i)&&(this.batcher.stopped&&new Date().getTime()-this.replayStartTime>=this.recordMinMs&&this.batcher.start(),e()),this.__enqueuePromise=this.batcher.enqueue(i)}).bind(this),blockClass:this.getConfig("record_block_class"),blockSelector:t,collectFonts:this.getConfig("record_collect_fonts"),dataURLOptions:{type:"image/webp",quality:.6},maskAllInputs:!0,maskTextClass:this.getConfig("record_mask_text_class"),maskTextSelector:this.getConfig("record_mask_text_selector"),recordCanvas:this.getConfig("record_canvas"),sampling:{canvas:15}})}catch(i){this.reportError("Unexpected error when starting rrweb recording.",i)}if(typeof this._stopRecording!="function"){this.reportError("rrweb failed to start, skipping this recording."),this._stopRecording=null,this.stopRecording();return}var r=this.maxExpires-new Date().getTime();this.maxTimeoutId=setTimeout(this._onMaxLengthReached.bind(this),r)},Bt.prototype.stopRecording=function(n){if(this.finalFlushUserIdInfo=this.getUserIdInfo(),!this.isRrwebStopped()){try{this._stopRecording()}catch(t){this.reportError("Error with rrweb stopRecording",t)}this._stopRecording=null}var e;return this.batcher.stopped?e=this.batcher.clear():n||(e=this.batcher.flush()),this.batcher.stop(),clearTimeout(this.idleTimeoutId),clearTimeout(this.maxTimeoutId),e},Bt.prototype.isRrwebStopped=function(){return this._stopRecording===null},Bt.prototype.flushEventsWithOptOut=function(n,e,t){var r=(function(i){i===0&&(this.stopRecording(),t({error:"Tracking has been opted out, stopping recording."}))}).bind(this);this._flushEvents(n,e,t,r)},Bt.prototype.serialize=function(){var n;try{n=this._mixpanel.get_tab_id()}catch(e){this.reportError("Error getting tab ID for serialization ",e),n=null}return{replayId:this.replayId,seqNo:this.seqNo,replayStartTime:this.replayStartTime,batchStartUrl:this.batchStartUrl,replayStartUrl:this.replayStartUrl,idleExpires:this.idleExpires,maxExpires:this.maxExpires,tabId:n}},Bt.deserialize=function(n,e){var t=new Bt(m.extend({},e,{replayId:n.replayId,batchStartUrl:n.batchStartUrl,replayStartUrl:n.replayStartUrl,idleExpires:n.idleExpires,maxExpires:n.maxExpires,replayStartTime:n.replayStartTime,seqNo:n.seqNo,sharedLockStorage:e.sharedLockStorage}));return t},Bt.prototype._sendRequest=function(n,e,t,r){var i=(function(s,o){s.status===200&&this.replayId===n&&(this.seqNo++,this.batchStartUrl=m.info.currentUrl()),this._onBatchSent(),r({status:0,httpStatusCode:s.status,responseBody:o,retryAfter:s.headers.get("Retry-After")})}).bind(this),A=this._mixpanel.get_api_host&&this._mixpanel.get_api_host("record")||this.getConfig("api_host");V.fetch(A+"/"+this.getConfig("api_routes").record+"?"+new URLSearchParams(e),{method:"POST",headers:{Authorization:"Basic "+btoa(this.getConfig("token")+":"),"Content-Type":"application/octet-stream"},body:t}).then(function(s){s.json().then(function(o){i(s,o)}).catch(function(o){r({error:o})})}).catch(function(s){r({error:s,httpStatusCode:0})})},Bt.prototype._flushEvents=Ir(function(n,e,t){var r=n.length;if(r>0){for(var i=this.replayId,A=1/0,s=-1/0,o=!1,a=0;a<r;a++)A=Math.min(A,n[a].timestamp),s=Math.max(s,n[a].timestamp),n[a].type===le.FullSnapshot&&(o=!0);if(this.seqNo===0){if(!o){t({error:"First batch does not contain a full snapshot. Aborting recording."}),this.stopRecording(!0);return}this.replayStartTime=A}else this.replayStartTime||(this.reportError("Replay start time not set but seqNo is not 0. Using current batch start time as a fallback."),this.replayStartTime=A);var c=s-this.replayStartTime,u={$current_url:this.batchStartUrl,$lib_version:gn.LIB_VERSION,batch_start_time:A/1e3,mp_lib:"web",replay_id:i,replay_length_ms:c,replay_start_time:this.replayStartTime/1e3,replay_start_url:this.replayStartUrl,seq:this.seqNo},l=JSON.stringify(n);if(Object.assign(u,this.getUserIdInfo()),nC){var d=new Blob([l],{type:"application/json"}).stream(),h=d.pipeThrough(new nC("gzip"));new Response(h).blob().then((function(f){u.format="gzip",this._sendRequest(i,u,f,t)}).bind(this))}else u.format="body",this._sendRequest(i,u,l,t)}}),Bt.prototype.reportError=function(n,e){rA.error.apply(rA.error,arguments);try{!e&&!(n instanceof Error)&&(n=new Error(n)),this.getConfig("error_reporter")(n,e)}catch(t){rA.error(t)}};var iA=function(n){this.idb=new In(ap),this.errorReporter=n.errorReporter,this.mixpanelInstance=n.mixpanelInstance,this.sharedLockStorage=n.sharedLockStorage};iA.prototype.handleError=function(n){this.errorReporter("IndexedDB error: ",n)},iA.prototype.setActiveRecording=function(n){var e=n.tabId;return e?this.idb.init().then((function(){return this.idb.setItem(e,n)}).bind(this)).catch(this.handleError.bind(this)):(console.warn("No tab ID is set, cannot persist recording metadata."),be.resolve())},iA.prototype.getActiveRecording=function(){return this.idb.init().then((function(){return this.idb.getItem(this.mixpanelInstance.get_tab_id())}).bind(this)).then((function(n){return dp(n)?null:n}).bind(this)).catch(this.handleError.bind(this))},iA.prototype.clearActiveRecording=function(){return this.getActiveRecording().then((function(n){if(n)return n.maxExpires=0,this.setActiveRecording(n)}).bind(this)).catch(this.handleError.bind(this))},iA.prototype.flushInactiveRecordings=function(){return this.idb.init().then((function(){return this.idb.getAll()}).bind(this)).then((function(n){var e=n.filter(function(t){return dp(t)}).map((function(t){var r=Bt.deserialize(t,{mixpanelInstance:this.mixpanelInstance,sharedLockStorage:this.sharedLockStorage});return r.unloadPersistedData().then((function(){return this.idb.removeItem(t.tabId)}).bind(this)).catch(this.handleError.bind(this))}).bind(this));return be.all(e)}).bind(this)).catch(this.handleError.bind(this))};var ks=ri("recorder"),Jn=function(n,e,t){this.mixpanelInstance=n,this.rrwebRecord=e||Sr,this.sharedLockStorage=t,this.recordingRegistry=new iA({mixpanelInstance:this.mixpanelInstance,errorReporter:ks.error,sharedLockStorage:t}),this._flushInactivePromise=this.recordingRegistry.flushInactiveRecordings(),this.activeRecording=null,this.stopRecordingInProgress=!1};Jn.prototype.startRecording=function(n){if(n=n||{},this.activeRecording&&!this.activeRecording.isRrwebStopped()){ks.log("Recording already in progress, skipping startRecording.");return}var e=(function(){ks.log("Idle timeout reached, restarting recording."),this.resetRecording()}).bind(this),t=(function(){ks.log("Max recording length reached, stopping recording."),this.resetRecording()}).bind(this),r=(function(){this.recordingRegistry.setActiveRecording(this.activeRecording.serialize()),this.__flushPromise=this.activeRecording.batcher._flushPromise}).bind(this),i={mixpanelInstance:this.mixpanelInstance,onBatchSent:r,onIdleTimeout:e,onMaxLengthReached:t,replayId:m.UUID(),rrwebRecord:this.rrwebRecord,sharedLockStorage:this.sharedLockStorage};return n.activeSerializedRecording?this.activeRecording=Bt.deserialize(n.activeSerializedRecording,i):this.activeRecording=new Bt(i),this.activeRecording.startRecording(n.shouldStopBatcher),this.recordingRegistry.setActiveRecording(this.activeRecording.serialize())},Jn.prototype.stopRecording=function(){return this.stopRecordingInProgress=!0,this._stopCurrentRecording(!1,!0).then((function(){return this.recordingRegistry.clearActiveRecording()}).bind(this)).then((function(){this.stopRecordingInProgress=!1}).bind(this))},Jn.prototype.pauseRecording=function(){return this._stopCurrentRecording(!1)},Jn.prototype._stopCurrentRecording=function(n,e){if(this.activeRecording){var t=this.activeRecording.stopRecording(n);return e&&(this.activeRecording=null),t}return be.resolve()},Jn.prototype.resumeRecording=function(n){return this.activeRecording&&this.activeRecording.isRrwebStopped()?(this.activeRecording.startRecording(!1),be.resolve(null)):this.recordingRegistry.getActiveRecording().then((function(e){return e&&!this.stopRecordingInProgress?this.startRecording({activeSerializedRecording:e}):n?this.startRecording({shouldStopBatcher:!1}):(ks.log("No resumable recording found."),null)}).bind(this))},Jn.prototype.resetRecording=function(){this.stopRecording(),this.startRecording({shouldStopBatcher:!0})},Jn.prototype.getActiveReplayId=function(){return this.activeRecording&&!this.activeRecording.isRrwebStopped()?this.activeRecording.replayId:null},Object.defineProperty(Jn.prototype,"replayId",{get:function(){return this.getActiveReplayId()}}),V.__mp_recorder=Jn;var Fc="change",ii="click",rC="hashchange",AA="mp_locationchange",iC="popstate",AC="scrollend",hp="submit",yD=["clientX","clientY","offsetX","offsetY","pageX","pageY","screenX","screenY","x","y"],sC=["mp-include"],pp=["mp-no-track"],oC=pp.concat(["mp-sensitive"]),wD=["aria-label","aria-labelledby","aria-describedby","href","name","role","title","type"],xt=ri("autocapture");function fp(n){for(var e={},t=aC(n).split(" "),r=0;r<t.length;r++){var i=t[r];i&&(e[i]=!0)}return e}function aC(n){switch(typeof n.className){case"string":return n.className;case"object":return n.className.baseVal||n.getAttribute("class")||"";default:return""}}function bD(n){if(n.previousElementSibling)return n.previousElementSibling;do n=n.previousSibling;while(n&&!lC(n));return n}function cC(n,e,t,r,i,A){var s={$classes:aC(n).split(" "),$tag_name:n.tagName.toLowerCase()},o=n.id;o&&(s.$id=o),vp(n,e,i,A)&&m.each(wD.concat(r),function(l){if(n.hasAttribute(l)&&!t[l]){var d=n.getAttribute(l);xc(d)&&(s["$attr-"+l]=d)}});for(var a=1,c=1,u=n;u=bD(u);)a++,u.tagName===n.tagName&&c++;return s.$nth_child=a,s.$nth_of_type=c,s}function BD(n,e){var t=e.allowElementCallback,r=e.allowSelectors||[],i=e.blockAttrs||[],A=e.blockElementCallback,s=e.blockSelectors||[],o=e.captureTextContent||!1,a=e.captureExtraAttrs||[],c=e.capturedForHeatMap||!1,u={};m.each(i,function(w){u[w]=!0});var l=null,d=typeof n.target>"u"?n.srcElement:n.target;if(dC(d)&&(d=d.parentNode),SD(d,n)&&gp(d,n,t,r)&&!mp(d,n,A,s)){for(var h=[d],f=d;f.parentNode&&!xn(f,"body");)h.push(f.parentNode),f=f.parentNode;var p=[],g,v=!1;if(m.each(h,function(w){var _=vp(w,n,t,r);!u.href&&w.tagName.toLowerCase()==="a"&&(g=w.getAttribute("href"),g=_&&xc(g)&&g),mp(w,n,A,s)&&(v=!0),p.push(cC(w,n,u,a,t,r))},this),!v){var y=ye.documentElement;if(l={$event_type:n.type,$host:V.location.host,$pathname:V.location.pathname,$elements:p,$el_attr__href:g,$viewportHeight:Math.max(y.clientHeight,V.innerHeight||0),$viewportWidth:Math.max(y.clientWidth,V.innerWidth||0),$pageHeight:ye.body.offsetHeight||0,$pageWidth:ye.body.offsetWidth||0},m.each(a,function(w){if(!u[w]&&d.hasAttribute(w)){var _=d.getAttribute(w);xc(_)&&(l["$el_attr__"+w]=_)}}),o&&(B=uC(d,n,t,r),B&&B.length&&(l.$el_text=B)),n.type===ii&&(m.each(yD,function(w){w in n&&(l["$"+w]=n[w])}),c&&(l.$captured_for_heatmap=!0),d=CD(n)),o){var B=uC(d,n,t,r);B&&B.length&&(l.$el_text=B)}if(d){if(!gp(d,n,t,r)||mp(d,n,A,s))return null;var b=cC(d,n,u,a,t,r);l.$target=b,l.$el_classes=b.$classes,m.extend(l,m.strip_empty_properties({$el_id:b.$id,$el_tag_name:b.$tag_name}))}}}return l}function uC(n,e,t,r){var i="";return vp(n,e,t,r)&&n.childNodes&&n.childNodes.length&&m.each(n.childNodes,function(A){dC(A)&&A.textContent&&(i+=m.trim(A.textContent).split(/(\s+)/).filter(xc).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),m.trim(i)}function CD(n){for(var e=n.target,t=n.composedPath(),r=0;r<t.length;r++){var i=t[r];if(xn(i,"a")||xn(i,"button")||xn(i,"input")||xn(i,"select")||i.getAttribute&&i.getAttribute("role")==="button"){e=i;break}if(i===e)break}return e}function gp(n,e,t,r){if(t)try{if(!t(n,e))return!1}catch(s){return xt.critical("Error while checking element in allowElementCallback",s),!1}if(!r.length)return!0;for(var i=0;i<r.length;i++){var A=r[i];try{if(n.matches(A))return!0}catch(s){xt.critical("Error while checking selector: "+A,s)}}return!1}function mp(n,e,t,r){var i;if(t)try{if(t(n,e))return!0}catch(o){return xt.critical("Error while checking element in blockElementCallback",o),!0}if(r&&r.length)for(i=0;i<r.length;i++){var A=r[i];try{if(n.matches(A))return!0}catch(o){xt.critical("Error while checking selector: "+A,o)}}var s=fp(n);for(i=0;i<pp.length;i++)if(s[pp[i]])return!0;return!1}function lC(n){return n&&n.nodeType===1}function xn(n,e){return n&&n.tagName&&n.tagName.toLowerCase()===e.toLowerCase()}function dC(n){return n&&n.nodeType===3}function _D(){try{var n=ye.createElement("div");return!!n.matches}catch{return!1}}function SD(n,e){if(!n||xn(n,"html")||!lC(n))return!1;var t=n.tagName.toLowerCase();switch(t){case"form":return e.type===hp;case"input":return["button","submit"].indexOf(n.getAttribute("type"))===-1?e.type===Fc:e.type===ii;case"select":case"textarea":return e.type===Fc;default:return e.type===ii}}function vp(n,e,t,r){var i;if(!gp(n,e,t,r))return!1;for(var A=n;A.parentNode&&!xn(A,"body");A=A.parentNode){var s=fp(A);for(i=0;i<oC.length;i++)if(s[oC[i]])return!1}var o=fp(n);for(i=0;i<sC.length;i++)if(o[sC[i]])return!0;if(xn(n,"input")||xn(n,"select")||xn(n,"textarea")||n.getAttribute("contenteditable")==="true")return!1;var a=n.type||"";if(typeof a=="string")switch(a.toLowerCase()){case"hidden":return!1;case"password":return!1}var c=n.name||n.id||"";if(typeof c=="string"){var u=/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i;if(u.test(c.replace(/[^a-zA-Z0-9]/g,"")))return!1}return!0}function xc(n){if(n===null||m.isUndefined(n))return!1;if(typeof n=="string"){n=m.trim(n);var e=/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/;if(e.test((n||"").replace(/[- ]/g,"")))return!1;var t=/(^\d{3}-?\d{2}-?\d{4}$)/;if(t.test(n))return!1}return!0}var kD=30,ED=1e3,UD=4;function hC(){this.clicks=[]}hC.prototype.isRageClick=function(n,e,t){t=t||{};var r=t.threshold_px||kD,i=t.timeout_ms||ED,A=t.click_count||UD,s=Date.now(),o=this.clicks[this.clicks.length-1];if(o&&s-o.timestamp<i&&Math.sqrt(Math.pow(n-o.x,2)+Math.pow(e-o.y,2))<r){if(this.clicks.push({x:n,y:e,timestamp:s}),this.clicks.length>=A)return this.clicks=[],!0}else this.clicks=[{x:n,y:e,timestamp:s}];return!1};var pC="autocapture",TD="track_pageview",fC="full-url",ID="url-with-path-and-query-string",FD="url-with-path",xD="allow_element_callback",gC="allow_selectors",mC="allow_url_regexes",vC="block_attrs",yC="block_element_callback",wC="block_selectors",bC="block_url_regexes",BC="capture_extra_attrs",CC="capture_text_content",_C="scroll_capture_all",SC="scroll_depth_percent_checkpoints",Qc="click",yp="input",kC="pageview",EC="rage_click",wp="scroll",bp="submit",gt={};gt[gC]=[],gt[mC]=[],gt[vC]=[],gt[yC]=null,gt[wC]=[],gt[bC]=[],gt[BC]=[],gt[CC]=!1,gt[_C]=!1,gt[SC]=[25,50,75,100],gt[Qc]=!0,gt[yp]=!0,gt[kC]=fC,gt[EC]=!0,gt[wp]=!0,gt[bp]=!0;var Rc={$mp_autocapture:!0},UC="$mp_click",QD="$mp_input_change",TC="$mp_rage_click",RD="$mp_scroll",PD="$mp_submit",Qt=function(n){this.mp=n};Qt.prototype.init=function(){if(!_D()){xt.critical("Autocapture unavailable: missing required DOM APIs");return}this.initPageviewTracking(),this.initClickTracking(),this.initInputTracking(),this.initScrollTracking(),this.initSubmitTracking(),this.initRageClickTracking()},Qt.prototype.getFullConfig=function(){var n=this.mp.get_config(pC);return n?m.isObject(n)?m.extend({},gt,n):gt:{}},Qt.prototype.getConfig=function(n){return this.getFullConfig()[n]},Qt.prototype.currentUrlBlocked=function(){var n,e=m.info.currentUrl(),t=this.getConfig(mC)||[];if(t.length){var r=!1;for(n=0;n<t.length;n++){var i=t[n];try{if(e.match(i)){r=!0;break}}catch(s){return xt.critical("Error while checking block URL regex: "+i,s),!0}}if(!r)return!0}var A=this.getConfig(bC)||[];if(!A||!A.length)return!1;for(n=0;n<A.length;n++)try{if(e.match(A[n]))return!0}catch(s){return xt.critical("Error while checking block URL regex: "+A[n],s),!0}return!1},Qt.prototype.pageviewTrackingConfig=function(){return this.mp.get_config(pC)?this.getConfig(kC):this.mp.get_config(TD)},Qt.prototype.trackDomEvent=function(n,e){if(!this.currentUrlBlocked()){var t=this.mp.is_recording_heatmap_data()&&(e===UC&&!this.getConfig(Qc)||e===TC&&!this._getRageClickConfig()),r=BD(n,{allowElementCallback:this.getConfig(xD),allowSelectors:this.getConfig(gC),blockAttrs:this.getConfig(vC),blockElementCallback:this.getConfig(yC),blockSelectors:this.getConfig(wC),captureExtraAttrs:this.getConfig(BC),captureTextContent:this.getConfig(CC),capturedForHeatMap:t});r&&(m.extend(r,Rc),this.mp.track(e,r))}},Qt.prototype._getRageClickConfig=function(){var n=this.getConfig(EC);return n?n===!0?{}:typeof n=="object"?n:{}:null},Qt.prototype.initClickTracking=function(){V.removeEventListener(ii,this.listenerClick),!(!this.getConfig(Qc)&&!this.mp.get_config("record_heatmap_data"))&&(xt.log("Initializing click tracking"),this.listenerClick=V.addEventListener(ii,(function(n){!this.getConfig(Qc)&&!this.mp.is_recording_heatmap_data()||this.trackDomEvent(n,UC)}).bind(this)))},Qt.prototype.initInputTracking=function(){V.removeEventListener(Fc,this.listenerChange),this.getConfig(yp)&&(xt.log("Initializing input tracking"),this.listenerChange=V.addEventListener(Fc,(function(n){this.getConfig(yp)&&this.trackDomEvent(n,QD)}).bind(this)))},Qt.prototype.initPageviewTracking=function(){if(V.removeEventListener(iC,this.listenerPopstate),V.removeEventListener(rC,this.listenerHashchange),V.removeEventListener(AA,this.listenerLocationchange),!!this.pageviewTrackingConfig()){xt.log("Initializing pageview tracking");var n="",e=!1;this.currentUrlBlocked()||(e=this.mp.track_pageview(Rc)),e&&(n=m.info.currentUrl()),this.listenerPopstate=V.addEventListener(iC,function(){V.dispatchEvent(new Event(AA))}),this.listenerHashchange=V.addEventListener(rC,function(){V.dispatchEvent(new Event(AA))});var t=V.history.pushState;typeof t=="function"&&(V.history.pushState=function(i,A,s){t.call(V.history,i,A,s),V.dispatchEvent(new Event(AA))});var r=V.history.replaceState;typeof r=="function"&&(V.history.replaceState=function(i,A,s){r.call(V.history,i,A,s),V.dispatchEvent(new Event(AA))}),this.listenerLocationchange=V.addEventListener(AA,ip((function(){if(!this.currentUrlBlocked()){var i=m.info.currentUrl(),A=!1,s=i.split("#")[0].split("?")[0]!==n.split("#")[0].split("?")[0],o=this.pageviewTrackingConfig();if(o===fC?A=i!==n:o===ID?A=i.split("#")[0]!==n.split("#")[0]:o===FD&&(A=s),A){var a=this.mp.track_pageview(Rc);a&&(n=i),s&&(this.lastScrollCheckpoint=0,xt.log("Path change: re-initializing scroll depth checkpoints"))}}}).bind(this)))}},Qt.prototype.initRageClickTracking=function(){V.removeEventListener(ii,this.listenerRageClick);var n=this._getRageClickConfig();!n&&!this.mp.get_config("record_heatmap_data")||(xt.log("Initializing rage click tracking"),this._rageClickTracker||(this._rageClickTracker=new hC),this.listenerRageClick=(function(e){var t=this._getRageClickConfig();!t&&!this.mp.is_recording_heatmap_data()||this.currentUrlBlocked()||this._rageClickTracker.isRageClick(e.pageX,e.pageY,t)&&this.trackDomEvent(e,TC)}).bind(this),V.addEventListener(ii,this.listenerRageClick))},Qt.prototype.initScrollTracking=function(){V.removeEventListener(AC,this.listenerScroll),this.getConfig(wp)&&(xt.log("Initializing scroll tracking"),this.lastScrollCheckpoint=0,this.listenerScroll=V.addEventListener(AC,ip((function(){if(this.getConfig(wp)&&!this.currentUrlBlocked()){var n=this.getConfig(_C),e=(this.getConfig(SC)||[]).slice().sort(function(a,c){return a-c}),t=V.scrollY,r=m.extend({$scroll_top:t},Rc);try{var i=ye.body.scrollHeight,A=Math.round(t/(i-V.innerHeight)*100);if(r.$scroll_height=i,r.$scroll_percentage=A,A>this.lastScrollCheckpoint)for(var s=0;s<e.length;s++){var o=e[s];A>=o&&this.lastScrollCheckpoint<o&&(r.$scroll_checkpoint=o,this.lastScrollCheckpoint=o,n=!0)}}catch(a){xt.critical("Error while calculating scroll percentage",a)}n&&this.mp.track(RD,r)}}).bind(this))))},Qt.prototype.initSubmitTracking=function(){V.removeEventListener(hp,this.listenerSubmit),this.getConfig(bp)&&(xt.log("Initializing submit tracking"),this.listenerSubmit=V.addEventListener(hp,(function(n){this.getConfig(bp)&&this.trackDomEvent(n,PD)}).bind(this)))},VB(Qt);var OD=V.fetch,Rt=ri("flags"),Pc="flags",Oc="context",Bp={};Bp[Oc]={};var ae=function(n){this.getFullApiRoute=n.getFullApiRoute,this.getMpConfig=n.getConfigFunc,this.setMpConfig=n.setConfigFunc,this.getMpProperty=n.getPropertyFunc,this.track=n.trackingFunc};ae.prototype.init=function(){if(!MD()){Rt.critical("Feature Flags unavailable: missing minimum required APIs");return}this.flags=null,this.fetchFlags(),this.trackedFeatures=new Set},ae.prototype.getFullConfig=function(){var n=this.getMpConfig(Pc);return n?m.isObject(n)?m.extend({},Bp,n):Bp:{}},ae.prototype.getConfig=function(n){return this.getFullConfig()[n]},ae.prototype.isSystemEnabled=function(){return!!this.getMpConfig(Pc)},ae.prototype.updateContext=function(n,e){if(!this.isSystemEnabled())return Rt.critical("Feature Flags not enabled, cannot update context"),Promise.resolve();var t=this.getMpConfig(Pc);m.isObject(t)||(t={});var r=e&&e.replace?{}:this.getConfig(Oc);return t[Oc]=m.extend({},r,n),this.setMpConfig(Pc,t),this.fetchFlags()},ae.prototype.areFlagsReady=function(){return this.isSystemEnabled()||Rt.error("Feature Flags not enabled"),!!this.flags},ae.prototype.fetchFlags=function(){if(!this.isSystemEnabled())return Promise.resolve();var n=this.getMpProperty("distinct_id"),e=this.getMpProperty("$device_id");Rt.log("Fetching flags for distinct ID: "+n);var t={context:m.extend({distinct_id:n,device_id:e},this.getConfig(Oc))};return this._fetchInProgressStartTime=Date.now(),this.fetchPromise=V.fetch(this.getFullApiRoute(),{method:"POST",headers:{Authorization:"Basic "+btoa(this.getMpConfig("token")+":"),"Content-Type":"application/octet-stream"},body:JSON.stringify(t)}).then((function(r){return this.markFetchComplete(),r.json().then((function(i){var A=i.flags;if(!A)throw new Error("No flags in API response");var s=new Map;m.each(A,function(o,a){s.set(a,{key:o.variant_key,value:o.variant_value})}),this.flags=s}).bind(this)).catch((function(i){this.markFetchComplete(),Rt.error(i)}).bind(this))}).bind(this)).catch((function(r){this.markFetchComplete(),Rt.error(r)}).bind(this)),this.fetchPromise},ae.prototype.markFetchComplete=function(){if(!this._fetchInProgressStartTime){Rt.error("Fetch in progress started time not set, cannot mark fetch complete");return}this._fetchStartTime=this._fetchInProgressStartTime,this._fetchCompleteTime=Date.now(),this._fetchLatency=this._fetchCompleteTime-this._fetchStartTime,this._fetchInProgressStartTime=null},ae.prototype.getVariant=function(n,e){return this.fetchPromise?this.fetchPromise.then((function(){return this.getVariantSync(n,e)}).bind(this)).catch(function(t){return Rt.error(t),e}):new Promise(function(t){Rt.critical("Feature Flags not initialized"),t(e)})},ae.prototype.getVariantSync=function(n,e){if(!this.areFlagsReady())return Rt.log("Flags not loaded yet"),e;var t=this.flags.get(n);return t?(this.trackFeatureCheck(n,t),t):(Rt.log('No flag found: "'+n+'"'),e)},ae.prototype.getVariantValue=function(n,e){return this.getVariant(n,{value:e}).then(function(t){return t.value}).catch(function(t){return Rt.error(t),e})},ae.prototype.getFeatureData=function(n,e){return Rt.critical("mixpanel.flags.get_feature_data() is deprecated and will be removed in a future release. Use mixpanel.flags.get_variant_value() instead."),this.getVariantValue(n,e)},ae.prototype.getVariantValueSync=function(n,e){return this.getVariantSync(n,{value:e}).value},ae.prototype.isEnabled=function(n,e){return this.getVariantValue(n).then((function(){return this.isEnabledSync(n,e)}).bind(this)).catch(function(t){return Rt.error(t),e})},ae.prototype.isEnabledSync=function(n,e){e=e||!1;var t=this.getVariantValueSync(n,e);return t!==!0&&t!==!1&&(Rt.error('Feature flag "'+n+'" value: '+t+" is not a boolean; returning fallback value: "+e),t=e),t},ae.prototype.trackFeatureCheck=function(n,e){this.trackedFeatures.has(n)||(this.trackedFeatures.add(n),this.track("$experiment_started",{"Experiment name":n,"Variant name":e.key,$experiment_type:"feature_flag","Variant fetch start time":new Date(this._fetchStartTime).toISOString(),"Variant fetch complete time":new Date(this._fetchCompleteTime).toISOString(),"Variant fetch latency (ms)":this._fetchLatency}))};function MD(){return!!OD&&typeof Promise<"u"&&typeof Map<"u"&&typeof Set<"u"}VB(ae),ae.prototype.are_flags_ready=ae.prototype.areFlagsReady,ae.prototype.get_variant=ae.prototype.getVariant,ae.prototype.get_variant_sync=ae.prototype.getVariantSync,ae.prototype.get_variant_value=ae.prototype.getVariantValue,ae.prototype.get_variant_value_sync=ae.prototype.getVariantValueSync,ae.prototype.is_enabled=ae.prototype.isEnabled,ae.prototype.is_enabled_sync=ae.prototype.isEnabledSync,ae.prototype.update_context=ae.prototype.updateContext,ae.prototype.get_feature_data=ae.prototype.getFeatureData;var zn=function(){};zn.prototype.create_properties=function(){},zn.prototype.event_handler=function(){},zn.prototype.after_track_handler=function(){},zn.prototype.init=function(n){return this.mp=n,this},zn.prototype.track=function(n,e,t,r){var i=this,A=m.dom_query(n);if(A.length===0){we.error("The DOM query ("+n+") returned 0 elements");return}return m.each(A,function(s){m.register_event(s,this.override_event,function(o){var a={},c=i.create_properties(t,this),u=i.mp.get_config("track_links_timeout");i.event_handler(o,this,a),window.setTimeout(i.track_callback(r,c,a,!0),u),i.mp.track(e,c,i.track_callback(r,c,a))})},this),!0},zn.prototype.track_callback=function(n,e,t,r){r=r||!1;var i=this;return function(){t.callback_fired||(t.callback_fired=!0,!(n&&n(r,e)===!1)&&i.after_track_handler(e,t,r))}},zn.prototype.create_properties=function(n,e){var t;return typeof n=="function"?t=n(e):t=m.extend({},n),t};var sA=function(){this.override_event="click"};m.inherit(sA,zn),sA.prototype.create_properties=function(n,e){var t=sA.superclass.create_properties.apply(this,arguments);return e.href&&(t.url=e.href),t},sA.prototype.event_handler=function(n,e,t){t.new_tab=n.which===2||n.metaKey||n.ctrlKey||e.target==="_blank",t.href=e.href,t.new_tab||n.preventDefault()},sA.prototype.after_track_handler=function(n,e){e.new_tab||setTimeout(function(){window.location=e.href},0)};var Mc=function(){this.override_event="submit"};m.inherit(Mc,zn),Mc.prototype.event_handler=function(n,e,t){t.element=e,n.preventDefault()},Mc.prototype.after_track_handler=function(n,e){setTimeout(function(){e.element.submit()},0)};var xr="$set",oA="$set_once",mn="$unset",Ai="$add",Qn="$append",si="$union",Xn="$remove",LD="$delete",IC={set_action:function(n,e){var t={},r={};return m.isObject(n)?m.each(n,function(i,A){this._is_reserved_property(A)||(r[A]=i)},this):r[n]=e,t[xr]=r,t},unset_action:function(n){var e={},t=[];return m.isArray(n)||(n=[n]),m.each(n,function(r){this._is_reserved_property(r)||t.push(r)},this),e[mn]=t,e},set_once_action:function(n,e){var t={},r={};return m.isObject(n)?m.each(n,function(i,A){this._is_reserved_property(A)||(r[A]=i)},this):r[n]=e,t[oA]=r,t},union_action:function(n,e){var t={},r={};return m.isObject(n)?m.each(n,function(i,A){this._is_reserved_property(A)||(r[A]=m.isArray(i)?i:[i])},this):r[n]=m.isArray(e)?e:[e],t[si]=r,t},append_action:function(n,e){var t={},r={};return m.isObject(n)?m.each(n,function(i,A){this._is_reserved_property(A)||(r[A]=i)},this):r[n]=e,t[Qn]=r,t},remove_action:function(n,e){var t={},r={};return m.isObject(n)?m.each(n,function(i,A){this._is_reserved_property(A)||(r[A]=i)},this):r[n]=e,t[Xn]=r,t},delete_action:function(){var n={};return n[LD]="",n}},De=function(){};m.extend(De.prototype,IC),De.prototype._init=function(n,e,t){this._mixpanel=n,this._group_key=e,this._group_id=t},De.prototype.set=nA(function(n,e,t){var r=this.set_action(n,e);return m.isObject(n)&&(t=e),this._send_request(r,t)}),De.prototype.set_once=nA(function(n,e,t){var r=this.set_once_action(n,e);return m.isObject(n)&&(t=e),this._send_request(r,t)}),De.prototype.unset=nA(function(n,e){var t=this.unset_action(n);return this._send_request(t,e)}),De.prototype.union=nA(function(n,e,t){m.isObject(n)&&(t=e);var r=this.union_action(n,e);return this._send_request(r,t)}),De.prototype.delete=nA(function(n){var e=this.delete_action();return this._send_request(e,n)}),De.prototype.remove=nA(function(n,e,t){var r=this.remove_action(n,e);return this._send_request(r,t)}),De.prototype._send_request=function(n,e){n.$group_key=this._group_key,n.$group_id=this._group_id,n.$token=this._get_config("token");var t=m.encodeDates(n);return this._mixpanel._track_or_batch({type:"groups",data:t,endpoint:this._mixpanel.get_api_host("groups")+"/"+this._get_config("api_routes").groups,batcher:this._mixpanel.request_batchers.groups},e)},De.prototype._is_reserved_property=function(n){return n==="$group_key"||n==="$group_id"},De.prototype._get_config=function(n){return this._mixpanel.get_config(n)},De.prototype.toString=function(){return this._mixpanel.toString()+".group."+this._group_key+"."+this._group_id},De.prototype.remove=De.prototype.remove,De.prototype.set=De.prototype.set,De.prototype.set_once=De.prototype.set_once,De.prototype.union=De.prototype.union,De.prototype.unset=De.prototype.unset,De.prototype.toString=De.prototype.toString;var $=function(){};m.extend($.prototype,IC),$.prototype._init=function(n){this._mixpanel=n},$.prototype.set=Fr(function(n,e,t){var r=this.set_action(n,e);return m.isObject(n)&&(t=e),this._get_config("save_referrer")&&this._mixpanel.persistence.update_referrer_info(document.referrer),r[xr]=m.extend({},m.info.people_properties(),r[xr]),this._send_request(r,t)}),$.prototype.set_once=Fr(function(n,e,t){var r=this.set_once_action(n,e);return m.isObject(n)&&(t=e),this._send_request(r,t)}),$.prototype.unset=Fr(function(n,e){var t=this.unset_action(n);return this._send_request(t,e)}),$.prototype.increment=Fr(function(n,e,t){var r={},i={};return m.isObject(n)?(m.each(n,function(A,s){if(!this._is_reserved_property(s))if(isNaN(parseFloat(A))){we.error("Invalid increment value passed to mixpanel.people.increment - must be a number");return}else i[s]=A},this),t=e):(m.isUndefined(e)&&(e=1),i[n]=e),r[Ai]=i,this._send_request(r,t)}),$.prototype.append=Fr(function(n,e,t){m.isObject(n)&&(t=e);var r=this.append_action(n,e);return this._send_request(r,t)}),$.prototype.remove=Fr(function(n,e,t){m.isObject(n)&&(t=e);var r=this.remove_action(n,e);return this._send_request(r,t)}),$.prototype.union=Fr(function(n,e,t){m.isObject(n)&&(t=e);var r=this.union_action(n,e);return this._send_request(r,t)}),$.prototype.track_charge=Fr(function(){we.error("mixpanel.people.track_charge() is deprecated and no longer has any effect.")}),$.prototype.clear_charges=function(n){return this.set("$transactions",[],n)},$.prototype.delete_user=function(){if(!this._identify_called()){we.error("mixpanel.people.delete_user() requires you to call identify() first");return}var n={$delete:this._mixpanel.get_distinct_id()};return this._send_request(n)},$.prototype.toString=function(){return this._mixpanel.toString()+".people"},$.prototype._send_request=function(n,e){n.$token=this._get_config("token"),n.$distinct_id=this._mixpanel.get_distinct_id();var t=this._mixpanel.get_property("$device_id"),r=this._mixpanel.get_property("$user_id"),i=this._mixpanel.get_property("$had_persisted_distinct_id");t&&(n.$device_id=t),r&&(n.$user_id=r),i&&(n.$had_persisted_distinct_id=i);var A=m.encodeDates(n);return this._identify_called()?this._mixpanel._track_or_batch({type:"people",data:A,endpoint:this._mixpanel.get_api_host("people")+"/"+this._get_config("api_routes").engage,batcher:this._mixpanel.request_batchers.people},e):(this._enqueue(n),m.isUndefined(e)||(this._get_config("verbose")?e({status:-1,error:null}):e(-1)),m.truncate(A,255))},$.prototype._get_config=function(n){return this._mixpanel.get_config(n)},$.prototype._identify_called=function(){return this._mixpanel._flags.identify_called===!0},$.prototype._enqueue=function(n){xr in n?this._mixpanel.persistence._add_to_people_queue(xr,n):oA in n?this._mixpanel.persistence._add_to_people_queue(oA,n):mn in n?this._mixpanel.persistence._add_to_people_queue(mn,n):Ai in n?this._mixpanel.persistence._add_to_people_queue(Ai,n):Qn in n?this._mixpanel.persistence._add_to_people_queue(Qn,n):Xn in n?this._mixpanel.persistence._add_to_people_queue(Xn,n):si in n?this._mixpanel.persistence._add_to_people_queue(si,n):we.error("Invalid call to _enqueue():",n)},$.prototype._flush_one_queue=function(n,e,t,r){var i=this,A=m.extend({},this._mixpanel.persistence.load_queue(n)),s=A;!m.isUndefined(A)&&m.isObject(A)&&!m.isEmptyObject(A)&&(i._mixpanel.persistence._pop_from_people_queue(n,A),i._mixpanel.persistence.save(),r&&(s=r(A)),e.call(i,s,function(o,a){o===0&&i._mixpanel.persistence._add_to_people_queue(n,A),m.isUndefined(t)||t(o,a)}))},$.prototype._flush=function(n,e,t,r,i,A,s){var o=this;this._flush_one_queue(xr,this.set,n),this._flush_one_queue(oA,this.set_once,r),this._flush_one_queue(mn,this.unset,A,function(g){return m.keys(g)}),this._flush_one_queue(Ai,this.increment,e),this._flush_one_queue(si,this.union,i);var a=this._mixpanel.persistence.load_queue(Qn);if(!m.isUndefined(a)&&m.isArray(a)&&a.length)for(var c,u=function(g,v){g===0&&o._mixpanel.persistence._add_to_people_queue(Qn,c),m.isUndefined(t)||t(g,v)},l=a.length-1;l>=0;l--)a=this._mixpanel.persistence.load_queue(Qn),c=a.pop(),o._mixpanel.persistence.save(),m.isEmptyObject(c)||o.append(c,u);var d=this._mixpanel.persistence.load_queue(Xn);if(!m.isUndefined(d)&&m.isArray(d)&&d.length)for(var h,f=function(g,v){g===0&&o._mixpanel.persistence._add_to_people_queue(Xn,h),m.isUndefined(s)||s(g,v)},p=d.length-1;p>=0;p--)d=this._mixpanel.persistence.load_queue(Xn),h=d.pop(),o._mixpanel.persistence.save(),m.isEmptyObject(h)||o.remove(h,f)},$.prototype._is_reserved_property=function(n){return n==="$distinct_id"||n==="$token"||n==="$device_id"||n==="$user_id"||n==="$had_persisted_distinct_id"},$.prototype.set=$.prototype.set,$.prototype.set_once=$.prototype.set_once,$.prototype.unset=$.prototype.unset,$.prototype.increment=$.prototype.increment,$.prototype.append=$.prototype.append,$.prototype.remove=$.prototype.remove,$.prototype.union=$.prototype.union,$.prototype.track_charge=$.prototype.track_charge,$.prototype.clear_charges=$.prototype.clear_charges,$.prototype.delete_user=$.prototype.delete_user,$.prototype.toString=$.prototype.toString;var Cp="__mps",_p="__mpso",Sp="__mpus",kp="__mpa",Ep="__mpap",Up="__mpr",Tp="__mpu",FC="$people_distinct_id",Lc="__alias",Es="__timers",DD=[Cp,_p,Sp,kp,Ep,Up,Tp,FC,Lc,Es],re=function(n){this.props={},this.campaign_params_saved=!1,n.persistence_name?this.name="mp_"+n.persistence_name:this.name="mp_"+n.token+"_mixpanel";var e=n.persistence;e!=="cookie"&&e!=="localStorage"&&(we.critical("Unknown persistence type "+e+"; falling back to cookie"),e=n.persistence="cookie"),e==="localStorage"&&m.localStorage.is_supported()?this.storage=m.localStorage:this.storage=m.cookie,this.load(),this.update_config(n),this.upgrade(),this.save()};re.prototype.properties=function(){var n={};return this.load(),m.each(this.props,function(e,t){m.include(DD,t)||(n[t]=e)}),n},re.prototype.load=function(){if(!this.disabled){var n=this.storage.parse(this.name);n&&(this.props=m.extend({},n))}},re.prototype.upgrade=function(){var n,e;this.storage===m.localStorage?(n=m.cookie.parse(this.name),m.cookie.remove(this.name),m.cookie.remove(this.name,!0),n&&this.register_once(n)):this.storage===m.cookie&&(e=m.localStorage.parse(this.name),m.localStorage.remove(this.name),e&&this.register_once(e))},re.prototype.save=function(){this.disabled||this.storage.set(this.name,tA(this.props),this.expire_days,this.cross_subdomain,this.secure,this.cross_site,this.cookie_domain)},re.prototype.load_prop=function(n){return this.load(),this.props[n]},re.prototype.remove=function(){this.storage.remove(this.name,!1,this.cookie_domain),this.storage.remove(this.name,!0,this.cookie_domain)},re.prototype.clear=function(){this.remove(),this.props={}},re.prototype.register_once=function(n,e,t){return m.isObject(n)?(typeof e>"u"&&(e="None"),this.expire_days=typeof t>"u"?this.default_expiry:t,this.load(),m.each(n,function(r,i){(!this.props.hasOwnProperty(i)||this.props[i]===e)&&(this.props[i]=r)},this),this.save(),!0):!1},re.prototype.register=function(n,e){return m.isObject(n)?(this.expire_days=typeof e>"u"?this.default_expiry:e,this.load(),m.extend(this.props,n),this.save(),!0):!1},re.prototype.unregister=function(n){this.load(),n in this.props&&(delete this.props[n],this.save())},re.prototype.update_search_keyword=function(n){this.register(m.info.searchInfo(n))},re.prototype.update_referrer_info=function(n){this.register_once({$initial_referrer:n||"$direct",$initial_referring_domain:m.info.referringDomain(n)||"$direct"},"")},re.prototype.get_referrer_info=function(){return m.strip_empty_properties({$initial_referrer:this.props.$initial_referrer,$initial_referring_domain:this.props.$initial_referring_domain})},re.prototype.update_config=function(n){this.default_expiry=this.expire_days=n.cookie_expiration,this.set_disabled(n.disable_persistence),this.set_cookie_domain(n.cookie_domain),this.set_cross_site(n.cross_site_cookie),this.set_cross_subdomain(n.cross_subdomain_cookie),this.set_secure(n.secure_cookie)},re.prototype.set_disabled=function(n){this.disabled=n,this.disabled?this.remove():this.save()},re.prototype.set_cookie_domain=function(n){n!==this.cookie_domain&&(this.remove(),this.cookie_domain=n,this.save())},re.prototype.set_cross_site=function(n){n!==this.cross_site&&(this.cross_site=n,this.remove(),this.save())},re.prototype.set_cross_subdomain=function(n){n!==this.cross_subdomain&&(this.cross_subdomain=n,this.remove(),this.save())},re.prototype.get_cross_subdomain=function(){return this.cross_subdomain},re.prototype.set_secure=function(n){n!==this.secure&&(this.secure=!!n,this.remove(),this.save())},re.prototype._add_to_people_queue=function(n,e){var t=this._get_queue_key(n),r=e[n],i=this._get_or_create_queue(xr),A=this._get_or_create_queue(oA),s=this._get_or_create_queue(mn),o=this._get_or_create_queue(Ai),a=this._get_or_create_queue(si),c=this._get_or_create_queue(Xn,[]),u=this._get_or_create_queue(Qn,[]);t===Cp?(m.extend(i,r),this._pop_from_people_queue(Ai,r),this._pop_from_people_queue(si,r),this._pop_from_people_queue(mn,r)):t===_p?(m.each(r,function(l,d){d in A||(A[d]=l)}),this._pop_from_people_queue(mn,r)):t===Sp?m.each(r,function(l){m.each([i,A,o,a],function(d){l in d&&delete d[l]}),m.each(u,function(d){l in d&&delete d[l]}),s[l]=!0}):t===kp?(m.each(r,function(l,d){d in i?i[d]+=l:(d in o||(o[d]=0),o[d]+=l)},this),this._pop_from_people_queue(mn,r)):t===Tp?(m.each(r,function(l,d){m.isArray(l)&&(d in a||(a[d]=[]),m.each(l,function(h){m.include(a[d],h)||a[d].push(h)}))}),this._pop_from_people_queue(mn,r)):t===Up?(c.push(r),this._pop_from_people_queue(Qn,r)):t===Ep&&(u.push(r),this._pop_from_people_queue(mn,r)),we.log("MIXPANEL PEOPLE REQUEST (QUEUED, PENDING IDENTIFY):"),we.log(e),this.save()},re.prototype._pop_from_people_queue=function(n,e){var t=this.props[this._get_queue_key(n)];m.isUndefined(t)||m.each(e,function(r,i){n===Qn||n===Xn?m.each(t,function(A){A[i]===r&&delete A[i]}):delete t[i]},this)},re.prototype.load_queue=function(n){return this.load_prop(this._get_queue_key(n))},re.prototype._get_queue_key=function(n){if(n===xr)return Cp;if(n===oA)return _p;if(n===mn)return Sp;if(n===Ai)return kp;if(n===Qn)return Ep;if(n===Xn)return Up;if(n===si)return Tp;we.error("Invalid queue:",n)},re.prototype._get_or_create_queue=function(n,e){var t=this._get_queue_key(n);return e=m.isUndefined(e)?{}:e,this.props[t]||(this.props[t]=e)},re.prototype.set_event_timer=function(n,e){var t=this.load_prop(Es)||{};t[n]=e,this.props[Es]=t,this.save()},re.prototype.remove_event_timer=function(n){var e=this.load_prop(Es)||{},t=e[n];return m.isUndefined(t)||(delete this.props[Es][n],this.save()),t};var Ip,xC=function(n,e){throw new Error(n+" not available in this build.")},Ut,QC=0,ND=1,HD=function(n){return n},en="mixpanel",RC="base64",KD="json",Fp="$device:",aA=V.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,PC=!aA&&qn.indexOf("MSIE")===-1&&qn.indexOf("Mozilla")===-1,Dc=null;Ur.sendBeacon&&(Dc=function(){return Ur.sendBeacon.apply(Ur,arguments)});var OC={track:"track/",engage:"engage/",groups:"groups/",record:"record/",flags:"flags/"},MC={api_host:"https://api-js.mixpanel.com",api_hosts:{},api_routes:OC,api_extra_query_params:{},api_method:"POST",api_transport:"XHR",api_payload_format:RC,app_host:"https://mixpanel.com",autocapture:!1,cdn:"https://cdn.mxpnl.com",cross_site_cookie:!1,cross_subdomain_cookie:!0,error_reporter:Tr,flags:!1,persistence:"cookie",persistence_name:"",cookie_domain:"",cookie_name:"",loaded:Tr,mp_loader:null,track_marketing:!0,track_pageview:!1,skip_first_touch_marketing:!1,store_google:!0,stop_utm_persistence:!1,save_referrer:!0,test:!1,verbose:!1,img:!1,debug:!1,track_links_timeout:300,cookie_expiration:365,upgrade:!1,disable_persistence:!1,disable_cookie:!1,secure_cookie:!1,ip:!0,opt_out_tracking_by_default:!1,opt_out_persistence_by_default:!1,opt_out_tracking_persistence_type:"localStorage",opt_out_tracking_cookie_prefix:null,property_blacklist:[],xhr_headers:{},ignore_dnt:!1,batch_requests:!0,batch_size:50,batch_flush_interval_ms:5e3,batch_request_timeout_ms:9e4,batch_autostart:!0,hooks:{},record_block_class:new RegExp("^(mp-block|fs-exclude|amp-block|rr-block|ph-no-capture)$"),record_block_selector:"img, video, audio",record_canvas:!1,record_collect_fonts:!1,record_heatmap_data:!1,record_idle_timeout_ms:30*60*1e3,record_mask_text_class:new RegExp("^(mp-mask|fs-mask|amp-mask|rr-mask|ph-mask)$"),record_mask_text_selector:"*",record_max_ms:bs,record_min_ms:0,record_sessions_percent:0,recorder_src:"https://cdn.mxpnl.com/libs/mixpanel-recorder.min.js"},LC=!1,U=function(){},xp=function(n,e,t){var r,i=t===en?Ut:Ut[t];if(i&&Ip===QC)r=i;else{if(i&&!m.isArray(i)){we.error("You have already initialized "+t);return}r=new U}if(r._cached_groups={},r._init(n,e,t),r.people=new $,r.people._init(r),!r.get_config("skip_first_touch_marketing")){var A=m.info.campaignParams(null),s={},o=!1;m.each(A,function(a,c){s["initial_"+c]=a,a&&(o=!0)}),o&&r.people.set_once(s)}return gn.DEBUG=gn.DEBUG||r.get_config("debug"),!m.isUndefined(i)&&m.isArray(i)&&(r._execute_array.call(r.people,i.people),r._execute_array(i)),r};U.prototype.init=function(n,e,t){if(m.isUndefined(t)){this.report_error("You must name your new library: init(token, config, name)");return}if(t===en){this.report_error("You must initialize the main mixpanel object right after you include the Mixpanel js snippet");return}var r=xp(n,e,t);return Ut[t]=r,r._loaded(),r},U.prototype._init=function(n,e,t){e=e||{},this.__loaded=!0,this.config={};var r={};if(!("api_payload_format"in e)){var i=e.api_host||MC.api_host;i.match(/\.mixpanel\.com/)&&(r.api_payload_format=KD)}if(this.set_config(m.extend({},MC,r,e,{name:t,token:n,callback_fn:(t===en?t:en+"."+t)+"._jsc"})),this._jsc=Tr,this.__dom_loaded_queue=[],this.__request_queue=[],this.__disabled_events=[],this._flags={disable_all_events:!1,identify_called:!1},this.request_batchers={},this._batch_requests=this.get_config("batch_requests"),this._batch_requests){if(!m.localStorage.is_supported(!0)||!aA)this._batch_requests=!1,we.log("Turning off Mixpanel request-queueing; needs XHR and localStorage support"),m.each(this.get_batcher_configs(),function(o){we.log("Clearing batch queue "+o.queue_key),m.localStorage.remove(o.queue_key)});else if(this.init_batchers(),Dc&&V.addEventListener){var A=m.bind(function(){this.request_batchers.events.stopped||this.request_batchers.events.flush({unloading:!0})},this);V.addEventListener("pagehide",function(o){o.persisted&&A()}),V.addEventListener("visibilitychange",function(){ye.visibilityState==="hidden"&&A()})}}this.persistence=this.cookie=new re(this.config),this.unpersisted_superprops={},this._gdpr_init();var s=m.UUID();this.get_distinct_id()||this.register_once({distinct_id:Fp+s,$device_id:s},""),this.flags=new ae({getFullApiRoute:m.bind(function(){return this.get_api_host("flags")+"/"+this.get_config("api_routes").flags},this),getConfigFunc:m.bind(this.get_config,this),setConfigFunc:m.bind(this.set_config,this),getPropertyFunc:m.bind(this.get_property,this),trackingFunc:m.bind(this.track,this)}),this.flags.init(),this.flags=this.flags,this.autocapture=new Qt(this),this.autocapture.init(),this._init_tab_id(),this._check_and_start_session_recording()},U.prototype._init_tab_id=function(){if(m.sessionStorage.is_supported())try{var n=this.get_config("name")+"_"+this.get_config("token"),e="mp_tab_id_"+n,t="mp_gen_new_tab_id_"+n;(m.sessionStorage.get(t)||!m.sessionStorage.get(e))&&m.sessionStorage.set(e,"$tab-"+m.UUID()),m.sessionStorage.set(t,"1"),this.tab_id=m.sessionStorage.get(e),V.addEventListener("beforeunload",function(){m.sessionStorage.remove(t)})}catch(r){this.report_error("Error initializing tab id",r)}else this.report_error("Session storage is not supported, cannot keep track of unique tab ID.")},U.prototype.get_tab_id=function(){return this.tab_id||null},U.prototype._should_load_recorder=function(){var n=new In(ap),e=this.get_tab_id();return n.init().then(function(){return n.getAll()}).then(function(t){for(var r=0;r<t.length;r++)if(dp(t[r])||t[r].tabId===e)return!0;return!1}).catch(m.bind(function(t){this.report_error("Error checking recording registry",t)},this))},U.prototype._check_and_start_session_recording=Ir(function(n){if(!V.MutationObserver){we.critical("Browser does not support MutationObserver; skipping session recording");return}var e=m.bind(function(r){var i=m.bind(function(){this._recorder=this._recorder||new V.__mp_recorder(this),this._recorder.resumeRecording(r)},this);m.isUndefined(V.__mp_recorder)?xC(this.get_config("recorder_src"),i):i()},this),t=this.get_config("record_sessions_percent")>0&&Math.random()*100<=this.get_config("record_sessions_percent");n||t?e(!0):this._should_load_recorder().then(function(r){r&&e(!1)})}),U.prototype.start_session_recording=function(){this._check_and_start_session_recording(!0)},U.prototype.stop_session_recording=function(){return this._recorder?this._recorder.stopRecording():Promise.resolve()},U.prototype.pause_session_recording=function(){return this._recorder?this._recorder.pauseRecording():Promise.resolve()},U.prototype.resume_session_recording=function(){return this._recorder?this._recorder.resumeRecording():Promise.resolve()},U.prototype.is_recording_heatmap_data=function(){return this._get_session_replay_id()&&this.get_config("record_heatmap_data")},U.prototype.get_session_recording_properties=function(){var n={},e=this._get_session_replay_id();return e&&(n.$mp_replay_id=e),n},U.prototype.get_session_replay_url=function(){var n=null,e=this._get_session_replay_id();if(e){var t=m.HTTPBuildQuery({replay_id:e,distinct_id:this.get_distinct_id(),token:this.get_config("token")});n="https://mixpanel.com/projects/replay-redirect?"+t}return n},U.prototype._get_session_replay_id=function(){var n=null;return this._recorder&&(n=this._recorder.replayId),n||null},U.prototype.__get_recorder=function(){return this._recorder},U.prototype._loaded=function(){if(this.get_config("loaded")(this),this._set_default_superprops(),this.people.set_once(this.persistence.get_referrer_info()),this.get_config("store_google")&&this.get_config("stop_utm_persistence")){var n=m.info.campaignParams(null);m.each(n,(function(e,t){this.unregister(t)}).bind(this))}},U.prototype._set_default_superprops=function(){this.persistence.update_search_keyword(ye.referrer),this.get_config("store_google")&&!this.get_config("stop_utm_persistence")&&this.register(m.info.campaignParams()),this.get_config("save_referrer")&&this.persistence.update_referrer_info(ye.referrer)},U.prototype._dom_loaded=function(){m.each(this.__dom_loaded_queue,function(n){this._track_dom.apply(this,n)},this),this.has_opted_out_tracking()||m.each(this.__request_queue,function(n){this._send_request.apply(this,n)},this),delete this.__dom_loaded_queue,delete this.__request_queue},U.prototype._track_dom=function(n,e){if(this.get_config("img"))return this.report_error("You can't use DOM tracking functions with img = true."),!1;if(!LC)return this.__dom_loaded_queue.push([n,e]),!1;var t=new n().init(this);return t.track.apply(t,e)},U.prototype._prepare_callback=function(n,e){if(m.isUndefined(n))return null;if(aA){var t=function(s){n(s,e)};return t}else{var r=this._jsc,i=""+Math.floor(Math.random()*1e8),A=this.get_config("callback_fn")+"["+i+"]";return r[i]=function(s){delete r[i],n(s,e)},A}},U.prototype._send_request=function(n,e,t,r){var i=!0;if(PC)return this.__request_queue.push(arguments),i;var A={method:this.get_config("api_method"),transport:this.get_config("api_transport"),verbose:this.get_config("verbose")},s=null;!r&&(m.isFunction(t)||typeof t=="string")&&(r=t,t=null),t=m.extend(A,t||{}),aA||(t.method="GET");var o=t.method==="POST",a=Dc&&o&&t.transport.toLowerCase()==="sendbeacon",c=t.verbose;e.verbose&&(c=!0),this.get_config("test")&&(e.test=1),c&&(e.verbose=1),this.get_config("img")&&(e.img=1),aA||(r?e.callback=r:(c||this.get_config("test"))&&(e.callback="(function(){})")),e.ip=this.get_config("ip")?1:0,e._=new Date().getTime().toString(),o&&(s="data="+encodeURIComponent(e.data),delete e.data),m.extend(e,this.get_config("api_extra_query_params")),n+="?"+m.HTTPBuildQuery(e);var u=this;if("img"in e){var l=ye.createElement("img");l.src=n,ye.body.appendChild(l)}else if(a){try{i=Dc(n,s)}catch(v){u.report_error(v),i=!1}try{r&&r(i?1:0)}catch(v){u.report_error(v)}}else if(aA)try{var d=new XMLHttpRequest;d.open(t.method,n,!0);var h=this.get_config("xhr_headers");if(o&&(h["Content-Type"]="application/x-www-form-urlencoded"),m.each(h,function(v,y){d.setRequestHeader(y,v)}),t.timeout_ms&&typeof d.timeout<"u"){d.timeout=t.timeout_ms;var f=new Date().getTime()}d.withCredentials=!0,d.onreadystatechange=function(){if(d.readyState===4)if(d.status===200){if(r)if(c){var v;try{v=m.JSONDecode(d.responseText)}catch(b){if(u.report_error(b),t.ignore_json_errors)v=d.responseText;else return}r(v)}else r(Number(d.responseText))}else{var y;if(d.timeout&&!d.status&&new Date().getTime()-f>=d.timeout?y="timeout":y="Bad HTTP status: "+d.status+" "+d.statusText,u.report_error(y),r)if(c){var B=d.responseHeaders||{};r({status:0,httpStatusCode:d.status,error:y,retryAfter:B["Retry-After"]})}else r(0)}},d.send(s)}catch(v){u.report_error(v),i=!1}else{var p=ye.createElement("script");p.type="text/javascript",p.async=!0,p.defer=!0,p.src=n;var g=ye.getElementsByTagName("script")[0];g.parentNode.insertBefore(p,g)}return i},U.prototype._execute_array=function(n){var e,t=[],r=[],i=[];m.each(n,function(s){s&&(e=s[0],m.isArray(e)?i.push(s):typeof s=="function"?s.call(this):m.isArray(s)&&e==="alias"?t.push(s):m.isArray(s)&&e.indexOf("track")!==-1&&typeof this[e]=="function"?i.push(s):r.push(s))},this);var A=function(s,o){m.each(s,function(a){if(m.isArray(a[0])){var c=o;m.each(a,function(u){c=c[u[0]].apply(c,u.slice(1))})}else this[a[0]].apply(this,a.slice(1))},o)};A(t,this),A(r,this),A(i,this)},U.prototype.are_batchers_initialized=function(){return!!this.request_batchers.events},U.prototype.get_batcher_configs=function(){var n="__mpq_"+this.get_config("token");return this._batcher_configs=this._batcher_configs||{events:{type:"events",api_name:"track",queue_key:n+"_ev"},people:{type:"people",api_name:"engage",queue_key:n+"_pp"},groups:{type:"groups",api_name:"groups",queue_key:n+"_gr"}},this._batcher_configs},U.prototype.init_batchers=function(){if(!this.are_batchers_initialized()){var n=m.bind(function(t){return new $t(t.queue_key,{libConfig:this.config,errorReporter:this.get_config("error_reporter"),sendRequestFunc:m.bind(function(r,i,A){var s=this.get_config("api_routes");this._send_request(this.get_api_host(t.api_name)+"/"+s[t.api_name],this._encode_data_for_request(r),i,this._prepare_callback(A,r))},this),beforeSendHook:m.bind(function(r){return this._run_hook("before_send_"+t.type,r)},this),stopAllBatchingFunc:m.bind(this.stop_batch_senders,this),usePersistence:!0})},this),e=this.get_batcher_configs();this.request_batchers={events:n(e.events),people:n(e.people),groups:n(e.groups)}}this.get_config("batch_autostart")&&this.start_batch_senders()},U.prototype.start_batch_senders=function(){this._batchers_were_started=!0,this.are_batchers_initialized()&&(this._batch_requests=!0,m.each(this.request_batchers,function(n){n.start()}))},U.prototype.stop_batch_senders=function(){this._batch_requests=!1,m.each(this.request_batchers,function(n){n.stop(),n.clear()})},U.prototype.push=function(n){this._execute_array([n])},U.prototype.disable=function(n){typeof n>"u"?this._flags.disable_all_events=!0:this.__disabled_events=this.__disabled_events.concat(n)},U.prototype._encode_data_for_request=function(n){var e=tA(n);return this.get_config("api_payload_format")===RC&&(e=m.base64Encode(e)),{data:e}},U.prototype._track_or_batch=function(n,e){var t=m.truncate(n.data,255),r=n.endpoint,i=n.batcher,A=n.should_send_immediately,s=n.send_request_options||{};e=e||Tr;var o=!0,a=m.bind(function(){return s.skip_hooks||(t=this._run_hook("before_send_"+n.type,t)),t?(we.log("MIXPANEL REQUEST:"),we.log(t),this._send_request(r,this._encode_data_for_request(t),s,this._prepare_callback(e,t))):null},this);return this._batch_requests&&!A?i.enqueue(t).then(function(c){c?e(1,t):a()}):o=a(),o&&t},U.prototype.track=Ir(function(n,e,t,r){!r&&typeof t=="function"&&(r=t,t=null),t=t||{};var i=t.transport;i&&(t.transport=i);var A=t.send_immediately;if(typeof r!="function"&&(r=Tr),m.isUndefined(n)){this.report_error("No event name provided to mixpanel.track");return}if(this._event_is_disabled(n)){r(0);return}e=m.extend({},e),e.token=this.get_config("token");var s=this.persistence.remove_event_timer(n);if(!m.isUndefined(s)){var o=new Date().getTime()-s;e.$duration=parseFloat((o/1e3).toFixed(3))}this._set_default_superprops();var a=this.get_config("track_marketing")?m.info.marketingParams():{};e=m.extend({},m.info.properties({mp_loader:this.get_config("mp_loader")}),a,this.persistence.properties(),this.unpersisted_superprops,this.get_session_recording_properties(),e);var c=this.get_config("property_blacklist");m.isArray(c)?m.each(c,function(d){delete e[d]}):this.report_error("Invalid value for property_blacklist config: "+c);var u={event:n,properties:e},l=this._track_or_batch({type:"events",data:u,endpoint:this.get_api_host("events")+"/"+this.get_config("api_routes").track,batcher:this.request_batchers.events,should_send_immediately:A,send_request_options:t},r);return l}),U.prototype.set_group=Ir(function(n,e,t){m.isArray(e)||(e=[e]);var r={};return r[n]=e,this.register(r),this.people.set(n,e,t)}),U.prototype.add_group=Ir(function(n,e,t){var r=this.get_property(n),i={};return r===void 0?(i[n]=[e],this.register(i)):r.indexOf(e)===-1&&(r.push(e),i[n]=r,this.register(i)),this.people.union(n,e,t)}),U.prototype.remove_group=Ir(function(n,e,t){var r=this.get_property(n);if(r!==void 0){var i=r.indexOf(e);i>-1&&(r.splice(i,1),this.register({group_key:r})),r.length===0&&this.unregister(n)}return this.people.remove(n,e,t)}),U.prototype.track_with_groups=Ir(function(n,e,t,r){var i=m.extend({},e||{});return m.each(t,function(A,s){A!=null&&(i[s]=A)}),this.track(n,i,r)}),U.prototype._create_map_key=function(n,e){return n+"_"+JSON.stringify(e)},U.prototype._remove_group_from_cache=function(n,e){delete this._cached_groups[this._create_map_key(n,e)]},U.prototype.get_group=function(n,e){var t=this._create_map_key(n,e),r=this._cached_groups[t];return(r===void 0||r._group_key!==n||r._group_id!==e)&&(r=new De,r._init(this,n,e),this._cached_groups[t]=r),r},U.prototype.track_pageview=Ir(function(n,e){typeof n!="object"&&(n={}),e=e||{};var t=e.event_name||"$mp_web_page_view",r=m.extend(m.info.mpPageViewProperties(),m.info.campaignParams(),m.info.clickParams()),i=m.extend({},r,n);return this.track(t,i)}),U.prototype.track_links=function(){return this._track_dom.call(this,sA,arguments)},U.prototype.track_forms=function(){return this._track_dom.call(this,Mc,arguments)},U.prototype.time_event=function(n){if(m.isUndefined(n)){this.report_error("No event name provided to mixpanel.time_event");return}this._event_is_disabled(n)||this.persistence.set_event_timer(n,new Date().getTime())};var VD={persistent:!0},Qp=function(n){var e;return m.isObject(n)?e=n:m.isUndefined(n)?e={}:e={days:n},m.extend({},VD,e)};U.prototype.register=function(n,e){var t=Qp(e);t.persistent?this.persistence.register(n,t.days):m.extend(this.unpersisted_superprops,n)},U.prototype.register_once=function(n,e,t){var r=Qp(t);r.persistent?this.persistence.register_once(n,e,r.days):(typeof e>"u"&&(e="None"),m.each(n,function(i,A){(!this.unpersisted_superprops.hasOwnProperty(A)||this.unpersisted_superprops[A]===e)&&(this.unpersisted_superprops[A]=i)},this))},U.prototype.unregister=function(n,e){e=Qp(e),e.persistent?this.persistence.unregister(n):delete this.unpersisted_superprops[n]},U.prototype._register_single=function(n,e){var t={};t[n]=e,this.register(t)},U.prototype.identify=function(n,e,t,r,i,A,s,o){var a=this.get_distinct_id();if(n&&a!==n){if(typeof n=="string"&&n.indexOf(Fp)===0)return this.report_error("distinct_id cannot have $device: prefix"),-1;this.register({$user_id:n})}if(!this.get_property("$device_id")){var c=a;this.register_once({$had_persisted_distinct_id:!0,$device_id:c},"")}n!==a&&n!==this.get_property(Lc)&&(this.unregister(Lc),this.register({distinct_id:n})),this._flags.identify_called=!0,this.people._flush(e,t,r,i,A,s,o),n!==a&&this.track("$identify",{distinct_id:n,$anon_distinct_id:a},{skip_hooks:!0}),n!==a&&this.flags.fetchFlags()},U.prototype.reset=function(){this.stop_session_recording(),this.persistence.clear(),this._flags.identify_called=!1;var n=m.UUID();this.register_once({distinct_id:Fp+n,$device_id:n},""),this._check_and_start_session_recording()},U.prototype.get_distinct_id=function(){return this.get_property("distinct_id")},U.prototype.alias=function(n,e){if(n===this.get_property(FC))return this.report_error("Attempting to create alias for existing People user - aborting."),-2;var t=this;return m.isUndefined(e)&&(e=this.get_distinct_id()),n!==e?(this._register_single(Lc,n),this.track("$create_alias",{alias:n,distinct_id:e},{skip_hooks:!0},function(){t.identify(n)})):(this.report_error("alias matches current distinct_id - skipping api call."),this.identify(n),-1)},U.prototype.name_tag=function(n){this._register_single("mp_name_tag",n)},U.prototype.set_config=function(n){if(m.isObject(n)){m.extend(this.config,n);var e=n.batch_size;e&&m.each(this.request_batchers,function(t){t.resetBatchSize()}),this.get_config("persistence_name")||(this.config.persistence_name=this.config.cookie_name),this.get_config("disable_persistence")||(this.config.disable_persistence=this.config.disable_cookie),this.persistence&&this.persistence.update_config(this.config),gn.DEBUG=gn.DEBUG||this.get_config("debug"),("autocapture"in n||"record_heatmap_data"in n)&&this.autocapture&&this.autocapture.init()}},U.prototype.get_config=function(n){return this.config[n]},U.prototype._run_hook=function(n){var e=(this.config.hooks[n]||HD).apply(this,ni.call(arguments,1));return typeof e>"u"&&(this.report_error(n+" hook did not return a value"),e=null),e},U.prototype.get_property=function(n){return this.persistence.load_prop([n])},U.prototype.get_api_host=function(n){return this.get_config("api_hosts")[n]||this.get_config("api_host")},U.prototype.toString=function(){var n=this.get_config("name");return n!==en&&(n=en+"."+n),n},U.prototype._event_is_disabled=function(n){return m.isBlockedUA(qn)||this._flags.disable_all_events||m.include(this.__disabled_events,n)},U.prototype._gdpr_init=function(){var n=this.get_config("opt_out_tracking_persistence_type")==="localStorage";n&&m.localStorage.is_supported()&&(!this.has_opted_in_tracking()&&this.has_opted_in_tracking({persistence_type:"cookie"})&&this.opt_in_tracking({enable_persistence:!1}),!this.has_opted_out_tracking()&&this.has_opted_out_tracking({persistence_type:"cookie"})&&this.opt_out_tracking({clear_persistence:!1}),this.clear_opt_in_out_tracking({persistence_type:"cookie",enable_persistence:!1})),this.has_opted_out_tracking()?this._gdpr_update_persistence({clear_persistence:!0}):!this.has_opted_in_tracking()&&(this.get_config("opt_out_tracking_by_default")||m.cookie.get("mp_optout"))&&(m.cookie.remove("mp_optout"),this.opt_out_tracking({clear_persistence:this.get_config("opt_out_persistence_by_default")}))},U.prototype._gdpr_update_persistence=function(n){var e;if(n&&n.clear_persistence)e=!0;else if(n&&n.enable_persistence)e=!1;else return;!this.get_config("disable_persistence")&&this.persistence.disabled!==e&&this.persistence.set_disabled(e),e?(this.stop_batch_senders(),this.stop_session_recording()):this._batchers_were_started&&this.start_batch_senders()},U.prototype._gdpr_call_func=function(n,e){return e=m.extend({track:m.bind(this.track,this),persistence_type:this.get_config("opt_out_tracking_persistence_type"),cookie_prefix:this.get_config("opt_out_tracking_cookie_prefix"),cookie_expiration:this.get_config("cookie_expiration"),cross_site_cookie:this.get_config("cross_site_cookie"),cross_subdomain_cookie:this.get_config("cross_subdomain_cookie"),cookie_domain:this.get_config("cookie_domain"),secure_cookie:this.get_config("secure_cookie"),ignore_dnt:this.get_config("ignore_dnt")},e),m.localStorage.is_supported()||(e.persistence_type="cookie"),n(this.get_config("token"),{track:e.track,trackEventName:e.track_event_name,trackProperties:e.track_properties,persistenceType:e.persistence_type,persistencePrefix:e.cookie_prefix,cookieDomain:e.cookie_domain,cookieExpiration:e.cookie_expiration,crossSiteCookie:e.cross_site_cookie,crossSubdomainCookie:e.cross_subdomain_cookie,secureCookie:e.secure_cookie,ignoreDnt:e.ignore_dnt})},U.prototype.opt_in_tracking=function(n){n=m.extend({enable_persistence:!0},n),this._gdpr_call_func(aD,n),this._gdpr_update_persistence(n)},U.prototype.opt_out_tracking=function(n){n=m.extend({clear_persistence:!0,delete_user:!0},n),n.delete_user&&this.people&&this.people._identify_called()&&(this.people.delete_user(),this.people.clear_charges()),this._gdpr_call_func(cD,n),this._gdpr_update_persistence(n)},U.prototype.has_opted_in_tracking=function(n){return this._gdpr_call_func(uD,n)},U.prototype.has_opted_out_tracking=function(n){return this._gdpr_call_func(zB,n)},U.prototype.clear_opt_in_out_tracking=function(n){n=m.extend({enable_persistence:!0},n),this._gdpr_call_func(lD,n),this._gdpr_update_persistence(n)},U.prototype.report_error=function(n,e){we.error.apply(we.error,arguments);try{!e&&!(n instanceof Error)&&(n=new Error(n)),this.get_config("error_reporter")(n,e)}catch(t){we.error(t)}},U.prototype.init=U.prototype.init,U.prototype.reset=U.prototype.reset,U.prototype.disable=U.prototype.disable,U.prototype.time_event=U.prototype.time_event,U.prototype.track=U.prototype.track,U.prototype.track_links=U.prototype.track_links,U.prototype.track_forms=U.prototype.track_forms,U.prototype.track_pageview=U.prototype.track_pageview,U.prototype.register=U.prototype.register,U.prototype.register_once=U.prototype.register_once,U.prototype.unregister=U.prototype.unregister,U.prototype.identify=U.prototype.identify,U.prototype.alias=U.prototype.alias,U.prototype.name_tag=U.prototype.name_tag,U.prototype.set_config=U.prototype.set_config,U.prototype.get_config=U.prototype.get_config,U.prototype.get_api_host=U.prototype.get_api_host,U.prototype.get_property=U.prototype.get_property,U.prototype.get_distinct_id=U.prototype.get_distinct_id,U.prototype.toString=U.prototype.toString,U.prototype.opt_out_tracking=U.prototype.opt_out_tracking,U.prototype.opt_in_tracking=U.prototype.opt_in_tracking,U.prototype.has_opted_out_tracking=U.prototype.has_opted_out_tracking,U.prototype.has_opted_in_tracking=U.prototype.has_opted_in_tracking,U.prototype.clear_opt_in_out_tracking=U.prototype.clear_opt_in_out_tracking,U.prototype.get_group=U.prototype.get_group,U.prototype.set_group=U.prototype.set_group,U.prototype.add_group=U.prototype.add_group,U.prototype.remove_group=U.prototype.remove_group,U.prototype.track_with_groups=U.prototype.track_with_groups,U.prototype.start_batch_senders=U.prototype.start_batch_senders,U.prototype.stop_batch_senders=U.prototype.stop_batch_senders,U.prototype.start_session_recording=U.prototype.start_session_recording,U.prototype.stop_session_recording=U.prototype.stop_session_recording,U.prototype.pause_session_recording=U.prototype.pause_session_recording,U.prototype.resume_session_recording=U.prototype.resume_session_recording,U.prototype.get_session_recording_properties=U.prototype.get_session_recording_properties,U.prototype.get_session_replay_url=U.prototype.get_session_replay_url,U.prototype.get_tab_id=U.prototype.get_tab_id,U.prototype.DEFAULT_API_ROUTES=OC,U.prototype.__get_recorder=U.prototype.__get_recorder,re.prototype.properties=re.prototype.properties,re.prototype.update_search_keyword=re.prototype.update_search_keyword,re.prototype.update_referrer_info=re.prototype.update_referrer_info,re.prototype.get_cross_subdomain=re.prototype.get_cross_subdomain,re.prototype.clear=re.prototype.clear;var cA={},GD=function(){m.each(cA,function(n,e){e!==en&&(Ut[e]=n)}),Ut._=m},jD=function(){Ut.init=function(n,e,t){if(t)return Ut[t]||(Ut[t]=cA[t]=xp(n,e,t),Ut[t]._loaded()),Ut[t];var r=Ut;cA[en]?r=cA[en]:n&&(r=xp(n,e,en),r._loaded(),cA[en]=r),Ut=r,Ip===ND&&(V[en]=Ut),GD()}},WD=function(){function n(){n.done||(n.done=!0,LC=!0,PC=!1,m.each(cA,function(r){r._dom_loaded()}))}function e(){try{ye.documentElement.doScroll("left")}catch{setTimeout(e,1);return}n()}if(ye.addEventListener)ye.readyState==="complete"?n():ye.addEventListener("DOMContentLoaded",n,!1);else if(ye.attachEvent){ye.attachEvent("onreadystatechange",n);var t=!1;try{t=V.frameElement===null}catch{}ye.documentElement.doScroll&&t&&e()}m.register_event(V,"load",n,!0)};function qD(n){return xC=n,Ip=QC,Ut=new U,jD(),Ut.init(),WD(),Ut}function JD(n,e){e()}var Nc=qD(JD);const DC={identify:()=>{},track:()=>{},page:()=>{},reset:()=>{}};Ay(DC);function zD(n,e={}){const t=e.instanceName||`obi_${Math.random().toString(36).slice(2)}`;Nc.init(n,{debug:e.debug===!0,track_pageview:!1,persistence:"localStorage",...e.config||{}},t);const r=Nc.get_instance?Nc.get_instance(t):Nc[t];return{identify:(i,A)=>{var s;try{r.identify(i),A&&((s=r==null?void 0:r.people)!=null&&s.set)&&r.people.set(A)}catch{}},track:(i,A)=>{try{r.track(i,A||{})}catch{}},page:(i,A)=>{try{r.track("Page Viewed",{name:i,...A||{}})}catch{}},reset:()=>{try{r.reset()}catch{}}}}let Hc=null;function Se(){if(Hc)return Hc;const n={VITE_API_BASE_URL:"https://staging.coragents.ai",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1}.VITE_MIXPANEL_TOKEN;return n?(Hc=zD(n),Hc):DC}const XD=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,NC="9.23.0",uA=globalThis;function YD(n,e,t=uA){const r=t.__SENTRY__=t.__SENTRY__||{},i=r[NC]=r[NC]||{};return i[n]||(i[n]=e())}const ZD="Sentry Logger ",HC=["debug","info","warn","error","log","assert","trace"],KC={};function $D(n){if(!("console"in uA))return n();const e=uA.console,t={},r=Object.keys(KC);r.forEach(i=>{const A=KC[i];t[i]=e[i],e[i]=A});try{return n()}finally{r.forEach(i=>{e[i]=t[i]})}}function e4(){let n=!1;const e={enable:()=>{n=!0},disable:()=>{n=!1},isEnabled:()=>n};return XD?HC.forEach(t=>{e[t]=(...r)=>{n&&$D(()=>{uA.console[t](`${ZD}[${t}]:`,...r)})}}):HC.forEach(t=>{e[t]=()=>{}}),e}YD("logger",e4);const VC=1e3;function t4(){return Date.now()/VC}function n4(){const{performance:n}=uA;if(!(n!=null&&n.now))return t4;const e=Date.now()-n.now(),t=n.timeOrigin==null?e:n.timeOrigin;return()=>(t+n.now())/VC}n4();const GC=50,lA="?",jC=/\(error: (.*)\)/,WC=/captureMessage|captureException/;function r4(...n){const e=n.sort((t,r)=>t[0]-r[0]).map(t=>t[1]);return(t,r=0,i=0)=>{const A=[],s=t.split(`
123
+ `);var e="",t,r,i=0,A;for(t=r=0,i=n.length,A=0;A<i;A++){var s=n.charCodeAt(A),o=null;s<128?r++:s>127&&s<2048?o=String.fromCharCode(s>>6|192,s&63|128):o=String.fromCharCode(s>>12|224,s>>6&63|128,s&63|128),o!==null&&(r>t&&(e+=n.substring(t,r)),e+=o,t=r=A+1)}return r>t&&(e+=n.substring(t,n.length)),e},m.UUID=function(){try{return V.crypto.randomUUID()}catch{for(var n=new Array(36),e=0;e<36;e++)n[e]=Math.floor(Math.random()*16);return n[14]=4,n[19]=n[19]&=-5,n[19]=n[19]|=8,n[8]=n[13]=n[18]=n[23]="-",m.map(n,function(t){return t.toString(16)}).join("")}};var GB=["ahrefsbot","ahrefssiteaudit","amazonbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","facebookexternal","petalbot","pinterest","screaming frog","yahoo! slurp","yandex","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleweblight","mediapartners-google","storebot-google"];m.isBlockedUA=function(n){var e;for(n=n.toLowerCase(),e=0;e<GB.length;e++)if(n.indexOf(GB[e])!==-1)return!0;return!1},m.HTTPBuildQuery=function(n,e){var t,r,i=[];return m.isUndefined(e)&&(e="&"),m.each(n,function(A,s){t=encodeURIComponent(A.toString()),r=encodeURIComponent(s),i[i.length]=r+"="+t}),i.join(e)},m.getQueryParam=function(n,e){e=e.replace(/[[]/g,"\\[").replace(/[\]]/g,"\\]");var t="[\\?&]"+e+"=([^&#]*)",r=new RegExp(t),i=r.exec(n);if(i===null||i&&typeof i[1]!="string"&&i[1].length)return"";var A=i[1];try{A=decodeURIComponent(A)}catch{we.error("Skipping decoding for malformed query param: "+A)}return A.replace(/\+/g," ")},m.cookie={get:function(n){for(var e=n+"=",t=ye.cookie.split(";"),r=0;r<t.length;r++){for(var i=t[r];i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return decodeURIComponent(i.substring(e.length,i.length))}return null},parse:function(n){var e;try{e=m.JSONDecode(m.cookie.get(n))||{}}catch{}return e},set_seconds:function(n,e,t,r,i,A,s){var o="",a="",c="";if(s)o="; domain="+s;else if(r){var u=qB(ye.location.hostname);o=u?"; domain=."+u:""}if(t){var l=new Date;l.setTime(l.getTime()+t*1e3),a="; expires="+l.toGMTString()}A&&(i=!0,c="; SameSite=None"),i&&(c+="; secure"),ye.cookie=n+"="+encodeURIComponent(e)+a+"; path=/"+o+c},set:function(n,e,t,r,i,A,s){var o="",a="",c="";if(s)o="; domain="+s;else if(r){var u=qB(ye.location.hostname);o=u?"; domain=."+u:""}if(t){var l=new Date;l.setTime(l.getTime()+t*24*60*60*1e3),a="; expires="+l.toGMTString()}A&&(i=!0,c="; SameSite=None"),i&&(c+="; secure");var d=n+"="+encodeURIComponent(e)+a+"; path=/"+o+c;return ye.cookie=d,d},remove:function(n,e,t){m.cookie.set(n,"",-1,e,!1,!1,t)}};var jB=function(n){var e=!0;try{var t="__mplss_"+op(8),r="xyz";n.setItem(t,r),n.getItem(t)!==r&&(e=!1),n.removeItem(t)}catch{e=!1}return e},Ap=null,Cs=function(n,e){return Ap!==null&&!e?Ap:Ap=jB(n||V.localStorage)},sp=null,XL=function(n,e){return sp!==null&&!e?sp:sp=jB(n||V.sessionStorage)};function WB(n,e,t){var r=function(i){we.error(e+" error: "+i)};return{is_supported:function(i){var A=t(n,i);return A||we.error(e+" unsupported"),A},error:r,get:function(i){try{return n.getItem(i)}catch(A){r(A)}return null},parse:function(i){try{return m.JSONDecode(n.getItem(i))||{}}catch{}return null},set:function(i,A){try{n.setItem(i,A)}catch(s){r(s)}},remove:function(i){try{n.removeItem(i)}catch(A){r(A)}}}}m.localStorage=WB(V.localStorage,"localStorage",Cs),m.sessionStorage=WB(V.sessionStorage,"sessionStorage",XL),m.register_event=function(){var n=function(r,i,A,s,o){if(!r){we.error("No valid element provided to register_event");return}if(r.addEventListener&&!s)r.addEventListener(i,A,!!o);else{var a="on"+i,c=r[a];r[a]=e(r,A,c)}};function e(r,i,A){var s=function(o){if(o=o||t(V.event),!!o){var a=!0,c,u;return m.isFunction(A)&&(c=A(o)),u=i.call(r,o),(c===!1||u===!1)&&(a=!1),a}};return s}function t(r){return r&&(r.preventDefault=t.preventDefault,r.stopPropagation=t.stopPropagation),r}return t.preventDefault=function(){this.returnValue=!1},t.stopPropagation=function(){this.cancelBubble=!0},n}();var YL=new RegExp('^(\\w*)\\[(\\w+)([=~\\|\\^\\$\\*]?)=?"?([^\\]"]*)"?\\]$');m.dom_query=function(){function n(i){return i.all?i.all:i.getElementsByTagName("*")}var e=/[\t\r\n]/g;function t(i,A){var s=" "+A+" ";return(" "+i.className+" ").replace(e," ").indexOf(s)>=0}function r(i){if(!ye.getElementsByTagName)return[];var A=i.split(" "),s,o,a,c,u,l,d,h,f,p,g=[ye];for(l=0;l<A.length;l++){if(s=A[l].replace(/^\s+/,"").replace(/\s+$/,""),s.indexOf("#")>-1){o=s.split("#"),a=o[0];var v=o[1],y=ye.getElementById(v);if(!y||a&&y.nodeName.toLowerCase()!=a)return[];g=[y];continue}if(s.indexOf(".")>-1){o=s.split("."),a=o[0];var B=o[1];for(a||(a="*"),c=[],u=0,d=0;d<g.length;d++)for(a=="*"?f=n(g[d]):f=g[d].getElementsByTagName(a),h=0;h<f.length;h++)c[u++]=f[h];for(g=[],p=0,d=0;d<c.length;d++)c[d].className&&m.isString(c[d].className)&&t(c[d],B)&&(g[p++]=c[d]);continue}var b=s.match(YL);if(b){a=b[1];var w=b[2],_=b[3],k=b[4];for(a||(a="*"),c=[],u=0,d=0;d<g.length;d++)for(a=="*"?f=n(g[d]):f=g[d].getElementsByTagName(a),h=0;h<f.length;h++)c[u++]=f[h];g=[],p=0;var T;switch(_){case"=":T=function(x){return x.getAttribute(w)==k};break;case"~":T=function(x){return x.getAttribute(w).match(new RegExp("\\b"+k+"\\b"))};break;case"|":T=function(x){return x.getAttribute(w).match(new RegExp("^"+k+"-?"))};break;case"^":T=function(x){return x.getAttribute(w).indexOf(k)===0};break;case"$":T=function(x){return x.getAttribute(w).lastIndexOf(k)==x.getAttribute(w).length-k.length};break;case"*":T=function(x){return x.getAttribute(w).indexOf(k)>-1};break;default:T=function(x){return x.getAttribute(w)}}for(g=[],p=0,d=0;d<c.length;d++)T(c[d])&&(g[p++]=c[d]);continue}for(a=s,c=[],u=0,d=0;d<g.length;d++)for(f=g[d].getElementsByTagName(a),h=0;h<f.length;h++)c[u++]=f[h];g=c}return g}return function(i){return m.isElement(i)?[i]:m.isObject(i)&&!m.isUndefined(i.length)?i:r.call(this,i)}}();var ZL=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","utm_id","utm_source_platform","utm_campaign_id","utm_creative_format","utm_marketing_tactic"],$L=["dclid","fbclid","gclid","ko_click_id","li_fat_id","msclkid","sccid","ttclid","twclid","wbraid"];m.info={campaignParams:function(n){var e="",t={};return m.each(ZL,function(r){e=m.getQueryParam(ye.URL,r),e.length?t[r]=e:n!==void 0&&(t[r]=n)}),t},clickParams:function(){var n="",e={};return m.each($L,function(t){n=m.getQueryParam(ye.URL,t),n.length&&(e[t]=n)}),e},marketingParams:function(){return m.extend(m.info.campaignParams(),m.info.clickParams())},searchEngine:function(n){return n.search("https?://(.*)google.([^/?]*)")===0?"google":n.search("https?://(.*)bing.com")===0?"bing":n.search("https?://(.*)yahoo.com")===0?"yahoo":n.search("https?://(.*)duckduckgo.com")===0?"duckduckgo":null},searchInfo:function(n){var e=m.info.searchEngine(n),t=e!="yahoo"?"q":"p",r={};if(e!==null){r.$search_engine=e;var i=m.getQueryParam(n,t);i.length&&(r.mp_keyword=i)}return r},browser:function(n,e,t){return e=e||"",t||m.includes(n," OPR/")?m.includes(n,"Mini")?"Opera Mini":"Opera":/(BlackBerry|PlayBook|BB10)/i.test(n)?"BlackBerry":m.includes(n,"IEMobile")||m.includes(n,"WPDesktop")?"Internet Explorer Mobile":m.includes(n,"SamsungBrowser/")?"Samsung Internet":m.includes(n,"Edge")||m.includes(n,"Edg/")?"Microsoft Edge":m.includes(n,"FBIOS")?"Facebook Mobile":m.includes(n,"Whale/")?"Whale Browser":m.includes(n,"Chrome")?"Chrome":m.includes(n,"CriOS")?"Chrome iOS":m.includes(n,"UCWEB")||m.includes(n,"UCBrowser")?"UC Browser":m.includes(n,"FxiOS")?"Firefox iOS":m.includes(e,"Apple")?m.includes(n,"Mobile")?"Mobile Safari":"Safari":m.includes(n,"Android")?"Android Mobile":m.includes(n,"Konqueror")?"Konqueror":m.includes(n,"Firefox")?"Firefox":m.includes(n,"MSIE")||m.includes(n,"Trident/")?"Internet Explorer":m.includes(n,"Gecko")?"Mozilla":""},browserVersion:function(n,e,t){var r=m.info.browser(n,e,t),i={"Internet Explorer Mobile":/rv:(\d+(\.\d+)?)/,"Microsoft Edge":/Edge?\/(\d+(\.\d+)?)/,Chrome:/Chrome\/(\d+(\.\d+)?)/,"Chrome iOS":/CriOS\/(\d+(\.\d+)?)/,"UC Browser":/(UCBrowser|UCWEB)\/(\d+(\.\d+)?)/,Safari:/Version\/(\d+(\.\d+)?)/,"Mobile Safari":/Version\/(\d+(\.\d+)?)/,Opera:/(Opera|OPR)\/(\d+(\.\d+)?)/,Firefox:/Firefox\/(\d+(\.\d+)?)/,"Firefox iOS":/FxiOS\/(\d+(\.\d+)?)/,Konqueror:/Konqueror:(\d+(\.\d+)?)/,BlackBerry:/BlackBerry (\d+(\.\d+)?)/,"Android Mobile":/android\s(\d+(\.\d+)?)/,"Samsung Internet":/SamsungBrowser\/(\d+(\.\d+)?)/,"Internet Explorer":/(rv:|MSIE )(\d+(\.\d+)?)/,Mozilla:/rv:(\d+(\.\d+)?)/,"Whale Browser":/Whale\/(\d+(\.\d+)?)/},A=i[r];if(A===void 0)return null;var s=n.match(A);return s?parseFloat(s[s.length-2]):null},os:function(){var n=qn;return/Windows/i.test(n)?/Phone/.test(n)||/WPDesktop/.test(n)?"Windows Phone":"Windows":/(iPhone|iPad|iPod)/.test(n)?"iOS":/Android/.test(n)?"Android":/(BlackBerry|PlayBook|BB10)/i.test(n)?"BlackBerry":/Mac/i.test(n)?"Mac OS X":/Linux/.test(n)?"Linux":/CrOS/.test(n)?"Chrome OS":""},device:function(n){return/Windows Phone/i.test(n)||/WPDesktop/.test(n)?"Windows Phone":/iPad/.test(n)?"iPad":/iPod/.test(n)?"iPod Touch":/iPhone/.test(n)?"iPhone":/(BlackBerry|PlayBook|BB10)/i.test(n)?"BlackBerry":/Android/.test(n)?"Android":""},referringDomain:function(n){var e=n.split("/");return e.length>=3?e[2]:""},currentUrl:function(){return V.location.href},properties:function(n){return typeof n!="object"&&(n={}),m.extend(m.strip_empty_properties({$os:m.info.os(),$browser:m.info.browser(qn,Ur.vendor,Tc),$referrer:ye.referrer,$referring_domain:m.info.referringDomain(ye.referrer),$device:m.info.device(qn)}),{$current_url:m.info.currentUrl(),$browser_version:m.info.browserVersion(qn,Ur.vendor,Tc),$screen_height:DB.height,$screen_width:DB.width,mp_lib:"web",$lib_version:gn.LIB_VERSION,$insert_id:op(),time:m.timestamp()/1e3},m.strip_empty_properties(n))},people_properties:function(){return m.extend(m.strip_empty_properties({$os:m.info.os(),$browser:m.info.browser(qn,Ur.vendor,Tc)}),{$browser_version:m.info.browserVersion(qn,Ur.vendor,Tc)})},mpPageViewProperties:function(){return m.strip_empty_properties({current_page_title:ye.title,current_domain:V.location.hostname,current_url_path:V.location.pathname,current_url_protocol:V.location.protocol,current_url_search:V.location.search})}};var eD=function(n,e){var t=null,r=[];return function(i){var A=this;return r.push(i),t||(t=new be(function(s){setTimeout(function(){var o=n.apply(A,[r]);t=null,r=[],s(o)},e)})),t}},op=function(n){var e=Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10);return n?e.substring(0,n):e},tD=/[a-z0-9][a-z0-9-]*\.[a-z]+$/i,nD=/[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i,qB=function(n){var e=nD,t=n.split("."),r=t[t.length-1];(r.length>4||r==="com"||r==="org")&&(e=tD);var i=n.match(e);return i?i[0]:""},rD=function(){var n=V.navigator.onLine;return m.isUndefined(n)||n},Tr=function(){},tA=null,Ic=null;typeof JSON<"u"&&(tA=JSON.stringify,Ic=JSON.parse),tA=tA||m.JSONEncode,Ic=Ic||m.JSONDecode,m.info=m.info,m.info.browser=m.info.browser,m.info.browserVersion=m.info.browserVersion,m.info.device=m.info.device,m.info.properties=m.info.properties,m.isBlockedUA=m.isBlockedUA,m.isEmptyObject=m.isEmptyObject,m.isObject=m.isObject,m.JSONDecode=m.JSONDecode,m.JSONEncode=m.JSONEncode,m.toArray=m.toArray,m.NPO=Er;var iD="mixpanelBrowserDb",JB="mixpanelRecordingEvents",ap="mixpanelRecordingRegistry",AD=1,sD=[JB,ap],In=function(n){this.dbPromise=null,this.storeName=n};In.prototype._openDb=function(){return new be(function(n,e){var t=V.indexedDB.open(iD,AD);t.onerror=function(){e(t.error)},t.onsuccess=function(){n(t.result)},t.onupgradeneeded=function(r){var i=r.target.result;sD.forEach(function(A){i.createObjectStore(A)})}})},In.prototype.init=function(){return V.indexedDB?(this.dbPromise||(this.dbPromise=this._openDb()),this.dbPromise.then(function(n){return n instanceof V.IDBDatabase?be.resolve():be.reject(n)})):be.reject("indexedDB is not supported in this browser")},In.prototype.makeTransaction=function(n,e){var t=this.storeName,r=function(i){return new be(function(A,s){var o=i.transaction(t,n);o.oncomplete=function(){A(o)},o.onabort=o.onerror=function(){s(o.error)},e(o.objectStore(t))})};return this.dbPromise.then(r).catch((function(i){return i&&i.name==="InvalidStateError"?(this.dbPromise=this._openDb(),this.dbPromise.then(r)):be.reject(i)}).bind(this))},In.prototype.setItem=function(n,e){return this.makeTransaction("readwrite",function(t){t.put(e,n)})},In.prototype.getItem=function(n){var e;return this.makeTransaction("readonly",function(t){e=t.get(n)}).then(function(){return e.result})},In.prototype.removeItem=function(n){return this.makeTransaction("readwrite",function(e){e.delete(n)})},In.prototype.getAll=function(){var n;return this.makeTransaction("readonly",function(e){n=e.getAll()}).then(function(){return n.result})};var oD="__mp_opt_in_out_";function aD(n,e){YB(!0,n,e)}function cD(n,e){YB(!1,n,e)}function uD(n,e){return XB(n,e)==="1"}function zB(n,e){if(dD(e))return we.warn('This browser has "Do Not Track" enabled. This will prevent the Mixpanel SDK from sending any data. To ignore the "Do Not Track" browser setting, initialize the Mixpanel instance with the config "ignore_dnt: true"'),!0;var t=XB(n,e)==="0";return t&&we.warn("You are opted out of Mixpanel tracking. This will prevent the Mixpanel SDK from sending any data."),t}function Ir(n){return lp(n,function(e){return this.get_config(e)})}function Fr(n){return lp(n,function(e){return this._get_config(e)})}function nA(n){return lp(n,function(e){return this._get_config(e)})}function lD(n,e){e=e||{},cp(e).remove(up(n,e),!!e.crossSubdomainCookie,e.cookieDomain)}function cp(n){return n=n||{},n.persistenceType==="localStorage"?m.localStorage:m.cookie}function up(n,e){return e=e||{},(e.persistencePrefix||oD)+n}function XB(n,e){return cp(e).get(up(n,e))}function dD(n){if(n&&n.ignoreDnt)return!1;var e=n&&n.window||V,t=e.navigator||{},r=!1;return m.each([t.doNotTrack,t.msDoNotTrack,e.doNotTrack],function(i){m.includes([!0,1,"1","yes"],i)&&(r=!0)}),r}function YB(n,e,t){if(!m.isString(e)||!e.length){we.error("gdpr."+(n?"optIn":"optOut")+" called with an invalid token");return}t=t||{},cp(t).set(up(e,t),n?1:0,m.isNumber(t.cookieExpiration)?t.cookieExpiration:null,!!t.crossSubdomainCookie,!!t.secureCookie,!!t.crossSiteCookie,t.cookieDomain),t.track&&n&&t.track(t.trackEventName||"$opt_in",t.trackProperties,{send_immediately:!0})}function lp(n,e){return function(){var t=!1;try{var r=e.call(this,"token"),i=e.call(this,"ignore_dnt"),A=e.call(this,"opt_out_tracking_persistence_type"),s=e.call(this,"opt_out_tracking_cookie_prefix"),o=e.call(this,"window");r&&(t=zB(r,{ignoreDnt:i,persistenceType:A,persistencePrefix:s,window:o}))}catch(c){we.error("Unexpected error when checking tracking opt-out status: "+c)}if(!t)return n.apply(this,arguments);var a=arguments[arguments.length-1];typeof a=="function"&&a(0)}}var hD=ri("lock"),ZB=function(n,e){e=e||{},this.storageKey=n,this.storage=e.storage||V.localStorage,this.pollIntervalMS=e.pollIntervalMS||100,this.timeoutMS=e.timeoutMS||2e3,this.promiseImpl=e.promiseImpl||be};ZB.prototype.withLock=function(n,e){var t=this.promiseImpl;return new t(m.bind(function(r,i){var A=e||new Date().getTime()+"|"+Math.random(),s=new Date().getTime(),o=this.storageKey,a=this.pollIntervalMS,c=this.timeoutMS,u=this.storage,l=o+":X",d=o+":Y",h=o+":Z",f=function(B){if(new Date().getTime()-s>c){hD.error("Timeout waiting for mutex on "+o+"; clearing lock. ["+A+"]"),u.removeItem(h),u.removeItem(d),v();return}setTimeout(function(){try{B()}catch(b){i(b)}},a*(Math.random()+.1))},p=function(B,b){B()?b():f(function(){p(B,b)})},g=function(){var B=u.getItem(d);return B&&B!==A?!1:(u.setItem(d,A),u.getItem(d)===A?!0:(Cs(u,!0)||i(new Error("localStorage support dropped while acquiring lock")),!1))},v=function(){u.setItem(l,A),p(g,function(){if(u.getItem(l)===A){y();return}f(function(){if(u.getItem(d)!==A){v();return}p(function(){return!u.getItem(h)},y)})})},y=function(){u.setItem(h,"1");var B=function(){u.removeItem(h),u.getItem(d)===A&&u.removeItem(d),u.getItem(l)===A&&u.removeItem(l)};n().then(function(b){B(),r(b)}).catch(function(b){B(),i(b)})};try{if(Cs(u,!0))v();else throw new Error("localStorage support check failed")}catch(B){i(B)}},this))};var _s=function(n){this.storage=n||V.localStorage};_s.prototype.init=function(){return be.resolve()},_s.prototype.setItem=function(n,e){return new be(m.bind(function(t,r){try{this.storage.setItem(n,tA(e))}catch(i){r(i)}t()},this))},_s.prototype.getItem=function(n){return new be(m.bind(function(e,t){var r;try{r=Ic(this.storage.getItem(n))}catch(i){t(i)}e(r)},this))},_s.prototype.removeItem=function(n){return new be(m.bind(function(e,t){try{this.storage.removeItem(n)}catch(r){t(r)}e()},this))};var $B=ri("batch"),Fn=function(n,e){e=e||{},this.storageKey=n,this.usePersistence=e.usePersistence,this.usePersistence&&(this.queueStorage=e.queueStorage||new _s,this.lock=new ZB(n,{storage:e.sharedLockStorage||V.localStorage,timeoutMS:e.sharedLockTimeoutMS})),this.reportError=e.errorReporter||m.bind($B.error,$B),this.pid=e.pid||null,this.memQueue=[],this.initialized=!1,e.enqueueThrottleMs?this.enqueuePersisted=eD(m.bind(this._enqueuePersisted,this),e.enqueueThrottleMs):this.enqueuePersisted=m.bind(function(t){return this._enqueuePersisted([t])},this)};Fn.prototype.ensureInit=function(){return this.initialized?be.resolve():this.queueStorage.init().then(m.bind(function(){this.initialized=!0},this)).catch(m.bind(function(n){this.reportError("Error initializing queue persistence. Disabling persistence",n),this.initialized=!0,this.usePersistence=!1},this))},Fn.prototype.enqueue=function(n,e){var t={id:op(),flushAfter:new Date().getTime()+e*2,payload:n};return this.usePersistence?this.enqueuePersisted(t):(this.memQueue.push(t),be.resolve(!0))},Fn.prototype._enqueuePersisted=function(n){var e=m.bind(function(){return this.ensureInit().then(m.bind(function(){return this.readFromStorage()},this)).then(m.bind(function(t){return this.saveToStorage(t.concat(n))},this)).then(m.bind(function(t){return t&&(this.memQueue=this.memQueue.concat(n)),t},this)).catch(m.bind(function(t){return this.reportError("Error enqueueing items",t,n),!1},this))},this);return this.lock.withLock(e,this.pid).catch(m.bind(function(t){return this.reportError("Error acquiring storage lock",t),!1},this))},Fn.prototype.fillBatch=function(n){var e=this.memQueue.slice(0,n);return this.usePersistence&&e.length<n?this.ensureInit().then(m.bind(function(){return this.readFromStorage()},this)).then(m.bind(function(t){if(t.length){var r={};m.each(e,function(s){r[s.id]=!0});for(var i=0;i<t.length;i++){var A=t[i];if(new Date().getTime()>A.flushAfter&&!r[A.id]&&(A.orphaned=!0,e.push(A),e.length>=n))break}}return e},this)):be.resolve(e)};var eC=function(n,e){var t=[];return m.each(n,function(r){r.id&&!e[r.id]&&t.push(r)}),t};Fn.prototype.removeItemsByID=function(n){var e={};if(m.each(n,function(r){e[r]=!0}),this.memQueue=eC(this.memQueue,e),this.usePersistence){var t=m.bind(function(){return this.ensureInit().then(m.bind(function(){return this.readFromStorage()},this)).then(m.bind(function(r){return r=eC(r,e),this.saveToStorage(r)},this)).then(m.bind(function(){return this.readFromStorage()},this)).then(m.bind(function(r){for(var i=0;i<r.length;i++){var A=r[i];if(A.id&&e[A.id])throw new Error("Item not removed from storage")}return!0},this)).catch(m.bind(function(r){return this.reportError("Error removing items",r,n),!1},this))},this);return this.lock.withLock(t,this.pid).catch(m.bind(function(r){return this.reportError("Error acquiring storage lock",r),Cs(this.lock.storage,!0)?!1:t().then(m.bind(function(i){return i||this.queueStorage.removeItem(this.storageKey).then(function(){return i})},this)).catch(m.bind(function(i){return this.reportError("Error clearing queue",i),!1},this))},this))}else return be.resolve(!0)};var tC=function(n,e){var t=[];return m.each(n,function(r){var i=r.id;if(i in e){var A=e[i];A!==null&&(r.payload=A,t.push(r))}else t.push(r)}),t};Fn.prototype.updatePayloads=function(n){return this.memQueue=tC(this.memQueue,n),this.usePersistence?this.lock.withLock(m.bind(function(){return this.ensureInit().then(m.bind(function(){return this.readFromStorage()},this)).then(m.bind(function(e){return e=tC(e,n),this.saveToStorage(e)},this)).catch(m.bind(function(e){return this.reportError("Error updating items",n,e),!1},this))},this),this.pid).catch(m.bind(function(e){return this.reportError("Error acquiring storage lock",e),!1},this)):be.resolve(!0)},Fn.prototype.readFromStorage=function(){return this.ensureInit().then(m.bind(function(){return this.queueStorage.getItem(this.storageKey)},this)).then(m.bind(function(n){return n&&(m.isArray(n)||(this.reportError("Invalid storage entry:",n),n=null)),n||[]},this)).catch(m.bind(function(n){return this.reportError("Error retrieving queue",n),[]},this))},Fn.prototype.saveToStorage=function(n){return this.ensureInit().then(m.bind(function(){return this.queueStorage.setItem(this.storageKey,n)},this)).then(function(){return!0}).catch(m.bind(function(e){return this.reportError("Error saving queue",e),!1},this))},Fn.prototype.clear=function(){return this.memQueue=[],this.usePersistence?this.ensureInit().then(m.bind(function(){return this.queueStorage.removeItem(this.storageKey)},this)):be.resolve()};var pD=10*60*1e3,Ss=ri("batch"),$t=function(n,e){this.errorReporter=e.errorReporter,this.queue=new Fn(n,{errorReporter:m.bind(this.reportError,this),queueStorage:e.queueStorage,sharedLockStorage:e.sharedLockStorage,sharedLockTimeoutMS:e.sharedLockTimeoutMS,usePersistence:e.usePersistence,enqueueThrottleMs:e.enqueueThrottleMs}),this.libConfig=e.libConfig,this.sendRequest=e.sendRequestFunc,this.beforeSendHook=e.beforeSendHook,this.stopAllBatching=e.stopAllBatchingFunc,this.batchSize=this.libConfig.batch_size,this.flushInterval=this.libConfig.batch_flush_interval_ms,this.stopped=!this.libConfig.batch_autostart,this.consecutiveRemovalFailures=0,this.itemIdsSentSuccessfully={},this.flushOnlyOnInterval=e.flushOnlyOnInterval||!1,this._flushPromise=null};$t.prototype.enqueue=function(n){return this.queue.enqueue(n,this.flushInterval)},$t.prototype.start=function(){return this.stopped=!1,this.consecutiveRemovalFailures=0,this.flush()},$t.prototype.stop=function(){this.stopped=!0,this.timeoutID&&(clearTimeout(this.timeoutID),this.timeoutID=null)},$t.prototype.clear=function(){return this.queue.clear()},$t.prototype.resetBatchSize=function(){this.batchSize=this.libConfig.batch_size},$t.prototype.resetFlush=function(){this.scheduleFlush(this.libConfig.batch_flush_interval_ms)},$t.prototype.scheduleFlush=function(n){this.flushInterval=n,this.stopped||(this.timeoutID=setTimeout(m.bind(function(){this.stopped||(this._flushPromise=this.flush())},this),this.flushInterval))},$t.prototype.sendRequestPromise=function(n,e){return new be(m.bind(function(t){this.sendRequest(n,e,t)},this))},$t.prototype.flush=function(n){if(this.requestInProgress)return Ss.log("Flush: Request already in progress"),be.resolve();this.requestInProgress=!0,n=n||{};var e=this.libConfig.batch_request_timeout_ms,t=new Date().getTime(),r=this.batchSize;return this.queue.fillBatch(r).then(m.bind(function(i){var A=i.length===r,s=[],o={};if(m.each(i,function(l){var d=l.payload;if(this.beforeSendHook&&!l.orphaned&&(d=this.beforeSendHook(d)),d){d.event&&d.properties&&(d.properties=m.extend({},d.properties,{mp_sent_by_lib_version:gn.LIB_VERSION}));var h=!0,f=l.id;f?(this.itemIdsSentSuccessfully[f]||0)>5&&(this.reportError("[dupe] item ID sent too many times, not sending",{item:l,batchSize:i.length,timesSent:this.itemIdsSentSuccessfully[f]}),h=!1):this.reportError("[dupe] found item with no ID",{item:l}),h&&s.push(d)}o[l.id]=d},this),s.length<1)return this.requestInProgress=!1,this.resetFlush(),be.resolve();var a=m.bind(function(){return this.queue.removeItemsByID(m.map(i,function(l){return l.id})).then(m.bind(function(l){return m.each(i,m.bind(function(d){var h=d.id;h?(this.itemIdsSentSuccessfully[h]=this.itemIdsSentSuccessfully[h]||0,this.itemIdsSentSuccessfully[h]++,this.itemIdsSentSuccessfully[h]>5&&this.reportError("[dupe] item ID sent too many times",{item:d,batchSize:i.length,timesSent:this.itemIdsSentSuccessfully[h]})):this.reportError("[dupe] found item with no ID while removing",{item:d})},this)),l?(this.consecutiveRemovalFailures=0,this.flushOnlyOnInterval&&!A?(this.resetFlush(),be.resolve()):this.flush()):(++this.consecutiveRemovalFailures>5?(this.reportError("Too many queue failures; disabling batching system."),this.stopAllBatching()):this.resetFlush(),be.resolve())},this))},this),c=m.bind(function(l){this.requestInProgress=!1;try{if(n.unloading)return this.queue.updatePayloads(o);if(m.isObject(l)&&l.error==="timeout"&&new Date().getTime()-t>=e)return this.reportError("Network timeout; retrying"),this.flush();if(m.isObject(l)&&(l.httpStatusCode>=500||l.httpStatusCode===429||l.httpStatusCode<=0&&!rD()||l.error==="timeout")){var d=this.flushInterval*2;return l.retryAfter&&(d=parseInt(l.retryAfter,10)*1e3||d),d=Math.min(pD,d),this.reportError("Error; retry in "+d+" ms"),this.scheduleFlush(d),be.resolve()}else if(m.isObject(l)&&l.httpStatusCode===413)if(i.length>1){var h=Math.max(1,Math.floor(r/2));return this.batchSize=Math.min(this.batchSize,h,i.length-1),this.reportError("413 response; reducing batch size to "+this.batchSize),this.resetFlush(),be.resolve()}else return this.reportError("Single-event request too large; dropping",i),this.resetBatchSize(),a();else return a()}catch(f){this.reportError("Error handling API response",f),this.resetFlush()}},this),u={method:"POST",verbose:!0,ignore_json_errors:!0,timeout_ms:e};return n.unloading&&(u.transport="sendBeacon"),Ss.log("MIXPANEL REQUEST:",s),this.sendRequestPromise(s,u).then(c)},this)).catch(m.bind(function(i){this.reportError("Error flushing request queue",i),this.resetFlush()},this))},$t.prototype.reportError=function(n,e){if(Ss.error.apply(Ss.error,arguments),this.errorReporter)try{e instanceof Error||(e=new Error(n)),this.errorReporter(n,e)}catch(t){Ss.error(t)}};var dp=function(n){var e=Date.now();return!n||e>n.maxExpires||e>n.idleExpires},fD=250,rA=ri("recorder"),nC=V.CompressionStream,gD={batch_size:1e3,batch_flush_interval_ms:10*1e3,batch_request_timeout_ms:90*1e3,batch_autostart:!0},mD=new Set([X.MouseMove,X.MouseInteraction,X.Scroll,X.ViewportResize,X.Input,X.TouchMove,X.MediaInteraction,X.Drag,X.Selection]);function vD(n){return n.type===le.IncrementalSnapshot&&mD.has(n.data.source)}var Bt=function(n){this._mixpanel=n.mixpanelInstance,this._onIdleTimeout=n.onIdleTimeout||Tr,this._onMaxLengthReached=n.onMaxLengthReached||Tr,this._onBatchSent=n.onBatchSent||Tr,this._rrwebRecord=n.rrwebRecord||null,this._stopRecording=null,this.replayId=n.replayId,this.batchStartUrl=n.batchStartUrl||null,this.replayStartUrl=n.replayStartUrl||null,this.idleExpires=n.idleExpires||null,this.maxExpires=n.maxExpires||null,this.replayStartTime=n.replayStartTime||null,this.seqNo=n.seqNo||0,this.idleTimeoutId=null,this.maxTimeoutId=null,this.recordMaxMs=bs,this.recordMinMs=0;var e=Cs(n.sharedLockStorage,!0);this.batcherKey="__mprec_"+this.getConfig("name")+"_"+this.getConfig("token")+"_"+this.replayId,this.queueStorage=new In(JB),this.batcher=new $t(this.batcherKey,{errorReporter:this.reportError.bind(this),flushOnlyOnInterval:!0,libConfig:gD,sendRequestFunc:this.flushEventsWithOptOut.bind(this),queueStorage:this.queueStorage,sharedLockStorage:n.sharedLockStorage,usePersistence:e,stopAllBatchingFunc:this.stopRecording.bind(this),enqueueThrottleMs:fD,sharedLockTimeoutMS:10*1e3})};Bt.prototype.getUserIdInfo=function(){if(this.finalFlushUserIdInfo)return this.finalFlushUserIdInfo;var n={distinct_id:String(this._mixpanel.get_distinct_id())},e=this._mixpanel.get_property("$device_id");e&&(n.$device_id=e);var t=this._mixpanel.get_property("$user_id");return t&&(n.$user_id=t),n},Bt.prototype.unloadPersistedData=function(){return this.batcher.stop(),this.batcher.flush().then((function(){return this.queueStorage.removeItem(this.batcherKey)}).bind(this))},Bt.prototype.getConfig=function(n){return this._mixpanel.get_config(n)},Bt.prototype.get_config=function(n){return this.getConfig(n)},Bt.prototype.startRecording=function(n){if(this._rrwebRecord===null){this.reportError("rrweb record function not provided. ");return}if(this._stopRecording!==null){rA.log("Recording already in progress, skipping startRecording.");return}this.recordMaxMs=this.getConfig("record_max_ms"),this.recordMaxMs>bs&&(this.recordMaxMs=bs,rA.critical("record_max_ms cannot be greater than "+bs+"ms. Capping value.")),this.maxExpires||(this.maxExpires=new Date().getTime()+this.recordMaxMs),this.recordMinMs=this.getConfig("record_min_ms"),this.recordMinMs>ep&&(this.recordMinMs=ep,rA.critical("record_min_ms cannot be greater than "+ep+"ms. Capping value.")),this.replayStartTime||(this.replayStartTime=new Date().getTime(),this.batchStartUrl=m.info.currentUrl(),this.replayStartUrl=m.info.currentUrl()),n||this.recordMinMs>0?this.batcher.stop():this.batcher.start();var e=(function(){clearTimeout(this.idleTimeoutId);var i=this.getConfig("record_idle_timeout_ms");this.idleTimeoutId=setTimeout(this._onIdleTimeout,i),this.idleExpires=new Date().getTime()+i}).bind(this);e();var t=this.getConfig("record_block_selector");(t===""||t===null)&&(t=void 0);try{this._stopRecording=this._rrwebRecord({emit:(function(i){if(this.idleExpires&&this.idleExpires<i.timestamp){this._onIdleTimeout();return}vD(i)&&(this.batcher.stopped&&new Date().getTime()-this.replayStartTime>=this.recordMinMs&&this.batcher.start(),e()),this.__enqueuePromise=this.batcher.enqueue(i)}).bind(this),blockClass:this.getConfig("record_block_class"),blockSelector:t,collectFonts:this.getConfig("record_collect_fonts"),dataURLOptions:{type:"image/webp",quality:.6},maskAllInputs:!0,maskTextClass:this.getConfig("record_mask_text_class"),maskTextSelector:this.getConfig("record_mask_text_selector"),recordCanvas:this.getConfig("record_canvas"),sampling:{canvas:15}})}catch(i){this.reportError("Unexpected error when starting rrweb recording.",i)}if(typeof this._stopRecording!="function"){this.reportError("rrweb failed to start, skipping this recording."),this._stopRecording=null,this.stopRecording();return}var r=this.maxExpires-new Date().getTime();this.maxTimeoutId=setTimeout(this._onMaxLengthReached.bind(this),r)},Bt.prototype.stopRecording=function(n){if(this.finalFlushUserIdInfo=this.getUserIdInfo(),!this.isRrwebStopped()){try{this._stopRecording()}catch(t){this.reportError("Error with rrweb stopRecording",t)}this._stopRecording=null}var e;return this.batcher.stopped?e=this.batcher.clear():n||(e=this.batcher.flush()),this.batcher.stop(),clearTimeout(this.idleTimeoutId),clearTimeout(this.maxTimeoutId),e},Bt.prototype.isRrwebStopped=function(){return this._stopRecording===null},Bt.prototype.flushEventsWithOptOut=function(n,e,t){var r=(function(i){i===0&&(this.stopRecording(),t({error:"Tracking has been opted out, stopping recording."}))}).bind(this);this._flushEvents(n,e,t,r)},Bt.prototype.serialize=function(){var n;try{n=this._mixpanel.get_tab_id()}catch(e){this.reportError("Error getting tab ID for serialization ",e),n=null}return{replayId:this.replayId,seqNo:this.seqNo,replayStartTime:this.replayStartTime,batchStartUrl:this.batchStartUrl,replayStartUrl:this.replayStartUrl,idleExpires:this.idleExpires,maxExpires:this.maxExpires,tabId:n}},Bt.deserialize=function(n,e){var t=new Bt(m.extend({},e,{replayId:n.replayId,batchStartUrl:n.batchStartUrl,replayStartUrl:n.replayStartUrl,idleExpires:n.idleExpires,maxExpires:n.maxExpires,replayStartTime:n.replayStartTime,seqNo:n.seqNo,sharedLockStorage:e.sharedLockStorage}));return t},Bt.prototype._sendRequest=function(n,e,t,r){var i=(function(s,o){s.status===200&&this.replayId===n&&(this.seqNo++,this.batchStartUrl=m.info.currentUrl()),this._onBatchSent(),r({status:0,httpStatusCode:s.status,responseBody:o,retryAfter:s.headers.get("Retry-After")})}).bind(this),A=this._mixpanel.get_api_host&&this._mixpanel.get_api_host("record")||this.getConfig("api_host");V.fetch(A+"/"+this.getConfig("api_routes").record+"?"+new URLSearchParams(e),{method:"POST",headers:{Authorization:"Basic "+btoa(this.getConfig("token")+":"),"Content-Type":"application/octet-stream"},body:t}).then(function(s){s.json().then(function(o){i(s,o)}).catch(function(o){r({error:o})})}).catch(function(s){r({error:s,httpStatusCode:0})})},Bt.prototype._flushEvents=Ir(function(n,e,t){var r=n.length;if(r>0){for(var i=this.replayId,A=1/0,s=-1/0,o=!1,a=0;a<r;a++)A=Math.min(A,n[a].timestamp),s=Math.max(s,n[a].timestamp),n[a].type===le.FullSnapshot&&(o=!0);if(this.seqNo===0){if(!o){t({error:"First batch does not contain a full snapshot. Aborting recording."}),this.stopRecording(!0);return}this.replayStartTime=A}else this.replayStartTime||(this.reportError("Replay start time not set but seqNo is not 0. Using current batch start time as a fallback."),this.replayStartTime=A);var c=s-this.replayStartTime,u={$current_url:this.batchStartUrl,$lib_version:gn.LIB_VERSION,batch_start_time:A/1e3,mp_lib:"web",replay_id:i,replay_length_ms:c,replay_start_time:this.replayStartTime/1e3,replay_start_url:this.replayStartUrl,seq:this.seqNo},l=JSON.stringify(n);if(Object.assign(u,this.getUserIdInfo()),nC){var d=new Blob([l],{type:"application/json"}).stream(),h=d.pipeThrough(new nC("gzip"));new Response(h).blob().then((function(f){u.format="gzip",this._sendRequest(i,u,f,t)}).bind(this))}else u.format="body",this._sendRequest(i,u,l,t)}}),Bt.prototype.reportError=function(n,e){rA.error.apply(rA.error,arguments);try{!e&&!(n instanceof Error)&&(n=new Error(n)),this.getConfig("error_reporter")(n,e)}catch(t){rA.error(t)}};var iA=function(n){this.idb=new In(ap),this.errorReporter=n.errorReporter,this.mixpanelInstance=n.mixpanelInstance,this.sharedLockStorage=n.sharedLockStorage};iA.prototype.handleError=function(n){this.errorReporter("IndexedDB error: ",n)},iA.prototype.setActiveRecording=function(n){var e=n.tabId;return e?this.idb.init().then((function(){return this.idb.setItem(e,n)}).bind(this)).catch(this.handleError.bind(this)):(console.warn("No tab ID is set, cannot persist recording metadata."),be.resolve())},iA.prototype.getActiveRecording=function(){return this.idb.init().then((function(){return this.idb.getItem(this.mixpanelInstance.get_tab_id())}).bind(this)).then((function(n){return dp(n)?null:n}).bind(this)).catch(this.handleError.bind(this))},iA.prototype.clearActiveRecording=function(){return this.getActiveRecording().then((function(n){if(n)return n.maxExpires=0,this.setActiveRecording(n)}).bind(this)).catch(this.handleError.bind(this))},iA.prototype.flushInactiveRecordings=function(){return this.idb.init().then((function(){return this.idb.getAll()}).bind(this)).then((function(n){var e=n.filter(function(t){return dp(t)}).map((function(t){var r=Bt.deserialize(t,{mixpanelInstance:this.mixpanelInstance,sharedLockStorage:this.sharedLockStorage});return r.unloadPersistedData().then((function(){return this.idb.removeItem(t.tabId)}).bind(this)).catch(this.handleError.bind(this))}).bind(this));return be.all(e)}).bind(this)).catch(this.handleError.bind(this))};var ks=ri("recorder"),Jn=function(n,e,t){this.mixpanelInstance=n,this.rrwebRecord=e||Sr,this.sharedLockStorage=t,this.recordingRegistry=new iA({mixpanelInstance:this.mixpanelInstance,errorReporter:ks.error,sharedLockStorage:t}),this._flushInactivePromise=this.recordingRegistry.flushInactiveRecordings(),this.activeRecording=null,this.stopRecordingInProgress=!1};Jn.prototype.startRecording=function(n){if(n=n||{},this.activeRecording&&!this.activeRecording.isRrwebStopped()){ks.log("Recording already in progress, skipping startRecording.");return}var e=(function(){ks.log("Idle timeout reached, restarting recording."),this.resetRecording()}).bind(this),t=(function(){ks.log("Max recording length reached, stopping recording."),this.resetRecording()}).bind(this),r=(function(){this.recordingRegistry.setActiveRecording(this.activeRecording.serialize()),this.__flushPromise=this.activeRecording.batcher._flushPromise}).bind(this),i={mixpanelInstance:this.mixpanelInstance,onBatchSent:r,onIdleTimeout:e,onMaxLengthReached:t,replayId:m.UUID(),rrwebRecord:this.rrwebRecord,sharedLockStorage:this.sharedLockStorage};return n.activeSerializedRecording?this.activeRecording=Bt.deserialize(n.activeSerializedRecording,i):this.activeRecording=new Bt(i),this.activeRecording.startRecording(n.shouldStopBatcher),this.recordingRegistry.setActiveRecording(this.activeRecording.serialize())},Jn.prototype.stopRecording=function(){return this.stopRecordingInProgress=!0,this._stopCurrentRecording(!1,!0).then((function(){return this.recordingRegistry.clearActiveRecording()}).bind(this)).then((function(){this.stopRecordingInProgress=!1}).bind(this))},Jn.prototype.pauseRecording=function(){return this._stopCurrentRecording(!1)},Jn.prototype._stopCurrentRecording=function(n,e){if(this.activeRecording){var t=this.activeRecording.stopRecording(n);return e&&(this.activeRecording=null),t}return be.resolve()},Jn.prototype.resumeRecording=function(n){return this.activeRecording&&this.activeRecording.isRrwebStopped()?(this.activeRecording.startRecording(!1),be.resolve(null)):this.recordingRegistry.getActiveRecording().then((function(e){return e&&!this.stopRecordingInProgress?this.startRecording({activeSerializedRecording:e}):n?this.startRecording({shouldStopBatcher:!1}):(ks.log("No resumable recording found."),null)}).bind(this))},Jn.prototype.resetRecording=function(){this.stopRecording(),this.startRecording({shouldStopBatcher:!0})},Jn.prototype.getActiveReplayId=function(){return this.activeRecording&&!this.activeRecording.isRrwebStopped()?this.activeRecording.replayId:null},Object.defineProperty(Jn.prototype,"replayId",{get:function(){return this.getActiveReplayId()}}),V.__mp_recorder=Jn;var Fc="change",ii="click",rC="hashchange",AA="mp_locationchange",iC="popstate",AC="scrollend",hp="submit",yD=["clientX","clientY","offsetX","offsetY","pageX","pageY","screenX","screenY","x","y"],sC=["mp-include"],pp=["mp-no-track"],oC=pp.concat(["mp-sensitive"]),wD=["aria-label","aria-labelledby","aria-describedby","href","name","role","title","type"],xt=ri("autocapture");function fp(n){for(var e={},t=aC(n).split(" "),r=0;r<t.length;r++){var i=t[r];i&&(e[i]=!0)}return e}function aC(n){switch(typeof n.className){case"string":return n.className;case"object":return n.className.baseVal||n.getAttribute("class")||"";default:return""}}function bD(n){if(n.previousElementSibling)return n.previousElementSibling;do n=n.previousSibling;while(n&&!lC(n));return n}function cC(n,e,t,r,i,A){var s={$classes:aC(n).split(" "),$tag_name:n.tagName.toLowerCase()},o=n.id;o&&(s.$id=o),vp(n,e,i,A)&&m.each(wD.concat(r),function(l){if(n.hasAttribute(l)&&!t[l]){var d=n.getAttribute(l);xc(d)&&(s["$attr-"+l]=d)}});for(var a=1,c=1,u=n;u=bD(u);)a++,u.tagName===n.tagName&&c++;return s.$nth_child=a,s.$nth_of_type=c,s}function BD(n,e){var t=e.allowElementCallback,r=e.allowSelectors||[],i=e.blockAttrs||[],A=e.blockElementCallback,s=e.blockSelectors||[],o=e.captureTextContent||!1,a=e.captureExtraAttrs||[],c=e.capturedForHeatMap||!1,u={};m.each(i,function(w){u[w]=!0});var l=null,d=typeof n.target>"u"?n.srcElement:n.target;if(dC(d)&&(d=d.parentNode),SD(d,n)&&gp(d,n,t,r)&&!mp(d,n,A,s)){for(var h=[d],f=d;f.parentNode&&!xn(f,"body");)h.push(f.parentNode),f=f.parentNode;var p=[],g,v=!1;if(m.each(h,function(w){var _=vp(w,n,t,r);!u.href&&w.tagName.toLowerCase()==="a"&&(g=w.getAttribute("href"),g=_&&xc(g)&&g),mp(w,n,A,s)&&(v=!0),p.push(cC(w,n,u,a,t,r))},this),!v){var y=ye.documentElement;if(l={$event_type:n.type,$host:V.location.host,$pathname:V.location.pathname,$elements:p,$el_attr__href:g,$viewportHeight:Math.max(y.clientHeight,V.innerHeight||0),$viewportWidth:Math.max(y.clientWidth,V.innerWidth||0),$pageHeight:ye.body.offsetHeight||0,$pageWidth:ye.body.offsetWidth||0},m.each(a,function(w){if(!u[w]&&d.hasAttribute(w)){var _=d.getAttribute(w);xc(_)&&(l["$el_attr__"+w]=_)}}),o&&(B=uC(d,n,t,r),B&&B.length&&(l.$el_text=B)),n.type===ii&&(m.each(yD,function(w){w in n&&(l["$"+w]=n[w])}),c&&(l.$captured_for_heatmap=!0),d=CD(n)),o){var B=uC(d,n,t,r);B&&B.length&&(l.$el_text=B)}if(d){if(!gp(d,n,t,r)||mp(d,n,A,s))return null;var b=cC(d,n,u,a,t,r);l.$target=b,l.$el_classes=b.$classes,m.extend(l,m.strip_empty_properties({$el_id:b.$id,$el_tag_name:b.$tag_name}))}}}return l}function uC(n,e,t,r){var i="";return vp(n,e,t,r)&&n.childNodes&&n.childNodes.length&&m.each(n.childNodes,function(A){dC(A)&&A.textContent&&(i+=m.trim(A.textContent).split(/(\s+)/).filter(xc).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),m.trim(i)}function CD(n){for(var e=n.target,t=n.composedPath(),r=0;r<t.length;r++){var i=t[r];if(xn(i,"a")||xn(i,"button")||xn(i,"input")||xn(i,"select")||i.getAttribute&&i.getAttribute("role")==="button"){e=i;break}if(i===e)break}return e}function gp(n,e,t,r){if(t)try{if(!t(n,e))return!1}catch(s){return xt.critical("Error while checking element in allowElementCallback",s),!1}if(!r.length)return!0;for(var i=0;i<r.length;i++){var A=r[i];try{if(n.matches(A))return!0}catch(s){xt.critical("Error while checking selector: "+A,s)}}return!1}function mp(n,e,t,r){var i;if(t)try{if(t(n,e))return!0}catch(o){return xt.critical("Error while checking element in blockElementCallback",o),!0}if(r&&r.length)for(i=0;i<r.length;i++){var A=r[i];try{if(n.matches(A))return!0}catch(o){xt.critical("Error while checking selector: "+A,o)}}var s=fp(n);for(i=0;i<pp.length;i++)if(s[pp[i]])return!0;return!1}function lC(n){return n&&n.nodeType===1}function xn(n,e){return n&&n.tagName&&n.tagName.toLowerCase()===e.toLowerCase()}function dC(n){return n&&n.nodeType===3}function _D(){try{var n=ye.createElement("div");return!!n.matches}catch{return!1}}function SD(n,e){if(!n||xn(n,"html")||!lC(n))return!1;var t=n.tagName.toLowerCase();switch(t){case"form":return e.type===hp;case"input":return["button","submit"].indexOf(n.getAttribute("type"))===-1?e.type===Fc:e.type===ii;case"select":case"textarea":return e.type===Fc;default:return e.type===ii}}function vp(n,e,t,r){var i;if(!gp(n,e,t,r))return!1;for(var A=n;A.parentNode&&!xn(A,"body");A=A.parentNode){var s=fp(A);for(i=0;i<oC.length;i++)if(s[oC[i]])return!1}var o=fp(n);for(i=0;i<sC.length;i++)if(o[sC[i]])return!0;if(xn(n,"input")||xn(n,"select")||xn(n,"textarea")||n.getAttribute("contenteditable")==="true")return!1;var a=n.type||"";if(typeof a=="string")switch(a.toLowerCase()){case"hidden":return!1;case"password":return!1}var c=n.name||n.id||"";if(typeof c=="string"){var u=/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i;if(u.test(c.replace(/[^a-zA-Z0-9]/g,"")))return!1}return!0}function xc(n){if(n===null||m.isUndefined(n))return!1;if(typeof n=="string"){n=m.trim(n);var e=/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/;if(e.test((n||"").replace(/[- ]/g,"")))return!1;var t=/(^\d{3}-?\d{2}-?\d{4}$)/;if(t.test(n))return!1}return!0}var kD=30,ED=1e3,UD=4;function hC(){this.clicks=[]}hC.prototype.isRageClick=function(n,e,t){t=t||{};var r=t.threshold_px||kD,i=t.timeout_ms||ED,A=t.click_count||UD,s=Date.now(),o=this.clicks[this.clicks.length-1];if(o&&s-o.timestamp<i&&Math.sqrt(Math.pow(n-o.x,2)+Math.pow(e-o.y,2))<r){if(this.clicks.push({x:n,y:e,timestamp:s}),this.clicks.length>=A)return this.clicks=[],!0}else this.clicks=[{x:n,y:e,timestamp:s}];return!1};var pC="autocapture",TD="track_pageview",fC="full-url",ID="url-with-path-and-query-string",FD="url-with-path",xD="allow_element_callback",gC="allow_selectors",mC="allow_url_regexes",vC="block_attrs",yC="block_element_callback",wC="block_selectors",bC="block_url_regexes",BC="capture_extra_attrs",CC="capture_text_content",_C="scroll_capture_all",SC="scroll_depth_percent_checkpoints",Qc="click",yp="input",kC="pageview",EC="rage_click",wp="scroll",bp="submit",gt={};gt[gC]=[],gt[mC]=[],gt[vC]=[],gt[yC]=null,gt[wC]=[],gt[bC]=[],gt[BC]=[],gt[CC]=!1,gt[_C]=!1,gt[SC]=[25,50,75,100],gt[Qc]=!0,gt[yp]=!0,gt[kC]=fC,gt[EC]=!0,gt[wp]=!0,gt[bp]=!0;var Rc={$mp_autocapture:!0},UC="$mp_click",QD="$mp_input_change",TC="$mp_rage_click",RD="$mp_scroll",PD="$mp_submit",Qt=function(n){this.mp=n};Qt.prototype.init=function(){if(!_D()){xt.critical("Autocapture unavailable: missing required DOM APIs");return}this.initPageviewTracking(),this.initClickTracking(),this.initInputTracking(),this.initScrollTracking(),this.initSubmitTracking(),this.initRageClickTracking()},Qt.prototype.getFullConfig=function(){var n=this.mp.get_config(pC);return n?m.isObject(n)?m.extend({},gt,n):gt:{}},Qt.prototype.getConfig=function(n){return this.getFullConfig()[n]},Qt.prototype.currentUrlBlocked=function(){var n,e=m.info.currentUrl(),t=this.getConfig(mC)||[];if(t.length){var r=!1;for(n=0;n<t.length;n++){var i=t[n];try{if(e.match(i)){r=!0;break}}catch(s){return xt.critical("Error while checking block URL regex: "+i,s),!0}}if(!r)return!0}var A=this.getConfig(bC)||[];if(!A||!A.length)return!1;for(n=0;n<A.length;n++)try{if(e.match(A[n]))return!0}catch(s){return xt.critical("Error while checking block URL regex: "+A[n],s),!0}return!1},Qt.prototype.pageviewTrackingConfig=function(){return this.mp.get_config(pC)?this.getConfig(kC):this.mp.get_config(TD)},Qt.prototype.trackDomEvent=function(n,e){if(!this.currentUrlBlocked()){var t=this.mp.is_recording_heatmap_data()&&(e===UC&&!this.getConfig(Qc)||e===TC&&!this._getRageClickConfig()),r=BD(n,{allowElementCallback:this.getConfig(xD),allowSelectors:this.getConfig(gC),blockAttrs:this.getConfig(vC),blockElementCallback:this.getConfig(yC),blockSelectors:this.getConfig(wC),captureExtraAttrs:this.getConfig(BC),captureTextContent:this.getConfig(CC),capturedForHeatMap:t});r&&(m.extend(r,Rc),this.mp.track(e,r))}},Qt.prototype._getRageClickConfig=function(){var n=this.getConfig(EC);return n?n===!0?{}:typeof n=="object"?n:{}:null},Qt.prototype.initClickTracking=function(){V.removeEventListener(ii,this.listenerClick),!(!this.getConfig(Qc)&&!this.mp.get_config("record_heatmap_data"))&&(xt.log("Initializing click tracking"),this.listenerClick=V.addEventListener(ii,(function(n){!this.getConfig(Qc)&&!this.mp.is_recording_heatmap_data()||this.trackDomEvent(n,UC)}).bind(this)))},Qt.prototype.initInputTracking=function(){V.removeEventListener(Fc,this.listenerChange),this.getConfig(yp)&&(xt.log("Initializing input tracking"),this.listenerChange=V.addEventListener(Fc,(function(n){this.getConfig(yp)&&this.trackDomEvent(n,QD)}).bind(this)))},Qt.prototype.initPageviewTracking=function(){if(V.removeEventListener(iC,this.listenerPopstate),V.removeEventListener(rC,this.listenerHashchange),V.removeEventListener(AA,this.listenerLocationchange),!!this.pageviewTrackingConfig()){xt.log("Initializing pageview tracking");var n="",e=!1;this.currentUrlBlocked()||(e=this.mp.track_pageview(Rc)),e&&(n=m.info.currentUrl()),this.listenerPopstate=V.addEventListener(iC,function(){V.dispatchEvent(new Event(AA))}),this.listenerHashchange=V.addEventListener(rC,function(){V.dispatchEvent(new Event(AA))});var t=V.history.pushState;typeof t=="function"&&(V.history.pushState=function(i,A,s){t.call(V.history,i,A,s),V.dispatchEvent(new Event(AA))});var r=V.history.replaceState;typeof r=="function"&&(V.history.replaceState=function(i,A,s){r.call(V.history,i,A,s),V.dispatchEvent(new Event(AA))}),this.listenerLocationchange=V.addEventListener(AA,ip((function(){if(!this.currentUrlBlocked()){var i=m.info.currentUrl(),A=!1,s=i.split("#")[0].split("?")[0]!==n.split("#")[0].split("?")[0],o=this.pageviewTrackingConfig();if(o===fC?A=i!==n:o===ID?A=i.split("#")[0]!==n.split("#")[0]:o===FD&&(A=s),A){var a=this.mp.track_pageview(Rc);a&&(n=i),s&&(this.lastScrollCheckpoint=0,xt.log("Path change: re-initializing scroll depth checkpoints"))}}}).bind(this)))}},Qt.prototype.initRageClickTracking=function(){V.removeEventListener(ii,this.listenerRageClick);var n=this._getRageClickConfig();!n&&!this.mp.get_config("record_heatmap_data")||(xt.log("Initializing rage click tracking"),this._rageClickTracker||(this._rageClickTracker=new hC),this.listenerRageClick=(function(e){var t=this._getRageClickConfig();!t&&!this.mp.is_recording_heatmap_data()||this.currentUrlBlocked()||this._rageClickTracker.isRageClick(e.pageX,e.pageY,t)&&this.trackDomEvent(e,TC)}).bind(this),V.addEventListener(ii,this.listenerRageClick))},Qt.prototype.initScrollTracking=function(){V.removeEventListener(AC,this.listenerScroll),this.getConfig(wp)&&(xt.log("Initializing scroll tracking"),this.lastScrollCheckpoint=0,this.listenerScroll=V.addEventListener(AC,ip((function(){if(this.getConfig(wp)&&!this.currentUrlBlocked()){var n=this.getConfig(_C),e=(this.getConfig(SC)||[]).slice().sort(function(a,c){return a-c}),t=V.scrollY,r=m.extend({$scroll_top:t},Rc);try{var i=ye.body.scrollHeight,A=Math.round(t/(i-V.innerHeight)*100);if(r.$scroll_height=i,r.$scroll_percentage=A,A>this.lastScrollCheckpoint)for(var s=0;s<e.length;s++){var o=e[s];A>=o&&this.lastScrollCheckpoint<o&&(r.$scroll_checkpoint=o,this.lastScrollCheckpoint=o,n=!0)}}catch(a){xt.critical("Error while calculating scroll percentage",a)}n&&this.mp.track(RD,r)}}).bind(this))))},Qt.prototype.initSubmitTracking=function(){V.removeEventListener(hp,this.listenerSubmit),this.getConfig(bp)&&(xt.log("Initializing submit tracking"),this.listenerSubmit=V.addEventListener(hp,(function(n){this.getConfig(bp)&&this.trackDomEvent(n,PD)}).bind(this)))},VB(Qt);var OD=V.fetch,Rt=ri("flags"),Pc="flags",Oc="context",Bp={};Bp[Oc]={};var ae=function(n){this.getFullApiRoute=n.getFullApiRoute,this.getMpConfig=n.getConfigFunc,this.setMpConfig=n.setConfigFunc,this.getMpProperty=n.getPropertyFunc,this.track=n.trackingFunc};ae.prototype.init=function(){if(!MD()){Rt.critical("Feature Flags unavailable: missing minimum required APIs");return}this.flags=null,this.fetchFlags(),this.trackedFeatures=new Set},ae.prototype.getFullConfig=function(){var n=this.getMpConfig(Pc);return n?m.isObject(n)?m.extend({},Bp,n):Bp:{}},ae.prototype.getConfig=function(n){return this.getFullConfig()[n]},ae.prototype.isSystemEnabled=function(){return!!this.getMpConfig(Pc)},ae.prototype.updateContext=function(n,e){if(!this.isSystemEnabled())return Rt.critical("Feature Flags not enabled, cannot update context"),Promise.resolve();var t=this.getMpConfig(Pc);m.isObject(t)||(t={});var r=e&&e.replace?{}:this.getConfig(Oc);return t[Oc]=m.extend({},r,n),this.setMpConfig(Pc,t),this.fetchFlags()},ae.prototype.areFlagsReady=function(){return this.isSystemEnabled()||Rt.error("Feature Flags not enabled"),!!this.flags},ae.prototype.fetchFlags=function(){if(!this.isSystemEnabled())return Promise.resolve();var n=this.getMpProperty("distinct_id"),e=this.getMpProperty("$device_id");Rt.log("Fetching flags for distinct ID: "+n);var t={context:m.extend({distinct_id:n,device_id:e},this.getConfig(Oc))};return this._fetchInProgressStartTime=Date.now(),this.fetchPromise=V.fetch(this.getFullApiRoute(),{method:"POST",headers:{Authorization:"Basic "+btoa(this.getMpConfig("token")+":"),"Content-Type":"application/octet-stream"},body:JSON.stringify(t)}).then((function(r){return this.markFetchComplete(),r.json().then((function(i){var A=i.flags;if(!A)throw new Error("No flags in API response");var s=new Map;m.each(A,function(o,a){s.set(a,{key:o.variant_key,value:o.variant_value})}),this.flags=s}).bind(this)).catch((function(i){this.markFetchComplete(),Rt.error(i)}).bind(this))}).bind(this)).catch((function(r){this.markFetchComplete(),Rt.error(r)}).bind(this)),this.fetchPromise},ae.prototype.markFetchComplete=function(){if(!this._fetchInProgressStartTime){Rt.error("Fetch in progress started time not set, cannot mark fetch complete");return}this._fetchStartTime=this._fetchInProgressStartTime,this._fetchCompleteTime=Date.now(),this._fetchLatency=this._fetchCompleteTime-this._fetchStartTime,this._fetchInProgressStartTime=null},ae.prototype.getVariant=function(n,e){return this.fetchPromise?this.fetchPromise.then((function(){return this.getVariantSync(n,e)}).bind(this)).catch(function(t){return Rt.error(t),e}):new Promise(function(t){Rt.critical("Feature Flags not initialized"),t(e)})},ae.prototype.getVariantSync=function(n,e){if(!this.areFlagsReady())return Rt.log("Flags not loaded yet"),e;var t=this.flags.get(n);return t?(this.trackFeatureCheck(n,t),t):(Rt.log('No flag found: "'+n+'"'),e)},ae.prototype.getVariantValue=function(n,e){return this.getVariant(n,{value:e}).then(function(t){return t.value}).catch(function(t){return Rt.error(t),e})},ae.prototype.getFeatureData=function(n,e){return Rt.critical("mixpanel.flags.get_feature_data() is deprecated and will be removed in a future release. Use mixpanel.flags.get_variant_value() instead."),this.getVariantValue(n,e)},ae.prototype.getVariantValueSync=function(n,e){return this.getVariantSync(n,{value:e}).value},ae.prototype.isEnabled=function(n,e){return this.getVariantValue(n).then((function(){return this.isEnabledSync(n,e)}).bind(this)).catch(function(t){return Rt.error(t),e})},ae.prototype.isEnabledSync=function(n,e){e=e||!1;var t=this.getVariantValueSync(n,e);return t!==!0&&t!==!1&&(Rt.error('Feature flag "'+n+'" value: '+t+" is not a boolean; returning fallback value: "+e),t=e),t},ae.prototype.trackFeatureCheck=function(n,e){this.trackedFeatures.has(n)||(this.trackedFeatures.add(n),this.track("$experiment_started",{"Experiment name":n,"Variant name":e.key,$experiment_type:"feature_flag","Variant fetch start time":new Date(this._fetchStartTime).toISOString(),"Variant fetch complete time":new Date(this._fetchCompleteTime).toISOString(),"Variant fetch latency (ms)":this._fetchLatency}))};function MD(){return!!OD&&typeof Promise<"u"&&typeof Map<"u"&&typeof Set<"u"}VB(ae),ae.prototype.are_flags_ready=ae.prototype.areFlagsReady,ae.prototype.get_variant=ae.prototype.getVariant,ae.prototype.get_variant_sync=ae.prototype.getVariantSync,ae.prototype.get_variant_value=ae.prototype.getVariantValue,ae.prototype.get_variant_value_sync=ae.prototype.getVariantValueSync,ae.prototype.is_enabled=ae.prototype.isEnabled,ae.prototype.is_enabled_sync=ae.prototype.isEnabledSync,ae.prototype.update_context=ae.prototype.updateContext,ae.prototype.get_feature_data=ae.prototype.getFeatureData;var zn=function(){};zn.prototype.create_properties=function(){},zn.prototype.event_handler=function(){},zn.prototype.after_track_handler=function(){},zn.prototype.init=function(n){return this.mp=n,this},zn.prototype.track=function(n,e,t,r){var i=this,A=m.dom_query(n);if(A.length===0){we.error("The DOM query ("+n+") returned 0 elements");return}return m.each(A,function(s){m.register_event(s,this.override_event,function(o){var a={},c=i.create_properties(t,this),u=i.mp.get_config("track_links_timeout");i.event_handler(o,this,a),window.setTimeout(i.track_callback(r,c,a,!0),u),i.mp.track(e,c,i.track_callback(r,c,a))})},this),!0},zn.prototype.track_callback=function(n,e,t,r){r=r||!1;var i=this;return function(){t.callback_fired||(t.callback_fired=!0,!(n&&n(r,e)===!1)&&i.after_track_handler(e,t,r))}},zn.prototype.create_properties=function(n,e){var t;return typeof n=="function"?t=n(e):t=m.extend({},n),t};var sA=function(){this.override_event="click"};m.inherit(sA,zn),sA.prototype.create_properties=function(n,e){var t=sA.superclass.create_properties.apply(this,arguments);return e.href&&(t.url=e.href),t},sA.prototype.event_handler=function(n,e,t){t.new_tab=n.which===2||n.metaKey||n.ctrlKey||e.target==="_blank",t.href=e.href,t.new_tab||n.preventDefault()},sA.prototype.after_track_handler=function(n,e){e.new_tab||setTimeout(function(){window.location=e.href},0)};var Mc=function(){this.override_event="submit"};m.inherit(Mc,zn),Mc.prototype.event_handler=function(n,e,t){t.element=e,n.preventDefault()},Mc.prototype.after_track_handler=function(n,e){setTimeout(function(){e.element.submit()},0)};var xr="$set",oA="$set_once",mn="$unset",Ai="$add",Qn="$append",si="$union",Xn="$remove",LD="$delete",IC={set_action:function(n,e){var t={},r={};return m.isObject(n)?m.each(n,function(i,A){this._is_reserved_property(A)||(r[A]=i)},this):r[n]=e,t[xr]=r,t},unset_action:function(n){var e={},t=[];return m.isArray(n)||(n=[n]),m.each(n,function(r){this._is_reserved_property(r)||t.push(r)},this),e[mn]=t,e},set_once_action:function(n,e){var t={},r={};return m.isObject(n)?m.each(n,function(i,A){this._is_reserved_property(A)||(r[A]=i)},this):r[n]=e,t[oA]=r,t},union_action:function(n,e){var t={},r={};return m.isObject(n)?m.each(n,function(i,A){this._is_reserved_property(A)||(r[A]=m.isArray(i)?i:[i])},this):r[n]=m.isArray(e)?e:[e],t[si]=r,t},append_action:function(n,e){var t={},r={};return m.isObject(n)?m.each(n,function(i,A){this._is_reserved_property(A)||(r[A]=i)},this):r[n]=e,t[Qn]=r,t},remove_action:function(n,e){var t={},r={};return m.isObject(n)?m.each(n,function(i,A){this._is_reserved_property(A)||(r[A]=i)},this):r[n]=e,t[Xn]=r,t},delete_action:function(){var n={};return n[LD]="",n}},De=function(){};m.extend(De.prototype,IC),De.prototype._init=function(n,e,t){this._mixpanel=n,this._group_key=e,this._group_id=t},De.prototype.set=nA(function(n,e,t){var r=this.set_action(n,e);return m.isObject(n)&&(t=e),this._send_request(r,t)}),De.prototype.set_once=nA(function(n,e,t){var r=this.set_once_action(n,e);return m.isObject(n)&&(t=e),this._send_request(r,t)}),De.prototype.unset=nA(function(n,e){var t=this.unset_action(n);return this._send_request(t,e)}),De.prototype.union=nA(function(n,e,t){m.isObject(n)&&(t=e);var r=this.union_action(n,e);return this._send_request(r,t)}),De.prototype.delete=nA(function(n){var e=this.delete_action();return this._send_request(e,n)}),De.prototype.remove=nA(function(n,e,t){var r=this.remove_action(n,e);return this._send_request(r,t)}),De.prototype._send_request=function(n,e){n.$group_key=this._group_key,n.$group_id=this._group_id,n.$token=this._get_config("token");var t=m.encodeDates(n);return this._mixpanel._track_or_batch({type:"groups",data:t,endpoint:this._mixpanel.get_api_host("groups")+"/"+this._get_config("api_routes").groups,batcher:this._mixpanel.request_batchers.groups},e)},De.prototype._is_reserved_property=function(n){return n==="$group_key"||n==="$group_id"},De.prototype._get_config=function(n){return this._mixpanel.get_config(n)},De.prototype.toString=function(){return this._mixpanel.toString()+".group."+this._group_key+"."+this._group_id},De.prototype.remove=De.prototype.remove,De.prototype.set=De.prototype.set,De.prototype.set_once=De.prototype.set_once,De.prototype.union=De.prototype.union,De.prototype.unset=De.prototype.unset,De.prototype.toString=De.prototype.toString;var $=function(){};m.extend($.prototype,IC),$.prototype._init=function(n){this._mixpanel=n},$.prototype.set=Fr(function(n,e,t){var r=this.set_action(n,e);return m.isObject(n)&&(t=e),this._get_config("save_referrer")&&this._mixpanel.persistence.update_referrer_info(document.referrer),r[xr]=m.extend({},m.info.people_properties(),r[xr]),this._send_request(r,t)}),$.prototype.set_once=Fr(function(n,e,t){var r=this.set_once_action(n,e);return m.isObject(n)&&(t=e),this._send_request(r,t)}),$.prototype.unset=Fr(function(n,e){var t=this.unset_action(n);return this._send_request(t,e)}),$.prototype.increment=Fr(function(n,e,t){var r={},i={};return m.isObject(n)?(m.each(n,function(A,s){if(!this._is_reserved_property(s))if(isNaN(parseFloat(A))){we.error("Invalid increment value passed to mixpanel.people.increment - must be a number");return}else i[s]=A},this),t=e):(m.isUndefined(e)&&(e=1),i[n]=e),r[Ai]=i,this._send_request(r,t)}),$.prototype.append=Fr(function(n,e,t){m.isObject(n)&&(t=e);var r=this.append_action(n,e);return this._send_request(r,t)}),$.prototype.remove=Fr(function(n,e,t){m.isObject(n)&&(t=e);var r=this.remove_action(n,e);return this._send_request(r,t)}),$.prototype.union=Fr(function(n,e,t){m.isObject(n)&&(t=e);var r=this.union_action(n,e);return this._send_request(r,t)}),$.prototype.track_charge=Fr(function(){we.error("mixpanel.people.track_charge() is deprecated and no longer has any effect.")}),$.prototype.clear_charges=function(n){return this.set("$transactions",[],n)},$.prototype.delete_user=function(){if(!this._identify_called()){we.error("mixpanel.people.delete_user() requires you to call identify() first");return}var n={$delete:this._mixpanel.get_distinct_id()};return this._send_request(n)},$.prototype.toString=function(){return this._mixpanel.toString()+".people"},$.prototype._send_request=function(n,e){n.$token=this._get_config("token"),n.$distinct_id=this._mixpanel.get_distinct_id();var t=this._mixpanel.get_property("$device_id"),r=this._mixpanel.get_property("$user_id"),i=this._mixpanel.get_property("$had_persisted_distinct_id");t&&(n.$device_id=t),r&&(n.$user_id=r),i&&(n.$had_persisted_distinct_id=i);var A=m.encodeDates(n);return this._identify_called()?this._mixpanel._track_or_batch({type:"people",data:A,endpoint:this._mixpanel.get_api_host("people")+"/"+this._get_config("api_routes").engage,batcher:this._mixpanel.request_batchers.people},e):(this._enqueue(n),m.isUndefined(e)||(this._get_config("verbose")?e({status:-1,error:null}):e(-1)),m.truncate(A,255))},$.prototype._get_config=function(n){return this._mixpanel.get_config(n)},$.prototype._identify_called=function(){return this._mixpanel._flags.identify_called===!0},$.prototype._enqueue=function(n){xr in n?this._mixpanel.persistence._add_to_people_queue(xr,n):oA in n?this._mixpanel.persistence._add_to_people_queue(oA,n):mn in n?this._mixpanel.persistence._add_to_people_queue(mn,n):Ai in n?this._mixpanel.persistence._add_to_people_queue(Ai,n):Qn in n?this._mixpanel.persistence._add_to_people_queue(Qn,n):Xn in n?this._mixpanel.persistence._add_to_people_queue(Xn,n):si in n?this._mixpanel.persistence._add_to_people_queue(si,n):we.error("Invalid call to _enqueue():",n)},$.prototype._flush_one_queue=function(n,e,t,r){var i=this,A=m.extend({},this._mixpanel.persistence.load_queue(n)),s=A;!m.isUndefined(A)&&m.isObject(A)&&!m.isEmptyObject(A)&&(i._mixpanel.persistence._pop_from_people_queue(n,A),i._mixpanel.persistence.save(),r&&(s=r(A)),e.call(i,s,function(o,a){o===0&&i._mixpanel.persistence._add_to_people_queue(n,A),m.isUndefined(t)||t(o,a)}))},$.prototype._flush=function(n,e,t,r,i,A,s){var o=this;this._flush_one_queue(xr,this.set,n),this._flush_one_queue(oA,this.set_once,r),this._flush_one_queue(mn,this.unset,A,function(g){return m.keys(g)}),this._flush_one_queue(Ai,this.increment,e),this._flush_one_queue(si,this.union,i);var a=this._mixpanel.persistence.load_queue(Qn);if(!m.isUndefined(a)&&m.isArray(a)&&a.length)for(var c,u=function(g,v){g===0&&o._mixpanel.persistence._add_to_people_queue(Qn,c),m.isUndefined(t)||t(g,v)},l=a.length-1;l>=0;l--)a=this._mixpanel.persistence.load_queue(Qn),c=a.pop(),o._mixpanel.persistence.save(),m.isEmptyObject(c)||o.append(c,u);var d=this._mixpanel.persistence.load_queue(Xn);if(!m.isUndefined(d)&&m.isArray(d)&&d.length)for(var h,f=function(g,v){g===0&&o._mixpanel.persistence._add_to_people_queue(Xn,h),m.isUndefined(s)||s(g,v)},p=d.length-1;p>=0;p--)d=this._mixpanel.persistence.load_queue(Xn),h=d.pop(),o._mixpanel.persistence.save(),m.isEmptyObject(h)||o.remove(h,f)},$.prototype._is_reserved_property=function(n){return n==="$distinct_id"||n==="$token"||n==="$device_id"||n==="$user_id"||n==="$had_persisted_distinct_id"},$.prototype.set=$.prototype.set,$.prototype.set_once=$.prototype.set_once,$.prototype.unset=$.prototype.unset,$.prototype.increment=$.prototype.increment,$.prototype.append=$.prototype.append,$.prototype.remove=$.prototype.remove,$.prototype.union=$.prototype.union,$.prototype.track_charge=$.prototype.track_charge,$.prototype.clear_charges=$.prototype.clear_charges,$.prototype.delete_user=$.prototype.delete_user,$.prototype.toString=$.prototype.toString;var Cp="__mps",_p="__mpso",Sp="__mpus",kp="__mpa",Ep="__mpap",Up="__mpr",Tp="__mpu",FC="$people_distinct_id",Lc="__alias",Es="__timers",DD=[Cp,_p,Sp,kp,Ep,Up,Tp,FC,Lc,Es],re=function(n){this.props={},this.campaign_params_saved=!1,n.persistence_name?this.name="mp_"+n.persistence_name:this.name="mp_"+n.token+"_mixpanel";var e=n.persistence;e!=="cookie"&&e!=="localStorage"&&(we.critical("Unknown persistence type "+e+"; falling back to cookie"),e=n.persistence="cookie"),e==="localStorage"&&m.localStorage.is_supported()?this.storage=m.localStorage:this.storage=m.cookie,this.load(),this.update_config(n),this.upgrade(),this.save()};re.prototype.properties=function(){var n={};return this.load(),m.each(this.props,function(e,t){m.include(DD,t)||(n[t]=e)}),n},re.prototype.load=function(){if(!this.disabled){var n=this.storage.parse(this.name);n&&(this.props=m.extend({},n))}},re.prototype.upgrade=function(){var n,e;this.storage===m.localStorage?(n=m.cookie.parse(this.name),m.cookie.remove(this.name),m.cookie.remove(this.name,!0),n&&this.register_once(n)):this.storage===m.cookie&&(e=m.localStorage.parse(this.name),m.localStorage.remove(this.name),e&&this.register_once(e))},re.prototype.save=function(){this.disabled||this.storage.set(this.name,tA(this.props),this.expire_days,this.cross_subdomain,this.secure,this.cross_site,this.cookie_domain)},re.prototype.load_prop=function(n){return this.load(),this.props[n]},re.prototype.remove=function(){this.storage.remove(this.name,!1,this.cookie_domain),this.storage.remove(this.name,!0,this.cookie_domain)},re.prototype.clear=function(){this.remove(),this.props={}},re.prototype.register_once=function(n,e,t){return m.isObject(n)?(typeof e>"u"&&(e="None"),this.expire_days=typeof t>"u"?this.default_expiry:t,this.load(),m.each(n,function(r,i){(!this.props.hasOwnProperty(i)||this.props[i]===e)&&(this.props[i]=r)},this),this.save(),!0):!1},re.prototype.register=function(n,e){return m.isObject(n)?(this.expire_days=typeof e>"u"?this.default_expiry:e,this.load(),m.extend(this.props,n),this.save(),!0):!1},re.prototype.unregister=function(n){this.load(),n in this.props&&(delete this.props[n],this.save())},re.prototype.update_search_keyword=function(n){this.register(m.info.searchInfo(n))},re.prototype.update_referrer_info=function(n){this.register_once({$initial_referrer:n||"$direct",$initial_referring_domain:m.info.referringDomain(n)||"$direct"},"")},re.prototype.get_referrer_info=function(){return m.strip_empty_properties({$initial_referrer:this.props.$initial_referrer,$initial_referring_domain:this.props.$initial_referring_domain})},re.prototype.update_config=function(n){this.default_expiry=this.expire_days=n.cookie_expiration,this.set_disabled(n.disable_persistence),this.set_cookie_domain(n.cookie_domain),this.set_cross_site(n.cross_site_cookie),this.set_cross_subdomain(n.cross_subdomain_cookie),this.set_secure(n.secure_cookie)},re.prototype.set_disabled=function(n){this.disabled=n,this.disabled?this.remove():this.save()},re.prototype.set_cookie_domain=function(n){n!==this.cookie_domain&&(this.remove(),this.cookie_domain=n,this.save())},re.prototype.set_cross_site=function(n){n!==this.cross_site&&(this.cross_site=n,this.remove(),this.save())},re.prototype.set_cross_subdomain=function(n){n!==this.cross_subdomain&&(this.cross_subdomain=n,this.remove(),this.save())},re.prototype.get_cross_subdomain=function(){return this.cross_subdomain},re.prototype.set_secure=function(n){n!==this.secure&&(this.secure=!!n,this.remove(),this.save())},re.prototype._add_to_people_queue=function(n,e){var t=this._get_queue_key(n),r=e[n],i=this._get_or_create_queue(xr),A=this._get_or_create_queue(oA),s=this._get_or_create_queue(mn),o=this._get_or_create_queue(Ai),a=this._get_or_create_queue(si),c=this._get_or_create_queue(Xn,[]),u=this._get_or_create_queue(Qn,[]);t===Cp?(m.extend(i,r),this._pop_from_people_queue(Ai,r),this._pop_from_people_queue(si,r),this._pop_from_people_queue(mn,r)):t===_p?(m.each(r,function(l,d){d in A||(A[d]=l)}),this._pop_from_people_queue(mn,r)):t===Sp?m.each(r,function(l){m.each([i,A,o,a],function(d){l in d&&delete d[l]}),m.each(u,function(d){l in d&&delete d[l]}),s[l]=!0}):t===kp?(m.each(r,function(l,d){d in i?i[d]+=l:(d in o||(o[d]=0),o[d]+=l)},this),this._pop_from_people_queue(mn,r)):t===Tp?(m.each(r,function(l,d){m.isArray(l)&&(d in a||(a[d]=[]),m.each(l,function(h){m.include(a[d],h)||a[d].push(h)}))}),this._pop_from_people_queue(mn,r)):t===Up?(c.push(r),this._pop_from_people_queue(Qn,r)):t===Ep&&(u.push(r),this._pop_from_people_queue(mn,r)),we.log("MIXPANEL PEOPLE REQUEST (QUEUED, PENDING IDENTIFY):"),we.log(e),this.save()},re.prototype._pop_from_people_queue=function(n,e){var t=this.props[this._get_queue_key(n)];m.isUndefined(t)||m.each(e,function(r,i){n===Qn||n===Xn?m.each(t,function(A){A[i]===r&&delete A[i]}):delete t[i]},this)},re.prototype.load_queue=function(n){return this.load_prop(this._get_queue_key(n))},re.prototype._get_queue_key=function(n){if(n===xr)return Cp;if(n===oA)return _p;if(n===mn)return Sp;if(n===Ai)return kp;if(n===Qn)return Ep;if(n===Xn)return Up;if(n===si)return Tp;we.error("Invalid queue:",n)},re.prototype._get_or_create_queue=function(n,e){var t=this._get_queue_key(n);return e=m.isUndefined(e)?{}:e,this.props[t]||(this.props[t]=e)},re.prototype.set_event_timer=function(n,e){var t=this.load_prop(Es)||{};t[n]=e,this.props[Es]=t,this.save()},re.prototype.remove_event_timer=function(n){var e=this.load_prop(Es)||{},t=e[n];return m.isUndefined(t)||(delete this.props[Es][n],this.save()),t};var Ip,xC=function(n,e){throw new Error(n+" not available in this build.")},Ut,QC=0,ND=1,HD=function(n){return n},en="mixpanel",RC="base64",KD="json",Fp="$device:",aA=V.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest,PC=!aA&&qn.indexOf("MSIE")===-1&&qn.indexOf("Mozilla")===-1,Dc=null;Ur.sendBeacon&&(Dc=function(){return Ur.sendBeacon.apply(Ur,arguments)});var OC={track:"track/",engage:"engage/",groups:"groups/",record:"record/",flags:"flags/"},MC={api_host:"https://api-js.mixpanel.com",api_hosts:{},api_routes:OC,api_extra_query_params:{},api_method:"POST",api_transport:"XHR",api_payload_format:RC,app_host:"https://mixpanel.com",autocapture:!1,cdn:"https://cdn.mxpnl.com",cross_site_cookie:!1,cross_subdomain_cookie:!0,error_reporter:Tr,flags:!1,persistence:"cookie",persistence_name:"",cookie_domain:"",cookie_name:"",loaded:Tr,mp_loader:null,track_marketing:!0,track_pageview:!1,skip_first_touch_marketing:!1,store_google:!0,stop_utm_persistence:!1,save_referrer:!0,test:!1,verbose:!1,img:!1,debug:!1,track_links_timeout:300,cookie_expiration:365,upgrade:!1,disable_persistence:!1,disable_cookie:!1,secure_cookie:!1,ip:!0,opt_out_tracking_by_default:!1,opt_out_persistence_by_default:!1,opt_out_tracking_persistence_type:"localStorage",opt_out_tracking_cookie_prefix:null,property_blacklist:[],xhr_headers:{},ignore_dnt:!1,batch_requests:!0,batch_size:50,batch_flush_interval_ms:5e3,batch_request_timeout_ms:9e4,batch_autostart:!0,hooks:{},record_block_class:new RegExp("^(mp-block|fs-exclude|amp-block|rr-block|ph-no-capture)$"),record_block_selector:"img, video, audio",record_canvas:!1,record_collect_fonts:!1,record_heatmap_data:!1,record_idle_timeout_ms:30*60*1e3,record_mask_text_class:new RegExp("^(mp-mask|fs-mask|amp-mask|rr-mask|ph-mask)$"),record_mask_text_selector:"*",record_max_ms:bs,record_min_ms:0,record_sessions_percent:0,recorder_src:"https://cdn.mxpnl.com/libs/mixpanel-recorder.min.js"},LC=!1,U=function(){},xp=function(n,e,t){var r,i=t===en?Ut:Ut[t];if(i&&Ip===QC)r=i;else{if(i&&!m.isArray(i)){we.error("You have already initialized "+t);return}r=new U}if(r._cached_groups={},r._init(n,e,t),r.people=new $,r.people._init(r),!r.get_config("skip_first_touch_marketing")){var A=m.info.campaignParams(null),s={},o=!1;m.each(A,function(a,c){s["initial_"+c]=a,a&&(o=!0)}),o&&r.people.set_once(s)}return gn.DEBUG=gn.DEBUG||r.get_config("debug"),!m.isUndefined(i)&&m.isArray(i)&&(r._execute_array.call(r.people,i.people),r._execute_array(i)),r};U.prototype.init=function(n,e,t){if(m.isUndefined(t)){this.report_error("You must name your new library: init(token, config, name)");return}if(t===en){this.report_error("You must initialize the main mixpanel object right after you include the Mixpanel js snippet");return}var r=xp(n,e,t);return Ut[t]=r,r._loaded(),r},U.prototype._init=function(n,e,t){e=e||{},this.__loaded=!0,this.config={};var r={};if(!("api_payload_format"in e)){var i=e.api_host||MC.api_host;i.match(/\.mixpanel\.com/)&&(r.api_payload_format=KD)}if(this.set_config(m.extend({},MC,r,e,{name:t,token:n,callback_fn:(t===en?t:en+"."+t)+"._jsc"})),this._jsc=Tr,this.__dom_loaded_queue=[],this.__request_queue=[],this.__disabled_events=[],this._flags={disable_all_events:!1,identify_called:!1},this.request_batchers={},this._batch_requests=this.get_config("batch_requests"),this._batch_requests){if(!m.localStorage.is_supported(!0)||!aA)this._batch_requests=!1,we.log("Turning off Mixpanel request-queueing; needs XHR and localStorage support"),m.each(this.get_batcher_configs(),function(o){we.log("Clearing batch queue "+o.queue_key),m.localStorage.remove(o.queue_key)});else if(this.init_batchers(),Dc&&V.addEventListener){var A=m.bind(function(){this.request_batchers.events.stopped||this.request_batchers.events.flush({unloading:!0})},this);V.addEventListener("pagehide",function(o){o.persisted&&A()}),V.addEventListener("visibilitychange",function(){ye.visibilityState==="hidden"&&A()})}}this.persistence=this.cookie=new re(this.config),this.unpersisted_superprops={},this._gdpr_init();var s=m.UUID();this.get_distinct_id()||this.register_once({distinct_id:Fp+s,$device_id:s},""),this.flags=new ae({getFullApiRoute:m.bind(function(){return this.get_api_host("flags")+"/"+this.get_config("api_routes").flags},this),getConfigFunc:m.bind(this.get_config,this),setConfigFunc:m.bind(this.set_config,this),getPropertyFunc:m.bind(this.get_property,this),trackingFunc:m.bind(this.track,this)}),this.flags.init(),this.flags=this.flags,this.autocapture=new Qt(this),this.autocapture.init(),this._init_tab_id(),this._check_and_start_session_recording()},U.prototype._init_tab_id=function(){if(m.sessionStorage.is_supported())try{var n=this.get_config("name")+"_"+this.get_config("token"),e="mp_tab_id_"+n,t="mp_gen_new_tab_id_"+n;(m.sessionStorage.get(t)||!m.sessionStorage.get(e))&&m.sessionStorage.set(e,"$tab-"+m.UUID()),m.sessionStorage.set(t,"1"),this.tab_id=m.sessionStorage.get(e),V.addEventListener("beforeunload",function(){m.sessionStorage.remove(t)})}catch(r){this.report_error("Error initializing tab id",r)}else this.report_error("Session storage is not supported, cannot keep track of unique tab ID.")},U.prototype.get_tab_id=function(){return this.tab_id||null},U.prototype._should_load_recorder=function(){var n=new In(ap),e=this.get_tab_id();return n.init().then(function(){return n.getAll()}).then(function(t){for(var r=0;r<t.length;r++)if(dp(t[r])||t[r].tabId===e)return!0;return!1}).catch(m.bind(function(t){this.report_error("Error checking recording registry",t)},this))},U.prototype._check_and_start_session_recording=Ir(function(n){if(!V.MutationObserver){we.critical("Browser does not support MutationObserver; skipping session recording");return}var e=m.bind(function(r){var i=m.bind(function(){this._recorder=this._recorder||new V.__mp_recorder(this),this._recorder.resumeRecording(r)},this);m.isUndefined(V.__mp_recorder)?xC(this.get_config("recorder_src"),i):i()},this),t=this.get_config("record_sessions_percent")>0&&Math.random()*100<=this.get_config("record_sessions_percent");n||t?e(!0):this._should_load_recorder().then(function(r){r&&e(!1)})}),U.prototype.start_session_recording=function(){this._check_and_start_session_recording(!0)},U.prototype.stop_session_recording=function(){return this._recorder?this._recorder.stopRecording():Promise.resolve()},U.prototype.pause_session_recording=function(){return this._recorder?this._recorder.pauseRecording():Promise.resolve()},U.prototype.resume_session_recording=function(){return this._recorder?this._recorder.resumeRecording():Promise.resolve()},U.prototype.is_recording_heatmap_data=function(){return this._get_session_replay_id()&&this.get_config("record_heatmap_data")},U.prototype.get_session_recording_properties=function(){var n={},e=this._get_session_replay_id();return e&&(n.$mp_replay_id=e),n},U.prototype.get_session_replay_url=function(){var n=null,e=this._get_session_replay_id();if(e){var t=m.HTTPBuildQuery({replay_id:e,distinct_id:this.get_distinct_id(),token:this.get_config("token")});n="https://mixpanel.com/projects/replay-redirect?"+t}return n},U.prototype._get_session_replay_id=function(){var n=null;return this._recorder&&(n=this._recorder.replayId),n||null},U.prototype.__get_recorder=function(){return this._recorder},U.prototype._loaded=function(){if(this.get_config("loaded")(this),this._set_default_superprops(),this.people.set_once(this.persistence.get_referrer_info()),this.get_config("store_google")&&this.get_config("stop_utm_persistence")){var n=m.info.campaignParams(null);m.each(n,(function(e,t){this.unregister(t)}).bind(this))}},U.prototype._set_default_superprops=function(){this.persistence.update_search_keyword(ye.referrer),this.get_config("store_google")&&!this.get_config("stop_utm_persistence")&&this.register(m.info.campaignParams()),this.get_config("save_referrer")&&this.persistence.update_referrer_info(ye.referrer)},U.prototype._dom_loaded=function(){m.each(this.__dom_loaded_queue,function(n){this._track_dom.apply(this,n)},this),this.has_opted_out_tracking()||m.each(this.__request_queue,function(n){this._send_request.apply(this,n)},this),delete this.__dom_loaded_queue,delete this.__request_queue},U.prototype._track_dom=function(n,e){if(this.get_config("img"))return this.report_error("You can't use DOM tracking functions with img = true."),!1;if(!LC)return this.__dom_loaded_queue.push([n,e]),!1;var t=new n().init(this);return t.track.apply(t,e)},U.prototype._prepare_callback=function(n,e){if(m.isUndefined(n))return null;if(aA){var t=function(s){n(s,e)};return t}else{var r=this._jsc,i=""+Math.floor(Math.random()*1e8),A=this.get_config("callback_fn")+"["+i+"]";return r[i]=function(s){delete r[i],n(s,e)},A}},U.prototype._send_request=function(n,e,t,r){var i=!0;if(PC)return this.__request_queue.push(arguments),i;var A={method:this.get_config("api_method"),transport:this.get_config("api_transport"),verbose:this.get_config("verbose")},s=null;!r&&(m.isFunction(t)||typeof t=="string")&&(r=t,t=null),t=m.extend(A,t||{}),aA||(t.method="GET");var o=t.method==="POST",a=Dc&&o&&t.transport.toLowerCase()==="sendbeacon",c=t.verbose;e.verbose&&(c=!0),this.get_config("test")&&(e.test=1),c&&(e.verbose=1),this.get_config("img")&&(e.img=1),aA||(r?e.callback=r:(c||this.get_config("test"))&&(e.callback="(function(){})")),e.ip=this.get_config("ip")?1:0,e._=new Date().getTime().toString(),o&&(s="data="+encodeURIComponent(e.data),delete e.data),m.extend(e,this.get_config("api_extra_query_params")),n+="?"+m.HTTPBuildQuery(e);var u=this;if("img"in e){var l=ye.createElement("img");l.src=n,ye.body.appendChild(l)}else if(a){try{i=Dc(n,s)}catch(v){u.report_error(v),i=!1}try{r&&r(i?1:0)}catch(v){u.report_error(v)}}else if(aA)try{var d=new XMLHttpRequest;d.open(t.method,n,!0);var h=this.get_config("xhr_headers");if(o&&(h["Content-Type"]="application/x-www-form-urlencoded"),m.each(h,function(v,y){d.setRequestHeader(y,v)}),t.timeout_ms&&typeof d.timeout<"u"){d.timeout=t.timeout_ms;var f=new Date().getTime()}d.withCredentials=!0,d.onreadystatechange=function(){if(d.readyState===4)if(d.status===200){if(r)if(c){var v;try{v=m.JSONDecode(d.responseText)}catch(b){if(u.report_error(b),t.ignore_json_errors)v=d.responseText;else return}r(v)}else r(Number(d.responseText))}else{var y;if(d.timeout&&!d.status&&new Date().getTime()-f>=d.timeout?y="timeout":y="Bad HTTP status: "+d.status+" "+d.statusText,u.report_error(y),r)if(c){var B=d.responseHeaders||{};r({status:0,httpStatusCode:d.status,error:y,retryAfter:B["Retry-After"]})}else r(0)}},d.send(s)}catch(v){u.report_error(v),i=!1}else{var p=ye.createElement("script");p.type="text/javascript",p.async=!0,p.defer=!0,p.src=n;var g=ye.getElementsByTagName("script")[0];g.parentNode.insertBefore(p,g)}return i},U.prototype._execute_array=function(n){var e,t=[],r=[],i=[];m.each(n,function(s){s&&(e=s[0],m.isArray(e)?i.push(s):typeof s=="function"?s.call(this):m.isArray(s)&&e==="alias"?t.push(s):m.isArray(s)&&e.indexOf("track")!==-1&&typeof this[e]=="function"?i.push(s):r.push(s))},this);var A=function(s,o){m.each(s,function(a){if(m.isArray(a[0])){var c=o;m.each(a,function(u){c=c[u[0]].apply(c,u.slice(1))})}else this[a[0]].apply(this,a.slice(1))},o)};A(t,this),A(r,this),A(i,this)},U.prototype.are_batchers_initialized=function(){return!!this.request_batchers.events},U.prototype.get_batcher_configs=function(){var n="__mpq_"+this.get_config("token");return this._batcher_configs=this._batcher_configs||{events:{type:"events",api_name:"track",queue_key:n+"_ev"},people:{type:"people",api_name:"engage",queue_key:n+"_pp"},groups:{type:"groups",api_name:"groups",queue_key:n+"_gr"}},this._batcher_configs},U.prototype.init_batchers=function(){if(!this.are_batchers_initialized()){var n=m.bind(function(t){return new $t(t.queue_key,{libConfig:this.config,errorReporter:this.get_config("error_reporter"),sendRequestFunc:m.bind(function(r,i,A){var s=this.get_config("api_routes");this._send_request(this.get_api_host(t.api_name)+"/"+s[t.api_name],this._encode_data_for_request(r),i,this._prepare_callback(A,r))},this),beforeSendHook:m.bind(function(r){return this._run_hook("before_send_"+t.type,r)},this),stopAllBatchingFunc:m.bind(this.stop_batch_senders,this),usePersistence:!0})},this),e=this.get_batcher_configs();this.request_batchers={events:n(e.events),people:n(e.people),groups:n(e.groups)}}this.get_config("batch_autostart")&&this.start_batch_senders()},U.prototype.start_batch_senders=function(){this._batchers_were_started=!0,this.are_batchers_initialized()&&(this._batch_requests=!0,m.each(this.request_batchers,function(n){n.start()}))},U.prototype.stop_batch_senders=function(){this._batch_requests=!1,m.each(this.request_batchers,function(n){n.stop(),n.clear()})},U.prototype.push=function(n){this._execute_array([n])},U.prototype.disable=function(n){typeof n>"u"?this._flags.disable_all_events=!0:this.__disabled_events=this.__disabled_events.concat(n)},U.prototype._encode_data_for_request=function(n){var e=tA(n);return this.get_config("api_payload_format")===RC&&(e=m.base64Encode(e)),{data:e}},U.prototype._track_or_batch=function(n,e){var t=m.truncate(n.data,255),r=n.endpoint,i=n.batcher,A=n.should_send_immediately,s=n.send_request_options||{};e=e||Tr;var o=!0,a=m.bind(function(){return s.skip_hooks||(t=this._run_hook("before_send_"+n.type,t)),t?(we.log("MIXPANEL REQUEST:"),we.log(t),this._send_request(r,this._encode_data_for_request(t),s,this._prepare_callback(e,t))):null},this);return this._batch_requests&&!A?i.enqueue(t).then(function(c){c?e(1,t):a()}):o=a(),o&&t},U.prototype.track=Ir(function(n,e,t,r){!r&&typeof t=="function"&&(r=t,t=null),t=t||{};var i=t.transport;i&&(t.transport=i);var A=t.send_immediately;if(typeof r!="function"&&(r=Tr),m.isUndefined(n)){this.report_error("No event name provided to mixpanel.track");return}if(this._event_is_disabled(n)){r(0);return}e=m.extend({},e),e.token=this.get_config("token");var s=this.persistence.remove_event_timer(n);if(!m.isUndefined(s)){var o=new Date().getTime()-s;e.$duration=parseFloat((o/1e3).toFixed(3))}this._set_default_superprops();var a=this.get_config("track_marketing")?m.info.marketingParams():{};e=m.extend({},m.info.properties({mp_loader:this.get_config("mp_loader")}),a,this.persistence.properties(),this.unpersisted_superprops,this.get_session_recording_properties(),e);var c=this.get_config("property_blacklist");m.isArray(c)?m.each(c,function(d){delete e[d]}):this.report_error("Invalid value for property_blacklist config: "+c);var u={event:n,properties:e},l=this._track_or_batch({type:"events",data:u,endpoint:this.get_api_host("events")+"/"+this.get_config("api_routes").track,batcher:this.request_batchers.events,should_send_immediately:A,send_request_options:t},r);return l}),U.prototype.set_group=Ir(function(n,e,t){m.isArray(e)||(e=[e]);var r={};return r[n]=e,this.register(r),this.people.set(n,e,t)}),U.prototype.add_group=Ir(function(n,e,t){var r=this.get_property(n),i={};return r===void 0?(i[n]=[e],this.register(i)):r.indexOf(e)===-1&&(r.push(e),i[n]=r,this.register(i)),this.people.union(n,e,t)}),U.prototype.remove_group=Ir(function(n,e,t){var r=this.get_property(n);if(r!==void 0){var i=r.indexOf(e);i>-1&&(r.splice(i,1),this.register({group_key:r})),r.length===0&&this.unregister(n)}return this.people.remove(n,e,t)}),U.prototype.track_with_groups=Ir(function(n,e,t,r){var i=m.extend({},e||{});return m.each(t,function(A,s){A!=null&&(i[s]=A)}),this.track(n,i,r)}),U.prototype._create_map_key=function(n,e){return n+"_"+JSON.stringify(e)},U.prototype._remove_group_from_cache=function(n,e){delete this._cached_groups[this._create_map_key(n,e)]},U.prototype.get_group=function(n,e){var t=this._create_map_key(n,e),r=this._cached_groups[t];return(r===void 0||r._group_key!==n||r._group_id!==e)&&(r=new De,r._init(this,n,e),this._cached_groups[t]=r),r},U.prototype.track_pageview=Ir(function(n,e){typeof n!="object"&&(n={}),e=e||{};var t=e.event_name||"$mp_web_page_view",r=m.extend(m.info.mpPageViewProperties(),m.info.campaignParams(),m.info.clickParams()),i=m.extend({},r,n);return this.track(t,i)}),U.prototype.track_links=function(){return this._track_dom.call(this,sA,arguments)},U.prototype.track_forms=function(){return this._track_dom.call(this,Mc,arguments)},U.prototype.time_event=function(n){if(m.isUndefined(n)){this.report_error("No event name provided to mixpanel.time_event");return}this._event_is_disabled(n)||this.persistence.set_event_timer(n,new Date().getTime())};var VD={persistent:!0},Qp=function(n){var e;return m.isObject(n)?e=n:m.isUndefined(n)?e={}:e={days:n},m.extend({},VD,e)};U.prototype.register=function(n,e){var t=Qp(e);t.persistent?this.persistence.register(n,t.days):m.extend(this.unpersisted_superprops,n)},U.prototype.register_once=function(n,e,t){var r=Qp(t);r.persistent?this.persistence.register_once(n,e,r.days):(typeof e>"u"&&(e="None"),m.each(n,function(i,A){(!this.unpersisted_superprops.hasOwnProperty(A)||this.unpersisted_superprops[A]===e)&&(this.unpersisted_superprops[A]=i)},this))},U.prototype.unregister=function(n,e){e=Qp(e),e.persistent?this.persistence.unregister(n):delete this.unpersisted_superprops[n]},U.prototype._register_single=function(n,e){var t={};t[n]=e,this.register(t)},U.prototype.identify=function(n,e,t,r,i,A,s,o){var a=this.get_distinct_id();if(n&&a!==n){if(typeof n=="string"&&n.indexOf(Fp)===0)return this.report_error("distinct_id cannot have $device: prefix"),-1;this.register({$user_id:n})}if(!this.get_property("$device_id")){var c=a;this.register_once({$had_persisted_distinct_id:!0,$device_id:c},"")}n!==a&&n!==this.get_property(Lc)&&(this.unregister(Lc),this.register({distinct_id:n})),this._flags.identify_called=!0,this.people._flush(e,t,r,i,A,s,o),n!==a&&this.track("$identify",{distinct_id:n,$anon_distinct_id:a},{skip_hooks:!0}),n!==a&&this.flags.fetchFlags()},U.prototype.reset=function(){this.stop_session_recording(),this.persistence.clear(),this._flags.identify_called=!1;var n=m.UUID();this.register_once({distinct_id:Fp+n,$device_id:n},""),this._check_and_start_session_recording()},U.prototype.get_distinct_id=function(){return this.get_property("distinct_id")},U.prototype.alias=function(n,e){if(n===this.get_property(FC))return this.report_error("Attempting to create alias for existing People user - aborting."),-2;var t=this;return m.isUndefined(e)&&(e=this.get_distinct_id()),n!==e?(this._register_single(Lc,n),this.track("$create_alias",{alias:n,distinct_id:e},{skip_hooks:!0},function(){t.identify(n)})):(this.report_error("alias matches current distinct_id - skipping api call."),this.identify(n),-1)},U.prototype.name_tag=function(n){this._register_single("mp_name_tag",n)},U.prototype.set_config=function(n){if(m.isObject(n)){m.extend(this.config,n);var e=n.batch_size;e&&m.each(this.request_batchers,function(t){t.resetBatchSize()}),this.get_config("persistence_name")||(this.config.persistence_name=this.config.cookie_name),this.get_config("disable_persistence")||(this.config.disable_persistence=this.config.disable_cookie),this.persistence&&this.persistence.update_config(this.config),gn.DEBUG=gn.DEBUG||this.get_config("debug"),("autocapture"in n||"record_heatmap_data"in n)&&this.autocapture&&this.autocapture.init()}},U.prototype.get_config=function(n){return this.config[n]},U.prototype._run_hook=function(n){var e=(this.config.hooks[n]||HD).apply(this,ni.call(arguments,1));return typeof e>"u"&&(this.report_error(n+" hook did not return a value"),e=null),e},U.prototype.get_property=function(n){return this.persistence.load_prop([n])},U.prototype.get_api_host=function(n){return this.get_config("api_hosts")[n]||this.get_config("api_host")},U.prototype.toString=function(){var n=this.get_config("name");return n!==en&&(n=en+"."+n),n},U.prototype._event_is_disabled=function(n){return m.isBlockedUA(qn)||this._flags.disable_all_events||m.include(this.__disabled_events,n)},U.prototype._gdpr_init=function(){var n=this.get_config("opt_out_tracking_persistence_type")==="localStorage";n&&m.localStorage.is_supported()&&(!this.has_opted_in_tracking()&&this.has_opted_in_tracking({persistence_type:"cookie"})&&this.opt_in_tracking({enable_persistence:!1}),!this.has_opted_out_tracking()&&this.has_opted_out_tracking({persistence_type:"cookie"})&&this.opt_out_tracking({clear_persistence:!1}),this.clear_opt_in_out_tracking({persistence_type:"cookie",enable_persistence:!1})),this.has_opted_out_tracking()?this._gdpr_update_persistence({clear_persistence:!0}):!this.has_opted_in_tracking()&&(this.get_config("opt_out_tracking_by_default")||m.cookie.get("mp_optout"))&&(m.cookie.remove("mp_optout"),this.opt_out_tracking({clear_persistence:this.get_config("opt_out_persistence_by_default")}))},U.prototype._gdpr_update_persistence=function(n){var e;if(n&&n.clear_persistence)e=!0;else if(n&&n.enable_persistence)e=!1;else return;!this.get_config("disable_persistence")&&this.persistence.disabled!==e&&this.persistence.set_disabled(e),e?(this.stop_batch_senders(),this.stop_session_recording()):this._batchers_were_started&&this.start_batch_senders()},U.prototype._gdpr_call_func=function(n,e){return e=m.extend({track:m.bind(this.track,this),persistence_type:this.get_config("opt_out_tracking_persistence_type"),cookie_prefix:this.get_config("opt_out_tracking_cookie_prefix"),cookie_expiration:this.get_config("cookie_expiration"),cross_site_cookie:this.get_config("cross_site_cookie"),cross_subdomain_cookie:this.get_config("cross_subdomain_cookie"),cookie_domain:this.get_config("cookie_domain"),secure_cookie:this.get_config("secure_cookie"),ignore_dnt:this.get_config("ignore_dnt")},e),m.localStorage.is_supported()||(e.persistence_type="cookie"),n(this.get_config("token"),{track:e.track,trackEventName:e.track_event_name,trackProperties:e.track_properties,persistenceType:e.persistence_type,persistencePrefix:e.cookie_prefix,cookieDomain:e.cookie_domain,cookieExpiration:e.cookie_expiration,crossSiteCookie:e.cross_site_cookie,crossSubdomainCookie:e.cross_subdomain_cookie,secureCookie:e.secure_cookie,ignoreDnt:e.ignore_dnt})},U.prototype.opt_in_tracking=function(n){n=m.extend({enable_persistence:!0},n),this._gdpr_call_func(aD,n),this._gdpr_update_persistence(n)},U.prototype.opt_out_tracking=function(n){n=m.extend({clear_persistence:!0,delete_user:!0},n),n.delete_user&&this.people&&this.people._identify_called()&&(this.people.delete_user(),this.people.clear_charges()),this._gdpr_call_func(cD,n),this._gdpr_update_persistence(n)},U.prototype.has_opted_in_tracking=function(n){return this._gdpr_call_func(uD,n)},U.prototype.has_opted_out_tracking=function(n){return this._gdpr_call_func(zB,n)},U.prototype.clear_opt_in_out_tracking=function(n){n=m.extend({enable_persistence:!0},n),this._gdpr_call_func(lD,n),this._gdpr_update_persistence(n)},U.prototype.report_error=function(n,e){we.error.apply(we.error,arguments);try{!e&&!(n instanceof Error)&&(n=new Error(n)),this.get_config("error_reporter")(n,e)}catch(t){we.error(t)}},U.prototype.init=U.prototype.init,U.prototype.reset=U.prototype.reset,U.prototype.disable=U.prototype.disable,U.prototype.time_event=U.prototype.time_event,U.prototype.track=U.prototype.track,U.prototype.track_links=U.prototype.track_links,U.prototype.track_forms=U.prototype.track_forms,U.prototype.track_pageview=U.prototype.track_pageview,U.prototype.register=U.prototype.register,U.prototype.register_once=U.prototype.register_once,U.prototype.unregister=U.prototype.unregister,U.prototype.identify=U.prototype.identify,U.prototype.alias=U.prototype.alias,U.prototype.name_tag=U.prototype.name_tag,U.prototype.set_config=U.prototype.set_config,U.prototype.get_config=U.prototype.get_config,U.prototype.get_api_host=U.prototype.get_api_host,U.prototype.get_property=U.prototype.get_property,U.prototype.get_distinct_id=U.prototype.get_distinct_id,U.prototype.toString=U.prototype.toString,U.prototype.opt_out_tracking=U.prototype.opt_out_tracking,U.prototype.opt_in_tracking=U.prototype.opt_in_tracking,U.prototype.has_opted_out_tracking=U.prototype.has_opted_out_tracking,U.prototype.has_opted_in_tracking=U.prototype.has_opted_in_tracking,U.prototype.clear_opt_in_out_tracking=U.prototype.clear_opt_in_out_tracking,U.prototype.get_group=U.prototype.get_group,U.prototype.set_group=U.prototype.set_group,U.prototype.add_group=U.prototype.add_group,U.prototype.remove_group=U.prototype.remove_group,U.prototype.track_with_groups=U.prototype.track_with_groups,U.prototype.start_batch_senders=U.prototype.start_batch_senders,U.prototype.stop_batch_senders=U.prototype.stop_batch_senders,U.prototype.start_session_recording=U.prototype.start_session_recording,U.prototype.stop_session_recording=U.prototype.stop_session_recording,U.prototype.pause_session_recording=U.prototype.pause_session_recording,U.prototype.resume_session_recording=U.prototype.resume_session_recording,U.prototype.get_session_recording_properties=U.prototype.get_session_recording_properties,U.prototype.get_session_replay_url=U.prototype.get_session_replay_url,U.prototype.get_tab_id=U.prototype.get_tab_id,U.prototype.DEFAULT_API_ROUTES=OC,U.prototype.__get_recorder=U.prototype.__get_recorder,re.prototype.properties=re.prototype.properties,re.prototype.update_search_keyword=re.prototype.update_search_keyword,re.prototype.update_referrer_info=re.prototype.update_referrer_info,re.prototype.get_cross_subdomain=re.prototype.get_cross_subdomain,re.prototype.clear=re.prototype.clear;var cA={},GD=function(){m.each(cA,function(n,e){e!==en&&(Ut[e]=n)}),Ut._=m},jD=function(){Ut.init=function(n,e,t){if(t)return Ut[t]||(Ut[t]=cA[t]=xp(n,e,t),Ut[t]._loaded()),Ut[t];var r=Ut;cA[en]?r=cA[en]:n&&(r=xp(n,e,en),r._loaded(),cA[en]=r),Ut=r,Ip===ND&&(V[en]=Ut),GD()}},WD=function(){function n(){n.done||(n.done=!0,LC=!0,PC=!1,m.each(cA,function(r){r._dom_loaded()}))}function e(){try{ye.documentElement.doScroll("left")}catch{setTimeout(e,1);return}n()}if(ye.addEventListener)ye.readyState==="complete"?n():ye.addEventListener("DOMContentLoaded",n,!1);else if(ye.attachEvent){ye.attachEvent("onreadystatechange",n);var t=!1;try{t=V.frameElement===null}catch{}ye.documentElement.doScroll&&t&&e()}m.register_event(V,"load",n,!0)};function qD(n){return xC=n,Ip=QC,Ut=new U,jD(),Ut.init(),WD(),Ut}function JD(n,e){e()}var Nc=qD(JD);const DC={identify:()=>{},track:()=>{},page:()=>{},reset:()=>{}};Ay(DC);function zD(n,e={}){const t=e.instanceName||`obi_${Math.random().toString(36).slice(2)}`;Nc.init(n,{debug:e.debug===!0,track_pageview:!1,persistence:"localStorage",...e.config||{}},t);const r=Nc.get_instance?Nc.get_instance(t):Nc[t];return{identify:(i,A)=>{var s;try{r.identify(i),A&&((s=r==null?void 0:r.people)!=null&&s.set)&&r.people.set(A)}catch{}},track:(i,A)=>{try{r.track(i,A||{})}catch{}},page:(i,A)=>{try{r.track("Page Viewed",{name:i,...A||{}})}catch{}},reset:()=>{try{r.reset()}catch{}}}}let Hc=null;function Se(){if(Hc)return Hc;const n={VITE_API_BASE_URL:"https://app.coragents.ai",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1}.VITE_MIXPANEL_TOKEN;return n?(Hc=zD(n),Hc):DC}const XD=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,NC="9.23.0",uA=globalThis;function YD(n,e,t=uA){const r=t.__SENTRY__=t.__SENTRY__||{},i=r[NC]=r[NC]||{};return i[n]||(i[n]=e())}const ZD="Sentry Logger ",HC=["debug","info","warn","error","log","assert","trace"],KC={};function $D(n){if(!("console"in uA))return n();const e=uA.console,t={},r=Object.keys(KC);r.forEach(i=>{const A=KC[i];t[i]=e[i],e[i]=A});try{return n()}finally{r.forEach(i=>{e[i]=t[i]})}}function e4(){let n=!1;const e={enable:()=>{n=!0},disable:()=>{n=!1},isEnabled:()=>n};return XD?HC.forEach(t=>{e[t]=(...r)=>{n&&$D(()=>{uA.console[t](`${ZD}[${t}]:`,...r)})}}):HC.forEach(t=>{e[t]=()=>{}}),e}YD("logger",e4);const VC=1e3;function t4(){return Date.now()/VC}function n4(){const{performance:n}=uA;if(!(n!=null&&n.now))return t4;const e=Date.now()-n.now(),t=n.timeOrigin==null?e:n.timeOrigin;return()=>(t+n.now())/VC}n4();const GC=50,lA="?",jC=/\(error: (.*)\)/,WC=/captureMessage|captureException/;function r4(...n){const e=n.sort((t,r)=>t[0]-r[0]).map(t=>t[1]);return(t,r=0,i=0)=>{const A=[],s=t.split(`
124
124
  `);for(let o=r;o<s.length;o++){const a=s[o];if(a.length>1024)continue;const c=jC.test(a)?a.replace(jC,"$1"):a;if(!c.match(/\S*Error: /)){for(const u of e){const l=u(c);if(l){A.push(l);break}}if(A.length>=GC+i)break}}return i4(A.slice(i))}}function i4(n){if(!n.length)return[];const e=Array.from(n);return/sentryWrapped/.test(Kc(e).function||"")&&e.pop(),e.reverse(),WC.test(Kc(e).function||"")&&(e.pop(),WC.test(Kc(e).function||"")&&e.pop()),e.slice(0,GC).map(t=>({...t,filename:t.filename||Kc(e).filename,function:t.function||lA}))}function Kc(n){return n[n.length-1]||{}}var qC;(function(n){n[n.PENDING=0]="PENDING";const e=1;n[n.RESOLVED=e]="RESOLVED";const t=2;n[n.REJECTED=t]="REJECTED"})(qC||(qC={})),uA._sentryClientToLogBufferMap=new WeakMap,typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const A4=30,s4=50;function Rp(n,e,t,r){const i={filename:n,function:e==="<anonymous>"?lA:e,in_app:!0};return t!==void 0&&(i.lineno=t),r!==void 0&&(i.colno=r),i}const o4=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,a4=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,c4=/\((\S*)(?::(\d+))(?::(\d+))\)/,u4=n=>{const e=o4.exec(n);if(e){const[,r,i,A]=e;return Rp(r,lA,+i,+A)}const t=a4.exec(n);if(t){if(t[2]&&t[2].indexOf("eval")===0){const A=c4.exec(t[2]);A&&(t[2]=A[1],t[3]=A[2],t[4]=A[3])}const[r,i]=JC(t[1]||lA,t[2]);return Rp(i,r,t[3]?+t[3]:void 0,t[4]?+t[4]:void 0)}},l4=[A4,u4],d4=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,h4=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i;r4(...[l4,[s4,n=>{const e=d4.exec(n);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){const i=h4.exec(e[3]);i&&(e[1]=e[1]||"eval",e[3]=i[1],e[4]=i[2],e[5]="")}let t=e[3],r=e[1]||lA;return[r,t]=JC(r,t),Rp(t,r,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}}]]);const JC=(n,e)=>{const t=n.indexOf("safari-extension")!==-1,r=n.indexOf("safari-web-extension")!==-1;return t||r?[n.indexOf("@")!==-1?n.split("@")[0]:lA,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[n,e]};typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__;const p4=`:root,:host{--obi-modal-padding: 48px 48px 32px;--obi-modal-background-color: #FFFFFF;--obi-modal-border-radius: 12px;--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: 545px;--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:flex;flex-direction:column;align-items:center;padding:0;gap:16px;width:100%}.tour-content .title{width:100%;font-family:Satoshi,sans-serif;font-style:normal;font-weight:700;font-size:32px;line-height:90%;text-align:center;letter-spacing:-.03em;color:#18181b;margin:0}.tour-content .subtitle{width:100%;font-family:Satoshi,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{width:480px;height:240px;margin-top:24px;border-radius:12px;display:flex;align-items:center;justify-content:center;position:relative}.tour-content .description{width:100%;min-height:48px;margin:24px 0 0;font-family:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:16px;line-height:140%;text-align:center;letter-spacing:-.01em;color:#18181b}.tour-content .button-container{display:flex;margin-top:24px;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;min-width:200px;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:Satoshi,sans-serif;font-style:normal;font-weight:400;font-size:16px;line-height:100%;color:#fbf3ff}.tour.content-area{flex:1;display:flex;flex-direction:column}.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-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-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-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-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-message{display:inline-flex;align-items:center;justify-content:center;min-width:140px;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:6px;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:2px 0;height:6px;flex:1;min-width:0}.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}.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-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-course-progress-container{display:none;width:100%;max-height:0;opacity:0;transform:translateY(-10px);overflow:hidden;transition:max-height .3s ease-in-out,opacity .3s ease-in-out,transform .3s ease-in-out}.obi-widget-panel:hover .obi-course-progress-container{display:block;max-width:22 0px;animation:expand-course-progress .3s ease-in-out forwards}.obi-widget-panel:hover .obi-course-progress-container.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}.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%}
125
- `;function f4(n){let e=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"__DOUBLE_STAR__").replace(/\*/g,"[^/]*").replace(/__DOUBLE_STAR__/g,".*").replace(/\?/g,"[^/]");return new RegExp(`^${e}$`,"i")}function g4(n,e){if(!e||e.length===0)return!1;const t=n.replace(/^https?:\/\//,"").replace(/\/$/,"");return e.some(r=>{try{const i=f4(r);return i.test(t)||i.test(n)}catch(i){return console.warn(`Invalid URL pattern: ${r}`,i),!1}})}function Pp(n){if(!n||n.length===0)return!1;const e=window.location.origin+window.location.pathname;return g4(e,n)}function m4(n){var b,w,_,k,T,x,P;const[e,t]=ge(!1),[r,i]=ge(!1),[A,s]=ge(null),o=v4(n.sdk,a,n.shadowHost,s);function a(E){var F;(F=o.client)!=null&&F.session||(t(E),E&&Se().track("course-list-opened"))}if(!o.client)return null;const c=y4((b=o.client.product)==null?void 0:b.widget_url_blacklist);let u=o.isActive;((_=(w=o.client)==null?void 0:w.product)==null?void 0:_.name)==="Canibuild"&&(u=!0);const l=o.client.session,d=!!l,h=d&&!e;let f;switch(l==null?void 0:l.speakingState){case"listening":f="user-speaking";break;case"speaking":f="agent-speaking";break;case"thinking":f="thinking";break;case"busy":f="busy";break}const p=l==null?void 0:l.isPaused,g=d||o.client.state==="ready"&&u&&!c&&(o.client.selectedPlan||!((k=o.client.product)!=null&&k.widget_link_only_access)),v=h?100:62,y=()=>{var E,F,M,J,N,q;return{name:(E=o.client.selectedPlan)==null?void 0:E.name,description:(F=o.client.selectedPlan)==null?void 0:F.description,appName:(M=o.client.product)==null?void 0:M.name,appLogoUrl:((J=o.client.product)==null?void 0:J.logo_url)||"",url:(N=o.client.product)==null?void 0:N.url,agentName:((q=o.client.product)==null?void 0:q.agent_name)||"Obi"}},B=((T=o.client.product)==null?void 0:T.widget_position)==="bottom-right"?{position:"fixed",top:`calc(100vh - ${v}px)`,right:"250px",width:"max-content",transform:"translateX(50%)"}:{position:"fixed",top:`calc(100vh - ${v}px)`,left:"50%",transform:"translateX(-50%)",width:"max-content"};return C("div",{children:[e&&C(pR,{open:e,courses:o.client.plans.map((E,F)=>{var M,J;return{id:E.uuid,name:E.name,description:E.description||"",duration:E.duration||0,completed:((J=(M=o.client)==null?void 0:M.planIsCompleted)==null?void 0:J[F])||!1}}),loading:!1,agentName:((x=o.client.product)==null?void 0:x.agent_name)||"Obi",onCourseHighlight:E=>{E&&Se().track("course-selected",{courseName:E.name,courseUuid:E.id})},onCourseSelect:E=>{const F=o.client.plans.find(M=>M.uuid===E.id)||null;F&&(F==null?void 0:F.uuid)!==o.client.selectedPlanUuid&&(o.client.selectPlan(F),t(!1),i(!0),Se().track("course-get-started",{courseName:E.name,courseUuid:E.id}))},onClose:E=>{E==="user-initiated"&&o.client.selectPlan(null),t(!1)}}),g&&C(St,{children:[C("div",{style:B,children:C(XQ,{inPlan:d,isActive:r?!1:void 0,defaultIsActive:!0,isPaused:p,messaging:(l==null?void 0:l.isMicShared)===!1?!0:void 0,speakingStatus:f,spectrum:()=>(l==null?void 0:l.audioSpectrum())||null,courseProgress:A,onOpen:()=>{t(!0),Se().track("course-list-opened")},onCancelClick:()=>{Se().track("close-button-clicked")},onCancelAbort:()=>{Se().track("close-confirmation-no")},onCancel:()=>{var E;(E=o.client.session)==null||E.stop(),Se().track("close-confirmation-yes")},onCancelReason:(E,F)=>{Se().track("close-survey-answered",{reason:E,reasonText:F})},onPause:()=>{var E,F;(F=(E=o.client.session)==null?void 0:E.pause)==null||F.call(E),Se().track("pause-button-clicked")},onUnpause:()=>{var E,F;(F=(E=o.client.session)==null?void 0:E.unpause)==null||F.call(E),Se().track("play-button-clicked")},onMessagingChange:E=>{var F,M,J,N;E?((M=(F=o.client.session)==null?void 0:F.muteMicrophone)==null||M.call(F),Se().track("switch-to-chat-clicked")):((N=(J=o.client.session)==null?void 0:J.unmuteMicrophone)==null||N.call(J),Se().track("switch-to-voice-clicked"))},onMessageChange:E=>{Se().track("chat-input-provided",{message:E,length:E.length})},onMessage:E=>{o.say(E),Se().track("chat-message-sent",{message:E,length:E.length})},onHover:E=>{E&&!d&&Se().track("widget-hover-on")},onOneClickAction:E=>{Se().track("one-click-action-clicked",{action:E})},onMinimize:()=>{Se().track("minimise-button-clicked",{inSession:d})},agentName:((P=o.client.product)==null?void 0:P.agent_name)||"Obi",completedTutorials:o.client.planIsCompleted.filter(Boolean).length,totalTutorials:o.client.plans.length})}),!!o.client.selectedPlan&&C(gR,{open:!0,session:y(),sessionState:(l==null?void 0:l.state)||null,speakingState:(l==null?void 0:l.speakingState)||null,spectrum:()=>(l==null?void 0:l.audioSpectrum())||null,onModalChange:E=>{E==="session-start"?Se().track("course-screen-opened"):E==="voice-guidance"?Se().track("can-you-hear-opened"):E==="overview"?Se().track("welcome-tour-opened"):E==="share-mic"&&Se().track("connect-mic-opened")},onClose:(E,F)=>{var M,J;E==="user-initiated"&&(F==="session-start"?Se().track("course-screen-closed"):F==="voice-guidance"?Se().track("can-you-hear-closed"):F==="overview"?Se().track("welcome-tour-closed"):F==="share-mic"&&Se().track("connect-mic-closed"),((M=o.client.session)==null?void 0:M.state)==="mic-share"?(J=o.client.session)==null||J.shareMicrophoneFailed():o.client.stopSession()),i(!1)},onStart:()=>{o.client.selectedPlanUuid&&(Se().track("course-screen-continue"),o.startSession())},onContinue:()=>{l==null||l.continue(),Se().track("can-you-hear-continue")},onShareMicrophone:()=>{l==null||l.shareMicrophone(),Se().track("connect-mic-continue")}})]})]})}function v4(n,e,t,r){const[i,A]=ge(0),[s,o]=ge(null);return Kt(()=>{n.on("showMenu",a=>{e(a)}),n.on("configUpdated",()=>{A(a=>a+1)})},[n]),Kt(()=>{n.client&&(n.client.session&&o(n.client.session),n.client.on("sessionStarted",a=>{o(a),A(c=>c+1)}),n.client.on("sessionStopped",()=>{o(null),A(a=>a+1)}),n.client.on("sessionShutdown",()=>{A(a=>a+1)}),n.client.on("sessionResumed",()=>{A(a=>a+1)}),n.client.on("stateChanged",()=>{var a;n.client.state==="ready"&&t.style.setProperty("--obi-color-primary",((a=n.client.product)==null?void 0:a.primary_color)||"#9500FF"),A(c=>c+1)}),n.client.on("planSelected",()=>{A(a=>a+1)}))},[n,n.client]),Kt(()=>{if(!s)return;s.on("stateChanged",()=>{A(c=>c+1)}),s.on("speakingStateChanged",()=>{A(c=>c+1)}),s.on("paused",()=>{A(c=>c+1)}),s.on("unpaused",()=>{A(c=>c+1)});const a=c=>{r(c)};return s.on&&s.on("courseProgress",a),()=>{s.off&&s.off("courseProgress",a)}},[s]),n}function y4(n){const[e,t]=ge(()=>Pp(n));return Kt(()=>{t(Pp(n))},[n]),Kt(()=>{w4();const r=()=>{t(Pp(n))};return window.addEventListener("locationchange",r),window.addEventListener("popstate",r),window.addEventListener("hashchange",r),()=>{window.removeEventListener("locationchange",r),window.removeEventListener("popstate",r),window.removeEventListener("hashchange",r)}},[n]),e}function w4(){const n=window;if(n.__obi_history_patched)return;const{pushState:e,replaceState:t}=window.history,r=i=>function(...A){const s=i.apply(this,A);return window.dispatchEvent(new Event("locationchange")),s};window.history.pushState=r(e),window.history.replaceState=r(t),n.__obi_history_patched=!0}function b4(n){if(document.querySelector("obi-widget"))return;B4();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"}),r=document.createElement("div");r.id="obi-container",t.appendChild(r);const i=new CSSStyleSheet;i.replaceSync(p4),t.adoptedStyleSheets=[i],mQ(C(m4,{sdk:n,shadowHost:e}),r),console.log("[obi-sdk] widget mounted")}function B4(){zC("https://fonts.cdnfonts.com/css/satoshi"),zC("https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap")}function zC(n){const e=document.createElement("link");e.href=n,e.rel="stylesheet",document.head.appendChild(e)}const XC="49206C6F7665204F6269_session",YC="obi-url-params";class C4 extends jc{constructor(e){super(),this.client=null,this.isActive=!1,this.primaryColour="#9500FF",this.passivePlanUuid=null,this.commandQueue=[],this._resumed=!1,this.dispatchCommand=(t,r)=>{var i,A,s,o,a;switch(t){case"update":this.updateConfig(r);break;case"startSession":if(!(r!=null&&r.planUuid)){console.warn("[obi] startSession command requires a planUuid",r);return}const c=(((i=this.client)==null?void 0:i.plans)||[]).find(u=>u.uuid===r.planUuid)||null;if(!c){console.warn("[obi] startSession command requires a valid planUuid",r);return}this.updateActive(!0),(s=(A=this.client)==null?void 0:A.selectPlan)==null||s.call(A,c);break;case"stopSession":(a=(o=this.client)==null?void 0:o.stopSession)==null||a.call(o);break;case"say":this.say(r);break;default:console.warn("[obi] unknown command",{commandType:t,args:r})}},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 r=this.load();if(r)try{t=fa.deserialise(r,e,"sdk",{apiBaseUrl:"https://staging.coragents.ai",captureScreen:this.captureScreen.bind(this)}),this._resumed=!0}catch(i){console.error("[obi] error loading cached client",i)}t||(t=new fa(e,"sdk",{apiBaseUrl:"https://staging.coragents.ai",captureScreen:this.captureScreen.bind(this)})),this.client=t,this.client.on("stateChanged",i=>{var A,s,o;i==="ready"&&this.updateConfig({isActive:(A=this.client)==null?void 0:A.showWidget,primaryColour:((o=(s=this.client)==null?void 0:s.product)==null?void 0:o.primary_color)||"#9500FF"})}),this.client.on("sessionStarted",()=>{this.save(),this.passivePlanUuid=null}),this.client.on("sessionStopped",()=>{localStorage.removeItem("obi-client"),this.passivePlanUuid=null}),this.client.on("sessionShutdown",i=>{i==="invalid-room"&&localStorage.removeItem("obi-client")}),this.client.on("trackEvent",(i,A)=>{Se().track(i,A)}),this.client.session&&this.client.resumeSession(i=>{i.on("stateChanged",A=>{A!=="disconnecting"&&A!=="disconnected"&&A!=="error"&&A!=="connecting"&&this.save()}),i.on("paused",()=>{this.save()}),i.on("unpaused",()=>{this.save()})})}async initialise(e={}){this.commandQueue=e.queuedCommands||[],this._resumed?(this._resumed=!1,this.dispatchCommandQueue()):this.client?this.client.initialise({planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised"),this.dispatchCommandQueue()}).catch(t=>{console.error("[obi] error initialising client",t),this.emit("error",t)}):this.dispatchCommandQueue()}async updateConfig(e){await this.updateAppToken(e.apiKey),this.updateActive(e.isActive),this.updatePrimaryColour(e.primaryColour),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")}).catch(r=>{console.error("[obi] error initialising client",r),this.emit("error",r)}))}updateActive(e){e===void 0||e==this.isActive||(this.isActive=e)}updatePrimaryColour(e){e===void 0||e==this.primaryColour||(this.primaryColour=e)}async updateIdentity(e){var r;if(e===void 0||e==((r=this.client)==null?void 0:r.identity))return;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")}).catch(i=>{console.error("[obi] error initialising client",i),this.emit("error",i)}),e!=null&&e.email&&Se().identify((e==null?void 0:e.email)||"",t)}updateShowMenu(e){e!==void 0&&this.emit("showMenu",e)}async say(e){var t,r,i;await((i=(r=(t=this.client)==null?void 0:t.session)==null?void 0:r.say)==null?void 0:i.call(r,e))}async startSession(){await this.client.startSession(this.client.selectedPlan.uuid,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(r){console.error("[obi] error dispatching command",r)}})}parsePassiveParams(){if(this.passivePlanUuid){this.passivePlanUuid;return}let e={};e=JSON.parse(localStorage.getItem(YC)||"{}"),Object.keys(e).length===0&&new URLSearchParams(window.location.search).forEach((A,s)=>{e[s]=A});const t=e[XC];if(!t)return null;const r=new URL(window.location.href);r.searchParams.delete(XC),window.history.replaceState({},"",r.toString()),r.toString(),localStorage.removeItem(YC),this.passivePlanUuid=t}mountWidget(){b4(this)}async captureScreen(){return(await CT(document.documentElement,{useCORS:!0,allowTaint:!0,foreignObjectRendering:!0})).toDataURL("image/png")}save(){var e;localStorage.setItem("obi-client",((e=this.client)==null?void 0:e.serialise())||"")}load(){return localStorage.getItem("obi-client")}}async function ZC(n){let e;try{e=window}catch{console.warn("[obi] no window object found"),e={}}return _4({appToken:n,window:e})}async function _4({appToken:n,window:e}){var i,A;if(e.obi){console.warn("[obi] obi object already found on window, skipping");return}n||(n=(i=e==null?void 0:e.obiWidgetConfig)==null?void 0:i.apiKey);let t;try{t=((A=e.ObiSDK)==null?void 0:A.q)||[]}catch{t=[]}const r=new C4(n);return e.ObiSDK=r.dispatchCommand,await r.initialise({queuedCommands:t}),e.obi=r,r.mountWidget(),r}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{ZC()}):ZC()})();
125
+ `;function f4(n){let e=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"__DOUBLE_STAR__").replace(/\*/g,"[^/]*").replace(/__DOUBLE_STAR__/g,".*").replace(/\?/g,"[^/]");return new RegExp(`^${e}$`,"i")}function g4(n,e){if(!e||e.length===0)return!1;const t=n.replace(/^https?:\/\//,"").replace(/\/$/,"");return e.some(r=>{try{const i=f4(r);return i.test(t)||i.test(n)}catch(i){return console.warn(`Invalid URL pattern: ${r}`,i),!1}})}function Pp(n){if(!n||n.length===0)return!1;const e=window.location.origin+window.location.pathname;return g4(e,n)}function m4(n){var b,w,_,k,T,x,P;const[e,t]=ge(!1),[r,i]=ge(!1),[A,s]=ge(null),o=v4(n.sdk,a,n.shadowHost,s);function a(E){var F;(F=o.client)!=null&&F.session||(t(E),E&&Se().track("course-list-opened"))}if(!o.client)return null;const c=y4((b=o.client.product)==null?void 0:b.widget_url_blacklist);let u=o.isActive;((_=(w=o.client)==null?void 0:w.product)==null?void 0:_.name)==="Canibuild"&&(u=!0);const l=o.client.session,d=!!l,h=d&&!e;let f;switch(l==null?void 0:l.speakingState){case"listening":f="user-speaking";break;case"speaking":f="agent-speaking";break;case"thinking":f="thinking";break;case"busy":f="busy";break}const p=l==null?void 0:l.isPaused,g=d||o.client.state==="ready"&&u&&!c&&(o.client.selectedPlan||!((k=o.client.product)!=null&&k.widget_link_only_access)),v=h?100:62,y=()=>{var E,F,M,J,N,q;return{name:(E=o.client.selectedPlan)==null?void 0:E.name,description:(F=o.client.selectedPlan)==null?void 0:F.description,appName:(M=o.client.product)==null?void 0:M.name,appLogoUrl:((J=o.client.product)==null?void 0:J.logo_url)||"",url:(N=o.client.product)==null?void 0:N.url,agentName:((q=o.client.product)==null?void 0:q.agent_name)||"Obi"}},B=((T=o.client.product)==null?void 0:T.widget_position)==="bottom-right"?{position:"fixed",top:`calc(100vh - ${v}px)`,right:"250px",width:"max-content",transform:"translateX(50%)"}:{position:"fixed",top:`calc(100vh - ${v}px)`,left:"50%",transform:"translateX(-50%)",width:"max-content"};return C("div",{children:[e&&C(pR,{open:e,courses:o.client.plans.map((E,F)=>{var M,J;return{id:E.uuid,name:E.name,description:E.description||"",duration:E.duration||0,completed:((J=(M=o.client)==null?void 0:M.planIsCompleted)==null?void 0:J[F])||!1}}),loading:!1,agentName:((x=o.client.product)==null?void 0:x.agent_name)||"Obi",onCourseHighlight:E=>{E&&Se().track("course-selected",{courseName:E.name,courseUuid:E.id})},onCourseSelect:E=>{const F=o.client.plans.find(M=>M.uuid===E.id)||null;F&&(F==null?void 0:F.uuid)!==o.client.selectedPlanUuid&&(o.client.selectPlan(F),t(!1),i(!0),Se().track("course-get-started",{courseName:E.name,courseUuid:E.id}))},onClose:E=>{E==="user-initiated"&&o.client.selectPlan(null),t(!1)}}),g&&C(St,{children:[C("div",{style:B,children:C(XQ,{inPlan:d,isActive:r?!1:void 0,defaultIsActive:!0,isPaused:p,messaging:(l==null?void 0:l.isMicShared)===!1?!0:void 0,speakingStatus:f,spectrum:()=>(l==null?void 0:l.audioSpectrum())||null,courseProgress:A,onOpen:()=>{t(!0),Se().track("course-list-opened")},onCancelClick:()=>{Se().track("close-button-clicked")},onCancelAbort:()=>{Se().track("close-confirmation-no")},onCancel:()=>{var E;(E=o.client.session)==null||E.stop(),Se().track("close-confirmation-yes")},onCancelReason:(E,F)=>{Se().track("close-survey-answered",{reason:E,reasonText:F})},onPause:()=>{var E,F;(F=(E=o.client.session)==null?void 0:E.pause)==null||F.call(E),Se().track("pause-button-clicked")},onUnpause:()=>{var E,F;(F=(E=o.client.session)==null?void 0:E.unpause)==null||F.call(E),Se().track("play-button-clicked")},onMessagingChange:E=>{var F,M,J,N;E?((M=(F=o.client.session)==null?void 0:F.muteMicrophone)==null||M.call(F),Se().track("switch-to-chat-clicked")):((N=(J=o.client.session)==null?void 0:J.unmuteMicrophone)==null||N.call(J),Se().track("switch-to-voice-clicked"))},onMessageChange:E=>{Se().track("chat-input-provided",{message:E,length:E.length})},onMessage:E=>{o.say(E),Se().track("chat-message-sent",{message:E,length:E.length})},onHover:E=>{E&&!d&&Se().track("widget-hover-on")},onOneClickAction:E=>{Se().track("one-click-action-clicked",{action:E})},onMinimize:()=>{Se().track("minimise-button-clicked",{inSession:d})},agentName:((P=o.client.product)==null?void 0:P.agent_name)||"Obi",completedTutorials:o.client.planIsCompleted.filter(Boolean).length,totalTutorials:o.client.plans.length})}),!!o.client.selectedPlan&&C(gR,{open:!0,session:y(),sessionState:(l==null?void 0:l.state)||null,speakingState:(l==null?void 0:l.speakingState)||null,spectrum:()=>(l==null?void 0:l.audioSpectrum())||null,onModalChange:E=>{E==="session-start"?Se().track("course-screen-opened"):E==="voice-guidance"?Se().track("can-you-hear-opened"):E==="overview"?Se().track("welcome-tour-opened"):E==="share-mic"&&Se().track("connect-mic-opened")},onClose:(E,F)=>{var M,J;E==="user-initiated"&&(F==="session-start"?Se().track("course-screen-closed"):F==="voice-guidance"?Se().track("can-you-hear-closed"):F==="overview"?Se().track("welcome-tour-closed"):F==="share-mic"&&Se().track("connect-mic-closed"),((M=o.client.session)==null?void 0:M.state)==="mic-share"?(J=o.client.session)==null||J.shareMicrophoneFailed():o.client.stopSession()),i(!1)},onStart:()=>{o.client.selectedPlanUuid&&(Se().track("course-screen-continue"),o.startSession())},onContinue:()=>{l==null||l.continue(),Se().track("can-you-hear-continue")},onShareMicrophone:()=>{l==null||l.shareMicrophone(),Se().track("connect-mic-continue")}})]})]})}function v4(n,e,t,r){const[i,A]=ge(0),[s,o]=ge(null);return Kt(()=>{n.on("showMenu",a=>{e(a)}),n.on("configUpdated",()=>{A(a=>a+1)})},[n]),Kt(()=>{n.client&&(n.client.session&&o(n.client.session),n.client.on("sessionStarted",a=>{o(a),A(c=>c+1)}),n.client.on("sessionStopped",()=>{o(null),A(a=>a+1)}),n.client.on("sessionShutdown",()=>{A(a=>a+1)}),n.client.on("sessionResumed",()=>{A(a=>a+1)}),n.client.on("stateChanged",()=>{var a;n.client.state==="ready"&&t.style.setProperty("--obi-color-primary",((a=n.client.product)==null?void 0:a.primary_color)||"#9500FF"),A(c=>c+1)}),n.client.on("planSelected",()=>{A(a=>a+1)}))},[n,n.client]),Kt(()=>{if(!s)return;s.on("stateChanged",()=>{A(c=>c+1)}),s.on("speakingStateChanged",()=>{A(c=>c+1)}),s.on("paused",()=>{A(c=>c+1)}),s.on("unpaused",()=>{A(c=>c+1)});const a=c=>{r(c)};return s.on&&s.on("courseProgress",a),()=>{s.off&&s.off("courseProgress",a)}},[s]),n}function y4(n){const[e,t]=ge(()=>Pp(n));return Kt(()=>{t(Pp(n))},[n]),Kt(()=>{w4();const r=()=>{t(Pp(n))};return window.addEventListener("locationchange",r),window.addEventListener("popstate",r),window.addEventListener("hashchange",r),()=>{window.removeEventListener("locationchange",r),window.removeEventListener("popstate",r),window.removeEventListener("hashchange",r)}},[n]),e}function w4(){const n=window;if(n.__obi_history_patched)return;const{pushState:e,replaceState:t}=window.history,r=i=>function(...A){const s=i.apply(this,A);return window.dispatchEvent(new Event("locationchange")),s};window.history.pushState=r(e),window.history.replaceState=r(t),n.__obi_history_patched=!0}function b4(n){if(document.querySelector("obi-widget"))return;B4();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"}),r=document.createElement("div");r.id="obi-container",t.appendChild(r);const i=new CSSStyleSheet;i.replaceSync(p4),t.adoptedStyleSheets=[i],mQ(C(m4,{sdk:n,shadowHost:e}),r),console.log("[obi-sdk] widget mounted")}function B4(){zC("https://fonts.cdnfonts.com/css/satoshi"),zC("https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap")}function zC(n){const e=document.createElement("link");e.href=n,e.rel="stylesheet",document.head.appendChild(e)}const XC="49206C6F7665204F6269_session",YC="obi-url-params";class C4 extends jc{constructor(e){super(),this.client=null,this.isActive=!1,this.primaryColour="#9500FF",this.passivePlanUuid=null,this.commandQueue=[],this._resumed=!1,this.dispatchCommand=(t,r)=>{var i,A,s,o,a;switch(t){case"update":this.updateConfig(r);break;case"startSession":if(!(r!=null&&r.planUuid)){console.warn("[obi] startSession command requires a planUuid",r);return}const c=(((i=this.client)==null?void 0:i.plans)||[]).find(u=>u.uuid===r.planUuid)||null;if(!c){console.warn("[obi] startSession command requires a valid planUuid",r);return}this.updateActive(!0),(s=(A=this.client)==null?void 0:A.selectPlan)==null||s.call(A,c);break;case"stopSession":(a=(o=this.client)==null?void 0:o.stopSession)==null||a.call(o);break;case"say":this.say(r);break;default:console.warn("[obi] unknown command",{commandType:t,args:r})}},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 r=this.load();if(r)try{t=fa.deserialise(r,e,"sdk",{apiBaseUrl:"https://app.coragents.ai",captureScreen:this.captureScreen.bind(this)}),this._resumed=!0}catch(i){console.error("[obi] error loading cached client",i)}t||(t=new fa(e,"sdk",{apiBaseUrl:"https://app.coragents.ai",captureScreen:this.captureScreen.bind(this)})),this.client=t,this.client.on("stateChanged",i=>{var A,s,o;i==="ready"&&this.updateConfig({isActive:(A=this.client)==null?void 0:A.showWidget,primaryColour:((o=(s=this.client)==null?void 0:s.product)==null?void 0:o.primary_color)||"#9500FF"})}),this.client.on("sessionStarted",()=>{this.save(),this.passivePlanUuid=null}),this.client.on("sessionStopped",()=>{localStorage.removeItem("obi-client"),this.passivePlanUuid=null}),this.client.on("sessionShutdown",i=>{i==="invalid-room"&&localStorage.removeItem("obi-client")}),this.client.on("trackEvent",(i,A)=>{Se().track(i,A)}),this.client.session&&this.client.resumeSession(i=>{i.on("stateChanged",A=>{A!=="disconnecting"&&A!=="disconnected"&&A!=="error"&&A!=="connecting"&&this.save()}),i.on("paused",()=>{this.save()}),i.on("unpaused",()=>{this.save()})})}async initialise(e={}){this.commandQueue=e.queuedCommands||[],this._resumed?(this._resumed=!1,this.dispatchCommandQueue()):this.client?this.client.initialise({planUuid:this.passivePlanUuid||void 0}).then(()=>{this.emit("initialised"),this.dispatchCommandQueue()}).catch(t=>{console.error("[obi] error initialising client",t),this.emit("error",t)}):this.dispatchCommandQueue()}async updateConfig(e){await this.updateAppToken(e.apiKey),this.updateActive(e.isActive),this.updatePrimaryColour(e.primaryColour),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")}).catch(r=>{console.error("[obi] error initialising client",r),this.emit("error",r)}))}updateActive(e){e===void 0||e==this.isActive||(this.isActive=e)}updatePrimaryColour(e){e===void 0||e==this.primaryColour||(this.primaryColour=e)}async updateIdentity(e){var r;if(e===void 0||e==((r=this.client)==null?void 0:r.identity))return;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")}).catch(i=>{console.error("[obi] error initialising client",i),this.emit("error",i)}),e!=null&&e.email&&Se().identify((e==null?void 0:e.email)||"",t)}updateShowMenu(e){e!==void 0&&this.emit("showMenu",e)}async say(e){var t,r,i;await((i=(r=(t=this.client)==null?void 0:t.session)==null?void 0:r.say)==null?void 0:i.call(r,e))}async startSession(){await this.client.startSession(this.client.selectedPlan.uuid,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(r){console.error("[obi] error dispatching command",r)}})}parsePassiveParams(){if(this.passivePlanUuid){this.passivePlanUuid;return}let e={};e=JSON.parse(localStorage.getItem(YC)||"{}"),Object.keys(e).length===0&&new URLSearchParams(window.location.search).forEach((A,s)=>{e[s]=A});const t=e[XC];if(!t)return null;const r=new URL(window.location.href);r.searchParams.delete(XC),window.history.replaceState({},"",r.toString()),r.toString(),localStorage.removeItem(YC),this.passivePlanUuid=t}mountWidget(){b4(this)}async captureScreen(){return(await CT(document.documentElement,{useCORS:!0,allowTaint:!0,foreignObjectRendering:!0})).toDataURL("image/png")}save(){var e;localStorage.setItem("obi-client",((e=this.client)==null?void 0:e.serialise())||"")}load(){return localStorage.getItem("obi-client")}}async function ZC(n){let e;try{e=window}catch{console.warn("[obi] no window object found"),e={}}return _4({appToken:n,window:e})}async function _4({appToken:n,window:e}){var i,A;if(e.obi){console.warn("[obi] obi object already found on window, skipping");return}n||(n=(i=e==null?void 0:e.obiWidgetConfig)==null?void 0:i.apiKey);let t;try{t=((A=e.ObiSDK)==null?void 0:A.q)||[]}catch{t=[]}const r=new C4(n);return e.ObiSDK=r.dispatchCommand,await r.initialise({queuedCommands:t}),e.obi=r,r.mountWidget(),r}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{ZC()}):ZC()})();