@telnyx/ai-agent-widget 0.34.0 → 0.34.1

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.
@@ -112,7 +112,7 @@ var Tw=Object.defineProperty;var Ew=(rt,K,Gt)=>K in rt?Tw(rt,K,{enumerable:!0,co
112
112
  `,JSON.stringify(s,null,2),`
113
113
  `),(n=this._wsClient)===null||n===void 0||n.send(JSON.stringify(s)),a}close(){if(y.debug("Connection.close() called",{hasWsClient:!!this._wsClient,closing:this.closing,closed:this.closed,socketGeneration:this.socketGeneration,safetyTimeoutId:this._safetyTimeoutId,sessionId:this.session.sessionid}),!this._wsClient||this.closing)return;this._cleanupPendingRequests();const e=this._wsClient;Ri(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout(()=>this._handleCloseTimeout(e),5e3))}_registerSocketEvents(e){const i=this.socketGeneration;e.onopen=n=>(y.debug("WebSocket onopen",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid}),B(P.SocketOpen,n,this.session.uuid)),e.onclose=n=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),y.debug("WebSocket onclose",{code:n==null?void 0:n.code,reason:n==null?void 0:n.reason,wasClean:n==null?void 0:n.wasClean,socketGeneration:i,sessionId:this.session.sessionid}),B(P.SocketClose,{event:n,socketGeneration:i},this.session.uuid)),e.onerror=n=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error"),y.debug("WebSocket onerror",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const s=ne(Wy);return B(P.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid),B(P.SocketError,{error:n,sessionId:this.session.sessionid,socketGeneration:i},this.session.uuid)},e.onmessage=n=>{var s,o;this.lastInboundAt=Date.now(),B(P.SocketActivity,{timestamp:this.lastInboundAt},this.session.uuid);const r=Qu(n.data);var a;if(typeof r!="string"){if(r.voice_sdk_id&&(this.session.callReportVoiceSdkId=r.voice_sdk_id,a=r.voice_sdk_id,sessionStorage.setItem(kr,a)),this._unsetTimer(r.id),y.debug(`RECV:
114
114
  `,JSON.stringify(r,null,2),`
115
- `),Oe[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!B(r.id,r)){const l=Er(r);B(P.SocketMessage,r,this.session.uuid),l&&(this.previousGatewayState=l)}}else this._handleStringResponse(r)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(e){this._safetyTimeoutId=null,e&&e.readyState!==ch?(y.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e?y.debug("Safety timeout: socket was replaced, not emitting SocketClose",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}):(y.debug("Safety timeout: emitting SocketClose for stuck socket",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}),B(P.SocketClose,{code:qu.ABNORMAL_CLOSURE,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1,socketGeneration:this.socketGeneration},this.session.uuid))):y.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(y.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,i){this._wsClient===e?(y.debug(`Nulling socket reference (reason: ${i})`),this._wsClient=null):y.debug(`Skipping socket cleanup - old socket already replaced (reason: ${i})`)}_cleanupPendingRequests(){Array.from(this._pendingRequestIds).forEach(e=>{bt(e);const i=this._pendingRequestTimers.get(e),n=this._pendingRequestRejecters.get(e);i&&(clearTimeout(i),this._pendingRequestTimers.delete(e),n&&n.reject(new Tr(e,n.generation,this.socketGeneration))),this._pendingRequestRejecters.delete(e)}),this._pendingRequestIds.clear()}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),B(P.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else y.warn("Unknown message from socket",e)}}fs.DEFAULT_REQUEST_TIMEOUT_MS=1e4;class Li{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:ki()},e)}buildNotification(e){this.request=Object.assign({jsonrpc:"2.0"},e)}}const dh={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class Ue extends Li{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=Pu(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const n in dh)n&&i.hasOwnProperty(n)&&(i[dh[n]]=i[n],delete i[n]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class uh extends Ue{constructor(e){super(),this.method=Z.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class j0{constructor(e){this.pendingRequestId=null,this.onSocketMessage=i=>V(this,void 0,void 0,function*(){i.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Er(i))}),this.getIsRegistered=()=>V(this,void 0,void 0,function*(){const i=new uh(gn());this.pendingRequestId=i.request.id,this.gatewayStateTask=th({}),this.session.execute(i);const n=yield this.gatewayStateTask.promise;return!!n&&[Oe.REGISTER,Oe.REGED].includes(n)}),this.session=e,this.gatewayStateTask=th({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Lr extends Ue{constructor(e){super(),this.method=Z.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Di{constructor(e){this._session=e,this._lastInboundAt=0,this._lastProbeSentAt=0,this._probeInFlight=!1,this._intervalId=null,this._pendingMediaRecovery=null,this._browserWasOffline=!1,this._onlineHandler=null,this._offlineHandler=null}static isCriticalMethod(e){return Di.CRITICAL_METHODS.has(e)}start(){this._intervalId||(y.debug("Signaling health: monitor started"),this._lastInboundAt=Date.now(),this._probeInFlight=!1,this._lastProbeSentAt=0,this._setupBrowserListeners(),this._intervalId=setInterval(()=>this._check(),3e3))}stop(){this._intervalId&&(clearInterval(this._intervalId),this._intervalId=null,this._probeInFlight=!1,this._lastProbeSentAt=0),this._pendingMediaRecovery=null,this._cleanupBrowserListeners(),y.debug("Signaling health: monitor stopped")}get isRunning(){return this._intervalId!==null}get isProbeInFlight(){return this._probeInFlight}onSocketActivity(){this._lastInboundAt=Date.now()}_resolveProbe(){if(!this._probeInFlight)return;if(this._probeInFlight=!1,this._lastProbeSentAt=0,this._lastInboundAt=Date.now(),y.debug("Signaling health: probe resolved by matching Ping response"),!this._pendingMediaRecovery)return void y.debug("Signaling health: probe resolved but no pending media recovery");const e=this._pendingMediaRecovery;this._pendingMediaRecovery=null,this._getSignalingHealthState()==="healthy"&&(y.info(`Signaling health: signaling probe resolved, triggering pending ICE restart for call ${e.callId}`),this._triggerIceRestart(e.callId,e.reason))}_probeIfNeeded(e){var i;!((i=this._session.connection)===null||i===void 0)&&i.connected&&(this._probeInFlight?y.debug(`Signaling health: probe already in flight, skipping duplicate probe (${e})`):(y.info(`Signaling health: ${e}, sending signaling probe`),this._sendProbe()))}onRequestTimeout(e,i,n=""){var s;!((s=this._session.connection)===null||s===void 0)&&s.connected&&(Di.isCriticalMethod(n)?(y.warn(`Critical signaling request timed out (id=${e}, method=${n}, timeout=${i}ms) — declaring signaling unhealthy`),this._triggerSignalingRecovery(`Critical signaling request timed out (method=${n}, id=${e}, timeout=${i}ms)`,"request")):y.warn(`Non-critical signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms) — logging but not triggering signaling recovery`))}onPeerFailure(e,i){y.warn(`Signaling health: peer failure reported (callId=${e}, evidence=${i})`),this._recoverMediaOrSignaling(e,`Peer connection failure (${i})`,`Peer failure detected (${i}) while signaling is unhealthy`,"peer_failure")}onNoRtp(e,i){y.warn(`Signaling health: no RTP detected (callId=${e}, direction=${i})`),this._recoverMediaOrSignaling(e,`No RTP ${i} while media should be active`,`No RTP ${i} while signaling is unhealthy`,"no_rtp")}_setupBrowserListeners(){typeof window>"u"||this._onlineHandler||(this._onlineHandler=()=>{this._browserWasOffline&&(y.debug(`Signaling health: browser online — clearing browser offline state for session ${this._session.sessionid}`),this._browserWasOffline=!1)},this._offlineHandler=()=>{this._browserWasOffline=!0,y.debug(`Signaling health: browser offline signal received for session ${this._session.sessionid}`);const e=ne(Yy);B(P.Error,{error:e,sessionId:this._session.sessionid},this._session.uuid),this.isRunning&&this._probeIfNeeded("browser offline signal while monitor is active")},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupBrowserListeners(){typeof window<"u"&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null,this._browserWasOffline=!1)}onIceRestartFailed(e){y.warn(`Signaling health: ICE restart failed (callId=${e}) — triggering socket reconnect`),this._triggerSignalingRecovery(`ICE restart failed for call ${e}`,"peer_failure")}_check(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return;const i=Date.now(),n=i-this._lastInboundAt;if(n<2e4)return;if(!this._probeInFlight)return y.info(`Signaling health: no inbound WS activity for ${Math.round(n/1e3)}s during active call, sending health probe`),void this._sendProbe();const s=i-this._lastProbeSentAt;s>=5e3&&(y.warn(`Signaling health: probe timed out after ${s}ms with no inbound activity — declaring signaling unhealthy`),this._triggerSignalingRecovery("Signaling health probe timed out: no inbound WS activity after probe","probe"))}_sendProbe(){var e;this._probeInFlight=!0,this._lastProbeSentAt=Date.now();const i=new Lr(gn());(e=this._session.connection)===null||e===void 0||e.send(i).then(()=>this._resolveProbe()).catch(n=>{y.warn("Signaling health: probe Ping failed to send",n)})}_recoverMediaOrSignaling(e,i,n,s){if(!this._session.hasActiveCall())return void y.debug(`Signaling health: ignoring ${s} recovery without an active call`);const o=this._getSignalingHealthState();return o==="healthy"?(y.info(`Signaling health: signaling is healthy, triggering ICE restart for call ${e}`),void this._triggerIceRestart(e,i)):o==="unknown"?(y.info(`Signaling health: signaling health is unknown, deferring ICE restart decision for call ${e}`),this._pendingMediaRecovery={callId:e,reason:i,source:s},void this._probeIfNeeded(`${s} detected with stale/unknown signaling`)):(y.info("Signaling health: signaling is unhealthy, triggering socket reconnect instead of ICE restart"),void this._triggerSignalingRecovery(n,s))}_getSignalingHealthState(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return"unhealthy";if(this._probeInFlight)return"unknown";const i=Date.now(),n=this._lastInboundAt||this._session.connection.lastInboundAt||0;return n===0?"unknown":i-n<3e3?"healthy":"unknown"}_triggerSignalingRecovery(e,i="probe"){var n,s,o;this._pendingMediaRecovery=null,this._probeInFlight=!1,this._lastProbeSentAt=0,y.debug(`Signaling recovery triggered (source=${i}, reason=${e})`);const r=Ne(p0);B(P.Warning,{warning:r,reason:e,source:i,sessionId:this._session.sessionid},this._session.uuid),!((n=this._session.connection)===null||n===void 0)&&n.connected?(y.info("Signaling health: force-closing WebSocket to trigger reconnect"),this._session.socketDisconnect()):y.debug("Signaling health: recovery triggered but connection not connected",{connected:(s=this._session.connection)===null||s===void 0?void 0:s.connected,hasConnection:!!this._session.connection,socketGeneration:(o=this._session.connection)===null||o===void 0?void 0:o.socketGeneration})}_triggerIceRestart(e,i){y.info(`Signaling health: triggering ICE restart for call ${e}`);const n=this._session.triggerIceRestart(e);if(!n.started)return void y.info(`Signaling health: ICE restart not started for call ${e}: ${n.reason}`);const s=Ne(g0);B(P.Warning,{warning:s,reason:i,callId:e,sessionId:this._session.sessionid},this._session.uuid)}}Di.CRITICAL_METHODS=new Set([Z.Modify,Z.Bye,Z.Ping]);var hh="2.27.8-beta.0",Dr=hh;class $0 extends Ue{constructor(e,i,n,s,o={},r){super(),this.method="login";const a={login:e,passwd:i,login_token:n,userVariables:o,reconnection:r,loginParams:{},"User-Agent":{sdkVersion:Dr,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class H0 extends Ue{constructor(e,i){super(),this.buildRequest({id:e,result:{method:i}})}}class fh extends Ue{toString(){return Z.Invite}}class ph extends Ue{toString(){return Z.Answer}}class gh extends Ue{toString(){return Z.Attach}}class W0 extends Ue{toString(){return Z.Bye}}class G0 extends Ue{toString(){return Z.Candidate}}class q0 extends Ue{toString(){return Z.EndOfCandidates}}class ps extends Ue{toString(){return Z.Modify}}class mh extends Ue{toString(){return Z.Info}}class z0 extends Ue{toString(){return Z.Broadcast}}class K0 extends Ue{toString(){return Z.Subscribe}}class Y0 extends Ue{toString(){return Z.Unsubscribe}}class X0 extends Ue{constructor(e){super(),this.method="anonymous_login";const{target_type:i,target_id:n,target_version_id:s,target_params:o,userVariables:r,sessionId:a,reconnection:l}=e,c={target_type:i,target_id:n,userVariables:r,reconnection:l,"User-Agent":{sdkVersion:Dr,data:navigator.userAgent}};a&&(c.sessid=a),s&&(c.target_version_id=s),o&&(c.target_params=o),this.buildRequest({method:this.method,params:c})}}class ti{constructor(e){if(this.options=e,this.uuid=ki(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.callReportId=null,this.callReportVoiceSdkId=null,this.dc=null,this.region=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._reconnectAttempts=0,this._reconnectCountedGeneration=-1,this._intentionalClose=!1,this._tokenExpiryTimeout=null,this._pendingCallReportUploads=new Set,this._signalingHealthMonitor=new Di(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var i,n;i=e.debug?"debug":"info",Ju=(n=ls[i])!==null&&n!==void 0?n:ls.info,this._onSocketOpen=this._onSocketOpen.bind(this),this.onNetworkClose=this.onNetworkClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._onSocketActivity=this._onSocketActivity.bind(this),this._attachListeners(),this.connection=new fs(this),this.registerAgent=new j0(this)}get __logger(){return y}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return V(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){const e=this._reconnectAttempts,i=Math.min(1e3*Math.pow(2,e-1),3e4),n=Math.floor(.25*i*(2*Math.random()-1)),s=i+n;return y.debug("Reconnect delay computed",{attempt:e,baseDelayMs:1e3,maxDelayMs:3e4,delayMs:i,jitterMs:n,totalDelay:s,sessionId:this.sessionid}),s}execute(e){var i;if(this._idle)return new Promise(s=>this._executeQueue.push({resolve:s,msg:e}));if(!this.connected)return new Promise(s=>{this._executeQueue.push({resolve:s,msg:e}),y.debug("Calling connect from execute since not currently connected."),this.connect()});const n=Di.isCriticalMethod(((i=e.request)===null||i===void 0?void 0:i.method)||"")?fs.DEFAULT_REQUEST_TIMEOUT_MS:void 0;return(n!=null?this.connection.send(e,n):this.connection.send(e)).catch(s=>V(this,void 0,void 0,function*(){if(s instanceof Tr)throw y.debug(`Stale request settled (id=${s.requestId}, gen=${s.staleGeneration}) — not triggering recovery`),s;if((s==null?void 0:s.name)==="RequestTimeoutError")throw this.onSignalingRequestTimeout(s.requestId,s.timeoutMs,s.method),s;if((s==null?void 0:s.code)===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const o=ne(zy,s,void 0,!0);B(P.Error,{error:o,sessionId:this.sessionid},this.uuid)}yield this.login()}throw s}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}trackCallReportUpload(e){this._pendingCallReportUploads.add(e),e.then(()=>this._pendingCallReportUploads.delete(e),()=>this._pendingCallReportUploads.delete(e))}_drainCallReportUploads(){return V(this,void 0,void 0,function*(){if(this._pendingCallReportUploads.size===0)return;const e=Array.from(this._pendingCallReportUploads);let i=!1;yield Promise.race([Promise.all(e.map(n=>n.catch(()=>{}))),new Promise(n=>setTimeout(()=>{i=!0,n()},ti.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS))]),i&&y.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})})}validateOptions(){return ds(this.options)||pn(this.options)}broadcast(e){}disconnect(){return V(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this._clearTokenExpiryTimeout(),this.subscriptions={},this._autoReconnect=!1,this._intentionalClose=!0,this._reconnectAttempts=0,this.relayProtocol=null,yield this._drainCallReportUploads(),this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),y.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,i){return Ut(e,i,this.uuid),this}off(e,i){return bt(e,i,this.uuid),this}connect(){return V(this,void 0,void 0,function*(){this.connection||(y.debug("No existing connection found, creating a new one."),this.connection=new fs(this)),this._attachListeners(),this._autoReconnect||(y.debug("autoReconnect was disabled, resetting reconnect attempts"),this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(y.debug("Connection wasn't alive, initiating connection to the server..."),this.connection.connect()),y.debug("Connect method called. Connection initiated.")})}resetReconnectAttempts(){this._reconnectAttempts=0,this._reconnectCountedGeneration=-1}_handleLoginError(e){const i=ne(Uu,e);B(P.Error,{error:i,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){nh()}_checkTokenExpiry(){this._clearTokenExpiryTimeout();const e=this.options.login_token;if(e&&typeof e=="string")try{const i=e.split(".");if(i.length!==3)return;const n=JSON.parse(atob(i[1])).exp;if(typeof n!="number")return;const s=n-Math.floor(Date.now()/1e3);if(s<=0)return;if(s<=ti.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const o=1e3*(s-ti.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout(()=>{this._emitTokenExpiryWarning()},o)}}catch{y.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=Ne(h0);B(P.Warning,{warning:e,sessionId:this.sessionid},this.uuid)}_clearTokenExpiryTimeout(){this._tokenExpiryTimeout!==null&&(clearTimeout(this._tokenExpiryTimeout),this._tokenExpiryTimeout=null)}login({creds:e,onSuccess:i,onError:n}={}){return V(this,void 0,void 0,function*(){if(this.connection&&this.connection.isAlive){if(e&&(e.login!==void 0&&(this.options.login=e.login),e.password!==void 0&&(this.options.password=e.password),e.passwd!==void 0&&(this.options.passwd=e.passwd),e.login_token!==void 0&&(this.options.login_token=e.login_token),e.userVariables!==void 0&&(this.options.userVariables=e.userVariables),e.anonymous_login!==void 0&&(this.options.anonymous_login=e.anonymous_login)),ds(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(pn(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const s="Invalid login options provided for authentication.";y.error(s);const o=ne(qy,void 0,s);return void B(P.Error,{error:o,type:P0.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:i,onError:n}){var s,o,r;return V(this,void 0,void 0,function*(){let a;const l=!!gn(),c=l&&(this.sessionid&&ih()?this.sessionid:function(d=Date.now()){const h=sessionStorage.getItem(us);return h?ih(d)?h:(sessionStorage.removeItem(us),sessionStorage.removeItem(hs),null):null}())||"";if(e==="login"){const d=(r=(s=this.options.pushWhenActive)!==null&&s!==void 0?s:(o=this.options.userVariables)===null||o===void 0?void 0:o.push_when_active)!==null&&r!==void 0&&r,h=Object.assign(Object.assign({},this.options.userVariables),{push_when_active:d,pn_late_fanout:d});a=new $0(this.options.login,this.options.password||this.options.passwd,this.options.login_token,c,h,l)}else a=new X0({target_id:this.options.anonymous_login.target_id,target_type:this.options.anonymous_login.target_type,target_version_id:this.options.anonymous_login.target_version_id,target_params:this.options.anonymous_login.target_params,sessionId:c,userVariables:this.options.userVariables,reconnection:l});const u=yield this.execute(a).catch(d=>{this._handleLoginError(d),n&&n(d)});u&&(this.sessionid=u.sessid,this.sessionid&&Rr(this.sessionid),this._checkTokenExpiry(),i&&i())})}_onSocketOpen(){return V(this,void 0,void 0,function*(){this.startSignalingHealthMonitor()})}_flushIntermediateCallReports(e){const i=this.calls;i&&Object.values(i).forEach(n=>{if(n!=null&&n.flushIntermediateCallReport)try{n.flushIntermediateCallReport(e)}catch(s){y.error("Failed to flush intermediate call report",{callId:n.id,flushReason:e,error:s})}})}_getSocketCloseCodeName(e){if(e===void 0)return;const i=Object.entries(qu).find(([,n])=>n===e);return i==null?void 0:i[0]}_getSocketCloseError(e){if(e)return e instanceof Error?e.message:String(e)}_createSocketCloseFlushReason(e){return{type:e!=null&&e.error?"socket-error":"socket-close",socketClose:{code:e==null?void 0:e.code,codeName:this._getSocketCloseCodeName(e==null?void 0:e.code),reason:e==null?void 0:e.reason,wasClean:e==null?void 0:e.wasClean,error:this._getSocketCloseError(e==null?void 0:e.error)}}}onNetworkClose(e){var i,n,s,o;const r=(n=(i=this.connection)===null||i===void 0?void 0:i.socketGeneration)!==null&&n!==void 0?n:0,a=(s=e==null?void 0:e.socketGeneration)!==null&&s!==void 0?s:r;if(a<r)y.debug(`Skipping stale onNetworkClose for socket generation ${a} (current generation is ${r})`);else if(a!==this._reconnectCountedGeneration){this._flushIntermediateCallReports(this._createSocketCloseFlushReason(e)),y.debug("onNetworkClose called",{closeCode:e==null?void 0:e.code,closeReason:e==null?void 0:e.reason,wasClean:e==null?void 0:e.wasClean,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,autoReconnect:this._autoReconnect,reconnectAttempts:this._reconnectAttempts}),this.relayProtocol&&xr(this.relayProtocol);for(const l in this.subscriptions)xr(l);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.stopSignalingHealthMonitor(),this.sessionid&&this._autoReconnect&&Rr(this.sessionid),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect){const l=(o=this.options.maxReconnectAttempts)!==null&&o!==void 0?o:10;if(this._reconnectCountedGeneration=a,this._reconnectAttempts+=1,l>0&&this._reconnectAttempts>l){y.info(`Reconnection exhausted after ${l} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1,this._terminateActiveCallsLocally();const u=ne(Sr);return void B(P.Error,{error:u,sessionId:this.sessionid},this.uuid)}const c=this.reconnectDelay;y.debug(`Reconnect attempt ${this._reconnectAttempts}${l>0?` of ${l}`:""} (delay=${c}ms)`),this._reconnectTimeout=setTimeout(()=>{y.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},c)}else if(y.debug("auto_reconnect disabled, not reconnecting",{voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,intentionalClose:this._intentionalClose}),!this._intentionalClose){const l=Ne(m0);B(P.Warning,{warning:l,reason:"auto_reconnect_disabled",sessionId:this.sessionid},this.uuid)}this._intentionalClose=!1}else y.debug(`Skipping duplicate onNetworkClose for socket generation ${a} (already handled, reconnect attempt ${this._reconnectAttempts})`)}_onSocketMessage(e){}_removeSubscription(e,i){this._existsSubscription(e,i)&&(i?(delete this.subscriptions[e][i],bt(e,null,i)):(delete this.subscriptions[e],xr(e)))}_addSubscription(e,i=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},Ri(i)&&Ut(e,i,n))}_existsSubscription(e,i){return!(!this.subscriptions.hasOwnProperty(e)||!(!i||i&&this.subscriptions[e].hasOwnProperty(i)))}_attachListeners(){this._detachListeners(),y.debug("Attaching socket event listeners"),this.on(P.SocketOpen,this._onSocketOpen),this.on(P.SocketClose,this.onNetworkClose),this.on(P.SocketError,this.onNetworkClose),this.on(P.SocketMessage,this._onSocketMessage),this.on(P.SocketActivity,this._onSocketActivity)}_detachListeners(){y.debug("Detaching socket event listeners"),this.off(P.SocketOpen,this._onSocketOpen),this.off(P.SocketClose,this.onNetworkClose),this.off(P.SocketError,this.onNetworkClose),this.off(P.SocketMessage,this._onSocketMessage),this.off(P.SocketActivity,this._onSocketActivity)}_emptyExecuteQueues(){this._executeQueue.forEach(({resolve:e,msg:i})=>{typeof i=="string"?this.executeRaw(i):e(this.execute(i))})}_closeConnection(){var e,i;this._idle=!0,clearTimeout(this._keepAliveTimeout),this.stopSignalingHealthMonitor(),y.debug("_closeConnection called",{connected:(e=this.connection)===null||e===void 0?void 0:e.connected,socketGeneration:(i=this.connection)===null||i===void 0?void 0:i.socketGeneration,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0}),this.connection&&this.connection.close()}_resetKeepAlive(){this._pong===!1&&(y.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Lr(gn()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){y.debug("Ping received"),this._pong=!0}_onSocketActivity(){this._signalingHealthMonitor.onSocketActivity()}hasActiveCall(){const e=this.calls;if(!e)return!1;const i=new Set([W.Early,W.Active,W.Held]);return Object.values(e).some(n=>n&&n._state!=null&&i.has(n._state))}_terminateActiveCallsLocally(){const e=this.calls;if(!e)return;const i=Object.keys(e);if(i.length!==0){y.debug(`Reconnection exhausted — locally terminating ${i.length} active call(s) (no BYE): ${i.join(", ")}`);for(const n of i){const s=e[n];s==null||s.hangup({},!1)}}}startSignalingHealthMonitor(){this._signalingHealthMonitor.start()}stopSignalingHealthMonitor(){this._signalingHealthMonitor.stop()}triggerIceRestart(e){const i=this.calls,n=i==null?void 0:i[e];if(!n)return y.warn(`Signaling health: cannot trigger ICE restart — call ${e} not found`),{started:!1,reason:"call not found"};const s=n.peer;if(!(s!=null&&s.restartIce))return y.warn(`Signaling health: cannot trigger ICE restart — no peer for call ${e}`),{started:!1,reason:"no peer"};const o=s.restartIce();return o.started||y.debug(`Signaling health: ICE restart skipped for call ${e}: ${o.reason}`),o}onSignalingRequestTimeout(e,i,n=""){this._signalingHealthMonitor.onRequestTimeout(e,i,n)}reportPeerFailure(e,i){this._signalingHealthMonitor.onPeerFailure(e,i)}reportNoRtp(e,i){this._signalingHealthMonitor.onNoRtp(e,i)}reportIceRestartFailed(e){this._signalingHealthMonitor.onIceRestartFailed(e)}static on(e,i){Ut(e,i)}static off(e){bt(e)}static uuid(){return ki()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}ti.TOKEN_EXPIRY_WARNING_SECONDS=120,ti.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;const gs=t=>navigator.mediaDevices.getUserMedia(t),vn=t=>t&&t instanceof MediaStream,ms=(t,e,i)=>{const n=fn(t);if(n!==null){if(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject&&n.srcObject!==e&&(y.warn("attachMediaStream: element already has a different MediaStream attached; overwriting will disrupt the existing call. Use a per-call remoteElement (client.newCall({ remoteElement }) or call.answer({ remoteElement })) for concurrent calls."),i)){const s=Ne(u0);B(P.Warning,{warning:s,callId:i.callId,sessionId:i.sessionId},i.eventTarget)}n.srcObject=e}},vh=(t,e)=>{const i=fn(t);if(i){if(e&&i.srcObject!==e)return;i.srcObject=null}},_h=(t,e)=>V(void 0,void 0,void 0,function*(){const i=fn(t);if(i===null)return y.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return y.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield i.setSinkId(e),!0}catch{return!1}}),J0=t=>{t&&t.readyState==="live"&&t.stop()},_n=t=>{vn(t)&&t.getTracks().forEach(J0),t=null},vs=t=>V(void 0,void 0,void 0,function*(){y.info("RTCService.getUserMedia",t);const{audio:e,video:i}=t;if(!e&&!i)return null;try{return yield gs(t)}catch(n){if(y.error("getUserMedia error: ",n),(s=>s.name==="NotReadableError"||s.name==="NotFoundError"||s.name==="OverconstrainedError")(n)){const s=(o=>{const{audio:r,video:a}=o;let l=!1,c=r,u=a;if(typeof r=="object"&&r!==null&&"deviceId"in r){l=!0;const d=Object.assign({},r);delete d.deviceId,c=Object.keys(d).length===0||d}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const d=Object.assign({},a);delete d.deviceId,u=Object.keys(d).length===0||d}return l?{audio:c,video:u}:null})(t);if(s){y.warn("Device not found or not readable, falling back to default device");try{return yield gs(s)}catch(o){throw y.error("Fallback getUserMedia also failed: ",o),n}}}throw n}}),yn=(t=null,e=!1)=>V(void 0,void 0,void 0,function*(){let i=[];const n=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===yt.AudioIn||s===yt.AudioOut,video:!s||s===yt.Video}))(t)).catch(s=>(y.error(s),null));if(n){if(_n(n),i=yield navigator.mediaDevices.enumerateDevices(),t&&(i=i.filter(o=>o.kind===t)),e===!0)return i;const s=[];i=i.filter(o=>{if(!o.groupId)return!0;const r=`${o.kind}-${o.groupId}`;return!s.includes(r)&&(s.push(r),!0)})}return i}),yh=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],_s=(t,e,i)=>V(void 0,void 0,void 0,function*(){const n=yield yn(i,!0);for(let s=0;s<n.length;s++){const{deviceId:o,label:r}=n[s];if(t===o||e===r)return o}return null}),Z0=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(i=>{e.hasOwnProperty(i)&&t[i]!==null&&t[i]!==void 0||delete t[i]})},Or=t=>t?{id:t.id,kind:t.kind,enabled:t.enabled,muted:t.muted,readyState:t.readyState}:null,bh=t=>{var e,i,n,s,o,r;return t?((i=(e=t.getTracks)===null||e===void 0?void 0:e.call(t))!==null&&i!==void 0?i:[...(s=(n=t.getAudioTracks)===null||n===void 0?void 0:n.call(t))!==null&&s!==void 0?s:[],...(r=(o=t.getVideoTracks)===null||o===void 0?void 0:o.call(t))!==null&&r!==void 0?r:[]]).map(a=>Or(a)):[]},Mr=(t,e)=>{if(!t)return!1;const{subscribed:i,alreadySubscribed:n}=Pr(t);return i.includes(e)||n.includes(e)},Pr=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(i=>{e[i]=t[`${i}Channels`]||[]}),e},Oi=(t,e=null,i=null)=>{if(!vn(t))return null;let n=[];switch(e){case"audio":n=t.getAudioTracks();break;case"video":n=t.getVideoTracks();break;default:n=t.getTracks()}n.forEach(s=>{switch(i){case"on":case!0:s.enabled=!0;break;case"off":case!1:s.enabled=!1;break;default:s.enabled=!s.enabled}})},Nr=t=>{Oi(t,"audio",!0)},ys=t=>{Oi(t,"audio",!1)};function Q0(){try{const{browserInfo:t,name:e,version:i,supportAudio:n,supportVideo:s}=function(){if(!window||!window.navigator||!window.navigator.userAgent)throw new Error("You should use @telnyx/webrtc in a web browser such as Chrome|Firefox|Safari");if(navigator.userAgent.match(/chrom(e|ium)/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/safari/gim)[0],d=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),h=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:h,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const u=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,l=window.navigator&&window.navigator.mediaDevices,c=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:i,supportWebRTC:!!(o&&r&&a&&l&&c),supportWebRTCAudio:n,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!vs}}catch(t){return t.message}}var Ee;function wh(t,e){const i=document.getElementById(e);if(i)return i;if(t&&e){const n=document.createElement("audio");return n.id=e,n.loop=!0,n.src=t,n.preload="auto",n.load(),document.body.appendChild(n),n}return null}function Sh(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{y.error("playAudio",e),t._playFulfilled=!0}))}function Ch(t){t&&(t._playFulfilled?(t.pause(),t.currentTime=0):t._promise&&t._promise.then?t._promise.then(()=>{t.pause(),t.currentTime=0}):setTimeout(()=>{t.pause(),t.currentTime=0},1e3))}(function(t){t.not_supported="not supported",t.full="full",t.partial="partial"})(Ee||(Ee={}));const Th=t=>{const e=[],i=[];return t&&t.length!==0?(t.forEach(n=>{const s=n.mimeType.toLocaleLowerCase();s.startsWith("audio/")?e.push(n):s.startsWith("video/")&&i.push(n)}),{audioCodecs:e,videoCodecs:i}):{audioCodecs:e,videoCodecs:i}};class eb extends Li{constructor(e,i){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:ki(),type:"message",role:"user",content:[{type:"input_text",text:e},...i==null?void 0:i.map(n=>({type:"image_url",image_url:{url:n}}))]}}})}}class tb extends Li{constructor(e){super(),this.method="ai_conversation",this.buildNotification({method:this.method,params:{type:"conversation.item.create",item:e}})}}class le{constructor(e,i){var n;this.peerConnection=null,this.intervalId=null,this.statsBuffer=[],this.intervalStartTime=null,this.callEndTime=null,this.logCollector=null,this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]},this.previousStats={},this.previousCandidatePairSnapshot=null,this.MAX_BUFFER_SIZE=360,this.onFlushNeeded=null,this.onWarning=null,this._breachCounters={},this._activeWarnings=new Set,this._lastWarningEmitted={},this._prevPacketsReceived=null,this._prevPacketsLost=null,this._previousStatsEntryForWarnings=null,this._isHeld=!1,this._lastLocalAudioTrackSnapshotJson=null,this._hasConfirmedLocalAudio=!1,this._confirmedLocalAudioSilenceMs=0,this._segmentIndex=0,this._flushing=!1,this._stopped=!1,this.options=e,this.logCollectorOptions=i||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this._lastIntermediateFlushTime=this.callStartTime,this.logCollectorOptions.enabled&&(this.logCollector=function(s){return new x0(s)}(this.logCollectorOptions),this.logCollector.start(),n=this.logCollector,Xu=n)}start(e){var i,n;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._lastIntermediateFlushTime=this.intervalStartTime,this._stopped=!1,y.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:le.INITIAL_COLLECTION_INTERVAL_MS,logCollectorActive:(n=(i=this.logCollector)===null||i===void 0?void 0:i.isActive())!==null&&n!==void 0&&n}),this._scheduleNextCollection())}stop(){var e,i;return V(this,void 0,void 0,function*(){this._stopped=!0,this.intervalId&&(clearTimeout(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&(yield this._collectStats(!0));const n=(i=(e=this.logCollector)===null||e===void 0?void 0:e.getLogCount())!==null&&i!==void 0?i:0;this.logCollector&&this.logCollector.stop(),y.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:n,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})})}flush(e,i){var n,s,o,r;const a=this.statsBuffer.length,l=(s=(n=this.logCollector)===null||n===void 0?void 0:n.getLogCount())!==null&&s!==void 0?s:0,c=(i==null?void 0:i.type)==="socket-close"||(i==null?void 0:i.type)==="socket-error",u=a>0||l>0||c;if(this._flushing||!u)return y.debug("CallReportCollector: Skipping intermediate flush",{reason:this._flushing?"already-flushing":"no-stats-or-logs",flushReason:i,statsIntervals:a,logEntries:l}),null;this._flushing=!0;try{const d=this._segmentIndex++,h=this.statsBuffer;this.statsBuffer=[];const p=(r=(o=this.logCollector)===null||o===void 0?void 0:o.drain())!==null&&r!==void 0?r:[],_=new Date;this._lastIntermediateFlushTime=_;const v=Object.assign(Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(_.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:_.toISOString()}),stats:h},p.length>0?{logs:p}:{}),{segment:d}),i?{flushReason:i}:{});return y.info("CallReportCollector: Flushed intermediate segment",{segment:d,intervals:h.length,logEntries:p.length,callId:e.callId,flushReason:i}),v}finally{this._flushing=!1}}postReport(e,i,n,s){var o,r;return V(this,void 0,void 0,function*(){const a=(o=this.logCollector)===null||o===void 0?void 0:o.getLogs(),l=a&&a.length>0;if(!this.options.enabled)return void y.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void y.info("CallReportCollector: Skipping report — no stats or logs collected");const c=this._segmentIndex>0,u=this._segmentIndex,d=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:this.callEndTime&&this.callStartTime?(this.callEndTime.getTime()-this.callStartTime.getTime())/1e3:void 0,startTimestamp:this.callStartTime.toISOString(),endTimestamp:(r=this.callEndTime)===null||r===void 0?void 0:r.toISOString()}),stats:this.statsBuffer},a&&a.length>0?{logs:a}:{}),c?{segment:u}:{});yield this._sendPayload(d,i,n,s,!0)})}sendPayload(e,i,n,s,o=!1){return V(this,void 0,void 0,function*(){yield this._sendPayload(e,i,n,s,!1,o)})}_sendPayload(e,i,n,s,o=!0,r=!1){var a,l;return V(this,void 0,void 0,function*(){const c=new URL(n),u=`${c.protocol.replace(/^ws/,"http")}//${c.host}/call_report`,d=o?"final report":`intermediate segment ${e.segment}`;y.info(`CallReportCollector: Posting ${d}`,{endpoint:u,intervals:e.stats.length,logEntries:(l=(a=e.logs)===null||a===void 0?void 0:a.length)!==null&&l!==void 0?l:0,callId:e.summary.callId,segment:e.segment});const h={"Content-Type":"application/json","x-call-report-id":i,"x-call-id":e.summary.callId};s&&(h["x-voice-sdk-id"]=s);const p=JSON.stringify(e),_=(o||r)&&p.length<=le.KEEPALIVE_BODY_LIMIT_BYTES;let v;for(let b=0;b<=le.RETRY_DELAYS_MS.length;b++){try{const C=yield fetch(u,Object.assign({method:"POST",headers:h,body:p},_?{keepalive:!0}:{}));if(C.ok)return void y.info(`CallReportCollector: Successfully posted ${d}`,{attempt:b+1,status:C.status});{const k=yield C.text();v=new Error(`Call report POST failed with status ${C.status}`),y.error(`CallReportCollector: Failed to post ${d}`,{attempt:b+1,status:C.status,error:k})}}catch(C){v=C,y.warn(`CallReportCollector: Network error posting ${d}`,{attempt:b+1,error:C})}const w=le.RETRY_DELAYS_MS[b];if(w===void 0)break;y.info(`CallReportCollector: Retrying ${d} in ${w}ms`,{attempt:b+2}),yield new Promise(C=>setTimeout(C,w))}throw y.error(`CallReportCollector: Exhausted retries posting ${d}`,{error:v}),v instanceof Error?v:new Error("Call report POST failed after retries")})}getStatsBuffer(){return this.statsBuffer}shouldForceRelayCandidateForRecovery(){var e,i,n,s,o,r,a,l,c,u,d,h,p,_,v,b;if(this.statsBuffer.length<2)return!1;const w=this.statsBuffer[this.statsBuffer.length-1],C=this.statsBuffer[this.statsBuffer.length-2],k=(e=w.ice)===null||e===void 0?void 0:e.local;if(!((k==null?void 0:k.networkType)==="vpn"&&(k==null?void 0:k.candidateType)!=="relay"))return!1;const L=((i=w.ice)===null||i===void 0?void 0:i.writable)===!1,R=((n=w.transport)===null||n===void 0?void 0:n.iceState)==="disconnected"||((s=w.transport)===null||s===void 0?void 0:s.iceState)==="failed",O=this._positiveDelta((o=w.ice)===null||o===void 0?void 0:o.requestsSent,(r=C.ice)===null||r===void 0?void 0:r.requestsSent),T=this._positiveDelta((a=w.ice)===null||a===void 0?void 0:a.responsesReceived,(l=C.ice)===null||l===void 0?void 0:l.responsesReceived),E=O>0&&T===0,g=this._positiveDelta((u=(c=w.audio)===null||c===void 0?void 0:c.outbound)===null||u===void 0?void 0:u.bytesSent,(h=(d=C.audio)===null||d===void 0?void 0:d.outbound)===null||h===void 0?void 0:h.bytesSent),m=this._positiveDelta((_=(p=w.audio)===null||p===void 0?void 0:p.inbound)===null||_===void 0?void 0:_.bytesReceived,(b=(v=C.audio)===null||v===void 0?void 0:v.inbound)===null||b===void 0?void 0:b.bytesReceived);return L||R||E||g>0&&m===0}getLogs(){var e,i;return(i=(e=this.logCollector)===null||e===void 0?void 0:e.getLogs())!==null&&i!==void 0?i:[]}_positiveDelta(e,i){return e===void 0||i===void 0?0:Math.max(0,e-i)}cleanup(){this._lastLocalAudioTrackSnapshotJson=null,this.logCollector&&(this.logCollector.clear(),this.logCollector=null)}setHeld(e){this._isHeld!==e&&(this._isHeld=e,this._trackBreach(as,!1),this._trackBreach(Cr,!1))}_scheduleNextCollection(){if(this._stopped||!this.peerConnection||!this.intervalStartTime||this.intervalId)return;const e=this._collectionIntervalFor();this.intervalId=setTimeout(()=>{this.intervalId=null,this._collectStats().finally(()=>{!this._stopped&&this.peerConnection&&this._scheduleNextCollection()})},e)}_collectionIntervalFor(){const e=this._positiveInterval(this.options.interval,5e3);return Math.min(le.INITIAL_COLLECTION_INTERVAL_MS,e)}_positiveInterval(e,i){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:i}_collectStats(e=!1){var i,n;return V(this,void 0,void 0,function*(){if(this.peerConnection&&this.intervalStartTime)try{const s=yield this.peerConnection.getStats(),o=new Date;let r=null,a=null,l=null,c=null,u=null,d=null;const h=[];let p=null;s.forEach(g=>{switch(g.type){case"outbound-rtp":g.kind==="audio"&&g.mediaType==="audio"&&(r=g);break;case"inbound-rtp":g.kind==="audio"&&g.mediaType==="audio"&&(a=g);break;case"media-playout":g.kind==="audio"&&(l=g);break;case"remote-inbound-rtp":g.kind==="audio"&&(c=g);break;case"remote-outbound-rtp":g.kind==="audio"&&(u=g);break;case"candidate-pair":(g.nominated||g.state==="succeeded")&&h.push(g);break;case"transport":p=g}});const _=p==null?void 0:p.selectedCandidatePairId,v=_?(n=(i=s).get)===null||n===void 0?void 0:n.call(i,_):void 0,b=this._getCodec(s,r==null?void 0:r.codecId),w=this._getCodec(s,a==null?void 0:a.codecId);if(d=(v==null?void 0:v.type)==="candidate-pair"?v:_?h.find(g=>g.id===_)||h[h.length-1]||null:h[h.length-1]||null,r){const g=this._getOutboundAudioLevel(s,r);if(g!==null&&this.intervalAudioLevels.outbound.push(g),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const m=(r.bytesSent||0)-this.previousStats.outboundBytes,f=(r.timestamp||o.getTime())-this.previousStats.timestamp;if(f>0){const S=8*m*1e3/f;this.intervalBitrates.outbound.push(S)}}this.previousStats.outboundBytes=r.bytesSent}if(a){const g=this._getInboundAudioLevel(s,a);if(g!==null&&this.intervalAudioLevels.inbound.push(g),a.jitter!==void 0&&this.intervalJitters.push(1e3*a.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const m=(a.bytesReceived||0)-this.previousStats.inboundBytes,f=(a.timestamp||o.getTime())-this.previousStats.timestamp;if(f>0){const S=8*m*1e3/f;this.intervalBitrates.inbound.push(S)}}this.previousStats.inboundBytes=a.bytesReceived}let C,k,L,R,O;d&&d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),d&&(C=this._resolveCandidate(s,d.localCandidateId),k=this._resolveCandidate(s,d.remoteCandidateId)),d&&(L=Object.assign(Object.assign({id:d.id,localCandidateId:d.localCandidateId,remoteCandidateId:d.remoteCandidateId,state:d.state,nominated:d.nominated,writable:d.writable,currentRoundTripTime:d.currentRoundTripTime,requestsSent:d.requestsSent,responsesReceived:d.responsesReceived},C?{local:C}:{}),k?{remote:k}:{}),this.previousCandidatePairSnapshot!==null&&d.id!==this.previousCandidatePairSnapshot.id&&(y.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:L}),this._emitWarning(a0)),this.previousCandidatePairSnapshot=L),r&&(R=this._getLocalAudioTrackSnapshot(),O=this._getOutboundAudioSourceStats(s,r)),this._logLocalAudioTrackSnapshot(R,O),this.previousStats.timestamp=o.getTime();const T=o.getTime()-this.intervalStartTime.getTime(),E=this._collectionIntervalFor();if(e||T>=E){const g=this._createStatsEntry(this.intervalStartTime,o,r,a,d,C,k,p,R,O,l,c,u,b,w);this.statsBuffer.push(g),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),y.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(g,a),this._requestIntermediateFlushIfNeeded(o),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(s){y.error("CallReportCollector: Error collecting stats",{error:s})}})}_getIntermediateReportInterval(){var e;return(e=this.options.intermediateReportInterval)!==null&&e!==void 0?e:le.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS}_requestIntermediateFlushIfNeeded(e){var i,n;const s=this.statsBuffer.length,o=(n=(i=this.logCollector)===null||i===void 0?void 0:i.getLogCount())!==null&&n!==void 0?n:0;if(!this.onFlushNeeded||this._flushing)return;if(s===0&&o===0)return void y.debug("CallReportCollector: Skipping intermediate flush request — no stats or logs buffered");const r=this._getIntermediateReportInterval(),a=e.getTime()-this._lastIntermediateFlushTime.getTime();let l=null;if(s>=le.STATS_FLUSH_THRESHOLD||o>=le.LOGS_FLUSH_THRESHOLD?l="buffer-limit":r>0&&a>=r&&(l="safety-interval"),l){y.info("CallReportCollector: Requesting intermediate report flush",{reason:l,statsIntervals:s,logEntries:o,msSinceLastFlush:a}),this._lastIntermediateFlushTime=e;try{this.onFlushNeeded()}catch(c){y.error("CallReportCollector: onFlushNeeded callback error",{error:c})}}}_checkQualityWarnings(e,i){var n,s,o,r,a,l,c,u,d,h,p,_,v,b,w;if(!this.onWarning)return;const C=(n=e.connection)===null||n===void 0?void 0:n.roundTripTimeAvg,k=(o=(s=e.audio)===null||s===void 0?void 0:s.inbound)===null||o===void 0?void 0:o.jitterAvg;let L;if(i){const R=(r=i.packetsReceived)!==null&&r!==void 0?r:0,O=(a=i.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const T=R-this._prevPacketsReceived,E=O-this._prevPacketsLost,g=T+E;g>0&&(L=E/g*100)}this._prevPacketsReceived=R,this._prevPacketsLost=O}if(this._trackBreach(Xy,C!==void 0&&C>le.THRESHOLD_RTT_MS),this._trackBreach(Jy,k!==void 0&&k>le.THRESHOLD_JITTER_MS),this._trackBreach(Zy,L!==void 0&&L>le.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),this._isHeld?this._trackBreach(as,!1):this._trackLowInboundAudio(e),C!==void 0&&k!==void 0&&L!==void 0){const R=93.2-.11*k-2.5*L-.01*(1e3*C),O=Math.max(1,Math.min(4.5,1+.035*R+R*(R-60)*(100-R)*7e-6));this._trackBreach(Hu,O<le.THRESHOLD_MOS)}else this._trackBreach(Hu,!1);if(((c=(l=e.audio)===null||l===void 0?void 0:l.inbound)===null||c===void 0?void 0:c.bytesReceived)!==void 0){const R=(h=(d=(u=this._previousStatsEntryForWarnings)===null||u===void 0?void 0:u.audio)===null||d===void 0?void 0:d.inbound)===null||h===void 0?void 0:h.bytesReceived,O=e.audio.inbound.bytesReceived;this._trackBreach(Cr,!this._isHeld&&R!==void 0&&O-R==0)}if(((_=(p=e.audio)===null||p===void 0?void 0:p.outbound)===null||_===void 0?void 0:_.bytesSent)!==void 0){const R=(w=(b=(v=this._previousStatsEntryForWarnings)===null||v===void 0?void 0:v.audio)===null||b===void 0?void 0:b.outbound)===null||w===void 0?void 0:w.bytesSent,O=e.audio.outbound.bytesSent;this._trackBreach(Wu,R!==void 0&&O-R==0)}this._previousStatsEntryForWarnings=e}_trackLowLocalAudio(e){var i;const n=(i=e.audio)===null||i===void 0?void 0:i.outbound,s=n==null?void 0:n.audioLevelAvg,o=n==null?void 0:n.localTrack;if(s===void 0||(o==null?void 0:o.enabled)===!1||(o==null?void 0:o.muted)===!0)return void this._resetLowLocalAudioWarning();if(!(s<=le.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(rs,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=le.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(rs)):this._trackBreach(rs,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(rs,!1)}_getStatsIntervalDurationMs(e){const i=new Date(e.intervalStartUtc).getTime(),n=new Date(e.intervalEndUtc).getTime()-i;return Number.isFinite(n)&&n>0?n:this.options.interval}_trackLowInboundAudio(e){var i;const n=(i=e.audio)===null||i===void 0?void 0:i.inbound,s=n==null?void 0:n.audioLevelAvg;if(s===void 0)return void this._trackBreach(as,!1);const o=s<=le.THRESHOLD_INBOUND_AUDIO_LEVEL;this._trackBreach(as,o)}_trackBreach(e,i){var n,s;if(i){if(this._breachCounters[e]=((n=this._breachCounters[e])!==null&&n!==void 0?n:0)+1,this._breachCounters[e]>=le.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=le.WARNING_THROTTLE_MS&&(this._lastWarningEmitted[e]=o,this._emitWarning(e))}}else this._breachCounters[e]=0,this._activeWarnings.delete(e),delete this._lastWarningEmitted[e]}_emitWarningOncePerEpisode(e){this._activeWarnings.has(e)||(this._activeWarnings.add(e),this._lastWarningEmitted[e]=Date.now(),this._emitWarning(e))}_emitWarning(e){var i;try{const n=Ne(e);y.warn(`CallReportCollector: warning ${n.code}: ${n.message}`),(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){y.error(`CallReportCollector: Failed to emit warning ${e}`,{error:n})}}_createStatsEntry(e,i,n,s,o,r,a,l,c,u,d,h,p,_,v){const b={intervalStartUtc:e.toISOString(),intervalEndUtc:i.toISOString(),audio:{}};if(n&&(b.audio.outbound=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({packetsSent:n.packetsSent,bytesSent:n.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)},c?{localTrack:c}:{}),u?{mediaSource:u}:{}),n.retransmittedPacketsSent!==void 0?{retransmittedPacketsSent:n.retransmittedPacketsSent}:{}),n.retransmittedBytesSent!==void 0?{retransmittedBytesSent:n.retransmittedBytesSent}:{}),n.headerBytesSent!==void 0?{headerBytesSent:n.headerBytesSent}:{}),n.nackCount!==void 0?{nackCount:n.nackCount}:{}),n.targetBitrate!==void 0?{targetBitrate:n.targetBitrate}:{}),n.totalPacketSendDelay!==void 0?{totalPacketSendDelay:n.totalPacketSendDelay}:{}),n.active!==void 0?{active:n.active}:{}),_?{codec:this._buildCodecSnapshot(_,n.codecId)}:{})),s&&(b.audio.inbound=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({packetsReceived:s.packetsReceived,bytesReceived:s.bytesReceived,packetsLost:s.packetsLost,packetsDiscarded:s.packetsDiscarded,jitterBufferDelay:s.jitterBufferDelay,jitterBufferEmittedCount:s.jitterBufferEmittedCount,totalSamplesReceived:s.totalSamplesReceived,concealedSamples:s.concealedSamples,concealmentEvents:s.concealmentEvents,audioLevelAvg:this._average(this.intervalAudioLevels.inbound),jitterAvg:this._average(this.intervalJitters),bitrateAvg:this._average(this.intervalBitrates.inbound)},s.nackCount!==void 0?{nackCount:s.nackCount}:{}),s.headerBytesReceived!==void 0?{headerBytesReceived:s.headerBytesReceived}:{}),s.fecPacketsReceived!==void 0?{fecPacketsReceived:s.fecPacketsReceived}:{}),s.fecPacketsDiscarded!==void 0?{fecPacketsDiscarded:s.fecPacketsDiscarded}:{}),s.jitterBufferTargetDelay!==void 0?{jitterBufferTargetDelay:s.jitterBufferTargetDelay}:{}),s.jitterBufferMinimumDelay!==void 0?{jitterBufferMinimumDelay:s.jitterBufferMinimumDelay}:{}),s.totalSamplesDecoded!==void 0?{totalSamplesDecoded:s.totalSamplesDecoded}:{}),s.samplesDecodedWithSilence!==void 0?{samplesDecodedWithSilence:s.samplesDecodedWithSilence}:{}),s.samplesDecodedWithConcealment!==void 0?{samplesDecodedWithConcealment:s.samplesDecodedWithConcealment}:{}),s.totalAudioEnergy!==void 0?{totalAudioEnergy:s.totalAudioEnergy}:{}),s.totalSamplesDuration!==void 0?{totalSamplesDuration:s.totalSamplesDuration}:{}),v?{codec:this._buildCodecSnapshot(v,s.codecId)}:{})),o&&(b.connection=Object.assign(Object.assign({roundTripTimeAvg:this._average(this.intervalRTTs),currentRoundTripTime:o.currentRoundTripTime},o.currentRoundTripTime!==void 0?{roundTripTimeSource:"candidate-pair.currentRoundTripTime"}:{}),{packetsSent:o.packetsSent,packetsReceived:o.packetsReceived,bytesSent:o.bytesSent,bytesReceived:o.bytesReceived}),b.ice=Object.assign(Object.assign({id:o.id,localCandidateId:o.localCandidateId,remoteCandidateId:o.remoteCandidateId,state:o.state,nominated:o.nominated,writable:o.writable,currentRoundTripTime:o.currentRoundTripTime,requestsSent:o.requestsSent,responsesReceived:o.responsesReceived},r?{local:r}:{}),a?{remote:a}:{})),l&&(b.transport=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},l.iceState!==void 0?{iceState:l.iceState}:{}),l.dtlsState!==void 0?{dtlsState:l.dtlsState}:{}),l.srtpCipher!==void 0?{srtpCipher:l.srtpCipher}:{}),l.tlsVersion!==void 0?{tlsVersion:l.tlsVersion}:{}),l.selectedCandidatePairChanges!==void 0?{selectedCandidatePairChanges:l.selectedCandidatePairChanges}:{}),l.selectedCandidatePairId!==void 0?{selectedCandidatePairId:l.selectedCandidatePairId}:{})),d&&(b.mediaPlayout=this._withoutUndefined({synthesizedSamples:d.synthesizedSamples,synthesizedDuration:d.synthesizedDuration,totalPlayoutDelay:d.totalPlayoutDelay,totalSampleCount:d.totalSampleCount})),h||p){const w={};if(h){const C=h.jitter!==void 0?1e3*h.jitter:void 0;let k;typeof h.totalRoundTripTime=="number"&&typeof h.roundTripTimeMeasurements=="number"&&h.roundTripTimeMeasurements>0&&(k=h.totalRoundTripTime/h.roundTripTimeMeasurements),w.inbound=this._withoutUndefined({packetsReceived:h.packetsReceived,packetsLost:h.packetsLost,fractionLost:h.fractionLost,jitter:C,roundTripTime:h.roundTripTime,totalRoundTripTime:h.totalRoundTripTime,roundTripTimeMeasurements:h.roundTripTimeMeasurements,roundTripTimeAvg:k,nackCount:h.nackCount,reportsReceived:h.reportsReceived,packetsDiscarded:h.packetsDiscarded})}p&&(w.outbound=this._withoutUndefined({packetsSent:p.packetsSent,bytesSent:p.bytesSent,reportsCount:p.reportsCount,roundTripTime:p.roundTripTime,totalPacketSendDelay:p.totalPacketSendDelay})),b.remoteRtcp=w}return b}_resolveCandidate(e,i){if(!i)return void y.debug("CallReportCollector: candidateId is empty, skipping resolve");const n=e.get(i);if(!n)return void y.debug("CallReportCollector: candidate not found in stats report",{candidateId:i});const s={};if(n.id!==void 0&&(s.id=n.id),n.address!==void 0?s.address=n.address:n.ip!==void 0&&(s.address=n.ip),n.port!==void 0&&(s.port=n.port),n.candidateType!==void 0&&(s.candidateType=n.candidateType),n.protocol!==void 0&&(s.protocol=n.protocol),n.networkType!==void 0&&(s.networkType=n.networkType),n.url!==void 0&&(s.url=n.url),n.relayProtocol!==void 0&&(s.relayProtocol=n.relayProtocol),Object.keys(s).length!==0)return s;y.debug("CallReportCollector: candidate report has no usable fields",{candidateId:i})}_getCodec(e,i){if(!i)return;const n=e.get(i);return n&&n.type==="codec"?n:void 0}_buildCodecSnapshot(e,i){const n=this._withoutUndefined(Object.assign({mimeType:e.mimeType,clockRate:e.clockRate,channels:e.channels,payloadType:e.payloadType,sdpFmtpLine:e.sdpFmtpLine},i!==void 0?{codecId:i}:{}));return Object.keys(n).length>0?n:void 0}_getOutboundMediaSource(e,i){let n;return i.mediaSourceId&&(n=e.get(i.mediaSourceId)),n||e.forEach(s=>{n||s.type!=="media-source"||s.kind!=="audio"||(n=s)}),n}_getLocalAudioTrackSnapshot(){var e,i;try{const n=(e=this.peerConnection)===null||e===void 0?void 0:e.getSenders().find(l=>{var c;return((c=l.track)===null||c===void 0?void 0:c.kind)==="audio"}),s=n==null?void 0:n.track;if(!s)return;const o=(i=s.getSettings)===null||i===void 0?void 0:i.call(s),r=this._withoutUndefined({deviceId:o==null?void 0:o.deviceId,groupId:o==null?void 0:o.groupId,channelCount:o==null?void 0:o.channelCount,sampleRate:o==null?void 0:o.sampleRate,sampleSize:o==null?void 0:o.sampleSize,latency:o==null?void 0:o.latency,echoCancellation:o==null?void 0:o.echoCancellation,noiseSuppression:o==null?void 0:o.noiseSuppression,autoGainControl:o==null?void 0:o.autoGainControl}),a=this._withoutUndefined(Object.assign({id:s.id,label:s.label,enabled:s.enabled,muted:s.muted,readyState:s.readyState,contentHint:s.contentHint},Object.keys(r).length>0?{settings:r}:{}));return Object.keys(a).length>0?a:void 0}catch(n){return void y.debug("CallReportCollector: unable to snapshot local audio track",{error:n})}}_getOutboundAudioSourceStats(e,i){const n=this._getOutboundMediaSource(e,i);if(!n)return;const s=this._withoutUndefined({id:n.id,trackIdentifier:n.trackIdentifier,audioLevel:n.audioLevel,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration,echoReturnLoss:n.echoReturnLoss,echoReturnLossEnhancement:n.echoReturnLossEnhancement});return Object.keys(s).length>0?s:void 0}_logLocalAudioTrackSnapshot(e,i){if(!e||Object.keys(e).length===0)return;const n=this._stableStringify(e);n!==this._lastLocalAudioTrackSnapshotJson&&(this._lastLocalAudioTrackSnapshotJson=n,y.debug("CallReportCollector: local audio track snapshot",{localTrack:e,mediaSource:i}))}_withoutUndefined(e){return Object.keys(e).reduce((i,n)=>{const s=e[n];return s!==void 0&&(i[n]=s),i},{})}_stableStringify(e){return JSON.stringify(this._sortObjectKeys(e))}_sortObjectKeys(e){return Array.isArray(e)?e.map(i=>this._sortObjectKeys(i)):e&&typeof e=="object"?Object.keys(e).sort().reduce((i,n)=>(i[n]=this._sortObjectKeys(e[n]),i),{}):e}_getOutboundAudioLevel(e,i){const n=this._getOutboundMediaSource(e,i);if((n==null?void 0:n.audioLevel)!==void 0)return n.audioLevel;if(n){const s=this._computeAudioLevelFromEnergy(n.totalAudioEnergy,n.totalSamplesDuration,"outbound");if(s!==null)return s}return this._getTrackAudioLevel(e,i.trackId)}_getInboundAudioLevel(e,i){if(i.audioLevel!==void 0)return i.audioLevel;const n=this._computeAudioLevelFromEnergy(i.totalAudioEnergy,i.totalSamplesDuration,"inbound");return n!==null?n:this._getTrackAudioLevel(e,i.trackId)}_computeAudioLevelFromEnergy(e,i,n){if(e===void 0||i===void 0)return null;const s=n==="inbound"?"inboundAudioEnergy":"outboundAudioEnergy",o=n==="inbound"?"inboundSamplesDuration":"outboundSamplesDuration",r=this.previousStats[s],a=this.previousStats[o];if(this.previousStats[s]=e,this.previousStats[o]=i,r===void 0||a===void 0)return null;const l=e-r,c=i-a;if(c<=0)return null;const u=Math.sqrt(l/c);return Math.min(1,Math.max(0,u))}_getTrackAudioLevel(e,i){var n;if(!i)return null;const s=e.get(i);return s&&(n=s.audioLevel)!==null&&n!==void 0?n:null}_average(e){if(e.length===0)return;const i=e.reduce((n,s)=>n+s,0);return parseFloat((i/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}le.INITIAL_COLLECTION_INTERVAL_MS=1e3,le.STATS_FLUSH_THRESHOLD=300,le.LOGS_FLUSH_THRESHOLD=800,le.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,le.CONSECUTIVE_BREACHES_REQUIRED=3,le.THRESHOLD_RTT_MS=.4,le.THRESHOLD_JITTER_MS=30,le.THRESHOLD_PACKET_LOSS_PCT=1,le.THRESHOLD_MOS=3.5,le.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,le.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,le.THRESHOLD_INBOUND_AUDIO_LEVEL=.001,le.WARNING_THROTTLE_MS=15e3,le.RETRY_DELAYS_MS=[500,1e3,2e3],le.KEEPALIVE_BODY_LIMIT_BYTES=61440;class je{constructor(e,i){this._buffers={local:[],remote:[]},this._bufferBytes={local:0,remote:0},this._trackStates={local:null,remote:null},this._processors=[],this._readerCancellers=[],this._flushTimerId=null,this._flushing=!1,this._stopped=!1,this._started=!1,this._startedAt=null,this._endedAt=null,this._overflowWarnedThisWindow={local:!1,remote:!1},this.onWarning=null,this._host=null,this._callReportId=null,this.options=e,this.callContext=i,this.recordingId=i.recordingId||`${i.callId}-${Date.now().toString(36)}`}start(e,i){if(!this.options.enabled||this._started)return;if(typeof MediaStreamTrackProcessor!="function")return y.warn("CallRecorder: MediaStreamTrackProcessor unavailable — recording disabled for this call"),this._emitWarning(Qy),void(this._started=!0);const n=this.options.tracks||["local","remote"];let s=0;if(n.includes("local")&&e&&(this._attach(e,"local"),s++),n.includes("remote")&&i&&(this._attach(i,"remote"),s++),s===0)return y.info("CallRecorder: no audio tracks available to record — recording idle for this call",{callId:this.callContext.callId}),void(this._started=!0);this._startedAt=new Date,this._started=!0,this._scheduleFlush(),y.info("CallRecorder: started",{callId:this.callContext.callId,tracksAttached:s,flushIntervalMs:this._flushIntervalMs(),maxBufferBytes:this._maxBufferBytes()})}stop(){this._stopped||(this._stopped=!0,this._clearFlushTimer(),this._cancelReaders(),this._endedAt=new Date,y.info("CallRecorder: stopped",{callId:this.callContext.callId,packetsBuffered:this._buffers.local.length+this._buffers.remote.length}))}postFinalReport(){return V(this,void 0,void 0,function*(){if(!this.options.enabled)return;if(this.stop(),!this._startedAt)return void y.debug("CallRecorder: postFinalReport skipped — never started");const e=this._resolveEndpointFromContext();if(!e)return void y.debug("CallRecorder: postFinalReport skipped — no host available");const i=this.options.tracks||["local","remote"],n=this._startedAt,s=this._endedAt||new Date,o=i.flatMap(l=>{const c=this._drain(l);if(c.length===0)return[];const u=this._buildEnvelope(c,l,"final",n,s);return[{envelope:u,bodyBytes:JSON.stringify(u).length}]}),r=o.reduce((l,c)=>l+c.bodyBytes,0)<=je.KEEPALIVE_BODY_LIMIT_BYTES,a=(yield Promise.allSettled(o.map(({envelope:l})=>this._postRecording(e,l,r)))).find(l=>l.status==="rejected");if(a)throw a.reason})}cleanup(){this._clearFlushTimer(),this._cancelReaders(),this._buffers={local:[],remote:[]},this._bufferBytes={local:0,remote:0},this._trackStates={local:null,remote:null}}_attach(e,i){this._trackStates[i]={ssrc:Math.floor(4294967295*Math.random())>>>0,seq:0,ts:0};try{const n=new MediaStreamTrackProcessor({track:e});this._processors.push(n);const s=n.readable.getReader();let o=!1;const r=()=>{o=!0,s.cancel().catch(()=>{}).finally(()=>{})};this._readerCancellers.push(r),V(this,void 0,void 0,function*(){try{for(;!o&&!this._stopped;){const{done:a,value:l}=yield s.read();if(a)break;this._onFrame(i,l)}}catch(a){this._stopped||y.warn("CallRecorder: reader loop error",{track:i,error:a})}})}catch(n){y.warn("CallRecorder: failed to attach track",{track:i,error:n}),this._trackStates[i]=null}}_onFrame(e,i){var n;const s=this._trackStates[e];if(!s||this._stopped)return;const o=i.numberOfFrames,r=new Float32Array(o);i.copyTo(r,{planeIndex:0}),(n=i.close)===null||n===void 0||n.call(i);const a=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);s.seq=s.seq+1&65535;const l=s.ts;s.ts+=o;const c={rtpSeq:s.seq,rtpTs:l,rtpSsrc:s.ssrc,capturedAt:new Date().toISOString(),payloadBytes:a};this._pushPacket(c,e)}_pushPacket(e,i){const n=e.payloadBytes.length+je.PACKET_OVERHEAD_BYTES,s=this._maxBufferBytes(),o=this._buffers[i];if(o.push(e),this._bufferBytes[i]+=n,this._bufferBytes[i]>s){for(;o.length>1&&this._bufferBytes[i]>s;){const r=o.shift();r&&(this._bufferBytes[i]-=r.payloadBytes.length+je.PACKET_OVERHEAD_BYTES)}this._overflowWarnedThisWindow[i]||(this._overflowWarnedThisWindow[i]=!0,y.warn("CallRecorder: buffer overflow — oldest packets dropped",{track:i}),this._emitWarning(e0))}}_flushIntervalMs(){var e;const i=(e=this.options.flushIntervalMs)!==null&&e!==void 0?e:15e3;return i<=0?i:Math.min(i,this._maxSafeFlushIntervalMs())}_maxSafeFlushIntervalMs(){const e=this._sampleRate()*je.BYTES_PER_SAMPLE+je.FRAMES_PER_SECOND*je.PACKET_OVERHEAD_BYTES;return Math.max(1e3,this._maxBufferBytes()/e*500)}_maxBufferBytes(){var e;return(e=this.options.maxBufferBytes)!==null&&e!==void 0?e:rh}_sampleRate(){var e;return(e=this.options.sampleRate)!==null&&e!==void 0?e:48e3}_scheduleFlush(){if(this._stopped||this._flushTimerId)return;const e=this._flushIntervalMs();e<=0||(this._flushTimerId=setInterval(()=>{this._periodicFlush().catch(i=>{y.error("CallRecorder: periodic flush error",{error:i})})},e))}_clearFlushTimer(){this._flushTimerId&&(clearInterval(this._flushTimerId),this._flushTimerId=null)}_cancelReaders(){for(const e of this._readerCancellers)try{e()}catch{}this._readerCancellers=[],this._processors=[]}_periodicFlush(){return V(this,void 0,void 0,function*(){if(!this._flushing&&!this._stopped){this._flushing=!0;try{const e=this._resolveEndpointFromContext();if(!e)return void y.debug("CallRecorder: periodic flush skipped — no host available");const i=this.options.tracks||["local","remote"],n=this._startedAt||new Date,s=new Date;yield Promise.allSettled(i.map(o=>{const r=this._drain(o);if(r.length===0)return Promise.resolve();const a=this._buildEnvelope(r,o,"intermediate",n,s);return this._postRecording(e,a,!1).catch(l=>{y.error("CallRecorder: intermediate flush failed",{track:o,error:l})})})),this._overflowWarnedThisWindow={local:!1,remote:!1}}finally{this._flushing=!1}}})}_drain(e){const i=this._buffers[e];return this._buffers[e]=[],this._bufferBytes[e]=0,i}_resolveEndpointFromContext(){const e=this.callContext.host;return e?this._resolveEndpoint(e):this._host?this._resolveEndpoint(this._host):null}_setHost(e){this._host=e}_setCallReportId(e){e&&(this._callReportId=e)}_resolveCallReportId(){return this._callReportId||this.callContext.callReportId}_resolveEndpoint(e){const i=this.options.endpoint||"/call_recording";try{const n=new URL(e);return`${`${n.protocol.replace(/^ws/,"http")}//${n.host}`}${i}`}catch{return/^https?:\/\//.test(e)?`${e}${i}`:`https://${e}${i}`}}_buildEnvelope(e,i,n,s,o){let r=0;const a=e.map(l=>(r+=l.payloadBytes.length,{rtp_seq:l.rtpSeq,rtp_ts:l.rtpTs,rtp_ssrc:l.rtpSsrc,captured_at:l.capturedAt,payload_b64:this._toBase64(l.payloadBytes)}));return Object.assign(Object.assign({call_report_id:this._resolveCallReportId(),call_id:this.callContext.callId},this.callContext.voiceSdkId?{voice_sdk_id:this.callContext.voiceSdkId}:{}),{recording_id:this.recordingId,segment:n,track:i,codec:"pcm-f32-le",sample_rate:this._sampleRate(),channels:1,started_at:s.toISOString(),ended_at:o.toISOString(),packet_count:e.length,byte_count:r,packets:a})}_postRecording(e,i,n){return V(this,void 0,void 0,function*(){const s={"Content-Type":"application/json","x-call-report-id":i.call_report_id,"x-call-id":i.call_id};i.voice_sdk_id&&(s["x-voice-sdk-id"]=i.voice_sdk_id);const o=JSON.stringify(i),r=n&&o.length<=je.KEEPALIVE_BODY_LIMIT_BYTES,a=this.options.fetchImpl||fetch;let l;for(let c=0;c<=je.RETRY_DELAYS_MS.length;c++){try{const d=yield a(e,Object.assign({method:"POST",headers:s,body:o},r?{keepalive:!0}:{}));if(d.ok)return void y.info("CallRecorder: posted",{track:i.track,segment:i.segment,attempt:c+1,status:d.status,packets:i.packet_count});{const h=yield d.text().catch(()=>"");l=new Error(`Call recording POST failed with status ${d.status}`),y.error("CallRecorder: failed to post",{track:i.track,segment:i.segment,attempt:c+1,status:d.status,error:h})}}catch(d){l=d,y.warn("CallRecorder: network error posting",{track:i.track,segment:i.segment,attempt:c+1,error:d})}const u=je.RETRY_DELAYS_MS[c];if(u===void 0)break;y.info("CallRecorder: retrying",{track:i.track,segment:i.segment,inMs:u,attempt:c+2}),yield new Promise(d=>setTimeout(d,u))}throw y.error("CallRecorder: exhausted retries",{track:i.track,segment:i.segment,error:l}),l instanceof Error?l:new Error("Call recording POST failed after retries")})}_emitWarning(e){var i;try{const n=Ne(e);(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){y.warn("CallRecorder: failed to emit warning",{code:e,error:n})}}_toBase64(e){let i="";for(let n=0;n<e.length;n+=32768){const s=e.subarray(n,n+32768);i+=String.fromCharCode.apply(null,Array.from(s))}return btoa(i)}}je.RETRY_DELAYS_MS=[500,1e3,2e3],je.KEEPALIVE_BODY_LIMIT_BYTES=61440,je.PACKET_OVERHEAD_BYTES=160,je.BYTES_PER_SAMPLE=4,je.FRAMES_PER_SECOND=100;class ib{constructor(){this._rawDeviceCache=[],this._deviceChangeHandler=null,this._stopped=!1}logDevicesAtStart(){return V(this,void 0,void 0,function*(){try{const e=yield this._enumerateAudioDevices();this._rawDeviceCache=e,y.debug("MediaDeviceCollector: devices at call start",{devices:e}),this._startDeviceChangeListener()}catch(e){y.debug("MediaDeviceCollector: failed to log devices at start",{error:e})}})}stop(){this._stopped=!0,this._removeDeviceChangeListener()}_enumerateAudioDevices(){return V(this,void 0,void 0,function*(){try{if(typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.enumerateDevices=="function")return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind==="audioinput"||e.kind==="audiooutput")}catch(e){y.debug("MediaDeviceCollector: enumerateDevices failed",{error:e})}return[]})}_startDeviceChangeListener(){typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.addEventListener=="function"&&(this._deviceChangeHandler=()=>{this._onDeviceChange()},navigator.mediaDevices.addEventListener("devicechange",this._deviceChangeHandler))}_removeDeviceChangeListener(){this._deviceChangeHandler&&typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.removeEventListener=="function"&&navigator.mediaDevices.removeEventListener("devicechange",this._deviceChangeHandler),this._deviceChangeHandler=null}_onDeviceChange(){return V(this,void 0,void 0,function*(){if(!this._stopped)try{const e=yield this._enumerateAudioDevices(),i=new Set(this._rawDeviceCache.map(r=>r.deviceId)),n=new Set(e.map(r=>r.deviceId)),s=e.filter(r=>!i.has(r.deviceId)),o=this._rawDeviceCache.filter(r=>!n.has(r.deviceId));(s.length>0||o.length>0)&&y.debug("MediaDeviceCollector: devices changed during call",{connected:s,disconnected:o}),this._rawDeviceCache=e}catch(e){y.debug("MediaDeviceCollector: error handling devicechange",{error:e})}})}}var bs,Eh=Ku(function(t,e){var i;function n(){}function s(){s.init.call(this)}function o(g){return g._maxListeners===void 0?s.defaultMaxListeners:g._maxListeners}function r(g,m,f,S){var I,A,x;if(typeof f!="function")throw new TypeError('"listener" argument must be a function');if((A=g._events)?(A.newListener&&(g.emit("newListener",m,f.listener?f.listener:f),A=g._events),x=A[m]):(A=g._events=new n,g._eventsCount=0),x){if(typeof x=="function"?x=A[m]=S?[f,x]:[x,f]:S?x.unshift(f):x.push(f),!x.warned&&(I=o(g))&&0<I&&x.length>I){x.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+x.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=g,N.type=m,N.count=x.length,function(M){typeof console.warn=="function"?console.warn(M):console.log(M)}(N)}}else x=A[m]=f,++g._eventsCount;return g}function a(g,m,f){function S(){g.removeListener(m,S),I||(I=!0,f.apply(g,arguments))}var I=!1;return S.listener=f,S}function l(g){var m=this._events;if(m){var f=m[g];if(typeof f=="function")return 1;if(f)return f.length}return 0}function c(g,m){for(var f=Array(m);m--;)f[m]=g[m];return f}Object.defineProperty(e,"__esModule",{value:!0}),n.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&i.active&&!(this instanceof i.Domain)&&(this.domain=i.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new n,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(g){if(typeof g!="number"||0>g||isNaN(g))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=g,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(g){var m,f,S,I,A,x,N,M=g==="error";if(x=this._events)M=M&&x.error==null;else if(!M)return!1;if(N=this.domain,M){if(m=arguments[1],!N){if(m instanceof Error)throw m;var F=new Error('Uncaught, unspecified "error" event. ('+m+")");throw F.context=m,F}return m||(m=new Error('Uncaught, unspecified "error" event')),m.domainEmitter=this,m.domain=N,m.domainThrown=!1,N.emit("error",m),!1}if(!(f=x[g]))return!1;var G=typeof f=="function";switch(S=arguments.length){case 1:(function(U,ae,q){if(ae)U.call(q);else for(var H=U.length,ce=c(U,H),J=0;J<H;++J)ce[J].call(q)})(f,G,this);break;case 2:(function(U,ae,q,H){if(ae)U.call(q,H);else for(var ce=U.length,J=c(U,ce),ee=0;ee<ce;++ee)J[ee].call(q,H)})(f,G,this,arguments[1]);break;case 3:(function(U,ae,q,H,ce){if(ae)U.call(q,H,ce);else for(var J=U.length,ee=c(U,J),te=0;te<J;++te)ee[te].call(q,H,ce)})(f,G,this,arguments[1],arguments[2]);break;case 4:(function(U,ae,q,H,ce,J){if(ae)U.call(q,H,ce,J);else for(var ee=U.length,te=c(U,ee),ie=0;ie<ee;++ie)te[ie].call(q,H,ce,J)})(f,G,this,arguments[1],arguments[2],arguments[3]);break;default:for(I=Array(S-1),A=1;A<S;A++)I[A-1]=arguments[A];(function(U,ae,q,H){if(ae)U.apply(q,H);else for(var ce=U.length,J=c(U,ce),ee=0;ee<ce;++ee)J[ee].apply(q,H)})(f,G,this,I)}return!0},s.prototype.addListener=function(g,m){return r(this,g,m,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(g,m){return r(this,g,m,!0)},s.prototype.once=function(g,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.on(g,a(this,g,m)),this},s.prototype.prependOnceListener=function(g,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(g,a(this,g,m)),this},s.prototype.removeListener=function(g,m){var f,S,I,A,x;if(typeof m!="function")throw new TypeError('"listener" argument must be a function');if(!(S=this._events))return this;if(!(f=S[g]))return this;if(f===m||f.listener&&f.listener===m)--this._eventsCount==0?this._events=new n:(delete S[g],S.removeListener&&this.emit("removeListener",g,f.listener||m));else if(typeof f!="function"){for(I=-1,A=f.length;0<A--;)if(f[A]===m||f[A].listener&&f[A].listener===m){x=f[A].listener,I=A;break}if(0>I)return this;if(f.length===1){if(f[0]=void 0,--this._eventsCount==0)return this._events=new n,this;delete S[g]}else(function(N,M){for(var F=M,G=F+1,U=N.length;G<U;F+=1,G+=1)N[F]=N[G];N.pop()})(f,I);S.removeListener&&this.emit("removeListener",g,x||m)}return this},s.prototype.removeAllListeners=function(g){var m,f;if(!(f=this._events))return this;if(!f.removeListener)return arguments.length===0?(this._events=new n,this._eventsCount=0):f[g]&&(--this._eventsCount==0?this._events=new n:delete f[g]),this;if(arguments.length===0){for(var S,I=Object.keys(f),A=0;A<I.length;++A)(S=I[A])!=="removeListener"&&this.removeAllListeners(S);return this.removeAllListeners("removeListener"),this._events=new n,this._eventsCount=0,this}if(typeof(m=f[g])=="function")this.removeListener(g,m);else if(m)do this.removeListener(g,m[m.length-1]);while(m[0]);return this},s.prototype.listeners=function(g){var m,f,S=this._events;return S?f=(m=S[g])?typeof m=="function"?[m.listener||m]:function(I){for(var A=Array(I.length),x=0;x<A.length;++x)A[x]=I[x].listener||I[x];return A}(m):[]:f=[],f},s.listenerCount=function(g,m){return typeof g.listenerCount=="function"?g.listenerCount(m):l.call(g,m)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var u,d=new Uint8Array(16);function h(){if(!u&&!(u=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return u(d)}for(var p=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,_=[],v=0;256>v;++v)_.push((v+256).toString(16).substr(1));function b(g){var m=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,f=(_[g[m+0]]+_[g[m+1]]+_[g[m+2]]+_[g[m+3]]+"-"+_[g[m+4]]+_[g[m+5]]+"-"+_[g[m+6]]+_[g[m+7]]+"-"+_[g[m+8]]+_[g[m+9]]+"-"+_[g[m+10]]+_[g[m+11]]+_[g[m+12]]+_[g[m+13]]+_[g[m+14]]+_[g[m+15]]).toLowerCase();if(!function(S){return typeof S=="string"&&p.test(S)}(f))throw TypeError("Stringified UUID is invalid");return f}function w(g,m,f){var S=(g=g||{}).random||(g.rng||h)();return S[6]=64|15&S[6],S[8]=128|63&S[8],b(S)}function C(g,m){if(!g||!m)return{};const f={...g};if(f.localCandidateId){const S=m.get(f.localCandidateId);f.local={...S}}if(f.remoteCandidateId){const S=m.get(f.remoteCandidateId);f.remote={...S}}return f}function k(g,m,f){return 8*function(S,I,A){const x=S[A],N=I?I[A]:null;return x===null||N===null?null:(x-N)/(S.timestamp-I.timestamp)*1e3}(g,m,f)}function L(g){if(!g.entries)return g;const m={};return g.forEach(function(f,S){m[S]=f}),m}function R(g,m,f={}){if(!g)return null;let S={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};f.remote&&(S.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const I of g.values())switch(I.type){case"outbound-rtp":{const A=I.mediaType||I.kind,x={};let N={};if(!["audio","video"].includes(A))continue;if(I.codecId){const M=g.get(I.codecId);M&&(x.clockRate=M.clockRate,x.mimeType=M.mimeType,x.payloadType=M.payloadType)}N=g.get(I.mediaSourceId)||g.get(I.trackId)||{},S[A].outbound.push({...I,...x,track:{...N}});break}case"inbound-rtp":{let A=I.mediaType||I.kind,x={};const N={};if(!["audio","video"].includes(A))if(I.id.includes("Video"))A="video";else{if(!I.id.includes("Audio"))continue;A="audio"}if(I.codecId){const M=g.get(I.codecId);M&&(N.clockRate=M.clockRate,N.mimeType=M.mimeType,N.payloadType=M.payloadType)}if(!S.connection.id&&I.transportId){const M=g.get(I.transportId);if(M&&M.selectedCandidatePairId){const F=g.get(M.selectedCandidatePairId);S.connection=C(F,g)}}x=g.get(I.mediaSourceId)||g.get(I.trackId)||{},S[A].inbound.push({...I,...N,track:{...x}});break}case"peer-connection":S.connection.dataChannelsClosed=I.dataChannelsClosed,S.connection.dataChannelsOpened=I.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!f.remote)break;let A=I.mediaType||I.kind;const x={};if(!["audio","video"].includes(A))if(I.id.includes("Video"))A="video";else{if(!I.id.includes("Audio"))continue;A="audio"}if(I.codecId){const N=g.get(I.codecId);N&&(x.clockRate=N.clockRate,x.mimeType=N.mimeType,x.payloadType=N.payloadType)}if(!S.connection.id&&I.transportId){const N=g.get(I.transportId);if(N&&N.selectedCandidatePairId){const M=g.get(N.selectedCandidatePairId);S.connection=C(M,g)}}S.remote[A].inbound.push({...I,...x});break}case"remote-outbound-rtp":{if(!f.remote)break;const A=I.mediaType||I.kind,x={};if(!["audio","video"].includes(A))continue;if(I.codecId){const N=g.get(I.codecId);N&&(x.clockRate=N.clockRate,x.mimeType=N.mimeType,x.payloadType=N.payloadType)}S.remote[A].outbound.push({...I,...x});break}}if(!S.connection.id)for(const I of g.values())I.type==="candidate-pair"&&I.nominated&&I.state==="succeeded"&&(S.connection=C(I,g));return S=function(I,A){return A&&(I.audio.inbound.map(x=>{let N=A.audio.inbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesReceived"),x.packetRate=k(x,N,"packetsReceived")}),I.audio.outbound.map(x=>{let N=A.audio.outbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesSent"),x.packetRate=k(x,N,"packetsSent")}),I.video.inbound.map(x=>{let N=A.video.inbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesReceived"),x.packetRate=k(x,N,"packetsReceived")}),I.video.outbound.map(x=>{let N=A.video.outbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesSent"),x.packetRate=k(x,N,"packetsSent")})),I}(S,m),S}let O,T={},E=[];e.WebRTCStats=class extends s{constructor(g){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],typeof window>"u")throw new Error("WebRTCStats only works in browser");const m={...g};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=m.getStatsInterval||1e3,this.rawStats=!!m.rawStats,this.statsObject=!!m.statsObject,this.filteredStats=!!m.filteredStats,this.shouldWrapGetUserMedia=!!m.wrapGetUserMedia,typeof m.remote=="boolean"&&(this.remote=m.remote),this.debug=!!m.debug,this.logLevel=m.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(g,m){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:g,pc:m})}async addConnection(g){const{pc:m,peerId:f}=g;let{connectionId:S,remote:I}=g;if(I=typeof I=="boolean"?I:this.remote,!(m&&m instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!f)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[f]){if(S&&S in this.peersToMonitor[f])throw new Error(`We are already monitoring connection with id ${S}.`);for(let x in this.peersToMonitor[f]){const N=this.peersToMonitor[f][x];if(N.pc===m)throw new Error(`We are already monitoring peer with id ${f}.`);N.pc.connectionState==="closed"&&this.removeConnection({pc:N.pc})}}const A=m.getConfiguration();return A.iceServers&&A.iceServers.forEach(function(x){delete x.credential}),S||(S=w()),this.emitEvent({event:"addConnection",tag:"peer",peerId:f,connectionId:S,data:{options:g,peerConfiguration:A}}),this.monitorPeer({peerId:f,connectionId:S,pc:m,remote:I}),{connectionId:S}}getTimeline(g){return this.timeline=this.timeline.sort((m,f)=>m.timestamp.getTime()-f.timestamp.getTime()),g?this.timeline.filter(m=>m.tag===g):this.timeline}get logger(){const g=m=>{const f=["none","error","warn","info","debug"];return f.slice(0,f.indexOf(this.logLevel)+1).indexOf(m)>-1};return{error(...m){this.debug&&g("error")&&console.error("[webrtc-stats][error] ",...m)},warn(...m){this.debug&&g("warn")&&console.warn("[webrtc-stats][warn] ",...m)},info(...m){this.debug&&g("info")&&console.log("[webrtc-stats][info] ",...m)},debug(...m){this.debug&&g("debug")&&console.debug("[webrtc-stats][debug] ",...m)}}}removeConnection(g){let m,{connectionId:f,pc:S}=g;if(!S&&!f)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(f){if(typeof f!="string")throw new Error("connectionId must be a string.");for(let I in this.peersToMonitor)f in this.peersToMonitor[I]&&(S=this.peersToMonitor[I][f].pc,m=I)}else if(S){if(!(S instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let I in this.peersToMonitor)for(let A in this.peersToMonitor[I])this.peersToMonitor[I][A].pc===S&&(f=A,m=I)}if(!S||!f)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(f,S),delete this.peersToMonitor[m][f],Object.values(this.peersToMonitor[m]).length===0&&delete this.peersToMonitor[m],{connectionId:f}}removeAllPeers(){for(let g in this.peersToMonitor)this.removePeer(g)}removePeer(g){if(this.logger.info(`Removing PeerConnection with id ${g}.`),this.peersToMonitor[g]){for(let m in this.peersToMonitor[g]){let f=this.peersToMonitor[g][m].pc;this.removePeerConnectionEventListeners(m,f)}delete this.peersToMonitor[g]}}destroy(){this.removeAllPeers(),E.forEach(g=>{this.removeTrackEventListeners(g)}),E=[],this.shouldWrapGetUserMedia&&O&&(navigator.mediaDevices.getUserMedia=O)}monitorPeer(g){let{peerId:m,connectionId:f,pc:S,remote:I}=g;if(!S)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const A={pc:S,connectionId:f,stream:null,stats:{parsed:null,raw:null},options:{remote:I}};if(this.peersToMonitor[m]){if(f in this.peersToMonitor[m])return void this.logger.warn(`Already watching connection with ID ${f}`);this.peersToMonitor[m][f]=A}else this.peersToMonitor[m]={[f]:A};this.addPeerConnectionEventListeners(m,f,S),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(g=>{g.forEach(m=>{this.emitEvent(m)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(g=null){this.logger.info(g?`Getting stats from peer ${g}`:"Getting stats from all peers");let m={};if(g){if(!this.peersToMonitor[g])throw new Error(`Cannot get stats. Peer with id ${g} does not exist`);m[g]=this.peersToMonitor[g]}else m=this.peersToMonitor;let f=[];for(const S in m)for(const I in m[S]){const A=m[S][I],x=A.pc;if(x&&!this.checkIfConnectionIsClosed(S,I,x))try{const N=this.getTimestamp(),M=x.getStats(null);if(M){const F=await M,G=this.getTimestamp(),U=L(F),ae={remote:A.options.remote},q=R(F,A.stats.parsed,ae),H={event:"stats",tag:"stats",peerId:S,connectionId:I,timeTaken:G-N,data:q};this.rawStats===!0&&(H.rawStats=F),this.statsObject===!0&&(H.statsObject=U),this.filteredStats===!0&&(H.filteredStats=this.filteroutStats(U)),f.push(H),A.stats.parsed=q}else this.logger.error(`PeerConnection from peer ${S} did not return any stats data`)}catch(N){this.logger.error(N)}}return f}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const g in this.peersToMonitor)for(const m in this.peersToMonitor[g]){const f=this.peersToMonitor[g][m].pc;this.checkIfConnectionIsClosed(g,m,f)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(g,m,f){const S=this.isConnectionClosed(f);if(S){this.removeConnection({pc:f});let I=f.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:I,peerId:g,connectionId:m,tag:"connection",data:"closed"})}return S}isConnectionClosed(g){return g.connectionState==="closed"||g.iceConnectionState==="closed"}stopConnectionStateMonitoring(){this.connectionMonitoringSetInterval&&(window.clearInterval(this.connectionMonitoringSetInterval),this.connectionMonitoringSetInterval=0)}wrapGetUserMedia(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return void this.logger.warn("'navigator.mediaDevices.getUserMedia' is not available in browser. Will not wrap getUserMedia.");this.logger.info("Wrapping getUsermedia functions."),O=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const g=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return g({constraints:arguments[0]}),O.apply(navigator.mediaDevices,arguments).then(m=>(g({stream:m}),m),m=>(g({error:m}),Promise.reject(m)))}).bind(navigator.mediaDevices)}filteroutStats(g={}){const m={...g};for(const S in m){var f=m[S];this.statsToMonitor.includes(f.type)||delete m[S]}return m}get peerConnectionListeners(){return{icecandidate:(g,m,f,S)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",S),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:g,connectionId:m,data:S.candidate})},track:(g,m,f,S)=>{this.logger.debug(`[pc-event] track | peerId: ${g}`,S);const I=S.track,A=S.streams[0];g in this.peersToMonitor&&m in this.peersToMonitor[g]&&(this.peersToMonitor[g][m].stream=A),this.addTrackEventListeners(I,m),this.emitEvent({event:"ontrack",tag:"track",peerId:g,connectionId:m,data:{stream:A?this.getStreamDetails(A):null,track:I?this.getMediaTrackDetails(I):null,title:S.track.kind+":"+S.track.id+" "+S.streams.map(function(x){return"stream:"+x.id})}})},signalingstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${g}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:g,connectionId:m,data:{signalingState:f.signalingState,localDescription:f.localDescription,remoteDescription:f.remoteDescription}})},iceconnectionstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${g}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:g,connectionId:m,data:f.iceConnectionState})},icegatheringstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${g}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:g,connectionId:m,data:f.iceGatheringState})},icecandidateerror:(g,m,f,S)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${g}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:g,connectionId:m,error:{errorCode:S.errorCode}})},connectionstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${g}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:g,connectionId:m,data:f.connectionState})},negotiationneeded:(g,m,f)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${g}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:g,connectionId:m})},datachannel:(g,m,f,S)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${g}`,S),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:g,connectionId:m,data:S.channel})}}}addPeerConnectionEventListeners(g,m,f){this.logger.debug(`Adding event listeners for peer ${g} and connection ${m}.`),T[m]={},Object.keys(this.peerConnectionListeners).forEach(S=>{T[m][S]=this.peerConnectionListeners[S].bind(this,g,m,f),f.addEventListener(S,T[m][S],!1)})}parseGetUserMedia(g){try{const m={event:"getUserMedia",tag:"getUserMedia",data:{...g}};g.stream&&(m.data.details=this.parseStream(g.stream),g.stream.getTracks().map(f=>{this.addTrackEventListeners(f),E.push(f)})),this.emitEvent(m)}catch{}}parseStream(g){const m={audio:[],video:[]};return g.getTracks().forEach(f=>{m[f.kind].push(this.getMediaTrackDetails(f))}),m}getMediaTrackDetails(g){return{enabled:g.enabled,id:g.id,contentHint:g.contentHint,kind:g.kind,label:g.label,muted:g.muted,readyState:g.readyState,constructorName:g.constructor.name,capabilities:g.getCapabilities?g.getCapabilities():{},constraints:g.getConstraints?g.getConstraints():{},settings:g.getSettings?g.getSettings():{},_track:g}}getStreamDetails(g){return{active:g.active,id:g.id,_stream:g}}getTrackEventObject(g){return{mute:m=>{this.emitEvent({event:"mute",tag:"track",connectionId:g,data:{event:m}})},unmute:m=>{this.emitEvent({event:"unmute",tag:"track",connectionId:g,data:{event:m}})},overconstrained:m=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:g,data:{event:m}})},ended:m=>{this.emitEvent({event:"ended",tag:"track",connectionId:g,data:{event:m}}),this.removeTrackEventListeners(m.target)}}}addTrackEventListeners(g,m){T[g.id]={};const f=this.getTrackEventObject(m);Object.keys(f).forEach(S=>{T[g.id][S]=f[S].bind(this),g.addEventListener(S,T[g.id][S])}),T[g.id].readyState=setInterval(()=>{if(g.readyState==="ended"){let S=new CustomEvent("ended",{detail:{check:"readyState"}});g.dispatchEvent(S)}},1e3)}removeTrackEventListeners(g){if(g.id in T){const m=this.getTrackEventObject();Object.keys(m).forEach(f=>{g.removeEventListener(f,T[g.id][f])}),clearInterval(T[g.id].readyState),delete T[g.id]}}addToTimeline(g){this.timeline.push(g),this.emit("timeline",g)}emitEvent(g){const m={...g,timestamp:new Date};this.addToTimeline(m),m.tag&&this.emit(m.tag,m)}set getStatsInterval(g){if(!Number.isInteger(g))throw new Error(`getStatsInterval should be an integer, got: ${g}`);this._getStatsInterval=g,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(g,m){g in T&&(Object.keys(this.peerConnectionListeners).forEach(f=>{m.removeEventListener(f,T[g][f],!1)}),delete T[g]),m.getSenders().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)}),m.getReceivers().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const g=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const m=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),f=function(){return g.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),m.apply(navigator.mediaDevices,arguments).then(function(S){return S},function(S){return g.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,S.name),Promise.reject(S)})};navigator.mediaDevices.getDisplayMedia=f.bind(navigator.mediaDevices)}}}});(bs=Eh)&&bs.__esModule&&Object.prototype.hasOwnProperty.call(bs,"default")&&bs.default;var nb=Eh.WebRTCStats;function sb(t){const{packetsLost:e,packetsReceived:i,jitter:n,rtt:s}=t,o=function(c){const{jitter:u,rtt:d}=c,h=u+d/2;return .024*h+.11*(h-177.3)*(h>177.3?1:0)}({rtt:s,jitter:n}),r=function(c){const{packetsLost:u,packetsReceived:d}=c,h=u/(d+u)*100;return 20*Math.log(1+h)}({packetsLost:e,packetsReceived:i}),a=93.2-o-r+0,l=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(l,1),5)}function ob(t){return isNaN(t)?null:t>4.2?"excellent":t>=4.1&&t<=4.2?"good":t>=3.7&&t<=4?"fair":t>=3.1&&t<=3.6?"poor":"bad"}class rb extends Li{constructor(e,i){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:i})}}class ab extends Li{constructor(e,i){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:i})}}class lb extends Li{constructor(e,i,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,call_id:i,debug_report_data:n})}}function cb(t,e){const i=ki();let n=!1;const s=new nb({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>V(this,void 0,void 0,function*(){r.event==="stats"&&B(P.StatsFrame,function({data:a}){var l,c,u,d,h,p,_,v;const{audio:b,remote:w}=a,{audio:C}=w,k=(c=(l=C.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,L=(d=(u=C.inbound[0])===null||u===void 0?void 0:u.roundTripTime)!==null&&d!==void 0?d:1/0,R=(p=(h=b.inbound[0])===null||h===void 0?void 0:h.packetsReceived)!==null&&p!==void 0?p:-1,O=(v=(_=b.inbound[0])===null||_===void 0?void 0:_.packetsLost)!==null&&v!==void 0?v:-1,T=sb({jitter:1e3*k,rtt:1e3*L,packetsLost:O,packetsReceived:R});return{jitter:k,rtt:L,mos:T,quality:ob(T),inboundAudio:b.inbound[0],outboundAudio:b.outbound[0],remoteInboundAudio:C.inbound[0],remoteOutboundAudio:C.outbound[0]}}(r),t.uuid),yield t.execute(new lb(i,e,r))});return{get isRunning(){return n},start:(r,a,l)=>V(this,void 0,void 0,function*(){if(n)y.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new rb(i,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),n=!0}catch(c){y.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:r=>V(this,void 0,void 0,function*(){const a=s.getTimeline();B(P.StatsReport,a,t.uuid),r==="file"&&function(l,c){const u=new Blob([JSON.stringify(l)],{type:"application/json"}),d=URL.createObjectURL(u),h=document.createElement("a");h.href=d,h.download=`${c}.json`,h.click(),URL.revokeObjectURL(d)}(a,`webrtc-stats-${i}-${Date.now()}`),yield t.execute(new ab(i,e)),s.removeAllPeers(),s.destroy(),n=!1}),reportConnectionStateChange:r=>{const a={event:"connectionstatechange-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)},reportIceCandidateError:r=>{const a={event:"icecandidateerror-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)}}}const kh=(t,e)=>{const{contentType:i,canvasType:n,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=e;o&&n!=="mcu-personal-canvas"&&delete o.memberID;const a={type:st.conferenceUpdate,call:t.calls[s],canvasInfo:db(o),currentLayerIdx:r};switch(i){case"layer-info":{const l=Object.assign({action:Ye.LayerInfo},a);B(P.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:Ye.LayoutInfo},a);B(P.Notification,l,t.uuid);break}}},db=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Qu(e)},Ih=["new-call-start","new-peer","get-user-media","peer-creation-end","start-negotiation","create-offer","create-answer","set-local-description","ice-gathering-started","first-candidate","first-non-host-candidate","send-sdp","ice-gathering-completed","ringing","telnyx-rtc-media","first-remote-media-track","set-remote-description","telnyx-rtc-answer","ice-connected","dtls-connected","call-active","answer-called"],ub={"new-call-start":"Call Start","new-peer":"Peer object created","get-user-media":"Media devices acquired","peer-creation-end":"Peer setup complete","start-negotiation":"SDP negotiation started","create-offer":"SDP offer generated","create-answer":"SDP answer generated","set-local-description":"Local description applied","ice-gathering-started":"ICE candidate gathering started","first-candidate":"First ICE candidate found","first-non-host-candidate":"First server-reflexive/relay candidate found","send-sdp":"SDP sent to server","ice-gathering-completed":"All ICE candidates gathered",ringing:"Remote side ringing","telnyx-rtc-media":"Early media received from server","first-remote-media-track":"First remote audio/video track received","set-remote-description":"Remote description applied","telnyx-rtc-answer":"Call answered by remote side","ice-connected":"ICE connection established","dtls-connected":"Secure media channel established (DTLS)","call-active":"Call is active","answer-called":"Answer delay (invite → call.answer)"};function re(t,e){return`telnyx:call:${t}:${e}`}function Rh(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}function Fr(t){for(const e of Ih)try{performance.clearMarks(re(t,e))}catch{y.warn("Clearing performance marks is failed")}}class ii{constructor(e,i,n,s,o){this.type=e,this.options=i,this.onSdpReadyTwice=null,this.statsReporter=null,this.isIceRestarting=!1,this.iceDone=!1,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this._iceGatheringSafetyTimeout=null,this._gatheredCandidatesCount=0,this._firstMediaTrackMarked=!1,this._timingsCollected=!1,this._iceRestartTimeoutId=null,this.handleConnectionStateChange=()=>V(this,void 0,void 0,function*(){var r,a;if(!this.instance)return void y.debug("Connection state change ignored: instance is null");const{connectionState:l}=this.instance;if(y.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${l}`),l!=="failed"&&l!=="disconnected"||(this.isDebugEnabled&&this.statsReporter&&function(c,u){return V(this,void 0,void 0,function*(){const d={connectionState:c.connectionState,previousConnectionState:u,iceConnectionState:c.iceConnectionState,iceGatheringState:c.iceGatheringState,signalingState:c.signalingState},h=c.getTransceivers();if(h.length>0){const p=h[0].sender,_=p==null?void 0:p.transport;_&&(d.dtlsState=_.state)}c.sctp&&(d.sctpState=c.sctp.state);try{const p=yield c.getStats();p.forEach(_=>{_.type==="candidate-pair"&&_.state==="succeeded"&&(d.candidatePairState=_.state,p.forEach(v=>{v.type==="local-candidate"&&v.id===_.localCandidateId&&(d.localCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.local={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType}),v.type==="remote-candidate"&&v.id===_.remoteCandidateId&&(d.remoteCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.remote={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType})})),_.type==="transport"&&(d.dtlsCipher=_.dtlsCipher,d.srtpCipher=_.srtpCipher,d.tlsVersion=_.tlsVersion,_.dtlsState&&(d.dtlsState=_.dtlsState))})}catch(p){y.error("Error gathering connection state details:",p)}return d})}(this.instance,this._prevConnectionState).then(c=>{this.statsReporter.reportConnectionStateChange(c)}),(a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"connection_failed")),l==="disconnected"){const c=Ne(t0);B(P.Warning,{warning:c,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(l==="failed"){const c=Ne(s0);B(P.PeerConnectionFailureError,{warning:c,error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${l}`),sessionId:this._session.sessionid},this.options.id)}this._prevConnectionState=l,l==="connected"&&(performance.mark(re(this.options.id,"dtls-connected")),this.tryCollectTimings(),this._restartedIceOnConnectionStateFailed=!1),this._isTrickleIce()&&(l==="connecting"&&performance.mark(re(this.options.id,"peer-connection-connecting")),l==="connected"&&(this._clearIceGatheringSafetyTimeout(),performance.mark(re(this.options.id,"peer-connection-connected"))))}),this._handleIceConnectionStateChange=()=>{var r,a;if(!this.instance)return void y.debug("ICE connection state change ignored: instance is null");const l=this.instance.iceConnectionState;y.debug(`[${new Date().toISOString()}] ICE Connection State`,l),l==="connected"&&performance.mark(re(this.options.id,"ice-connected")),l==="failed"&&((a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"ice_failed"))},this._handleIceGatheringStateChange=()=>{const r=this.instance.iceGatheringState;y.debug(`[${new Date().toISOString()}] ICE Gathering State`,r),r==="gathering"?(this._gatheredCandidatesCount=0,this._startIceGatheringSafetyTimeout()):r==="complete"&&this._clearIceGatheringSafetyTimeout()},this._setCodecs=(r,a)=>{if(r.setCodecPreferences)return r.setCodecPreferences(a)},y.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!i.video},this._sdpReady=this._sdpReady.bind(this),this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this._session=n,this._trickleIceSdpFn=s,this._registerPeerEvents=o}finishIceRestart(){this.isIceRestarting&&(this.isIceRestarting=!1,this._iceRestartTimeoutId&&(clearTimeout(this._iceRestartTimeoutId),this._iceRestartTimeoutId=null))}restartIce(){return this.instance?this.isIceRestarting?(y.debug("ICE restart: already in progress, skipping"),{started:!1,reason:"already in progress"}):this._session.connected?(this.isIceRestarting=!0,this._restartedIceOnConnectionStateFailed=!0,this.instance.restartIce(),this.iceDone=!1,this._iceRestartTimeoutId=setTimeout(()=>{this.isIceRestarting&&(y.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null},ii.ICE_RESTART_TIMEOUT_MS),y.info("ICE restart: initiated by signaling health monitor"),{started:!0}):(y.debug("ICE restart: session not connected, skipping"),{started:!1,reason:"session not connected"}):(y.warn("ICE restart: no RTCPeerConnection instance"),{started:!1,reason:"no RTCPeerConnection instance"})}get isOffer(){return this.type===Fe.Offer}get isAnswer(){return this.type===Fe.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get restartedIceOnConnectionStateFailed(){return this._restartedIceOnConnectionStateFailed}isConnectionHealthy(){return this.instance.connectionState==="connected"&&this.instance.iceConnectionState==="connected"&&this.instance.signalingState!=="closed"}startNegotiation(){performance.mark(re(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?this._createOffer().catch(e=>this._emitNegotiationError(e)):this._createAnswer().catch(e=>this._emitNegotiationError(e))}startTrickleIceNegotiation(){return V(this,void 0,void 0,function*(){performance.mark(re(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_emitNegotiationError(e){e instanceof Vt&&B(P.Error,{error:e,sessionId:this._session.sessionid},this.options.id)}_logTransceivers(){this.instance?(y.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,i)=>{y.info(`>> Transceiver [${i}]:`,e.mid,e.direction,e.stopped),y.info(`>> Sender Params [${i}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):y.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(y.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":B(P.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(y.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){y.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?y.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation().catch(e=>this._emitNegotiationError(e)):this.startNegotiation()}handleTrackEvent(e){this._firstMediaTrackMarked||(performance.mark(re(this.options.id,"first-remote-media-track")),this._firstMediaTrackMarked=!0);const{streams:[i]}=e,{remoteElement:n,screenShare:s}=this.options;this.options.remoteStream=i,s===!1&&ms(n,this.options.remoteStream,{callId:this.options.id,sessionId:this._session.sessionid,eventTarget:this._session.uuid})}tryCollectTimings(){if(this._timingsCollected||!(performance.getEntriesByName(re(this.options.id,"call-active"),"mark").length>0)||this.instance.connectionState!=="connected")return;this._timingsCollected=!0;const e=this._isTrickleIce()?"trickle":"non-trickle",i=this.isOffer?"outbound":"inbound",n=function(s,o,r){const a=Rh(re(s,"new-call-start"));if(a===void 0)return{mode:o,direction:r,steps:[]};const l=[];for(const d of Ih){if(d==="new-call-start")continue;const h=Rh(re(s,d));h!==void 0&&l.push({label:ub[d]||d,fromStart:h-a})}l.sort((d,h)=>d.fromStart-h.fromStart);const c=[];let u=0;for(const d of l)c.push({label:d.label,fromStart:d.fromStart,delta:d.fromStart-u}),u=d.fromStart;return{mode:o,direction:r,steps:c}}(this.options.id,e,i);(function(s){const{mode:o,direction:r,steps:a}=s,l=`[CallTimings][${r}][${o}]`;if(a.length===0)return void y.info(`${l} No timing data collected`);const c=Math.max(...a.map(_=>_.label.length),4)+2,u=(_,v)=>{for(;_.length<v;)_+=" ";return _},d=(_,v)=>{for(;_.length<v;)_=" "+_;return _},h=u("Step",c)+d("Delta",14)+d("From Start",14);let p="";for(let _=0;_<h.length;_++)p+="-";y.info(`${l} Call establishment timing breakdown:`),y.info(`${l} ${h}`),y.info(`${l} ${p}`),y.info(`${l} ${u("Call Start",c)}${d("-",14)}${d("0.00ms",14)}`);for(const _ of a){const v=_.delta.toFixed(2)+"ms",b=_.fromStart.toFixed(2)+"ms";y.info(`${l} ${u(_.label,c)}${d(v,14)}${d(b,14)}`)}y.info(`${l} ${p}`)})(n),Fr(this.options.id)}createPeerConnection(){return V(this,void 0,void 0,function*(){var e;if(this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",s=>{this.options.remoteStream=s.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Fe.Offer}),performance.mark(re(this.options.id,"set-remote-description")),!this.instance))throw ne(wr);const i=!!this.options.receiveOnlyAudio&&!this.options.audio;let n=null;if(this.options.localStream=yield this._retrieveLocalStream().catch(s=>V(this,void 0,void 0,function*(){const o=this._session.options.mediaPermissionsRecovery;if(o!=null&&o.enabled&&this._isAnswer()){let r=null,a=null;return yield new Promise((l,c)=>{a=setTimeout(()=>c(new Error("Media recovery flow timed out!")),o.timeout),B(P.Error,{error:ne(Ii(s),s,void 0,!1),callId:this.options.id,sessionId:this._session.sessionid,recoverable:!0,retryDeadline:Date.now()+o.timeout,resume:()=>{l()},reject:()=>{c(new Error("Call was rejected during media recovery flow!"))}},this._session.uuid)}).then(()=>V(this,void 0,void 0,function*(){var l;a&&(clearTimeout(a),a=null),r=yield this._retrieveLocalStream(),(l=o.onSuccess)===null||l===void 0||l.call(o)})).catch(l=>{var c;a&&(clearTimeout(a),a=null),n=l,(c=o.onError)===null||c===void 0||c.call(o,l)}),r}return n=s,null})),!this.instance)throw ne(wr);if(!this.options.localStream&&!i)throw ne(n?Ii(n):Vu,n??void 0);performance.mark(re(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&vn(this.options.localStream)&&(y.info("Muting local audio tracks on start"),ys(this.options.localStream)),this.options.applyDesiredAudioMuteState&&this.options.applyDesiredAudioMuteState(),performance.mark(re(this.options.id,"peer-creation-end"))})}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout(()=>{if(this.instance){if(this._gatheredCandidatesCount===0){const e=Ne(n0);B(P.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=Ne(i0);B(P.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},ii.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){this._iceGatheringSafetyTimeout!==null&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return V(this,void 0,void 0,function*(){if(yield this.createPeerConnection(),!this.instance)throw ne(wr);this.isDebugEnabled&&(this.statsReporter=cb(this._session,this.options.id),yield(e=this.statsReporter)===null||e===void 0?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid));const{localElement:i,localStream:n=null,screenShare:s=!1}=this.options;if(vn(n)){const o=n.getAudioTracks();let r=[...o];if(y.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{y.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=n.getVideoTracks();r=[...o,...c],y.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(u=>{y.info("Local video tracks constraints: ",u.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=Th(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={direction:"sendrecv",streams:[n]};r.forEach(u=>{u.kind==="audio"&&(this.options.userVariables.microphoneLabel=u.label),u.kind==="video"&&(this.options.userVariables.cameraLabel=u.label);const d=this.instance.addTransceiver(u,c);u.kind==="audio"&&a.length>0&&this._setCodecs(d,a),u.kind==="video"&&l.length>0&&this._setCodecs(d,l)})}else typeof this.instance.addTrack=="function"?(r.forEach(c=>{c.kind==="audio"&&(this.options.userVariables.microphoneLabel=c.label),c.kind==="video"&&(this.options.userVariables.cameraLabel=c.label),this.instance.addTrack(c,n)}),this.instance.getTransceivers().forEach(c=>{c.receiver.track.kind==="audio"&&a.length>0&&this._setCodecs(c,a),c.receiver.track.kind==="video"&&l.length>0&&this._setCodecs(c,l)})):this.instance.addStream(n);s===!1&&ms(i,n)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});y.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=Th(this.options.preferred_codecs);r.length>0&&this._setCodecs(o,r)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation().catch(o=>this._emitNegotiationError(o)),this._logTransceivers()})}_getSenderByKind(e){return this.instance.getSenders().find(({track:i})=>i&&i.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const i=this.instance.addTransceiver(e);y.info("Add transceiver",e,i)}}_createOffer(){return V(this,void 0,void 0,function*(){if(this._isOffer()||this.isIceRestarting){this._constraints.offerToReceiveAudio=this.options.audio!==!1||!!this.options.receiveOnlyAudio,this._constraints.offerToReceiveVideo=!!this.options.video,y.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark(re(this.options.id,"create-offer")),yield this._setLocalDescription(e),performance.mark(re(this.options.id,"set-local-description")),performance.mark(re(this.options.id,"ice-gathering-started")),this._isTrickleIce()||this._sdpReady(),e}catch(e){throw y.error("Peer _createOffer error:",e),e instanceof Vt?e:ne(My,e)}}})}_setRemoteDescription(e){return V(this,void 0,void 0,function*(){y.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(i){throw y.error("Peer _setRemoteDescription error:",i),ne(Bu,i)}})}_createAnswer(){return V(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return y.debug("Skipping negotiation, state:",this.instance.signalingState),y.debug(" - But the signaling state isn't stable, so triggering rollback"),void(yield Promise.all([this.instance.setLocalDescription({type:"rollback"}),this.instance.setRemoteDescription({sdp:this.options.remoteSdp,type:Fe.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark(re(this.options.id,"create-answer")),yield this._setLocalDescription(e),performance.mark(re(this.options.id,"set-local-description")),performance.mark(re(this.options.id,"ice-gathering-started")),e}catch(e){throw y.error("Peer _createAnswer error:",e),e instanceof Vt?e:ne(Py,e)}}})}_setLocalDescription(e){return V(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(i){throw y.error("Peer _setLocalDescription error:",i),ne(Ny,i)}})}_sdpReady(){Ri(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return V(this,void 0,void 0,function*(){if(vn(this.options.localStream))return this.options.localStream;const e=yield(i=this.options,V(void 0,void 0,void 0,function*(){let{audio:n=!0,micId:s,video:o=!1,camId:r}=i;const{micLabel:a="",camLabel:l=""}=i;return s&&(s=yield _s(s,a,yt.AudioIn).catch(()=>null),s&&(typeof n=="boolean"&&(n={}),n.deviceId={exact:s})),r&&(r=yield _s(r,l,yt.Video).catch(()=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:n,video:o}}));var i;return vs(e)})}_isOffer(){return this.type===Fe.Offer}_isAnswer(){return this.type===Fe.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:i,iceServers:n}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:n,iceTransportPolicy:i?"relay":"all"};return y.info("RTC config",s),s}restartStatsReporter(){return V(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?y.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(y.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):y.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return V(this,void 0,void 0,function*(){Fr(this.options.id),this.finishIceRestart(),this._clearIceGatheringSafetyTimeout(),this._sleepWakeupIntervalId!==null&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)})}}ii.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,ii.ICE_RESTART_TIMEOUT_MS=15e3;const ws=Dr;class Ah{constructor(e,i){this.session=e,this._callReportCollector=null,this._callRecorder=null,this._mediaDeviceCollector=null,this.id="",this.recoveredCallId="",this.state=W[W.New],this.prevState="",this.channels=[],this.role=Ar.Participant,this.extension=null,this._state=W.New,this._prevState=W.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!1,this._desiredAudioMuted=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1,this._isRecovering=!1,this._wasHeldBeforeRecovery=!1,this._checkConferenceSerno=b=>{const w=b<0||!this._lastSerno||this._lastSerno&&b===this._lastSerno+1;return w&&b>=0&&(this._lastSerno=b),w},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(b=>{b.forEach(w=>{this._statsBindings.forEach(C=>{if(C.callback){if(C.constraints){for(const k in C.constraints)if(C.constraints.hasOwnProperty(k)&&C.constraints[k]!==w[k])return}C.callback(w)}})})})};const{iceServers:n,speaker:s,micId:o,micLabel:r,camId:a,camLabel:l,localElement:c,remoteElement:u,options:d,mediaConstraints:{audio:h,video:p},ringtoneFile:_,ringbackFile:v}=e;this.options=Object.assign({},N0,{audio:h,video:p,iceServers:i!=null&&i.iceServers&&Array.isArray(i.iceServers)?i.iceServers:n,localElement:c,remoteElement:u,micId:o,micLabel:r,camId:a,camLabel:l,speakerId:s,ringtoneFile:_,ringbackFile:v,debug:d.debug,debugOutput:d.debugOutput,trickleIce:d.trickleIce,prefetchIceCandidates:d.prefetchIceCandidates,forceRelayCandidate:d.forceRelayCandidate,keepConnectionAliveOnSocketClose:d.keepConnectionAliveOnSocketClose,mutedMicOnStart:d.mutedMicOnStart},i),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.bind(this),this._onPeerConnectionSignalingStateClosed=this._onPeerConnectionSignalingStateClosed.bind(this),this._onTrickleIceSdp=this._onTrickleIceSdp.bind(this),this._registerPeerEvents=this._registerPeerEvents.bind(this),this._desiredAudioMuted=!!this.options.mutedMicOnStart,this.options.applyDesiredAudioMuteState=this._applyDesiredAudioMuteState.bind(this),this._init(),this.options&&(this._ringtone=wh(this.options.ringtoneFile,"_ringtone"),this._ringback=wh(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}_captureHangupCallerStack(){const e=new Error("Call.hangup caller").stack;return e?e.split(`
115
+ `),Oe[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!B(r.id,r)){const l=Er(r);B(P.SocketMessage,r,this.session.uuid),l&&(this.previousGatewayState=l)}}else this._handleStringResponse(r)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(e){this._safetyTimeoutId=null,e&&e.readyState!==ch?(y.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e?y.debug("Safety timeout: socket was replaced, not emitting SocketClose",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}):(y.debug("Safety timeout: emitting SocketClose for stuck socket",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}),B(P.SocketClose,{code:qu.ABNORMAL_CLOSURE,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1,socketGeneration:this.socketGeneration},this.session.uuid))):y.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(y.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,i){this._wsClient===e?(y.debug(`Nulling socket reference (reason: ${i})`),this._wsClient=null):y.debug(`Skipping socket cleanup - old socket already replaced (reason: ${i})`)}_cleanupPendingRequests(){Array.from(this._pendingRequestIds).forEach(e=>{bt(e);const i=this._pendingRequestTimers.get(e),n=this._pendingRequestRejecters.get(e);i&&(clearTimeout(i),this._pendingRequestTimers.delete(e),n&&n.reject(new Tr(e,n.generation,this.socketGeneration))),this._pendingRequestRejecters.delete(e)}),this._pendingRequestIds.clear()}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),B(P.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else y.warn("Unknown message from socket",e)}}fs.DEFAULT_REQUEST_TIMEOUT_MS=1e4;class Li{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:ki()},e)}buildNotification(e){this.request=Object.assign({jsonrpc:"2.0"},e)}}const dh={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class Ue extends Li{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=Pu(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const n in dh)n&&i.hasOwnProperty(n)&&(i[dh[n]]=i[n],delete i[n]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class uh extends Ue{constructor(e){super(),this.method=Z.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class j0{constructor(e){this.pendingRequestId=null,this.onSocketMessage=i=>V(this,void 0,void 0,function*(){i.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Er(i))}),this.getIsRegistered=()=>V(this,void 0,void 0,function*(){const i=new uh(gn());this.pendingRequestId=i.request.id,this.gatewayStateTask=th({}),this.session.execute(i);const n=yield this.gatewayStateTask.promise;return!!n&&[Oe.REGISTER,Oe.REGED].includes(n)}),this.session=e,this.gatewayStateTask=th({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Lr extends Ue{constructor(e){super(),this.method=Z.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Di{constructor(e){this._session=e,this._lastInboundAt=0,this._lastProbeSentAt=0,this._probeInFlight=!1,this._intervalId=null,this._pendingMediaRecovery=null,this._browserWasOffline=!1,this._onlineHandler=null,this._offlineHandler=null}static isCriticalMethod(e){return Di.CRITICAL_METHODS.has(e)}start(){this._intervalId||(y.debug("Signaling health: monitor started"),this._lastInboundAt=Date.now(),this._probeInFlight=!1,this._lastProbeSentAt=0,this._setupBrowserListeners(),this._intervalId=setInterval(()=>this._check(),3e3))}stop(){this._intervalId&&(clearInterval(this._intervalId),this._intervalId=null,this._probeInFlight=!1,this._lastProbeSentAt=0),this._pendingMediaRecovery=null,this._cleanupBrowserListeners(),y.debug("Signaling health: monitor stopped")}get isRunning(){return this._intervalId!==null}get isProbeInFlight(){return this._probeInFlight}onSocketActivity(){this._lastInboundAt=Date.now()}_resolveProbe(){if(!this._probeInFlight)return;if(this._probeInFlight=!1,this._lastProbeSentAt=0,this._lastInboundAt=Date.now(),y.debug("Signaling health: probe resolved by matching Ping response"),!this._pendingMediaRecovery)return void y.debug("Signaling health: probe resolved but no pending media recovery");const e=this._pendingMediaRecovery;this._pendingMediaRecovery=null,this._getSignalingHealthState()==="healthy"&&(y.info(`Signaling health: signaling probe resolved, triggering pending ICE restart for call ${e.callId}`),this._triggerIceRestart(e.callId,e.reason))}_probeIfNeeded(e){var i;!((i=this._session.connection)===null||i===void 0)&&i.connected&&(this._probeInFlight?y.debug(`Signaling health: probe already in flight, skipping duplicate probe (${e})`):(y.info(`Signaling health: ${e}, sending signaling probe`),this._sendProbe()))}onRequestTimeout(e,i,n=""){var s;!((s=this._session.connection)===null||s===void 0)&&s.connected&&(Di.isCriticalMethod(n)?(y.warn(`Critical signaling request timed out (id=${e}, method=${n}, timeout=${i}ms) — declaring signaling unhealthy`),this._triggerSignalingRecovery(`Critical signaling request timed out (method=${n}, id=${e}, timeout=${i}ms)`,"request")):y.warn(`Non-critical signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms) — logging but not triggering signaling recovery`))}onPeerFailure(e,i){y.warn(`Signaling health: peer failure reported (callId=${e}, evidence=${i})`),this._recoverMediaOrSignaling(e,`Peer connection failure (${i})`,`Peer failure detected (${i}) while signaling is unhealthy`,"peer_failure")}onNoRtp(e,i){y.warn(`Signaling health: no RTP detected (callId=${e}, direction=${i})`),this._recoverMediaOrSignaling(e,`No RTP ${i} while media should be active`,`No RTP ${i} while signaling is unhealthy`,"no_rtp")}_setupBrowserListeners(){typeof window>"u"||this._onlineHandler||(this._onlineHandler=()=>{this._browserWasOffline&&(y.debug(`Signaling health: browser online — clearing browser offline state for session ${this._session.sessionid}`),this._browserWasOffline=!1)},this._offlineHandler=()=>{this._browserWasOffline=!0,y.debug(`Signaling health: browser offline signal received for session ${this._session.sessionid}`);const e=ne(Yy);B(P.Error,{error:e,sessionId:this._session.sessionid},this._session.uuid),this.isRunning&&this._probeIfNeeded("browser offline signal while monitor is active")},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupBrowserListeners(){typeof window<"u"&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null,this._browserWasOffline=!1)}onIceRestartFailed(e){y.warn(`Signaling health: ICE restart failed (callId=${e}) — triggering socket reconnect`),this._triggerSignalingRecovery(`ICE restart failed for call ${e}`,"peer_failure")}_check(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return;const i=Date.now(),n=i-this._lastInboundAt;if(n<2e4)return;if(!this._probeInFlight)return y.info(`Signaling health: no inbound WS activity for ${Math.round(n/1e3)}s during active call, sending health probe`),void this._sendProbe();const s=i-this._lastProbeSentAt;s>=5e3&&(y.warn(`Signaling health: probe timed out after ${s}ms with no inbound activity — declaring signaling unhealthy`),this._triggerSignalingRecovery("Signaling health probe timed out: no inbound WS activity after probe","probe"))}_sendProbe(){var e;this._probeInFlight=!0,this._lastProbeSentAt=Date.now();const i=new Lr(gn());(e=this._session.connection)===null||e===void 0||e.send(i).then(()=>this._resolveProbe()).catch(n=>{y.warn("Signaling health: probe Ping failed to send",n)})}_recoverMediaOrSignaling(e,i,n,s){if(!this._session.hasActiveCall())return void y.debug(`Signaling health: ignoring ${s} recovery without an active call`);const o=this._getSignalingHealthState();return o==="healthy"?(y.info(`Signaling health: signaling is healthy, triggering ICE restart for call ${e}`),void this._triggerIceRestart(e,i)):o==="unknown"?(y.info(`Signaling health: signaling health is unknown, deferring ICE restart decision for call ${e}`),this._pendingMediaRecovery={callId:e,reason:i,source:s},void this._probeIfNeeded(`${s} detected with stale/unknown signaling`)):(y.info("Signaling health: signaling is unhealthy, triggering socket reconnect instead of ICE restart"),void this._triggerSignalingRecovery(n,s))}_getSignalingHealthState(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return"unhealthy";if(this._probeInFlight)return"unknown";const i=Date.now(),n=this._lastInboundAt||this._session.connection.lastInboundAt||0;return n===0?"unknown":i-n<3e3?"healthy":"unknown"}_triggerSignalingRecovery(e,i="probe"){var n,s,o;this._pendingMediaRecovery=null,this._probeInFlight=!1,this._lastProbeSentAt=0,y.debug(`Signaling recovery triggered (source=${i}, reason=${e})`);const r=Ne(p0);B(P.Warning,{warning:r,reason:e,source:i,sessionId:this._session.sessionid},this._session.uuid),!((n=this._session.connection)===null||n===void 0)&&n.connected?(y.info("Signaling health: force-closing WebSocket to trigger reconnect"),this._session.socketDisconnect()):y.debug("Signaling health: recovery triggered but connection not connected",{connected:(s=this._session.connection)===null||s===void 0?void 0:s.connected,hasConnection:!!this._session.connection,socketGeneration:(o=this._session.connection)===null||o===void 0?void 0:o.socketGeneration})}_triggerIceRestart(e,i){y.info(`Signaling health: triggering ICE restart for call ${e}`);const n=this._session.triggerIceRestart(e);if(!n.started)return void y.info(`Signaling health: ICE restart not started for call ${e}: ${n.reason}`);const s=Ne(g0);B(P.Warning,{warning:s,reason:i,callId:e,sessionId:this._session.sessionid},this._session.uuid)}}Di.CRITICAL_METHODS=new Set([Z.Modify,Z.Bye,Z.Ping]);var hh="2.27.8",Dr=hh;class $0 extends Ue{constructor(e,i,n,s,o={},r){super(),this.method="login";const a={login:e,passwd:i,login_token:n,userVariables:o,reconnection:r,loginParams:{},"User-Agent":{sdkVersion:Dr,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class H0 extends Ue{constructor(e,i){super(),this.buildRequest({id:e,result:{method:i}})}}class fh extends Ue{toString(){return Z.Invite}}class ph extends Ue{toString(){return Z.Answer}}class gh extends Ue{toString(){return Z.Attach}}class W0 extends Ue{toString(){return Z.Bye}}class G0 extends Ue{toString(){return Z.Candidate}}class q0 extends Ue{toString(){return Z.EndOfCandidates}}class ps extends Ue{toString(){return Z.Modify}}class mh extends Ue{toString(){return Z.Info}}class z0 extends Ue{toString(){return Z.Broadcast}}class K0 extends Ue{toString(){return Z.Subscribe}}class Y0 extends Ue{toString(){return Z.Unsubscribe}}class X0 extends Ue{constructor(e){super(),this.method="anonymous_login";const{target_type:i,target_id:n,target_version_id:s,target_params:o,userVariables:r,sessionId:a,reconnection:l}=e,c={target_type:i,target_id:n,userVariables:r,reconnection:l,"User-Agent":{sdkVersion:Dr,data:navigator.userAgent}};a&&(c.sessid=a),s&&(c.target_version_id=s),o&&(c.target_params=o),this.buildRequest({method:this.method,params:c})}}class ti{constructor(e){if(this.options=e,this.uuid=ki(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.callReportId=null,this.callReportVoiceSdkId=null,this.dc=null,this.region=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._reconnectAttempts=0,this._reconnectCountedGeneration=-1,this._intentionalClose=!1,this._tokenExpiryTimeout=null,this._pendingCallReportUploads=new Set,this._signalingHealthMonitor=new Di(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var i,n;i=e.debug?"debug":"info",Ju=(n=ls[i])!==null&&n!==void 0?n:ls.info,this._onSocketOpen=this._onSocketOpen.bind(this),this.onNetworkClose=this.onNetworkClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._onSocketActivity=this._onSocketActivity.bind(this),this._attachListeners(),this.connection=new fs(this),this.registerAgent=new j0(this)}get __logger(){return y}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return V(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){const e=this._reconnectAttempts,i=Math.min(1e3*Math.pow(2,e-1),3e4),n=Math.floor(.25*i*(2*Math.random()-1)),s=i+n;return y.debug("Reconnect delay computed",{attempt:e,baseDelayMs:1e3,maxDelayMs:3e4,delayMs:i,jitterMs:n,totalDelay:s,sessionId:this.sessionid}),s}execute(e){var i;if(this._idle)return new Promise(s=>this._executeQueue.push({resolve:s,msg:e}));if(!this.connected)return new Promise(s=>{this._executeQueue.push({resolve:s,msg:e}),y.debug("Calling connect from execute since not currently connected."),this.connect()});const n=Di.isCriticalMethod(((i=e.request)===null||i===void 0?void 0:i.method)||"")?fs.DEFAULT_REQUEST_TIMEOUT_MS:void 0;return(n!=null?this.connection.send(e,n):this.connection.send(e)).catch(s=>V(this,void 0,void 0,function*(){if(s instanceof Tr)throw y.debug(`Stale request settled (id=${s.requestId}, gen=${s.staleGeneration}) — not triggering recovery`),s;if((s==null?void 0:s.name)==="RequestTimeoutError")throw this.onSignalingRequestTimeout(s.requestId,s.timeoutMs,s.method),s;if((s==null?void 0:s.code)===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const o=ne(zy,s,void 0,!0);B(P.Error,{error:o,sessionId:this.sessionid},this.uuid)}yield this.login()}throw s}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}trackCallReportUpload(e){this._pendingCallReportUploads.add(e),e.then(()=>this._pendingCallReportUploads.delete(e),()=>this._pendingCallReportUploads.delete(e))}_drainCallReportUploads(){return V(this,void 0,void 0,function*(){if(this._pendingCallReportUploads.size===0)return;const e=Array.from(this._pendingCallReportUploads);let i=!1;yield Promise.race([Promise.all(e.map(n=>n.catch(()=>{}))),new Promise(n=>setTimeout(()=>{i=!0,n()},ti.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS))]),i&&y.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})})}validateOptions(){return ds(this.options)||pn(this.options)}broadcast(e){}disconnect(){return V(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this._clearTokenExpiryTimeout(),this.subscriptions={},this._autoReconnect=!1,this._intentionalClose=!0,this._reconnectAttempts=0,this.relayProtocol=null,yield this._drainCallReportUploads(),this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),y.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,i){return Ut(e,i,this.uuid),this}off(e,i){return bt(e,i,this.uuid),this}connect(){return V(this,void 0,void 0,function*(){this.connection||(y.debug("No existing connection found, creating a new one."),this.connection=new fs(this)),this._attachListeners(),this._autoReconnect||(y.debug("autoReconnect was disabled, resetting reconnect attempts"),this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(y.debug("Connection wasn't alive, initiating connection to the server..."),this.connection.connect()),y.debug("Connect method called. Connection initiated.")})}resetReconnectAttempts(){this._reconnectAttempts=0,this._reconnectCountedGeneration=-1}_handleLoginError(e){const i=ne(Uu,e);B(P.Error,{error:i,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){nh()}_checkTokenExpiry(){this._clearTokenExpiryTimeout();const e=this.options.login_token;if(e&&typeof e=="string")try{const i=e.split(".");if(i.length!==3)return;const n=JSON.parse(atob(i[1])).exp;if(typeof n!="number")return;const s=n-Math.floor(Date.now()/1e3);if(s<=0)return;if(s<=ti.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const o=1e3*(s-ti.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout(()=>{this._emitTokenExpiryWarning()},o)}}catch{y.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=Ne(h0);B(P.Warning,{warning:e,sessionId:this.sessionid},this.uuid)}_clearTokenExpiryTimeout(){this._tokenExpiryTimeout!==null&&(clearTimeout(this._tokenExpiryTimeout),this._tokenExpiryTimeout=null)}login({creds:e,onSuccess:i,onError:n}={}){return V(this,void 0,void 0,function*(){if(this.connection&&this.connection.isAlive){if(e&&(e.login!==void 0&&(this.options.login=e.login),e.password!==void 0&&(this.options.password=e.password),e.passwd!==void 0&&(this.options.passwd=e.passwd),e.login_token!==void 0&&(this.options.login_token=e.login_token),e.userVariables!==void 0&&(this.options.userVariables=e.userVariables),e.anonymous_login!==void 0&&(this.options.anonymous_login=e.anonymous_login)),ds(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(pn(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const s="Invalid login options provided for authentication.";y.error(s);const o=ne(qy,void 0,s);return void B(P.Error,{error:o,type:P0.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:i,onError:n}){var s,o,r;return V(this,void 0,void 0,function*(){let a;const l=!!gn(),c=l&&(this.sessionid&&ih()?this.sessionid:function(d=Date.now()){const h=sessionStorage.getItem(us);return h?ih(d)?h:(sessionStorage.removeItem(us),sessionStorage.removeItem(hs),null):null}())||"";if(e==="login"){const d=(r=(s=this.options.pushWhenActive)!==null&&s!==void 0?s:(o=this.options.userVariables)===null||o===void 0?void 0:o.push_when_active)!==null&&r!==void 0&&r,h=Object.assign(Object.assign({},this.options.userVariables),{push_when_active:d,pn_late_fanout:d});a=new $0(this.options.login,this.options.password||this.options.passwd,this.options.login_token,c,h,l)}else a=new X0({target_id:this.options.anonymous_login.target_id,target_type:this.options.anonymous_login.target_type,target_version_id:this.options.anonymous_login.target_version_id,target_params:this.options.anonymous_login.target_params,sessionId:c,userVariables:this.options.userVariables,reconnection:l});const u=yield this.execute(a).catch(d=>{this._handleLoginError(d),n&&n(d)});u&&(this.sessionid=u.sessid,this.sessionid&&Rr(this.sessionid),this._checkTokenExpiry(),i&&i())})}_onSocketOpen(){return V(this,void 0,void 0,function*(){this.startSignalingHealthMonitor()})}_flushIntermediateCallReports(e){const i=this.calls;i&&Object.values(i).forEach(n=>{if(n!=null&&n.flushIntermediateCallReport)try{n.flushIntermediateCallReport(e)}catch(s){y.error("Failed to flush intermediate call report",{callId:n.id,flushReason:e,error:s})}})}_getSocketCloseCodeName(e){if(e===void 0)return;const i=Object.entries(qu).find(([,n])=>n===e);return i==null?void 0:i[0]}_getSocketCloseError(e){if(e)return e instanceof Error?e.message:String(e)}_createSocketCloseFlushReason(e){return{type:e!=null&&e.error?"socket-error":"socket-close",socketClose:{code:e==null?void 0:e.code,codeName:this._getSocketCloseCodeName(e==null?void 0:e.code),reason:e==null?void 0:e.reason,wasClean:e==null?void 0:e.wasClean,error:this._getSocketCloseError(e==null?void 0:e.error)}}}onNetworkClose(e){var i,n,s,o;const r=(n=(i=this.connection)===null||i===void 0?void 0:i.socketGeneration)!==null&&n!==void 0?n:0,a=(s=e==null?void 0:e.socketGeneration)!==null&&s!==void 0?s:r;if(a<r)y.debug(`Skipping stale onNetworkClose for socket generation ${a} (current generation is ${r})`);else if(a!==this._reconnectCountedGeneration){this._flushIntermediateCallReports(this._createSocketCloseFlushReason(e)),y.debug("onNetworkClose called",{closeCode:e==null?void 0:e.code,closeReason:e==null?void 0:e.reason,wasClean:e==null?void 0:e.wasClean,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,autoReconnect:this._autoReconnect,reconnectAttempts:this._reconnectAttempts}),this.relayProtocol&&xr(this.relayProtocol);for(const l in this.subscriptions)xr(l);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.stopSignalingHealthMonitor(),this.sessionid&&this._autoReconnect&&Rr(this.sessionid),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect){const l=(o=this.options.maxReconnectAttempts)!==null&&o!==void 0?o:10;if(this._reconnectCountedGeneration=a,this._reconnectAttempts+=1,l>0&&this._reconnectAttempts>l){y.info(`Reconnection exhausted after ${l} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1,this._terminateActiveCallsLocally();const u=ne(Sr);return void B(P.Error,{error:u,sessionId:this.sessionid},this.uuid)}const c=this.reconnectDelay;y.debug(`Reconnect attempt ${this._reconnectAttempts}${l>0?` of ${l}`:""} (delay=${c}ms)`),this._reconnectTimeout=setTimeout(()=>{y.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},c)}else if(y.debug("auto_reconnect disabled, not reconnecting",{voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,intentionalClose:this._intentionalClose}),!this._intentionalClose){const l=Ne(m0);B(P.Warning,{warning:l,reason:"auto_reconnect_disabled",sessionId:this.sessionid},this.uuid)}this._intentionalClose=!1}else y.debug(`Skipping duplicate onNetworkClose for socket generation ${a} (already handled, reconnect attempt ${this._reconnectAttempts})`)}_onSocketMessage(e){}_removeSubscription(e,i){this._existsSubscription(e,i)&&(i?(delete this.subscriptions[e][i],bt(e,null,i)):(delete this.subscriptions[e],xr(e)))}_addSubscription(e,i=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},Ri(i)&&Ut(e,i,n))}_existsSubscription(e,i){return!(!this.subscriptions.hasOwnProperty(e)||!(!i||i&&this.subscriptions[e].hasOwnProperty(i)))}_attachListeners(){this._detachListeners(),y.debug("Attaching socket event listeners"),this.on(P.SocketOpen,this._onSocketOpen),this.on(P.SocketClose,this.onNetworkClose),this.on(P.SocketError,this.onNetworkClose),this.on(P.SocketMessage,this._onSocketMessage),this.on(P.SocketActivity,this._onSocketActivity)}_detachListeners(){y.debug("Detaching socket event listeners"),this.off(P.SocketOpen,this._onSocketOpen),this.off(P.SocketClose,this.onNetworkClose),this.off(P.SocketError,this.onNetworkClose),this.off(P.SocketMessage,this._onSocketMessage),this.off(P.SocketActivity,this._onSocketActivity)}_emptyExecuteQueues(){this._executeQueue.forEach(({resolve:e,msg:i})=>{typeof i=="string"?this.executeRaw(i):e(this.execute(i))})}_closeConnection(){var e,i;this._idle=!0,clearTimeout(this._keepAliveTimeout),this.stopSignalingHealthMonitor(),y.debug("_closeConnection called",{connected:(e=this.connection)===null||e===void 0?void 0:e.connected,socketGeneration:(i=this.connection)===null||i===void 0?void 0:i.socketGeneration,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0}),this.connection&&this.connection.close()}_resetKeepAlive(){this._pong===!1&&(y.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Lr(gn()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){y.debug("Ping received"),this._pong=!0}_onSocketActivity(){this._signalingHealthMonitor.onSocketActivity()}hasActiveCall(){const e=this.calls;if(!e)return!1;const i=new Set([W.Early,W.Active,W.Held]);return Object.values(e).some(n=>n&&n._state!=null&&i.has(n._state))}_terminateActiveCallsLocally(){const e=this.calls;if(!e)return;const i=Object.keys(e);if(i.length!==0){y.debug(`Reconnection exhausted — locally terminating ${i.length} active call(s) (no BYE): ${i.join(", ")}`);for(const n of i){const s=e[n];s==null||s.hangup({},!1)}}}startSignalingHealthMonitor(){this._signalingHealthMonitor.start()}stopSignalingHealthMonitor(){this._signalingHealthMonitor.stop()}triggerIceRestart(e){const i=this.calls,n=i==null?void 0:i[e];if(!n)return y.warn(`Signaling health: cannot trigger ICE restart — call ${e} not found`),{started:!1,reason:"call not found"};const s=n.peer;if(!(s!=null&&s.restartIce))return y.warn(`Signaling health: cannot trigger ICE restart — no peer for call ${e}`),{started:!1,reason:"no peer"};const o=s.restartIce();return o.started||y.debug(`Signaling health: ICE restart skipped for call ${e}: ${o.reason}`),o}onSignalingRequestTimeout(e,i,n=""){this._signalingHealthMonitor.onRequestTimeout(e,i,n)}reportPeerFailure(e,i){this._signalingHealthMonitor.onPeerFailure(e,i)}reportNoRtp(e,i){this._signalingHealthMonitor.onNoRtp(e,i)}reportIceRestartFailed(e){this._signalingHealthMonitor.onIceRestartFailed(e)}static on(e,i){Ut(e,i)}static off(e){bt(e)}static uuid(){return ki()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}ti.TOKEN_EXPIRY_WARNING_SECONDS=120,ti.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;const gs=t=>navigator.mediaDevices.getUserMedia(t),vn=t=>t&&t instanceof MediaStream,ms=(t,e,i)=>{const n=fn(t);if(n!==null){if(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject&&n.srcObject!==e&&(y.warn("attachMediaStream: element already has a different MediaStream attached; overwriting will disrupt the existing call. Use a per-call remoteElement (client.newCall({ remoteElement }) or call.answer({ remoteElement })) for concurrent calls."),i)){const s=Ne(u0);B(P.Warning,{warning:s,callId:i.callId,sessionId:i.sessionId},i.eventTarget)}n.srcObject=e}},vh=(t,e)=>{const i=fn(t);if(i){if(e&&i.srcObject!==e)return;i.srcObject=null}},_h=(t,e)=>V(void 0,void 0,void 0,function*(){const i=fn(t);if(i===null)return y.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return y.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield i.setSinkId(e),!0}catch{return!1}}),J0=t=>{t&&t.readyState==="live"&&t.stop()},_n=t=>{vn(t)&&t.getTracks().forEach(J0),t=null},vs=t=>V(void 0,void 0,void 0,function*(){y.info("RTCService.getUserMedia",t);const{audio:e,video:i}=t;if(!e&&!i)return null;try{return yield gs(t)}catch(n){if(y.error("getUserMedia error: ",n),(s=>s.name==="NotReadableError"||s.name==="NotFoundError"||s.name==="OverconstrainedError")(n)){const s=(o=>{const{audio:r,video:a}=o;let l=!1,c=r,u=a;if(typeof r=="object"&&r!==null&&"deviceId"in r){l=!0;const d=Object.assign({},r);delete d.deviceId,c=Object.keys(d).length===0||d}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const d=Object.assign({},a);delete d.deviceId,u=Object.keys(d).length===0||d}return l?{audio:c,video:u}:null})(t);if(s){y.warn("Device not found or not readable, falling back to default device");try{return yield gs(s)}catch(o){throw y.error("Fallback getUserMedia also failed: ",o),n}}}throw n}}),yn=(t=null,e=!1)=>V(void 0,void 0,void 0,function*(){let i=[];const n=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===yt.AudioIn||s===yt.AudioOut,video:!s||s===yt.Video}))(t)).catch(s=>(y.error(s),null));if(n){if(_n(n),i=yield navigator.mediaDevices.enumerateDevices(),t&&(i=i.filter(o=>o.kind===t)),e===!0)return i;const s=[];i=i.filter(o=>{if(!o.groupId)return!0;const r=`${o.kind}-${o.groupId}`;return!s.includes(r)&&(s.push(r),!0)})}return i}),yh=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],_s=(t,e,i)=>V(void 0,void 0,void 0,function*(){const n=yield yn(i,!0);for(let s=0;s<n.length;s++){const{deviceId:o,label:r}=n[s];if(t===o||e===r)return o}return null}),Z0=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(i=>{e.hasOwnProperty(i)&&t[i]!==null&&t[i]!==void 0||delete t[i]})},Or=t=>t?{id:t.id,kind:t.kind,enabled:t.enabled,muted:t.muted,readyState:t.readyState}:null,bh=t=>{var e,i,n,s,o,r;return t?((i=(e=t.getTracks)===null||e===void 0?void 0:e.call(t))!==null&&i!==void 0?i:[...(s=(n=t.getAudioTracks)===null||n===void 0?void 0:n.call(t))!==null&&s!==void 0?s:[],...(r=(o=t.getVideoTracks)===null||o===void 0?void 0:o.call(t))!==null&&r!==void 0?r:[]]).map(a=>Or(a)):[]},Mr=(t,e)=>{if(!t)return!1;const{subscribed:i,alreadySubscribed:n}=Pr(t);return i.includes(e)||n.includes(e)},Pr=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(i=>{e[i]=t[`${i}Channels`]||[]}),e},Oi=(t,e=null,i=null)=>{if(!vn(t))return null;let n=[];switch(e){case"audio":n=t.getAudioTracks();break;case"video":n=t.getVideoTracks();break;default:n=t.getTracks()}n.forEach(s=>{switch(i){case"on":case!0:s.enabled=!0;break;case"off":case!1:s.enabled=!1;break;default:s.enabled=!s.enabled}})},Nr=t=>{Oi(t,"audio",!0)},ys=t=>{Oi(t,"audio",!1)};function Q0(){try{const{browserInfo:t,name:e,version:i,supportAudio:n,supportVideo:s}=function(){if(!window||!window.navigator||!window.navigator.userAgent)throw new Error("You should use @telnyx/webrtc in a web browser such as Chrome|Firefox|Safari");if(navigator.userAgent.match(/chrom(e|ium)/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/safari/gim)[0],d=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),h=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:h,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const u=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,l=window.navigator&&window.navigator.mediaDevices,c=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:i,supportWebRTC:!!(o&&r&&a&&l&&c),supportWebRTCAudio:n,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!vs}}catch(t){return t.message}}var Ee;function wh(t,e){const i=document.getElementById(e);if(i)return i;if(t&&e){const n=document.createElement("audio");return n.id=e,n.loop=!0,n.src=t,n.preload="auto",n.load(),document.body.appendChild(n),n}return null}function Sh(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{y.error("playAudio",e),t._playFulfilled=!0}))}function Ch(t){t&&(t._playFulfilled?(t.pause(),t.currentTime=0):t._promise&&t._promise.then?t._promise.then(()=>{t.pause(),t.currentTime=0}):setTimeout(()=>{t.pause(),t.currentTime=0},1e3))}(function(t){t.not_supported="not supported",t.full="full",t.partial="partial"})(Ee||(Ee={}));const Th=t=>{const e=[],i=[];return t&&t.length!==0?(t.forEach(n=>{const s=n.mimeType.toLocaleLowerCase();s.startsWith("audio/")?e.push(n):s.startsWith("video/")&&i.push(n)}),{audioCodecs:e,videoCodecs:i}):{audioCodecs:e,videoCodecs:i}};class eb extends Li{constructor(e,i){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:ki(),type:"message",role:"user",content:[{type:"input_text",text:e},...i==null?void 0:i.map(n=>({type:"image_url",image_url:{url:n}}))]}}})}}class tb extends Li{constructor(e){super(),this.method="ai_conversation",this.buildNotification({method:this.method,params:{type:"conversation.item.create",item:e}})}}class le{constructor(e,i){var n;this.peerConnection=null,this.intervalId=null,this.statsBuffer=[],this.intervalStartTime=null,this.callEndTime=null,this.logCollector=null,this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]},this.previousStats={},this.previousCandidatePairSnapshot=null,this.MAX_BUFFER_SIZE=360,this.onFlushNeeded=null,this.onWarning=null,this._breachCounters={},this._activeWarnings=new Set,this._lastWarningEmitted={},this._prevPacketsReceived=null,this._prevPacketsLost=null,this._previousStatsEntryForWarnings=null,this._isHeld=!1,this._lastLocalAudioTrackSnapshotJson=null,this._hasConfirmedLocalAudio=!1,this._confirmedLocalAudioSilenceMs=0,this._segmentIndex=0,this._flushing=!1,this._stopped=!1,this.options=e,this.logCollectorOptions=i||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this._lastIntermediateFlushTime=this.callStartTime,this.logCollectorOptions.enabled&&(this.logCollector=function(s){return new x0(s)}(this.logCollectorOptions),this.logCollector.start(),n=this.logCollector,Xu=n)}start(e){var i,n;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._lastIntermediateFlushTime=this.intervalStartTime,this._stopped=!1,y.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:le.INITIAL_COLLECTION_INTERVAL_MS,logCollectorActive:(n=(i=this.logCollector)===null||i===void 0?void 0:i.isActive())!==null&&n!==void 0&&n}),this._scheduleNextCollection())}stop(){var e,i;return V(this,void 0,void 0,function*(){this._stopped=!0,this.intervalId&&(clearTimeout(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&(yield this._collectStats(!0));const n=(i=(e=this.logCollector)===null||e===void 0?void 0:e.getLogCount())!==null&&i!==void 0?i:0;this.logCollector&&this.logCollector.stop(),y.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:n,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})})}flush(e,i){var n,s,o,r;const a=this.statsBuffer.length,l=(s=(n=this.logCollector)===null||n===void 0?void 0:n.getLogCount())!==null&&s!==void 0?s:0,c=(i==null?void 0:i.type)==="socket-close"||(i==null?void 0:i.type)==="socket-error",u=a>0||l>0||c;if(this._flushing||!u)return y.debug("CallReportCollector: Skipping intermediate flush",{reason:this._flushing?"already-flushing":"no-stats-or-logs",flushReason:i,statsIntervals:a,logEntries:l}),null;this._flushing=!0;try{const d=this._segmentIndex++,h=this.statsBuffer;this.statsBuffer=[];const p=(r=(o=this.logCollector)===null||o===void 0?void 0:o.drain())!==null&&r!==void 0?r:[],_=new Date;this._lastIntermediateFlushTime=_;const v=Object.assign(Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(_.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:_.toISOString()}),stats:h},p.length>0?{logs:p}:{}),{segment:d}),i?{flushReason:i}:{});return y.info("CallReportCollector: Flushed intermediate segment",{segment:d,intervals:h.length,logEntries:p.length,callId:e.callId,flushReason:i}),v}finally{this._flushing=!1}}postReport(e,i,n,s){var o,r;return V(this,void 0,void 0,function*(){const a=(o=this.logCollector)===null||o===void 0?void 0:o.getLogs(),l=a&&a.length>0;if(!this.options.enabled)return void y.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void y.info("CallReportCollector: Skipping report — no stats or logs collected");const c=this._segmentIndex>0,u=this._segmentIndex,d=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:this.callEndTime&&this.callStartTime?(this.callEndTime.getTime()-this.callStartTime.getTime())/1e3:void 0,startTimestamp:this.callStartTime.toISOString(),endTimestamp:(r=this.callEndTime)===null||r===void 0?void 0:r.toISOString()}),stats:this.statsBuffer},a&&a.length>0?{logs:a}:{}),c?{segment:u}:{});yield this._sendPayload(d,i,n,s,!0)})}sendPayload(e,i,n,s,o=!1){return V(this,void 0,void 0,function*(){yield this._sendPayload(e,i,n,s,!1,o)})}_sendPayload(e,i,n,s,o=!0,r=!1){var a,l;return V(this,void 0,void 0,function*(){const c=new URL(n),u=`${c.protocol.replace(/^ws/,"http")}//${c.host}/call_report`,d=o?"final report":`intermediate segment ${e.segment}`;y.info(`CallReportCollector: Posting ${d}`,{endpoint:u,intervals:e.stats.length,logEntries:(l=(a=e.logs)===null||a===void 0?void 0:a.length)!==null&&l!==void 0?l:0,callId:e.summary.callId,segment:e.segment});const h={"Content-Type":"application/json","x-call-report-id":i,"x-call-id":e.summary.callId};s&&(h["x-voice-sdk-id"]=s);const p=JSON.stringify(e),_=(o||r)&&p.length<=le.KEEPALIVE_BODY_LIMIT_BYTES;let v;for(let b=0;b<=le.RETRY_DELAYS_MS.length;b++){try{const C=yield fetch(u,Object.assign({method:"POST",headers:h,body:p},_?{keepalive:!0}:{}));if(C.ok)return void y.info(`CallReportCollector: Successfully posted ${d}`,{attempt:b+1,status:C.status});{const k=yield C.text();v=new Error(`Call report POST failed with status ${C.status}`),y.error(`CallReportCollector: Failed to post ${d}`,{attempt:b+1,status:C.status,error:k})}}catch(C){v=C,y.warn(`CallReportCollector: Network error posting ${d}`,{attempt:b+1,error:C})}const w=le.RETRY_DELAYS_MS[b];if(w===void 0)break;y.info(`CallReportCollector: Retrying ${d} in ${w}ms`,{attempt:b+2}),yield new Promise(C=>setTimeout(C,w))}throw y.error(`CallReportCollector: Exhausted retries posting ${d}`,{error:v}),v instanceof Error?v:new Error("Call report POST failed after retries")})}getStatsBuffer(){return this.statsBuffer}shouldForceRelayCandidateForRecovery(){var e,i,n,s,o,r,a,l,c,u,d,h,p,_,v,b;if(this.statsBuffer.length<2)return!1;const w=this.statsBuffer[this.statsBuffer.length-1],C=this.statsBuffer[this.statsBuffer.length-2],k=(e=w.ice)===null||e===void 0?void 0:e.local;if(!((k==null?void 0:k.networkType)==="vpn"&&(k==null?void 0:k.candidateType)!=="relay"))return!1;const L=((i=w.ice)===null||i===void 0?void 0:i.writable)===!1,R=((n=w.transport)===null||n===void 0?void 0:n.iceState)==="disconnected"||((s=w.transport)===null||s===void 0?void 0:s.iceState)==="failed",O=this._positiveDelta((o=w.ice)===null||o===void 0?void 0:o.requestsSent,(r=C.ice)===null||r===void 0?void 0:r.requestsSent),T=this._positiveDelta((a=w.ice)===null||a===void 0?void 0:a.responsesReceived,(l=C.ice)===null||l===void 0?void 0:l.responsesReceived),E=O>0&&T===0,g=this._positiveDelta((u=(c=w.audio)===null||c===void 0?void 0:c.outbound)===null||u===void 0?void 0:u.bytesSent,(h=(d=C.audio)===null||d===void 0?void 0:d.outbound)===null||h===void 0?void 0:h.bytesSent),m=this._positiveDelta((_=(p=w.audio)===null||p===void 0?void 0:p.inbound)===null||_===void 0?void 0:_.bytesReceived,(b=(v=C.audio)===null||v===void 0?void 0:v.inbound)===null||b===void 0?void 0:b.bytesReceived);return L||R||E||g>0&&m===0}getLogs(){var e,i;return(i=(e=this.logCollector)===null||e===void 0?void 0:e.getLogs())!==null&&i!==void 0?i:[]}_positiveDelta(e,i){return e===void 0||i===void 0?0:Math.max(0,e-i)}cleanup(){this._lastLocalAudioTrackSnapshotJson=null,this.logCollector&&(this.logCollector.clear(),this.logCollector=null)}setHeld(e){this._isHeld!==e&&(this._isHeld=e,this._trackBreach(as,!1),this._trackBreach(Cr,!1))}_scheduleNextCollection(){if(this._stopped||!this.peerConnection||!this.intervalStartTime||this.intervalId)return;const e=this._collectionIntervalFor();this.intervalId=setTimeout(()=>{this.intervalId=null,this._collectStats().finally(()=>{!this._stopped&&this.peerConnection&&this._scheduleNextCollection()})},e)}_collectionIntervalFor(){const e=this._positiveInterval(this.options.interval,5e3);return Math.min(le.INITIAL_COLLECTION_INTERVAL_MS,e)}_positiveInterval(e,i){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:i}_collectStats(e=!1){var i,n;return V(this,void 0,void 0,function*(){if(this.peerConnection&&this.intervalStartTime)try{const s=yield this.peerConnection.getStats(),o=new Date;let r=null,a=null,l=null,c=null,u=null,d=null;const h=[];let p=null;s.forEach(g=>{switch(g.type){case"outbound-rtp":g.kind==="audio"&&g.mediaType==="audio"&&(r=g);break;case"inbound-rtp":g.kind==="audio"&&g.mediaType==="audio"&&(a=g);break;case"media-playout":g.kind==="audio"&&(l=g);break;case"remote-inbound-rtp":g.kind==="audio"&&(c=g);break;case"remote-outbound-rtp":g.kind==="audio"&&(u=g);break;case"candidate-pair":(g.nominated||g.state==="succeeded")&&h.push(g);break;case"transport":p=g}});const _=p==null?void 0:p.selectedCandidatePairId,v=_?(n=(i=s).get)===null||n===void 0?void 0:n.call(i,_):void 0,b=this._getCodec(s,r==null?void 0:r.codecId),w=this._getCodec(s,a==null?void 0:a.codecId);if(d=(v==null?void 0:v.type)==="candidate-pair"?v:_?h.find(g=>g.id===_)||h[h.length-1]||null:h[h.length-1]||null,r){const g=this._getOutboundAudioLevel(s,r);if(g!==null&&this.intervalAudioLevels.outbound.push(g),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const m=(r.bytesSent||0)-this.previousStats.outboundBytes,f=(r.timestamp||o.getTime())-this.previousStats.timestamp;if(f>0){const S=8*m*1e3/f;this.intervalBitrates.outbound.push(S)}}this.previousStats.outboundBytes=r.bytesSent}if(a){const g=this._getInboundAudioLevel(s,a);if(g!==null&&this.intervalAudioLevels.inbound.push(g),a.jitter!==void 0&&this.intervalJitters.push(1e3*a.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const m=(a.bytesReceived||0)-this.previousStats.inboundBytes,f=(a.timestamp||o.getTime())-this.previousStats.timestamp;if(f>0){const S=8*m*1e3/f;this.intervalBitrates.inbound.push(S)}}this.previousStats.inboundBytes=a.bytesReceived}let C,k,L,R,O;d&&d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),d&&(C=this._resolveCandidate(s,d.localCandidateId),k=this._resolveCandidate(s,d.remoteCandidateId)),d&&(L=Object.assign(Object.assign({id:d.id,localCandidateId:d.localCandidateId,remoteCandidateId:d.remoteCandidateId,state:d.state,nominated:d.nominated,writable:d.writable,currentRoundTripTime:d.currentRoundTripTime,requestsSent:d.requestsSent,responsesReceived:d.responsesReceived},C?{local:C}:{}),k?{remote:k}:{}),this.previousCandidatePairSnapshot!==null&&d.id!==this.previousCandidatePairSnapshot.id&&(y.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:L}),this._emitWarning(a0)),this.previousCandidatePairSnapshot=L),r&&(R=this._getLocalAudioTrackSnapshot(),O=this._getOutboundAudioSourceStats(s,r)),this._logLocalAudioTrackSnapshot(R,O),this.previousStats.timestamp=o.getTime();const T=o.getTime()-this.intervalStartTime.getTime(),E=this._collectionIntervalFor();if(e||T>=E){const g=this._createStatsEntry(this.intervalStartTime,o,r,a,d,C,k,p,R,O,l,c,u,b,w);this.statsBuffer.push(g),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),y.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(g,a),this._requestIntermediateFlushIfNeeded(o),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(s){y.error("CallReportCollector: Error collecting stats",{error:s})}})}_getIntermediateReportInterval(){var e;return(e=this.options.intermediateReportInterval)!==null&&e!==void 0?e:le.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS}_requestIntermediateFlushIfNeeded(e){var i,n;const s=this.statsBuffer.length,o=(n=(i=this.logCollector)===null||i===void 0?void 0:i.getLogCount())!==null&&n!==void 0?n:0;if(!this.onFlushNeeded||this._flushing)return;if(s===0&&o===0)return void y.debug("CallReportCollector: Skipping intermediate flush request — no stats or logs buffered");const r=this._getIntermediateReportInterval(),a=e.getTime()-this._lastIntermediateFlushTime.getTime();let l=null;if(s>=le.STATS_FLUSH_THRESHOLD||o>=le.LOGS_FLUSH_THRESHOLD?l="buffer-limit":r>0&&a>=r&&(l="safety-interval"),l){y.info("CallReportCollector: Requesting intermediate report flush",{reason:l,statsIntervals:s,logEntries:o,msSinceLastFlush:a}),this._lastIntermediateFlushTime=e;try{this.onFlushNeeded()}catch(c){y.error("CallReportCollector: onFlushNeeded callback error",{error:c})}}}_checkQualityWarnings(e,i){var n,s,o,r,a,l,c,u,d,h,p,_,v,b,w;if(!this.onWarning)return;const C=(n=e.connection)===null||n===void 0?void 0:n.roundTripTimeAvg,k=(o=(s=e.audio)===null||s===void 0?void 0:s.inbound)===null||o===void 0?void 0:o.jitterAvg;let L;if(i){const R=(r=i.packetsReceived)!==null&&r!==void 0?r:0,O=(a=i.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const T=R-this._prevPacketsReceived,E=O-this._prevPacketsLost,g=T+E;g>0&&(L=E/g*100)}this._prevPacketsReceived=R,this._prevPacketsLost=O}if(this._trackBreach(Xy,C!==void 0&&C>le.THRESHOLD_RTT_MS),this._trackBreach(Jy,k!==void 0&&k>le.THRESHOLD_JITTER_MS),this._trackBreach(Zy,L!==void 0&&L>le.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),this._isHeld?this._trackBreach(as,!1):this._trackLowInboundAudio(e),C!==void 0&&k!==void 0&&L!==void 0){const R=93.2-.11*k-2.5*L-.01*(1e3*C),O=Math.max(1,Math.min(4.5,1+.035*R+R*(R-60)*(100-R)*7e-6));this._trackBreach(Hu,O<le.THRESHOLD_MOS)}else this._trackBreach(Hu,!1);if(((c=(l=e.audio)===null||l===void 0?void 0:l.inbound)===null||c===void 0?void 0:c.bytesReceived)!==void 0){const R=(h=(d=(u=this._previousStatsEntryForWarnings)===null||u===void 0?void 0:u.audio)===null||d===void 0?void 0:d.inbound)===null||h===void 0?void 0:h.bytesReceived,O=e.audio.inbound.bytesReceived;this._trackBreach(Cr,!this._isHeld&&R!==void 0&&O-R==0)}if(((_=(p=e.audio)===null||p===void 0?void 0:p.outbound)===null||_===void 0?void 0:_.bytesSent)!==void 0){const R=(w=(b=(v=this._previousStatsEntryForWarnings)===null||v===void 0?void 0:v.audio)===null||b===void 0?void 0:b.outbound)===null||w===void 0?void 0:w.bytesSent,O=e.audio.outbound.bytesSent;this._trackBreach(Wu,R!==void 0&&O-R==0)}this._previousStatsEntryForWarnings=e}_trackLowLocalAudio(e){var i;const n=(i=e.audio)===null||i===void 0?void 0:i.outbound,s=n==null?void 0:n.audioLevelAvg,o=n==null?void 0:n.localTrack;if(s===void 0||(o==null?void 0:o.enabled)===!1||(o==null?void 0:o.muted)===!0)return void this._resetLowLocalAudioWarning();if(!(s<=le.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(rs,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=le.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(rs)):this._trackBreach(rs,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(rs,!1)}_getStatsIntervalDurationMs(e){const i=new Date(e.intervalStartUtc).getTime(),n=new Date(e.intervalEndUtc).getTime()-i;return Number.isFinite(n)&&n>0?n:this.options.interval}_trackLowInboundAudio(e){var i;const n=(i=e.audio)===null||i===void 0?void 0:i.inbound,s=n==null?void 0:n.audioLevelAvg;if(s===void 0)return void this._trackBreach(as,!1);const o=s<=le.THRESHOLD_INBOUND_AUDIO_LEVEL;this._trackBreach(as,o)}_trackBreach(e,i){var n,s;if(i){if(this._breachCounters[e]=((n=this._breachCounters[e])!==null&&n!==void 0?n:0)+1,this._breachCounters[e]>=le.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=le.WARNING_THROTTLE_MS&&(this._lastWarningEmitted[e]=o,this._emitWarning(e))}}else this._breachCounters[e]=0,this._activeWarnings.delete(e),delete this._lastWarningEmitted[e]}_emitWarningOncePerEpisode(e){this._activeWarnings.has(e)||(this._activeWarnings.add(e),this._lastWarningEmitted[e]=Date.now(),this._emitWarning(e))}_emitWarning(e){var i;try{const n=Ne(e);y.warn(`CallReportCollector: warning ${n.code}: ${n.message}`),(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){y.error(`CallReportCollector: Failed to emit warning ${e}`,{error:n})}}_createStatsEntry(e,i,n,s,o,r,a,l,c,u,d,h,p,_,v){const b={intervalStartUtc:e.toISOString(),intervalEndUtc:i.toISOString(),audio:{}};if(n&&(b.audio.outbound=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({packetsSent:n.packetsSent,bytesSent:n.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)},c?{localTrack:c}:{}),u?{mediaSource:u}:{}),n.retransmittedPacketsSent!==void 0?{retransmittedPacketsSent:n.retransmittedPacketsSent}:{}),n.retransmittedBytesSent!==void 0?{retransmittedBytesSent:n.retransmittedBytesSent}:{}),n.headerBytesSent!==void 0?{headerBytesSent:n.headerBytesSent}:{}),n.nackCount!==void 0?{nackCount:n.nackCount}:{}),n.targetBitrate!==void 0?{targetBitrate:n.targetBitrate}:{}),n.totalPacketSendDelay!==void 0?{totalPacketSendDelay:n.totalPacketSendDelay}:{}),n.active!==void 0?{active:n.active}:{}),_?{codec:this._buildCodecSnapshot(_,n.codecId)}:{})),s&&(b.audio.inbound=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({packetsReceived:s.packetsReceived,bytesReceived:s.bytesReceived,packetsLost:s.packetsLost,packetsDiscarded:s.packetsDiscarded,jitterBufferDelay:s.jitterBufferDelay,jitterBufferEmittedCount:s.jitterBufferEmittedCount,totalSamplesReceived:s.totalSamplesReceived,concealedSamples:s.concealedSamples,concealmentEvents:s.concealmentEvents,audioLevelAvg:this._average(this.intervalAudioLevels.inbound),jitterAvg:this._average(this.intervalJitters),bitrateAvg:this._average(this.intervalBitrates.inbound)},s.nackCount!==void 0?{nackCount:s.nackCount}:{}),s.headerBytesReceived!==void 0?{headerBytesReceived:s.headerBytesReceived}:{}),s.fecPacketsReceived!==void 0?{fecPacketsReceived:s.fecPacketsReceived}:{}),s.fecPacketsDiscarded!==void 0?{fecPacketsDiscarded:s.fecPacketsDiscarded}:{}),s.jitterBufferTargetDelay!==void 0?{jitterBufferTargetDelay:s.jitterBufferTargetDelay}:{}),s.jitterBufferMinimumDelay!==void 0?{jitterBufferMinimumDelay:s.jitterBufferMinimumDelay}:{}),s.totalSamplesDecoded!==void 0?{totalSamplesDecoded:s.totalSamplesDecoded}:{}),s.samplesDecodedWithSilence!==void 0?{samplesDecodedWithSilence:s.samplesDecodedWithSilence}:{}),s.samplesDecodedWithConcealment!==void 0?{samplesDecodedWithConcealment:s.samplesDecodedWithConcealment}:{}),s.totalAudioEnergy!==void 0?{totalAudioEnergy:s.totalAudioEnergy}:{}),s.totalSamplesDuration!==void 0?{totalSamplesDuration:s.totalSamplesDuration}:{}),v?{codec:this._buildCodecSnapshot(v,s.codecId)}:{})),o&&(b.connection=Object.assign(Object.assign({roundTripTimeAvg:this._average(this.intervalRTTs),currentRoundTripTime:o.currentRoundTripTime},o.currentRoundTripTime!==void 0?{roundTripTimeSource:"candidate-pair.currentRoundTripTime"}:{}),{packetsSent:o.packetsSent,packetsReceived:o.packetsReceived,bytesSent:o.bytesSent,bytesReceived:o.bytesReceived}),b.ice=Object.assign(Object.assign({id:o.id,localCandidateId:o.localCandidateId,remoteCandidateId:o.remoteCandidateId,state:o.state,nominated:o.nominated,writable:o.writable,currentRoundTripTime:o.currentRoundTripTime,requestsSent:o.requestsSent,responsesReceived:o.responsesReceived},r?{local:r}:{}),a?{remote:a}:{})),l&&(b.transport=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},l.iceState!==void 0?{iceState:l.iceState}:{}),l.dtlsState!==void 0?{dtlsState:l.dtlsState}:{}),l.srtpCipher!==void 0?{srtpCipher:l.srtpCipher}:{}),l.tlsVersion!==void 0?{tlsVersion:l.tlsVersion}:{}),l.selectedCandidatePairChanges!==void 0?{selectedCandidatePairChanges:l.selectedCandidatePairChanges}:{}),l.selectedCandidatePairId!==void 0?{selectedCandidatePairId:l.selectedCandidatePairId}:{})),d&&(b.mediaPlayout=this._withoutUndefined({synthesizedSamples:d.synthesizedSamples,synthesizedDuration:d.synthesizedDuration,totalPlayoutDelay:d.totalPlayoutDelay,totalSampleCount:d.totalSampleCount})),h||p){const w={};if(h){const C=h.jitter!==void 0?1e3*h.jitter:void 0;let k;typeof h.totalRoundTripTime=="number"&&typeof h.roundTripTimeMeasurements=="number"&&h.roundTripTimeMeasurements>0&&(k=h.totalRoundTripTime/h.roundTripTimeMeasurements),w.inbound=this._withoutUndefined({packetsReceived:h.packetsReceived,packetsLost:h.packetsLost,fractionLost:h.fractionLost,jitter:C,roundTripTime:h.roundTripTime,totalRoundTripTime:h.totalRoundTripTime,roundTripTimeMeasurements:h.roundTripTimeMeasurements,roundTripTimeAvg:k,nackCount:h.nackCount,reportsReceived:h.reportsReceived,packetsDiscarded:h.packetsDiscarded})}p&&(w.outbound=this._withoutUndefined({packetsSent:p.packetsSent,bytesSent:p.bytesSent,reportsCount:p.reportsCount,roundTripTime:p.roundTripTime,totalPacketSendDelay:p.totalPacketSendDelay})),b.remoteRtcp=w}return b}_resolveCandidate(e,i){if(!i)return void y.debug("CallReportCollector: candidateId is empty, skipping resolve");const n=e.get(i);if(!n)return void y.debug("CallReportCollector: candidate not found in stats report",{candidateId:i});const s={};if(n.id!==void 0&&(s.id=n.id),n.address!==void 0?s.address=n.address:n.ip!==void 0&&(s.address=n.ip),n.port!==void 0&&(s.port=n.port),n.candidateType!==void 0&&(s.candidateType=n.candidateType),n.protocol!==void 0&&(s.protocol=n.protocol),n.networkType!==void 0&&(s.networkType=n.networkType),n.url!==void 0&&(s.url=n.url),n.relayProtocol!==void 0&&(s.relayProtocol=n.relayProtocol),Object.keys(s).length!==0)return s;y.debug("CallReportCollector: candidate report has no usable fields",{candidateId:i})}_getCodec(e,i){if(!i)return;const n=e.get(i);return n&&n.type==="codec"?n:void 0}_buildCodecSnapshot(e,i){const n=this._withoutUndefined(Object.assign({mimeType:e.mimeType,clockRate:e.clockRate,channels:e.channels,payloadType:e.payloadType,sdpFmtpLine:e.sdpFmtpLine},i!==void 0?{codecId:i}:{}));return Object.keys(n).length>0?n:void 0}_getOutboundMediaSource(e,i){let n;return i.mediaSourceId&&(n=e.get(i.mediaSourceId)),n||e.forEach(s=>{n||s.type!=="media-source"||s.kind!=="audio"||(n=s)}),n}_getLocalAudioTrackSnapshot(){var e,i;try{const n=(e=this.peerConnection)===null||e===void 0?void 0:e.getSenders().find(l=>{var c;return((c=l.track)===null||c===void 0?void 0:c.kind)==="audio"}),s=n==null?void 0:n.track;if(!s)return;const o=(i=s.getSettings)===null||i===void 0?void 0:i.call(s),r=this._withoutUndefined({deviceId:o==null?void 0:o.deviceId,groupId:o==null?void 0:o.groupId,channelCount:o==null?void 0:o.channelCount,sampleRate:o==null?void 0:o.sampleRate,sampleSize:o==null?void 0:o.sampleSize,latency:o==null?void 0:o.latency,echoCancellation:o==null?void 0:o.echoCancellation,noiseSuppression:o==null?void 0:o.noiseSuppression,autoGainControl:o==null?void 0:o.autoGainControl}),a=this._withoutUndefined(Object.assign({id:s.id,label:s.label,enabled:s.enabled,muted:s.muted,readyState:s.readyState,contentHint:s.contentHint},Object.keys(r).length>0?{settings:r}:{}));return Object.keys(a).length>0?a:void 0}catch(n){return void y.debug("CallReportCollector: unable to snapshot local audio track",{error:n})}}_getOutboundAudioSourceStats(e,i){const n=this._getOutboundMediaSource(e,i);if(!n)return;const s=this._withoutUndefined({id:n.id,trackIdentifier:n.trackIdentifier,audioLevel:n.audioLevel,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration,echoReturnLoss:n.echoReturnLoss,echoReturnLossEnhancement:n.echoReturnLossEnhancement});return Object.keys(s).length>0?s:void 0}_logLocalAudioTrackSnapshot(e,i){if(!e||Object.keys(e).length===0)return;const n=this._stableStringify(e);n!==this._lastLocalAudioTrackSnapshotJson&&(this._lastLocalAudioTrackSnapshotJson=n,y.debug("CallReportCollector: local audio track snapshot",{localTrack:e,mediaSource:i}))}_withoutUndefined(e){return Object.keys(e).reduce((i,n)=>{const s=e[n];return s!==void 0&&(i[n]=s),i},{})}_stableStringify(e){return JSON.stringify(this._sortObjectKeys(e))}_sortObjectKeys(e){return Array.isArray(e)?e.map(i=>this._sortObjectKeys(i)):e&&typeof e=="object"?Object.keys(e).sort().reduce((i,n)=>(i[n]=this._sortObjectKeys(e[n]),i),{}):e}_getOutboundAudioLevel(e,i){const n=this._getOutboundMediaSource(e,i);if((n==null?void 0:n.audioLevel)!==void 0)return n.audioLevel;if(n){const s=this._computeAudioLevelFromEnergy(n.totalAudioEnergy,n.totalSamplesDuration,"outbound");if(s!==null)return s}return this._getTrackAudioLevel(e,i.trackId)}_getInboundAudioLevel(e,i){if(i.audioLevel!==void 0)return i.audioLevel;const n=this._computeAudioLevelFromEnergy(i.totalAudioEnergy,i.totalSamplesDuration,"inbound");return n!==null?n:this._getTrackAudioLevel(e,i.trackId)}_computeAudioLevelFromEnergy(e,i,n){if(e===void 0||i===void 0)return null;const s=n==="inbound"?"inboundAudioEnergy":"outboundAudioEnergy",o=n==="inbound"?"inboundSamplesDuration":"outboundSamplesDuration",r=this.previousStats[s],a=this.previousStats[o];if(this.previousStats[s]=e,this.previousStats[o]=i,r===void 0||a===void 0)return null;const l=e-r,c=i-a;if(c<=0)return null;const u=Math.sqrt(l/c);return Math.min(1,Math.max(0,u))}_getTrackAudioLevel(e,i){var n;if(!i)return null;const s=e.get(i);return s&&(n=s.audioLevel)!==null&&n!==void 0?n:null}_average(e){if(e.length===0)return;const i=e.reduce((n,s)=>n+s,0);return parseFloat((i/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}le.INITIAL_COLLECTION_INTERVAL_MS=1e3,le.STATS_FLUSH_THRESHOLD=300,le.LOGS_FLUSH_THRESHOLD=800,le.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,le.CONSECUTIVE_BREACHES_REQUIRED=3,le.THRESHOLD_RTT_MS=.4,le.THRESHOLD_JITTER_MS=30,le.THRESHOLD_PACKET_LOSS_PCT=1,le.THRESHOLD_MOS=3.5,le.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,le.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,le.THRESHOLD_INBOUND_AUDIO_LEVEL=.001,le.WARNING_THROTTLE_MS=15e3,le.RETRY_DELAYS_MS=[500,1e3,2e3],le.KEEPALIVE_BODY_LIMIT_BYTES=61440;class je{constructor(e,i){this._buffers={local:[],remote:[]},this._bufferBytes={local:0,remote:0},this._trackStates={local:null,remote:null},this._processors=[],this._readerCancellers=[],this._flushTimerId=null,this._flushing=!1,this._stopped=!1,this._started=!1,this._startedAt=null,this._endedAt=null,this._overflowWarnedThisWindow={local:!1,remote:!1},this.onWarning=null,this._host=null,this._callReportId=null,this.options=e,this.callContext=i,this.recordingId=i.recordingId||`${i.callId}-${Date.now().toString(36)}`}start(e,i){if(!this.options.enabled||this._started)return;if(typeof MediaStreamTrackProcessor!="function")return y.warn("CallRecorder: MediaStreamTrackProcessor unavailable — recording disabled for this call"),this._emitWarning(Qy),void(this._started=!0);const n=this.options.tracks||["local","remote"];let s=0;if(n.includes("local")&&e&&(this._attach(e,"local"),s++),n.includes("remote")&&i&&(this._attach(i,"remote"),s++),s===0)return y.info("CallRecorder: no audio tracks available to record — recording idle for this call",{callId:this.callContext.callId}),void(this._started=!0);this._startedAt=new Date,this._started=!0,this._scheduleFlush(),y.info("CallRecorder: started",{callId:this.callContext.callId,tracksAttached:s,flushIntervalMs:this._flushIntervalMs(),maxBufferBytes:this._maxBufferBytes()})}stop(){this._stopped||(this._stopped=!0,this._clearFlushTimer(),this._cancelReaders(),this._endedAt=new Date,y.info("CallRecorder: stopped",{callId:this.callContext.callId,packetsBuffered:this._buffers.local.length+this._buffers.remote.length}))}postFinalReport(){return V(this,void 0,void 0,function*(){if(!this.options.enabled)return;if(this.stop(),!this._startedAt)return void y.debug("CallRecorder: postFinalReport skipped — never started");const e=this._resolveEndpointFromContext();if(!e)return void y.debug("CallRecorder: postFinalReport skipped — no host available");const i=this.options.tracks||["local","remote"],n=this._startedAt,s=this._endedAt||new Date,o=i.flatMap(l=>{const c=this._drain(l);if(c.length===0)return[];const u=this._buildEnvelope(c,l,"final",n,s);return[{envelope:u,bodyBytes:JSON.stringify(u).length}]}),r=o.reduce((l,c)=>l+c.bodyBytes,0)<=je.KEEPALIVE_BODY_LIMIT_BYTES,a=(yield Promise.allSettled(o.map(({envelope:l})=>this._postRecording(e,l,r)))).find(l=>l.status==="rejected");if(a)throw a.reason})}cleanup(){this._clearFlushTimer(),this._cancelReaders(),this._buffers={local:[],remote:[]},this._bufferBytes={local:0,remote:0},this._trackStates={local:null,remote:null}}_attach(e,i){this._trackStates[i]={ssrc:Math.floor(4294967295*Math.random())>>>0,seq:0,ts:0};try{const n=new MediaStreamTrackProcessor({track:e});this._processors.push(n);const s=n.readable.getReader();let o=!1;const r=()=>{o=!0,s.cancel().catch(()=>{}).finally(()=>{})};this._readerCancellers.push(r),V(this,void 0,void 0,function*(){try{for(;!o&&!this._stopped;){const{done:a,value:l}=yield s.read();if(a)break;this._onFrame(i,l)}}catch(a){this._stopped||y.warn("CallRecorder: reader loop error",{track:i,error:a})}})}catch(n){y.warn("CallRecorder: failed to attach track",{track:i,error:n}),this._trackStates[i]=null}}_onFrame(e,i){var n;const s=this._trackStates[e];if(!s||this._stopped)return;const o=i.numberOfFrames,r=new Float32Array(o);i.copyTo(r,{planeIndex:0}),(n=i.close)===null||n===void 0||n.call(i);const a=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);s.seq=s.seq+1&65535;const l=s.ts;s.ts+=o;const c={rtpSeq:s.seq,rtpTs:l,rtpSsrc:s.ssrc,capturedAt:new Date().toISOString(),payloadBytes:a};this._pushPacket(c,e)}_pushPacket(e,i){const n=e.payloadBytes.length+je.PACKET_OVERHEAD_BYTES,s=this._maxBufferBytes(),o=this._buffers[i];if(o.push(e),this._bufferBytes[i]+=n,this._bufferBytes[i]>s){for(;o.length>1&&this._bufferBytes[i]>s;){const r=o.shift();r&&(this._bufferBytes[i]-=r.payloadBytes.length+je.PACKET_OVERHEAD_BYTES)}this._overflowWarnedThisWindow[i]||(this._overflowWarnedThisWindow[i]=!0,y.warn("CallRecorder: buffer overflow — oldest packets dropped",{track:i}),this._emitWarning(e0))}}_flushIntervalMs(){var e;const i=(e=this.options.flushIntervalMs)!==null&&e!==void 0?e:15e3;return i<=0?i:Math.min(i,this._maxSafeFlushIntervalMs())}_maxSafeFlushIntervalMs(){const e=this._sampleRate()*je.BYTES_PER_SAMPLE+je.FRAMES_PER_SECOND*je.PACKET_OVERHEAD_BYTES;return Math.max(1e3,this._maxBufferBytes()/e*500)}_maxBufferBytes(){var e;return(e=this.options.maxBufferBytes)!==null&&e!==void 0?e:rh}_sampleRate(){var e;return(e=this.options.sampleRate)!==null&&e!==void 0?e:48e3}_scheduleFlush(){if(this._stopped||this._flushTimerId)return;const e=this._flushIntervalMs();e<=0||(this._flushTimerId=setInterval(()=>{this._periodicFlush().catch(i=>{y.error("CallRecorder: periodic flush error",{error:i})})},e))}_clearFlushTimer(){this._flushTimerId&&(clearInterval(this._flushTimerId),this._flushTimerId=null)}_cancelReaders(){for(const e of this._readerCancellers)try{e()}catch{}this._readerCancellers=[],this._processors=[]}_periodicFlush(){return V(this,void 0,void 0,function*(){if(!this._flushing&&!this._stopped){this._flushing=!0;try{const e=this._resolveEndpointFromContext();if(!e)return void y.debug("CallRecorder: periodic flush skipped — no host available");const i=this.options.tracks||["local","remote"],n=this._startedAt||new Date,s=new Date;yield Promise.allSettled(i.map(o=>{const r=this._drain(o);if(r.length===0)return Promise.resolve();const a=this._buildEnvelope(r,o,"intermediate",n,s);return this._postRecording(e,a,!1).catch(l=>{y.error("CallRecorder: intermediate flush failed",{track:o,error:l})})})),this._overflowWarnedThisWindow={local:!1,remote:!1}}finally{this._flushing=!1}}})}_drain(e){const i=this._buffers[e];return this._buffers[e]=[],this._bufferBytes[e]=0,i}_resolveEndpointFromContext(){const e=this.callContext.host;return e?this._resolveEndpoint(e):this._host?this._resolveEndpoint(this._host):null}_setHost(e){this._host=e}_setCallReportId(e){e&&(this._callReportId=e)}_resolveCallReportId(){return this._callReportId||this.callContext.callReportId}_resolveEndpoint(e){const i=this.options.endpoint||"/call_recording";try{const n=new URL(e);return`${`${n.protocol.replace(/^ws/,"http")}//${n.host}`}${i}`}catch{return/^https?:\/\//.test(e)?`${e}${i}`:`https://${e}${i}`}}_buildEnvelope(e,i,n,s,o){let r=0;const a=e.map(l=>(r+=l.payloadBytes.length,{rtp_seq:l.rtpSeq,rtp_ts:l.rtpTs,rtp_ssrc:l.rtpSsrc,captured_at:l.capturedAt,payload_b64:this._toBase64(l.payloadBytes)}));return Object.assign(Object.assign({call_report_id:this._resolveCallReportId(),call_id:this.callContext.callId},this.callContext.voiceSdkId?{voice_sdk_id:this.callContext.voiceSdkId}:{}),{recording_id:this.recordingId,segment:n,track:i,codec:"pcm-f32-le",sample_rate:this._sampleRate(),channels:1,started_at:s.toISOString(),ended_at:o.toISOString(),packet_count:e.length,byte_count:r,packets:a})}_postRecording(e,i,n){return V(this,void 0,void 0,function*(){const s={"Content-Type":"application/json","x-call-report-id":i.call_report_id,"x-call-id":i.call_id};i.voice_sdk_id&&(s["x-voice-sdk-id"]=i.voice_sdk_id);const o=JSON.stringify(i),r=n&&o.length<=je.KEEPALIVE_BODY_LIMIT_BYTES,a=this.options.fetchImpl||fetch;let l;for(let c=0;c<=je.RETRY_DELAYS_MS.length;c++){try{const d=yield a(e,Object.assign({method:"POST",headers:s,body:o},r?{keepalive:!0}:{}));if(d.ok)return void y.info("CallRecorder: posted",{track:i.track,segment:i.segment,attempt:c+1,status:d.status,packets:i.packet_count});{const h=yield d.text().catch(()=>"");l=new Error(`Call recording POST failed with status ${d.status}`),y.error("CallRecorder: failed to post",{track:i.track,segment:i.segment,attempt:c+1,status:d.status,error:h})}}catch(d){l=d,y.warn("CallRecorder: network error posting",{track:i.track,segment:i.segment,attempt:c+1,error:d})}const u=je.RETRY_DELAYS_MS[c];if(u===void 0)break;y.info("CallRecorder: retrying",{track:i.track,segment:i.segment,inMs:u,attempt:c+2}),yield new Promise(d=>setTimeout(d,u))}throw y.error("CallRecorder: exhausted retries",{track:i.track,segment:i.segment,error:l}),l instanceof Error?l:new Error("Call recording POST failed after retries")})}_emitWarning(e){var i;try{const n=Ne(e);(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){y.warn("CallRecorder: failed to emit warning",{code:e,error:n})}}_toBase64(e){let i="";for(let n=0;n<e.length;n+=32768){const s=e.subarray(n,n+32768);i+=String.fromCharCode.apply(null,Array.from(s))}return btoa(i)}}je.RETRY_DELAYS_MS=[500,1e3,2e3],je.KEEPALIVE_BODY_LIMIT_BYTES=61440,je.PACKET_OVERHEAD_BYTES=160,je.BYTES_PER_SAMPLE=4,je.FRAMES_PER_SECOND=100;class ib{constructor(){this._rawDeviceCache=[],this._deviceChangeHandler=null,this._stopped=!1}logDevicesAtStart(){return V(this,void 0,void 0,function*(){try{const e=yield this._enumerateAudioDevices();this._rawDeviceCache=e,y.debug("MediaDeviceCollector: devices at call start",{devices:e}),this._startDeviceChangeListener()}catch(e){y.debug("MediaDeviceCollector: failed to log devices at start",{error:e})}})}stop(){this._stopped=!0,this._removeDeviceChangeListener()}_enumerateAudioDevices(){return V(this,void 0,void 0,function*(){try{if(typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.enumerateDevices=="function")return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind==="audioinput"||e.kind==="audiooutput")}catch(e){y.debug("MediaDeviceCollector: enumerateDevices failed",{error:e})}return[]})}_startDeviceChangeListener(){typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.addEventListener=="function"&&(this._deviceChangeHandler=()=>{this._onDeviceChange()},navigator.mediaDevices.addEventListener("devicechange",this._deviceChangeHandler))}_removeDeviceChangeListener(){this._deviceChangeHandler&&typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.removeEventListener=="function"&&navigator.mediaDevices.removeEventListener("devicechange",this._deviceChangeHandler),this._deviceChangeHandler=null}_onDeviceChange(){return V(this,void 0,void 0,function*(){if(!this._stopped)try{const e=yield this._enumerateAudioDevices(),i=new Set(this._rawDeviceCache.map(r=>r.deviceId)),n=new Set(e.map(r=>r.deviceId)),s=e.filter(r=>!i.has(r.deviceId)),o=this._rawDeviceCache.filter(r=>!n.has(r.deviceId));(s.length>0||o.length>0)&&y.debug("MediaDeviceCollector: devices changed during call",{connected:s,disconnected:o}),this._rawDeviceCache=e}catch(e){y.debug("MediaDeviceCollector: error handling devicechange",{error:e})}})}}var bs,Eh=Ku(function(t,e){var i;function n(){}function s(){s.init.call(this)}function o(g){return g._maxListeners===void 0?s.defaultMaxListeners:g._maxListeners}function r(g,m,f,S){var I,A,x;if(typeof f!="function")throw new TypeError('"listener" argument must be a function');if((A=g._events)?(A.newListener&&(g.emit("newListener",m,f.listener?f.listener:f),A=g._events),x=A[m]):(A=g._events=new n,g._eventsCount=0),x){if(typeof x=="function"?x=A[m]=S?[f,x]:[x,f]:S?x.unshift(f):x.push(f),!x.warned&&(I=o(g))&&0<I&&x.length>I){x.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+x.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=g,N.type=m,N.count=x.length,function(M){typeof console.warn=="function"?console.warn(M):console.log(M)}(N)}}else x=A[m]=f,++g._eventsCount;return g}function a(g,m,f){function S(){g.removeListener(m,S),I||(I=!0,f.apply(g,arguments))}var I=!1;return S.listener=f,S}function l(g){var m=this._events;if(m){var f=m[g];if(typeof f=="function")return 1;if(f)return f.length}return 0}function c(g,m){for(var f=Array(m);m--;)f[m]=g[m];return f}Object.defineProperty(e,"__esModule",{value:!0}),n.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&i.active&&!(this instanceof i.Domain)&&(this.domain=i.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new n,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(g){if(typeof g!="number"||0>g||isNaN(g))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=g,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(g){var m,f,S,I,A,x,N,M=g==="error";if(x=this._events)M=M&&x.error==null;else if(!M)return!1;if(N=this.domain,M){if(m=arguments[1],!N){if(m instanceof Error)throw m;var F=new Error('Uncaught, unspecified "error" event. ('+m+")");throw F.context=m,F}return m||(m=new Error('Uncaught, unspecified "error" event')),m.domainEmitter=this,m.domain=N,m.domainThrown=!1,N.emit("error",m),!1}if(!(f=x[g]))return!1;var G=typeof f=="function";switch(S=arguments.length){case 1:(function(U,ae,q){if(ae)U.call(q);else for(var H=U.length,ce=c(U,H),J=0;J<H;++J)ce[J].call(q)})(f,G,this);break;case 2:(function(U,ae,q,H){if(ae)U.call(q,H);else for(var ce=U.length,J=c(U,ce),ee=0;ee<ce;++ee)J[ee].call(q,H)})(f,G,this,arguments[1]);break;case 3:(function(U,ae,q,H,ce){if(ae)U.call(q,H,ce);else for(var J=U.length,ee=c(U,J),te=0;te<J;++te)ee[te].call(q,H,ce)})(f,G,this,arguments[1],arguments[2]);break;case 4:(function(U,ae,q,H,ce,J){if(ae)U.call(q,H,ce,J);else for(var ee=U.length,te=c(U,ee),ie=0;ie<ee;++ie)te[ie].call(q,H,ce,J)})(f,G,this,arguments[1],arguments[2],arguments[3]);break;default:for(I=Array(S-1),A=1;A<S;A++)I[A-1]=arguments[A];(function(U,ae,q,H){if(ae)U.apply(q,H);else for(var ce=U.length,J=c(U,ce),ee=0;ee<ce;++ee)J[ee].apply(q,H)})(f,G,this,I)}return!0},s.prototype.addListener=function(g,m){return r(this,g,m,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(g,m){return r(this,g,m,!0)},s.prototype.once=function(g,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.on(g,a(this,g,m)),this},s.prototype.prependOnceListener=function(g,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(g,a(this,g,m)),this},s.prototype.removeListener=function(g,m){var f,S,I,A,x;if(typeof m!="function")throw new TypeError('"listener" argument must be a function');if(!(S=this._events))return this;if(!(f=S[g]))return this;if(f===m||f.listener&&f.listener===m)--this._eventsCount==0?this._events=new n:(delete S[g],S.removeListener&&this.emit("removeListener",g,f.listener||m));else if(typeof f!="function"){for(I=-1,A=f.length;0<A--;)if(f[A]===m||f[A].listener&&f[A].listener===m){x=f[A].listener,I=A;break}if(0>I)return this;if(f.length===1){if(f[0]=void 0,--this._eventsCount==0)return this._events=new n,this;delete S[g]}else(function(N,M){for(var F=M,G=F+1,U=N.length;G<U;F+=1,G+=1)N[F]=N[G];N.pop()})(f,I);S.removeListener&&this.emit("removeListener",g,x||m)}return this},s.prototype.removeAllListeners=function(g){var m,f;if(!(f=this._events))return this;if(!f.removeListener)return arguments.length===0?(this._events=new n,this._eventsCount=0):f[g]&&(--this._eventsCount==0?this._events=new n:delete f[g]),this;if(arguments.length===0){for(var S,I=Object.keys(f),A=0;A<I.length;++A)(S=I[A])!=="removeListener"&&this.removeAllListeners(S);return this.removeAllListeners("removeListener"),this._events=new n,this._eventsCount=0,this}if(typeof(m=f[g])=="function")this.removeListener(g,m);else if(m)do this.removeListener(g,m[m.length-1]);while(m[0]);return this},s.prototype.listeners=function(g){var m,f,S=this._events;return S?f=(m=S[g])?typeof m=="function"?[m.listener||m]:function(I){for(var A=Array(I.length),x=0;x<A.length;++x)A[x]=I[x].listener||I[x];return A}(m):[]:f=[],f},s.listenerCount=function(g,m){return typeof g.listenerCount=="function"?g.listenerCount(m):l.call(g,m)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var u,d=new Uint8Array(16);function h(){if(!u&&!(u=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return u(d)}for(var p=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,_=[],v=0;256>v;++v)_.push((v+256).toString(16).substr(1));function b(g){var m=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,f=(_[g[m+0]]+_[g[m+1]]+_[g[m+2]]+_[g[m+3]]+"-"+_[g[m+4]]+_[g[m+5]]+"-"+_[g[m+6]]+_[g[m+7]]+"-"+_[g[m+8]]+_[g[m+9]]+"-"+_[g[m+10]]+_[g[m+11]]+_[g[m+12]]+_[g[m+13]]+_[g[m+14]]+_[g[m+15]]).toLowerCase();if(!function(S){return typeof S=="string"&&p.test(S)}(f))throw TypeError("Stringified UUID is invalid");return f}function w(g,m,f){var S=(g=g||{}).random||(g.rng||h)();return S[6]=64|15&S[6],S[8]=128|63&S[8],b(S)}function C(g,m){if(!g||!m)return{};const f={...g};if(f.localCandidateId){const S=m.get(f.localCandidateId);f.local={...S}}if(f.remoteCandidateId){const S=m.get(f.remoteCandidateId);f.remote={...S}}return f}function k(g,m,f){return 8*function(S,I,A){const x=S[A],N=I?I[A]:null;return x===null||N===null?null:(x-N)/(S.timestamp-I.timestamp)*1e3}(g,m,f)}function L(g){if(!g.entries)return g;const m={};return g.forEach(function(f,S){m[S]=f}),m}function R(g,m,f={}){if(!g)return null;let S={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};f.remote&&(S.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const I of g.values())switch(I.type){case"outbound-rtp":{const A=I.mediaType||I.kind,x={};let N={};if(!["audio","video"].includes(A))continue;if(I.codecId){const M=g.get(I.codecId);M&&(x.clockRate=M.clockRate,x.mimeType=M.mimeType,x.payloadType=M.payloadType)}N=g.get(I.mediaSourceId)||g.get(I.trackId)||{},S[A].outbound.push({...I,...x,track:{...N}});break}case"inbound-rtp":{let A=I.mediaType||I.kind,x={};const N={};if(!["audio","video"].includes(A))if(I.id.includes("Video"))A="video";else{if(!I.id.includes("Audio"))continue;A="audio"}if(I.codecId){const M=g.get(I.codecId);M&&(N.clockRate=M.clockRate,N.mimeType=M.mimeType,N.payloadType=M.payloadType)}if(!S.connection.id&&I.transportId){const M=g.get(I.transportId);if(M&&M.selectedCandidatePairId){const F=g.get(M.selectedCandidatePairId);S.connection=C(F,g)}}x=g.get(I.mediaSourceId)||g.get(I.trackId)||{},S[A].inbound.push({...I,...N,track:{...x}});break}case"peer-connection":S.connection.dataChannelsClosed=I.dataChannelsClosed,S.connection.dataChannelsOpened=I.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!f.remote)break;let A=I.mediaType||I.kind;const x={};if(!["audio","video"].includes(A))if(I.id.includes("Video"))A="video";else{if(!I.id.includes("Audio"))continue;A="audio"}if(I.codecId){const N=g.get(I.codecId);N&&(x.clockRate=N.clockRate,x.mimeType=N.mimeType,x.payloadType=N.payloadType)}if(!S.connection.id&&I.transportId){const N=g.get(I.transportId);if(N&&N.selectedCandidatePairId){const M=g.get(N.selectedCandidatePairId);S.connection=C(M,g)}}S.remote[A].inbound.push({...I,...x});break}case"remote-outbound-rtp":{if(!f.remote)break;const A=I.mediaType||I.kind,x={};if(!["audio","video"].includes(A))continue;if(I.codecId){const N=g.get(I.codecId);N&&(x.clockRate=N.clockRate,x.mimeType=N.mimeType,x.payloadType=N.payloadType)}S.remote[A].outbound.push({...I,...x});break}}if(!S.connection.id)for(const I of g.values())I.type==="candidate-pair"&&I.nominated&&I.state==="succeeded"&&(S.connection=C(I,g));return S=function(I,A){return A&&(I.audio.inbound.map(x=>{let N=A.audio.inbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesReceived"),x.packetRate=k(x,N,"packetsReceived")}),I.audio.outbound.map(x=>{let N=A.audio.outbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesSent"),x.packetRate=k(x,N,"packetsSent")}),I.video.inbound.map(x=>{let N=A.video.inbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesReceived"),x.packetRate=k(x,N,"packetsReceived")}),I.video.outbound.map(x=>{let N=A.video.outbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesSent"),x.packetRate=k(x,N,"packetsSent")})),I}(S,m),S}let O,T={},E=[];e.WebRTCStats=class extends s{constructor(g){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],typeof window>"u")throw new Error("WebRTCStats only works in browser");const m={...g};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=m.getStatsInterval||1e3,this.rawStats=!!m.rawStats,this.statsObject=!!m.statsObject,this.filteredStats=!!m.filteredStats,this.shouldWrapGetUserMedia=!!m.wrapGetUserMedia,typeof m.remote=="boolean"&&(this.remote=m.remote),this.debug=!!m.debug,this.logLevel=m.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(g,m){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:g,pc:m})}async addConnection(g){const{pc:m,peerId:f}=g;let{connectionId:S,remote:I}=g;if(I=typeof I=="boolean"?I:this.remote,!(m&&m instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!f)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[f]){if(S&&S in this.peersToMonitor[f])throw new Error(`We are already monitoring connection with id ${S}.`);for(let x in this.peersToMonitor[f]){const N=this.peersToMonitor[f][x];if(N.pc===m)throw new Error(`We are already monitoring peer with id ${f}.`);N.pc.connectionState==="closed"&&this.removeConnection({pc:N.pc})}}const A=m.getConfiguration();return A.iceServers&&A.iceServers.forEach(function(x){delete x.credential}),S||(S=w()),this.emitEvent({event:"addConnection",tag:"peer",peerId:f,connectionId:S,data:{options:g,peerConfiguration:A}}),this.monitorPeer({peerId:f,connectionId:S,pc:m,remote:I}),{connectionId:S}}getTimeline(g){return this.timeline=this.timeline.sort((m,f)=>m.timestamp.getTime()-f.timestamp.getTime()),g?this.timeline.filter(m=>m.tag===g):this.timeline}get logger(){const g=m=>{const f=["none","error","warn","info","debug"];return f.slice(0,f.indexOf(this.logLevel)+1).indexOf(m)>-1};return{error(...m){this.debug&&g("error")&&console.error("[webrtc-stats][error] ",...m)},warn(...m){this.debug&&g("warn")&&console.warn("[webrtc-stats][warn] ",...m)},info(...m){this.debug&&g("info")&&console.log("[webrtc-stats][info] ",...m)},debug(...m){this.debug&&g("debug")&&console.debug("[webrtc-stats][debug] ",...m)}}}removeConnection(g){let m,{connectionId:f,pc:S}=g;if(!S&&!f)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(f){if(typeof f!="string")throw new Error("connectionId must be a string.");for(let I in this.peersToMonitor)f in this.peersToMonitor[I]&&(S=this.peersToMonitor[I][f].pc,m=I)}else if(S){if(!(S instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let I in this.peersToMonitor)for(let A in this.peersToMonitor[I])this.peersToMonitor[I][A].pc===S&&(f=A,m=I)}if(!S||!f)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(f,S),delete this.peersToMonitor[m][f],Object.values(this.peersToMonitor[m]).length===0&&delete this.peersToMonitor[m],{connectionId:f}}removeAllPeers(){for(let g in this.peersToMonitor)this.removePeer(g)}removePeer(g){if(this.logger.info(`Removing PeerConnection with id ${g}.`),this.peersToMonitor[g]){for(let m in this.peersToMonitor[g]){let f=this.peersToMonitor[g][m].pc;this.removePeerConnectionEventListeners(m,f)}delete this.peersToMonitor[g]}}destroy(){this.removeAllPeers(),E.forEach(g=>{this.removeTrackEventListeners(g)}),E=[],this.shouldWrapGetUserMedia&&O&&(navigator.mediaDevices.getUserMedia=O)}monitorPeer(g){let{peerId:m,connectionId:f,pc:S,remote:I}=g;if(!S)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const A={pc:S,connectionId:f,stream:null,stats:{parsed:null,raw:null},options:{remote:I}};if(this.peersToMonitor[m]){if(f in this.peersToMonitor[m])return void this.logger.warn(`Already watching connection with ID ${f}`);this.peersToMonitor[m][f]=A}else this.peersToMonitor[m]={[f]:A};this.addPeerConnectionEventListeners(m,f,S),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(g=>{g.forEach(m=>{this.emitEvent(m)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(g=null){this.logger.info(g?`Getting stats from peer ${g}`:"Getting stats from all peers");let m={};if(g){if(!this.peersToMonitor[g])throw new Error(`Cannot get stats. Peer with id ${g} does not exist`);m[g]=this.peersToMonitor[g]}else m=this.peersToMonitor;let f=[];for(const S in m)for(const I in m[S]){const A=m[S][I],x=A.pc;if(x&&!this.checkIfConnectionIsClosed(S,I,x))try{const N=this.getTimestamp(),M=x.getStats(null);if(M){const F=await M,G=this.getTimestamp(),U=L(F),ae={remote:A.options.remote},q=R(F,A.stats.parsed,ae),H={event:"stats",tag:"stats",peerId:S,connectionId:I,timeTaken:G-N,data:q};this.rawStats===!0&&(H.rawStats=F),this.statsObject===!0&&(H.statsObject=U),this.filteredStats===!0&&(H.filteredStats=this.filteroutStats(U)),f.push(H),A.stats.parsed=q}else this.logger.error(`PeerConnection from peer ${S} did not return any stats data`)}catch(N){this.logger.error(N)}}return f}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const g in this.peersToMonitor)for(const m in this.peersToMonitor[g]){const f=this.peersToMonitor[g][m].pc;this.checkIfConnectionIsClosed(g,m,f)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(g,m,f){const S=this.isConnectionClosed(f);if(S){this.removeConnection({pc:f});let I=f.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:I,peerId:g,connectionId:m,tag:"connection",data:"closed"})}return S}isConnectionClosed(g){return g.connectionState==="closed"||g.iceConnectionState==="closed"}stopConnectionStateMonitoring(){this.connectionMonitoringSetInterval&&(window.clearInterval(this.connectionMonitoringSetInterval),this.connectionMonitoringSetInterval=0)}wrapGetUserMedia(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return void this.logger.warn("'navigator.mediaDevices.getUserMedia' is not available in browser. Will not wrap getUserMedia.");this.logger.info("Wrapping getUsermedia functions."),O=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const g=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return g({constraints:arguments[0]}),O.apply(navigator.mediaDevices,arguments).then(m=>(g({stream:m}),m),m=>(g({error:m}),Promise.reject(m)))}).bind(navigator.mediaDevices)}filteroutStats(g={}){const m={...g};for(const S in m){var f=m[S];this.statsToMonitor.includes(f.type)||delete m[S]}return m}get peerConnectionListeners(){return{icecandidate:(g,m,f,S)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",S),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:g,connectionId:m,data:S.candidate})},track:(g,m,f,S)=>{this.logger.debug(`[pc-event] track | peerId: ${g}`,S);const I=S.track,A=S.streams[0];g in this.peersToMonitor&&m in this.peersToMonitor[g]&&(this.peersToMonitor[g][m].stream=A),this.addTrackEventListeners(I,m),this.emitEvent({event:"ontrack",tag:"track",peerId:g,connectionId:m,data:{stream:A?this.getStreamDetails(A):null,track:I?this.getMediaTrackDetails(I):null,title:S.track.kind+":"+S.track.id+" "+S.streams.map(function(x){return"stream:"+x.id})}})},signalingstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${g}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:g,connectionId:m,data:{signalingState:f.signalingState,localDescription:f.localDescription,remoteDescription:f.remoteDescription}})},iceconnectionstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${g}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:g,connectionId:m,data:f.iceConnectionState})},icegatheringstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${g}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:g,connectionId:m,data:f.iceGatheringState})},icecandidateerror:(g,m,f,S)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${g}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:g,connectionId:m,error:{errorCode:S.errorCode}})},connectionstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${g}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:g,connectionId:m,data:f.connectionState})},negotiationneeded:(g,m,f)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${g}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:g,connectionId:m})},datachannel:(g,m,f,S)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${g}`,S),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:g,connectionId:m,data:S.channel})}}}addPeerConnectionEventListeners(g,m,f){this.logger.debug(`Adding event listeners for peer ${g} and connection ${m}.`),T[m]={},Object.keys(this.peerConnectionListeners).forEach(S=>{T[m][S]=this.peerConnectionListeners[S].bind(this,g,m,f),f.addEventListener(S,T[m][S],!1)})}parseGetUserMedia(g){try{const m={event:"getUserMedia",tag:"getUserMedia",data:{...g}};g.stream&&(m.data.details=this.parseStream(g.stream),g.stream.getTracks().map(f=>{this.addTrackEventListeners(f),E.push(f)})),this.emitEvent(m)}catch{}}parseStream(g){const m={audio:[],video:[]};return g.getTracks().forEach(f=>{m[f.kind].push(this.getMediaTrackDetails(f))}),m}getMediaTrackDetails(g){return{enabled:g.enabled,id:g.id,contentHint:g.contentHint,kind:g.kind,label:g.label,muted:g.muted,readyState:g.readyState,constructorName:g.constructor.name,capabilities:g.getCapabilities?g.getCapabilities():{},constraints:g.getConstraints?g.getConstraints():{},settings:g.getSettings?g.getSettings():{},_track:g}}getStreamDetails(g){return{active:g.active,id:g.id,_stream:g}}getTrackEventObject(g){return{mute:m=>{this.emitEvent({event:"mute",tag:"track",connectionId:g,data:{event:m}})},unmute:m=>{this.emitEvent({event:"unmute",tag:"track",connectionId:g,data:{event:m}})},overconstrained:m=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:g,data:{event:m}})},ended:m=>{this.emitEvent({event:"ended",tag:"track",connectionId:g,data:{event:m}}),this.removeTrackEventListeners(m.target)}}}addTrackEventListeners(g,m){T[g.id]={};const f=this.getTrackEventObject(m);Object.keys(f).forEach(S=>{T[g.id][S]=f[S].bind(this),g.addEventListener(S,T[g.id][S])}),T[g.id].readyState=setInterval(()=>{if(g.readyState==="ended"){let S=new CustomEvent("ended",{detail:{check:"readyState"}});g.dispatchEvent(S)}},1e3)}removeTrackEventListeners(g){if(g.id in T){const m=this.getTrackEventObject();Object.keys(m).forEach(f=>{g.removeEventListener(f,T[g.id][f])}),clearInterval(T[g.id].readyState),delete T[g.id]}}addToTimeline(g){this.timeline.push(g),this.emit("timeline",g)}emitEvent(g){const m={...g,timestamp:new Date};this.addToTimeline(m),m.tag&&this.emit(m.tag,m)}set getStatsInterval(g){if(!Number.isInteger(g))throw new Error(`getStatsInterval should be an integer, got: ${g}`);this._getStatsInterval=g,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(g,m){g in T&&(Object.keys(this.peerConnectionListeners).forEach(f=>{m.removeEventListener(f,T[g][f],!1)}),delete T[g]),m.getSenders().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)}),m.getReceivers().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const g=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const m=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),f=function(){return g.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),m.apply(navigator.mediaDevices,arguments).then(function(S){return S},function(S){return g.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,S.name),Promise.reject(S)})};navigator.mediaDevices.getDisplayMedia=f.bind(navigator.mediaDevices)}}}});(bs=Eh)&&bs.__esModule&&Object.prototype.hasOwnProperty.call(bs,"default")&&bs.default;var nb=Eh.WebRTCStats;function sb(t){const{packetsLost:e,packetsReceived:i,jitter:n,rtt:s}=t,o=function(c){const{jitter:u,rtt:d}=c,h=u+d/2;return .024*h+.11*(h-177.3)*(h>177.3?1:0)}({rtt:s,jitter:n}),r=function(c){const{packetsLost:u,packetsReceived:d}=c,h=u/(d+u)*100;return 20*Math.log(1+h)}({packetsLost:e,packetsReceived:i}),a=93.2-o-r+0,l=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(l,1),5)}function ob(t){return isNaN(t)?null:t>4.2?"excellent":t>=4.1&&t<=4.2?"good":t>=3.7&&t<=4?"fair":t>=3.1&&t<=3.6?"poor":"bad"}class rb extends Li{constructor(e,i){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:i})}}class ab extends Li{constructor(e,i){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:i})}}class lb extends Li{constructor(e,i,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,call_id:i,debug_report_data:n})}}function cb(t,e){const i=ki();let n=!1;const s=new nb({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>V(this,void 0,void 0,function*(){r.event==="stats"&&B(P.StatsFrame,function({data:a}){var l,c,u,d,h,p,_,v;const{audio:b,remote:w}=a,{audio:C}=w,k=(c=(l=C.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,L=(d=(u=C.inbound[0])===null||u===void 0?void 0:u.roundTripTime)!==null&&d!==void 0?d:1/0,R=(p=(h=b.inbound[0])===null||h===void 0?void 0:h.packetsReceived)!==null&&p!==void 0?p:-1,O=(v=(_=b.inbound[0])===null||_===void 0?void 0:_.packetsLost)!==null&&v!==void 0?v:-1,T=sb({jitter:1e3*k,rtt:1e3*L,packetsLost:O,packetsReceived:R});return{jitter:k,rtt:L,mos:T,quality:ob(T),inboundAudio:b.inbound[0],outboundAudio:b.outbound[0],remoteInboundAudio:C.inbound[0],remoteOutboundAudio:C.outbound[0]}}(r),t.uuid),yield t.execute(new lb(i,e,r))});return{get isRunning(){return n},start:(r,a,l)=>V(this,void 0,void 0,function*(){if(n)y.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new rb(i,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),n=!0}catch(c){y.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:r=>V(this,void 0,void 0,function*(){const a=s.getTimeline();B(P.StatsReport,a,t.uuid),r==="file"&&function(l,c){const u=new Blob([JSON.stringify(l)],{type:"application/json"}),d=URL.createObjectURL(u),h=document.createElement("a");h.href=d,h.download=`${c}.json`,h.click(),URL.revokeObjectURL(d)}(a,`webrtc-stats-${i}-${Date.now()}`),yield t.execute(new ab(i,e)),s.removeAllPeers(),s.destroy(),n=!1}),reportConnectionStateChange:r=>{const a={event:"connectionstatechange-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)},reportIceCandidateError:r=>{const a={event:"icecandidateerror-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)}}}const kh=(t,e)=>{const{contentType:i,canvasType:n,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=e;o&&n!=="mcu-personal-canvas"&&delete o.memberID;const a={type:st.conferenceUpdate,call:t.calls[s],canvasInfo:db(o),currentLayerIdx:r};switch(i){case"layer-info":{const l=Object.assign({action:Ye.LayerInfo},a);B(P.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:Ye.LayoutInfo},a);B(P.Notification,l,t.uuid);break}}},db=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Qu(e)},Ih=["new-call-start","new-peer","get-user-media","peer-creation-end","start-negotiation","create-offer","create-answer","set-local-description","ice-gathering-started","first-candidate","first-non-host-candidate","send-sdp","ice-gathering-completed","ringing","telnyx-rtc-media","first-remote-media-track","set-remote-description","telnyx-rtc-answer","ice-connected","dtls-connected","call-active","answer-called"],ub={"new-call-start":"Call Start","new-peer":"Peer object created","get-user-media":"Media devices acquired","peer-creation-end":"Peer setup complete","start-negotiation":"SDP negotiation started","create-offer":"SDP offer generated","create-answer":"SDP answer generated","set-local-description":"Local description applied","ice-gathering-started":"ICE candidate gathering started","first-candidate":"First ICE candidate found","first-non-host-candidate":"First server-reflexive/relay candidate found","send-sdp":"SDP sent to server","ice-gathering-completed":"All ICE candidates gathered",ringing:"Remote side ringing","telnyx-rtc-media":"Early media received from server","first-remote-media-track":"First remote audio/video track received","set-remote-description":"Remote description applied","telnyx-rtc-answer":"Call answered by remote side","ice-connected":"ICE connection established","dtls-connected":"Secure media channel established (DTLS)","call-active":"Call is active","answer-called":"Answer delay (invite → call.answer)"};function re(t,e){return`telnyx:call:${t}:${e}`}function Rh(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}function Fr(t){for(const e of Ih)try{performance.clearMarks(re(t,e))}catch{y.warn("Clearing performance marks is failed")}}class ii{constructor(e,i,n,s,o){this.type=e,this.options=i,this.onSdpReadyTwice=null,this.statsReporter=null,this.isIceRestarting=!1,this.iceDone=!1,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this._iceGatheringSafetyTimeout=null,this._gatheredCandidatesCount=0,this._firstMediaTrackMarked=!1,this._timingsCollected=!1,this._iceRestartTimeoutId=null,this.handleConnectionStateChange=()=>V(this,void 0,void 0,function*(){var r,a;if(!this.instance)return void y.debug("Connection state change ignored: instance is null");const{connectionState:l}=this.instance;if(y.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${l}`),l!=="failed"&&l!=="disconnected"||(this.isDebugEnabled&&this.statsReporter&&function(c,u){return V(this,void 0,void 0,function*(){const d={connectionState:c.connectionState,previousConnectionState:u,iceConnectionState:c.iceConnectionState,iceGatheringState:c.iceGatheringState,signalingState:c.signalingState},h=c.getTransceivers();if(h.length>0){const p=h[0].sender,_=p==null?void 0:p.transport;_&&(d.dtlsState=_.state)}c.sctp&&(d.sctpState=c.sctp.state);try{const p=yield c.getStats();p.forEach(_=>{_.type==="candidate-pair"&&_.state==="succeeded"&&(d.candidatePairState=_.state,p.forEach(v=>{v.type==="local-candidate"&&v.id===_.localCandidateId&&(d.localCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.local={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType}),v.type==="remote-candidate"&&v.id===_.remoteCandidateId&&(d.remoteCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.remote={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType})})),_.type==="transport"&&(d.dtlsCipher=_.dtlsCipher,d.srtpCipher=_.srtpCipher,d.tlsVersion=_.tlsVersion,_.dtlsState&&(d.dtlsState=_.dtlsState))})}catch(p){y.error("Error gathering connection state details:",p)}return d})}(this.instance,this._prevConnectionState).then(c=>{this.statsReporter.reportConnectionStateChange(c)}),(a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"connection_failed")),l==="disconnected"){const c=Ne(t0);B(P.Warning,{warning:c,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(l==="failed"){const c=Ne(s0);B(P.PeerConnectionFailureError,{warning:c,error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${l}`),sessionId:this._session.sessionid},this.options.id)}this._prevConnectionState=l,l==="connected"&&(performance.mark(re(this.options.id,"dtls-connected")),this.tryCollectTimings(),this._restartedIceOnConnectionStateFailed=!1),this._isTrickleIce()&&(l==="connecting"&&performance.mark(re(this.options.id,"peer-connection-connecting")),l==="connected"&&(this._clearIceGatheringSafetyTimeout(),performance.mark(re(this.options.id,"peer-connection-connected"))))}),this._handleIceConnectionStateChange=()=>{var r,a;if(!this.instance)return void y.debug("ICE connection state change ignored: instance is null");const l=this.instance.iceConnectionState;y.debug(`[${new Date().toISOString()}] ICE Connection State`,l),l==="connected"&&performance.mark(re(this.options.id,"ice-connected")),l==="failed"&&((a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"ice_failed"))},this._handleIceGatheringStateChange=()=>{const r=this.instance.iceGatheringState;y.debug(`[${new Date().toISOString()}] ICE Gathering State`,r),r==="gathering"?(this._gatheredCandidatesCount=0,this._startIceGatheringSafetyTimeout()):r==="complete"&&this._clearIceGatheringSafetyTimeout()},this._setCodecs=(r,a)=>{if(r.setCodecPreferences)return r.setCodecPreferences(a)},y.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!i.video},this._sdpReady=this._sdpReady.bind(this),this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this._session=n,this._trickleIceSdpFn=s,this._registerPeerEvents=o}finishIceRestart(){this.isIceRestarting&&(this.isIceRestarting=!1,this._iceRestartTimeoutId&&(clearTimeout(this._iceRestartTimeoutId),this._iceRestartTimeoutId=null))}restartIce(){return this.instance?this.isIceRestarting?(y.debug("ICE restart: already in progress, skipping"),{started:!1,reason:"already in progress"}):this._session.connected?(this.isIceRestarting=!0,this._restartedIceOnConnectionStateFailed=!0,this.instance.restartIce(),this.iceDone=!1,this._iceRestartTimeoutId=setTimeout(()=>{this.isIceRestarting&&(y.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null},ii.ICE_RESTART_TIMEOUT_MS),y.info("ICE restart: initiated by signaling health monitor"),{started:!0}):(y.debug("ICE restart: session not connected, skipping"),{started:!1,reason:"session not connected"}):(y.warn("ICE restart: no RTCPeerConnection instance"),{started:!1,reason:"no RTCPeerConnection instance"})}get isOffer(){return this.type===Fe.Offer}get isAnswer(){return this.type===Fe.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get restartedIceOnConnectionStateFailed(){return this._restartedIceOnConnectionStateFailed}isConnectionHealthy(){return this.instance.connectionState==="connected"&&this.instance.iceConnectionState==="connected"&&this.instance.signalingState!=="closed"}startNegotiation(){performance.mark(re(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?this._createOffer().catch(e=>this._emitNegotiationError(e)):this._createAnswer().catch(e=>this._emitNegotiationError(e))}startTrickleIceNegotiation(){return V(this,void 0,void 0,function*(){performance.mark(re(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_emitNegotiationError(e){e instanceof Vt&&B(P.Error,{error:e,sessionId:this._session.sessionid},this.options.id)}_logTransceivers(){this.instance?(y.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,i)=>{y.info(`>> Transceiver [${i}]:`,e.mid,e.direction,e.stopped),y.info(`>> Sender Params [${i}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):y.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(y.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":B(P.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(y.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){y.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?y.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation().catch(e=>this._emitNegotiationError(e)):this.startNegotiation()}handleTrackEvent(e){this._firstMediaTrackMarked||(performance.mark(re(this.options.id,"first-remote-media-track")),this._firstMediaTrackMarked=!0);const{streams:[i]}=e,{remoteElement:n,screenShare:s}=this.options;this.options.remoteStream=i,s===!1&&ms(n,this.options.remoteStream,{callId:this.options.id,sessionId:this._session.sessionid,eventTarget:this._session.uuid})}tryCollectTimings(){if(this._timingsCollected||!(performance.getEntriesByName(re(this.options.id,"call-active"),"mark").length>0)||this.instance.connectionState!=="connected")return;this._timingsCollected=!0;const e=this._isTrickleIce()?"trickle":"non-trickle",i=this.isOffer?"outbound":"inbound",n=function(s,o,r){const a=Rh(re(s,"new-call-start"));if(a===void 0)return{mode:o,direction:r,steps:[]};const l=[];for(const d of Ih){if(d==="new-call-start")continue;const h=Rh(re(s,d));h!==void 0&&l.push({label:ub[d]||d,fromStart:h-a})}l.sort((d,h)=>d.fromStart-h.fromStart);const c=[];let u=0;for(const d of l)c.push({label:d.label,fromStart:d.fromStart,delta:d.fromStart-u}),u=d.fromStart;return{mode:o,direction:r,steps:c}}(this.options.id,e,i);(function(s){const{mode:o,direction:r,steps:a}=s,l=`[CallTimings][${r}][${o}]`;if(a.length===0)return void y.info(`${l} No timing data collected`);const c=Math.max(...a.map(_=>_.label.length),4)+2,u=(_,v)=>{for(;_.length<v;)_+=" ";return _},d=(_,v)=>{for(;_.length<v;)_=" "+_;return _},h=u("Step",c)+d("Delta",14)+d("From Start",14);let p="";for(let _=0;_<h.length;_++)p+="-";y.info(`${l} Call establishment timing breakdown:`),y.info(`${l} ${h}`),y.info(`${l} ${p}`),y.info(`${l} ${u("Call Start",c)}${d("-",14)}${d("0.00ms",14)}`);for(const _ of a){const v=_.delta.toFixed(2)+"ms",b=_.fromStart.toFixed(2)+"ms";y.info(`${l} ${u(_.label,c)}${d(v,14)}${d(b,14)}`)}y.info(`${l} ${p}`)})(n),Fr(this.options.id)}createPeerConnection(){return V(this,void 0,void 0,function*(){var e;if(this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",s=>{this.options.remoteStream=s.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Fe.Offer}),performance.mark(re(this.options.id,"set-remote-description")),!this.instance))throw ne(wr);const i=!!this.options.receiveOnlyAudio&&!this.options.audio;let n=null;if(this.options.localStream=yield this._retrieveLocalStream().catch(s=>V(this,void 0,void 0,function*(){const o=this._session.options.mediaPermissionsRecovery;if(o!=null&&o.enabled&&this._isAnswer()){let r=null,a=null;return yield new Promise((l,c)=>{a=setTimeout(()=>c(new Error("Media recovery flow timed out!")),o.timeout),B(P.Error,{error:ne(Ii(s),s,void 0,!1),callId:this.options.id,sessionId:this._session.sessionid,recoverable:!0,retryDeadline:Date.now()+o.timeout,resume:()=>{l()},reject:()=>{c(new Error("Call was rejected during media recovery flow!"))}},this._session.uuid)}).then(()=>V(this,void 0,void 0,function*(){var l;a&&(clearTimeout(a),a=null),r=yield this._retrieveLocalStream(),(l=o.onSuccess)===null||l===void 0||l.call(o)})).catch(l=>{var c;a&&(clearTimeout(a),a=null),n=l,(c=o.onError)===null||c===void 0||c.call(o,l)}),r}return n=s,null})),!this.instance)throw ne(wr);if(!this.options.localStream&&!i)throw ne(n?Ii(n):Vu,n??void 0);performance.mark(re(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&vn(this.options.localStream)&&(y.info("Muting local audio tracks on start"),ys(this.options.localStream)),this.options.applyDesiredAudioMuteState&&this.options.applyDesiredAudioMuteState(),performance.mark(re(this.options.id,"peer-creation-end"))})}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout(()=>{if(this.instance){if(this._gatheredCandidatesCount===0){const e=Ne(n0);B(P.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=Ne(i0);B(P.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},ii.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){this._iceGatheringSafetyTimeout!==null&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return V(this,void 0,void 0,function*(){if(yield this.createPeerConnection(),!this.instance)throw ne(wr);this.isDebugEnabled&&(this.statsReporter=cb(this._session,this.options.id),yield(e=this.statsReporter)===null||e===void 0?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid));const{localElement:i,localStream:n=null,screenShare:s=!1}=this.options;if(vn(n)){const o=n.getAudioTracks();let r=[...o];if(y.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{y.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=n.getVideoTracks();r=[...o,...c],y.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(u=>{y.info("Local video tracks constraints: ",u.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=Th(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={direction:"sendrecv",streams:[n]};r.forEach(u=>{u.kind==="audio"&&(this.options.userVariables.microphoneLabel=u.label),u.kind==="video"&&(this.options.userVariables.cameraLabel=u.label);const d=this.instance.addTransceiver(u,c);u.kind==="audio"&&a.length>0&&this._setCodecs(d,a),u.kind==="video"&&l.length>0&&this._setCodecs(d,l)})}else typeof this.instance.addTrack=="function"?(r.forEach(c=>{c.kind==="audio"&&(this.options.userVariables.microphoneLabel=c.label),c.kind==="video"&&(this.options.userVariables.cameraLabel=c.label),this.instance.addTrack(c,n)}),this.instance.getTransceivers().forEach(c=>{c.receiver.track.kind==="audio"&&a.length>0&&this._setCodecs(c,a),c.receiver.track.kind==="video"&&l.length>0&&this._setCodecs(c,l)})):this.instance.addStream(n);s===!1&&ms(i,n)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});y.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=Th(this.options.preferred_codecs);r.length>0&&this._setCodecs(o,r)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation().catch(o=>this._emitNegotiationError(o)),this._logTransceivers()})}_getSenderByKind(e){return this.instance.getSenders().find(({track:i})=>i&&i.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const i=this.instance.addTransceiver(e);y.info("Add transceiver",e,i)}}_createOffer(){return V(this,void 0,void 0,function*(){if(this._isOffer()||this.isIceRestarting){this._constraints.offerToReceiveAudio=this.options.audio!==!1||!!this.options.receiveOnlyAudio,this._constraints.offerToReceiveVideo=!!this.options.video,y.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark(re(this.options.id,"create-offer")),yield this._setLocalDescription(e),performance.mark(re(this.options.id,"set-local-description")),performance.mark(re(this.options.id,"ice-gathering-started")),this._isTrickleIce()||this._sdpReady(),e}catch(e){throw y.error("Peer _createOffer error:",e),e instanceof Vt?e:ne(My,e)}}})}_setRemoteDescription(e){return V(this,void 0,void 0,function*(){y.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(i){throw y.error("Peer _setRemoteDescription error:",i),ne(Bu,i)}})}_createAnswer(){return V(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return y.debug("Skipping negotiation, state:",this.instance.signalingState),y.debug(" - But the signaling state isn't stable, so triggering rollback"),void(yield Promise.all([this.instance.setLocalDescription({type:"rollback"}),this.instance.setRemoteDescription({sdp:this.options.remoteSdp,type:Fe.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark(re(this.options.id,"create-answer")),yield this._setLocalDescription(e),performance.mark(re(this.options.id,"set-local-description")),performance.mark(re(this.options.id,"ice-gathering-started")),e}catch(e){throw y.error("Peer _createAnswer error:",e),e instanceof Vt?e:ne(Py,e)}}})}_setLocalDescription(e){return V(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(i){throw y.error("Peer _setLocalDescription error:",i),ne(Ny,i)}})}_sdpReady(){Ri(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return V(this,void 0,void 0,function*(){if(vn(this.options.localStream))return this.options.localStream;const e=yield(i=this.options,V(void 0,void 0,void 0,function*(){let{audio:n=!0,micId:s,video:o=!1,camId:r}=i;const{micLabel:a="",camLabel:l=""}=i;return s&&(s=yield _s(s,a,yt.AudioIn).catch(()=>null),s&&(typeof n=="boolean"&&(n={}),n.deviceId={exact:s})),r&&(r=yield _s(r,l,yt.Video).catch(()=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:n,video:o}}));var i;return vs(e)})}_isOffer(){return this.type===Fe.Offer}_isAnswer(){return this.type===Fe.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:i,iceServers:n}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:n,iceTransportPolicy:i?"relay":"all"};return y.info("RTC config",s),s}restartStatsReporter(){return V(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?y.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(y.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):y.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return V(this,void 0,void 0,function*(){Fr(this.options.id),this.finishIceRestart(),this._clearIceGatheringSafetyTimeout(),this._sleepWakeupIntervalId!==null&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)})}}ii.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,ii.ICE_RESTART_TIMEOUT_MS=15e3;const ws=Dr;class Ah{constructor(e,i){this.session=e,this._callReportCollector=null,this._callRecorder=null,this._mediaDeviceCollector=null,this.id="",this.recoveredCallId="",this.state=W[W.New],this.prevState="",this.channels=[],this.role=Ar.Participant,this.extension=null,this._state=W.New,this._prevState=W.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!1,this._desiredAudioMuted=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1,this._isRecovering=!1,this._wasHeldBeforeRecovery=!1,this._checkConferenceSerno=b=>{const w=b<0||!this._lastSerno||this._lastSerno&&b===this._lastSerno+1;return w&&b>=0&&(this._lastSerno=b),w},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(b=>{b.forEach(w=>{this._statsBindings.forEach(C=>{if(C.callback){if(C.constraints){for(const k in C.constraints)if(C.constraints.hasOwnProperty(k)&&C.constraints[k]!==w[k])return}C.callback(w)}})})})};const{iceServers:n,speaker:s,micId:o,micLabel:r,camId:a,camLabel:l,localElement:c,remoteElement:u,options:d,mediaConstraints:{audio:h,video:p},ringtoneFile:_,ringbackFile:v}=e;this.options=Object.assign({},N0,{audio:h,video:p,iceServers:i!=null&&i.iceServers&&Array.isArray(i.iceServers)?i.iceServers:n,localElement:c,remoteElement:u,micId:o,micLabel:r,camId:a,camLabel:l,speakerId:s,ringtoneFile:_,ringbackFile:v,debug:d.debug,debugOutput:d.debugOutput,trickleIce:d.trickleIce,prefetchIceCandidates:d.prefetchIceCandidates,forceRelayCandidate:d.forceRelayCandidate,keepConnectionAliveOnSocketClose:d.keepConnectionAliveOnSocketClose,mutedMicOnStart:d.mutedMicOnStart},i),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.bind(this),this._onPeerConnectionSignalingStateClosed=this._onPeerConnectionSignalingStateClosed.bind(this),this._onTrickleIceSdp=this._onTrickleIceSdp.bind(this),this._registerPeerEvents=this._registerPeerEvents.bind(this),this._desiredAudioMuted=!!this.options.mutedMicOnStart,this.options.applyDesiredAudioMuteState=this._applyDesiredAudioMuteState.bind(this),this._init(),this.options&&(this._ringtone=wh(this.options.ringtoneFile,"_ringtone"),this._ringback=wh(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}_captureHangupCallerStack(){const e=new Error("Call.hangup caller").stack;return e?e.split(`
116
116
  `).map(i=>i.trim()).filter(Boolean).slice(1,11):[]}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}get isVideoCall(){return!!this.options.video}get telnyxIDs(){return{telnyxCallControlId:this.options.telnyxCallControlId,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId}}get localStream(){return this.options.localStream}get remoteStream(){return this.options.remoteStream}get memberChannel(){return`conference-member.${this.id}`}get isAudioMuted(){return this._desiredAudioMuted}_getLocalAudioTrackId(){var e,i;return(i=(e=this.options.localStream)===null||e===void 0?void 0:e.getAudioTracks()[0])===null||i===void 0?void 0:i.id}_hasActiveUnmutedLocalAudioTrack(){const e=this.options.localStream;return!!(e!=null&&e.getAudioTracks)&&e.getAudioTracks().some(i=>i.enabled===!0&&i.muted!==!0&&i.readyState==="live")}shouldForceRelayCandidateForRecovery(){var e,i;return!this.options.forceRelayCandidate&&!!this.recoveredCallId&&(i=(e=this._callReportCollector)===null||e===void 0?void 0:e.shouldForceRelayCandidateForRecovery())!==null&&i!==void 0&&i}invite(){return V(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=_t.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(re(this.id,"new-peer")),this.peer=new ii(Fe.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){y.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const i=e instanceof Vt?e:ne($u,e instanceof Error?e:void 0);return B(P.Error,{error:i,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void this.hangup({initiator:"sdk:peer-init-failed"},!1)}this._creatingPeer=!1})}answer(e={}){var i,n,s,o,r,a,l,c;return V(this,void 0,void 0,function*(){const u=((s=(n=(i=this.session).getActiveCalls)===null||n===void 0?void 0:n.call(i))!==null&&s!==void 0?s:[]).filter(d=>d.id!==this.id);if(u.length>0&&y.debug(`[${this.id}] answer(): answering inbound call while ${u.length} other active call(s) exist in session ${this.session.sessionid}`),this._creatingPeer||((o=this.peer)===null||o===void 0?void 0:o.instance)&&this.peer.instance.signalingState!=="closed"){const d=Ne(r0);return B(P.Warning,{warning:d,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void y.warn(`[${this.id}] answer() ignored: peer connection already exists or is being created (signalingState: ${(l=(a=(r=this.peer)===null||r===void 0?void 0:r.instance)===null||a===void 0?void 0:a.signalingState)!==null&&l!==void 0?l:"creating"})`)}if(this._registerInboundAnswerAttempt()){performance.mark(re(this.id,"answer-called")),this._creatingPeer=!0,this.stopRingtone(),this.direction=_t.Inbound,((c=e==null?void 0:e.customHeaders)===null||c===void 0?void 0:c.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),e.remoteElement===void 0&&e.localElement===void 0||(this.options=Object.assign(Object.assign(Object.assign({},this.options),e.remoteElement!==void 0&&{remoteElement:e.remoteElement}),e.localElement!==void 0&&{localElement:e.localElement})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(re(this.id,"new-peer")),this.peer=new ii(Fe.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(d){y.error("Peer init failed, aborting call",d),this._creatingPeer=!1;const h=d instanceof Vt?d:ne($u,d instanceof Error?d:void 0);return B(P.Error,{error:h,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void(yield this.hangup({initiator:"sdk:peer-init-failed"},!0))}this._creatingPeer=!1}})}playRingtone(){Sh(this._ringtone)}stopRingtone(){Ch(this._ringtone)}playRingback(){Sh(this._ringback)}stopRingback(){Ch(this._ringback)}hangup(e,i){var n,s,o,r,a,l;return V(this,void 0,void 0,function*(){const c=e||{},u=i!==!1,d=this.state,h=this.prevState,p=this._captureHangupCallerStack(),_=c.initiator||"app:call.hangup",v=this._state<W.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=c.cause||v.cause,this.causeCode=c.causeCode||v.causeCode,this.sipCode=c.sipCode||null,this.sipReason=c.sipReason||null,this.sipCallId=c.sip_call_id||null,this.options.customHeaders=[...(n=this.options.customHeaders)!==null&&n!==void 0?n:[],...(o=(s=c==null?void 0:c.dialogParams)===null||s===void 0?void 0:s.customHeaders)!==null&&o!==void 0?o:[]],y.debug(`[${this.id}] hangup() invoked`,{callId:this.id,execute:u,state:d,prevState:h,cause:this.cause,causeCode:this.causeCode,initiator:_,sipCode:this.sipCode,sipReason:this.sipReason,sipCallId:this.sipCallId,isRecovering:!!c.isRecovering,hasDialogCustomHeaders:!!(!((a=(r=c.dialogParams)===null||r===void 0?void 0:r.customHeaders)===null||a===void 0)&&a.length),callerStack:p}),c.isRecovering)return this._isRecovering=!0,this.setState(W.Recovering),void this._finalize();if(this.setState(W.Hangup),this.stopRingtone(),this.stopRingback(),u){const b=new W0({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});let w;try{yield Promise.race([this._execute(b),new Promise(C=>{w=setTimeout(()=>{y.warn(`[${this.id}] BYE execution timed out after 5000ms — proceeding to destroy.`),C()},5e3)})])}catch(C){y.error("telnyx_rtc.bye failed!",C);const k=ne(jy,C);B(P.Error,{error:k,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}finally{w&&clearTimeout(w)}}y.debug(`[${this.id}] Closing peer from hangup`),(l=this.peer)===null||l===void 0||l.close(),this.setState(W.Destroy)})}hold(){const e=new ps({sessid:this.session.sessionid,action:Ai.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new ps({sessid:this.session.sessionid,action:Ai.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new ps({sessid:this.session.sessionid,action:Ai.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const i=new mh({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(i)}message(e,i){const n={from:this.session.options.login,to:e,body:i},s=new mh({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(s)}muteAudio(){y.debug("muteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!0,ys(this.options.localStream)}unmuteAudio(){y.debug("unmuteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!1,Nr(this.options.localStream)}_applyDesiredAudioMuteState(){y.debug("applyDesiredAudioMuteState called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted?ys(this.options.localStream):Nr(this.options.localStream)}toggleAudioMute(){y.debug("toggleAudioMute called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!this._desiredAudioMuted,this._applyDesiredAudioMuteState()}setAudioInDevice(e,i=this._desiredAudioMuted){var n,s,o;return V(this,void 0,void 0,function*(){const r=!!i,{instance:a}=this.peer,l=a.getSenders().find(({track:{kind:h}})=>h==="audio");if(!l)return y.warn("Skipping audio input device change: no audio sender found",{callId:this.id,deviceId:e,audioMuted:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),void B(P.Warning,{warning:Ne(l0),callId:this.id,deviceId:e,sessionId:this.session.sessionid},((n=this.options)===null||n===void 0?void 0:n.id)||this.id);let c;y.debug("Starting audio input device change",{callId:this.id,state:this.state,deviceId:e,previousDesiredAudioMuted:this._desiredAudioMuted,newDesiredMuted:r,currentSenderTrack:Or(l.track),localTracks:bh(this.options.localStream)});try{c=yield gs({audio:{deviceId:{exact:e}}})}catch(h){const p=ne(Ii(h),h);return void B(P.MediaError,p,((s=this.options)===null||s===void 0?void 0:s.id)||this.id)}const u=c.getAudioTracks()[0];u.enabled=!r;try{yield l.replaceTrack(u)}catch(h){const p=ne(Ii(h),h);return B(P.MediaError,p,((o=this.options)===null||o===void 0?void 0:o.id)||this.id),void c.getTracks().forEach(_=>_.stop())}this._desiredAudioMuted=r,this.options.micId=e;const{localStream:d}=this.options;d.getAudioTracks().forEach(h=>h.stop()),d.getVideoTracks().forEach(h=>c.addTrack(h)),this.options.localStream=c,y.debug("Finished audio input device change",{callId:this.id,state:this.state,deviceId:e,desiredAudioMuted:this._desiredAudioMuted,senderTrack:Or(l.track),localTracks:bh(this.options.localStream)})})}muteVideo(){var e;e=this.options.localStream,Oi(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Oi(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Oi(e,"video",null)}setVideoDevice(e){return V(this,void 0,void 0,function*(){const{instance:i}=this.peer,n=i.getSenders().find(({track:{kind:s}})=>s==="video");if(n){const s=yield gs({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];n.replaceTrack(o);const{localElement:r,localStream:a}=this.options;ms(r,s),this.options.camId=e,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s,this._applyDesiredAudioMuteState()}})}deaf(){ys(this.options.remoteStream)}undeaf(){Nr(this.options.remoteStream)}toggleDeaf(){var e;e=this.options.remoteStream,Oi(e,"audio",null)}setBandwidthEncodingsMaxBps(e,i){return V(this,void 0,void 0,function*(){if(!this||!this.peer)return void y.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:n}=this.peer,s=n.getSenders();if(!s)return void y.error("Could not set bandwidth (reason: no senders). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const o=s.find(({track:{kind:r}})=>r===i);if(o){const r=o.getParameters();r.encodings||(r.encodings=[{rid:"h"}]),y.info("Parameters: ",r),y.info("Setting max ",i==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{y.info(i==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>y.error(a))}else y.error("Could not set bandwidth (reason: no "+i+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")})}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}_isTerminatingOrTerminated(){return[W.Hangup,W.Destroy,W.Purge].includes(this._state)}getStats(e,i){if(!e)return;const n={callback:e,constraints:i};this._statsBindings.push(n),!this._statsIntervalId&&this._startStats(2e3)}setState(e){var i,n,s,o,r,a,l;switch(this._prevState=this._state,this._state=e,this.state=W[this._state].toLowerCase(),this.prevState=W[this._prevState].toLowerCase(),y.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:st.callUpdate,call:this}),e){case W.Purge:y.info(`[${this.id}] Entering Purge state.`);break;case W.Active:if(performance.mark(re(this.id,"call-active")),(i=this.peer)===null||i===void 0||i.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,y.debug(`[${this.id}] Recovery complete, call is active`)),this._wasHeldBeforeRecovery&&(y.debug(`[${this.id}] Cleared held-before-recovery intent on transition to Active`),this._wasHeldBeforeRecovery=!1),(n=this._callReportCollector)===null||n===void 0||n.setHeld(!1),this.session.startSignalingHealthMonitor(),setTimeout(()=>{const{remoteElement:c,speakerId:u}=this.options;c&&u&&_h(c,u)},0),this._callReportCollector&&!((s=this.peer)===null||s===void 0)&&s.instance&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance),this._callRecorder){const c=(o=this.session.connection)===null||o===void 0?void 0:o.host;c&&this._callRecorder._setHost(c),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const u=(r=this.options.localStream)===null||r===void 0?void 0:r.getAudioTracks()[0],d=(a=this.options.remoteStream)===null||a===void 0?void 0:a.getAudioTracks()[0];this._callRecorder.start(u,d)}this._mediaDeviceCollector=new ib,this._mediaDeviceCollector.logDevicesAtStart();break;case W.Held:(l=this._callReportCollector)===null||l===void 0||l.setHeld(!0);break;case W.Destroy:this._finalize()}}handleMessage(e){const{method:i,params:n}=e;switch(i){case Z.Answer:if(performance.mark(re(this.id,"telnyx-rtc-answer")),this.gotAnswer=!0,n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id),this._state>=W.Active)return;this._state>=W.Early&&this.setState(W.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case Z.Media:if(performance.mark(re(this.id,"telnyx-rtc-media")),this._state>=W.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case Z.Display:{const{display_name:o,display_number:r,display_direction:a}=n;this.extension=r;const l=a===_t.Inbound?_t.Outbound:_t.Inbound,c={type:st[i],call:this,displayName:o,displayNumber:r,displayDirection:l};B(P.Notification,c,this.id)||B(P.Notification,c,this.session.uuid);break}case Z.Candidate:this._addIceCandidate(n);break;case Z.Info:case Z.Event:{const o=Object.assign(Object.assign({},n),{type:st.generic,call:this});B(P.Notification,o,this.id)||B(P.Notification,o,this.session.uuid);break}case Z.Ringing:performance.mark(re(this.id,"ringing")),this.playRingback(),n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id);break;case Z.Bye:const s=n.client_state||n.clientState;s&&(this.options.clientState=s),this.stopRingback(),this.stopRingtone(),this.hangup(Object.assign(Object.assign({},n),{initiator:"remote:telnyx_rtc.bye"}),!1)}}handleConferenceUpdate(e,i){return V(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==i.laName)return y.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:n,data:s,hashKey:o=String(this._lastSerno),arrIndex:r}=e;switch(n){case"bootObj":{this._lastSerno=0;const{chatChannel:a,infoChannel:l,modChannel:c,laName:u,conferenceMemberID:d,role:h}=i;this._dispatchConferenceUpdate({action:Ye.Join,conferenceName:u,participantId:Number(d),role:h}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l));const p=[];for(const _ in s)p.push(Object.assign({callId:s[_][0],index:Number(_)},cs(s[_][1])));this._dispatchConferenceUpdate({action:Ye.Bootstrap,participants:p});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:Ye.Add,callId:o,index:r},cs(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:Ye.Modify,callId:o,index:r},cs(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:Ye.Delete,callId:o,index:r},cs(s)));break;case"clear":this._dispatchConferenceUpdate({action:Ye.Clear});break;default:this._dispatchConferenceUpdate({action:n,data:s,callId:o,index:r})}})}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const i=this.session.relayProtocol;this.session._existsSubscription(i,e)&&(this.session.subscriptions[i][e]=Object.assign(Object.assign({},this.session.subscriptions[i][e]),{callId:this.id}))}_subscribeConferenceChat(e){return V(this,void 0,void 0,function*(){const i={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:o,from:r,fromDisplay:a,message:l,type:c}=s.data;this._dispatchConferenceUpdate({action:Ye.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},n=yield this.session.vertoSubscribe(i).catch(s=>{y.error("ConfChat subscription error:",s)});Mr(n,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(s,o)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:s,type:o}})}}}))})}_subscribeConferenceInfo(e){return V(this,void 0,void 0,function*(){const i={nodeId:this.nodeId,channels:[e],handler:s=>{const{eventData:o}=s;o.contentType==="layout-info"?(o.callID=this.id,kh(this.session,o)):y.error("Conference-Info unknown contentType",s)}},n=yield this.session.vertoSubscribe(i).catch(s=>{y.error("ConfInfo subscription error:",s)});Mr(n,e)&&this._addChannel(e)})}_confControl(e,i={}){const n=Object.assign({application:"conf-control",callID:this.id,value:null},i);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:n})}_handleChangeHoldStateSuccess(e){return e.holdState==="active"?this.setState(W.Active):this.setState(W.Held),!0}_handleChangeHoldStateError(e){y.error(`Failed to ${e.action} on call ${this.id}`);const i=ne(Vy,e);return B(P.Error,{error:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e,i={}){const n=new ps(Object.assign(Object.assign({sessid:this.session.sessionid,action:Ai.UpdateMedia,callID:this.options.id,sdp:e},i.trickle?{trickle:!0}:{}),{dialogParams:this.options}));y.info(`ICE restart: sending ${i.trickle?"trickle ":""}Modify with new offer SDP`),this._execute(n).then(s=>V(this,void 0,void 0,function*(){var o;s!=null&&s.sdp?(y.info("ICE restart Modify response received"),(o=this.peer)===null||o===void 0||o.finishIceRestart(),yield this._onRemoteSdp(s.sdp)):this._onIceRestartFailed("ICE restart Modify response missing SDP")})).catch(s=>{this._onIceRestartFailed("ICE restart Modify failed",s)})}_onIceRestartFailed(e,i){var n,s,o;y.error(e,i),(n=this.peer)===null||n===void 0||n.finishIceRestart();const r=ne(Ky,i);B(P.Error,{error:r,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),(o=(s=this.session).reportIceRestartFailed)===null||o===void 0||o.call(s,this.id)}_onRemoteSdp(e){return V(this,void 0,void 0,function*(){const i=new RTCSessionDescription({sdp:e,type:Fe.Answer});yield this.peer.instance.setRemoteDescription(i).then(()=>{performance.mark(re(this.id,"set-remote-description")),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(W.Early),this.gotAnswer&&this._state!==W.Held&&this.setState(W.Active)}).catch(n=>V(this,void 0,void 0,function*(){y.error("Call setRemoteDescription Error: ",n);const s=ne(Bu,n);B(P.Error,{error:s,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:set-remote-description-failure"},!0)}catch(o){y.error("Error during hangup after setRemoteDescription failure:",o)}}))})}_requestAnotherLocalDescription(){if(Ri(this.peer.onSdpReadyTwice)){const e=ne(br,new Error("SDP without candidates for the second time!"));B(P.Error,{error:e,sessionId:this.session.sessionid},this.session.uuid)}else Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this.peer.iceDone=!1,this.peer.startNegotiation()}_onIceSdp(e){var i,n,s;if(this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this.peer&&(this.peer.iceDone=!0),!e)return void y.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:o,type:r}=e;if(o.indexOf("candidate")===-1)return y.info(`No candidate - retry
117
117
  `),void this._requestAnotherLocalDescription();if((n=(i=this.peer)===null||i===void 0?void 0:i.instance)===null||n===void 0||n.removeEventListener("icecandidate",this._onIce),!v0.test(o)){const c=Ne(o0);y.warn(`[${this.id}] Warning ${c.code}: ${c.message}`),B(P.Warning,{warning:c,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}performance.mark(re(this.id,"ice-gathering-end"));let a=null;const l={sessid:this.session.sessionid,sdp:o,dialogParams:this.options,"User-Agent":`Web-${ws}`};if(!((s=this.peer)===null||s===void 0)&&s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case Fe.Offer:this.setState(W.Requesting),a=new fh(l);break;case Fe.Answer:this._isRecovering||this.setState(W.Answering),a=this.options.attach===!0?new gh(l):new ph(l);break;default:return y.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(re(this.id,"send-sdp")),this._execute(a).then(c=>{if(this._isTerminatingOrTerminated())return void y.debug(`[${this.id}] Ignoring ${r} response because call is ${this.state}`);const{node_id:u=null}=c;this._targetNodeId=u,r===Fe.Offer?this.setState(W.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(W.Held):this.setState(W.Active)}).catch(c=>V(this,void 0,void 0,function*(){y.error(`${this.id} - Sending ${r} error:`,c);const u=ne(br,c);B(P.Error,{error:u,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:sdp-send-failure"},!0)}catch(d){y.error("Error during hangup after SDP send failure:",d)}}))}}_onTrickleIceSdp(e){var i;if(!e)return y.error("No SDP data provided"),void this.hangup({initiator:"sdk:missing-local-sdp"},!1);const{sdp:n,type:s}=e;let o=null;const r={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${ws}`};if(!((i=this.peer)===null||i===void 0)&&i.isIceRestarting)this._sendIceRestartModify(n,{trickle:!0});else{switch(s){case Fe.Offer:this.setState(W.Requesting),o=new fh(r);break;case Fe.Answer:this._isRecovering||this.setState(W.Answering),o=this.options.attach===!0?new gh(r):new ph(r);break;default:return y.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(re(this.id,"send-sdp")),this._execute(o).then(a=>{if(this._isTerminatingOrTerminated())return void y.debug(`[${this.id}] Ignoring ${s} response because call is ${this.state}`);const{node_id:l=null}=a;this._targetNodeId=l,s===Fe.Offer?this.setState(W.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(W.Held):this.setState(W.Active)}).catch(a=>V(this,void 0,void 0,function*(){y.error(`${this.id} - Sending ${s} error:`,a);const l=ne(br,a);B(P.Error,{error:l,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:sdp-send-failure"},!0)}catch(c){y.error("Error during hangup after SDP send failure:",c)}}))}}_onIce(e){var i;const{instance:n}=this.peer;if(this._iceTimeout===null){const s=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),s)}e.candidate?(y.debug("RTCPeer Candidate:",e.candidate),(i=this.peer)===null||i===void 0||i.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate)):this._onIceSdp(n.localDescription)}_onTrickleIce(e){var i;e.candidate&&e.candidate.candidate?(y.debug("RTCPeer Candidate:",e.candidate),(i=this.peer)===null||i===void 0||i.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const i=new G0({sessid:this.session.sessionid,candidate:e.candidate,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,dialogParams:this.options});this._execute(i)}_addIceCandidate(e){if(!this._isRemoteDescriptionSet)return y.debug("Remote description not set. Queued ICE candidate.",e),void this._pendingIceCandidates.push(e);this._addIceCandidateToPeer(e)}_addIceCandidateToPeer(e){const i=this.peer.instance.addIceCandidate(e);Promise.resolve(i).then(()=>{y.debug("Successfully added ICE candidate:",e)}).catch(n=>{y.error("Failed to add ICE candidate:",n,e)})}_sendEndOfCandidates(){const e=new q0({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var i;if(this._firstCandidateSent||(performance.mark(re(this.id,"first-candidate")),this._firstCandidateSent=!0),!this._firstNonHostCandidateSent){const n=(i=e.candidate.match(/typ (\w+)/))===null||i===void 0?void 0:i[1];n&&n!=="host"&&(performance.mark(re(this.id,"first-non-host-candidate")),this._firstNonHostCandidateSent=!0)}}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach(i=>{this._addIceCandidateToPeer(i)})}_registerPeerEvents(e){e.onicecandidate=i=>{var n;this.options.trickleIce?this._onTrickleIce(i):!((n=this.peer)===null||n===void 0)&&n.iceDone||this._onIce(i)},e.onicegatheringstatechange=i=>{y.debug("ICE gathering state changed:",e.iceGatheringState,i),e.iceGatheringState==="complete"&&(y.debug("Finished gathering candidates"),performance.mark(re(this.id,"ice-gathering-completed")))},e.onicecandidateerror=i=>{var n;if(y.debug("ICE candidate error:",i),(n=this.peer)===null||n===void 0?void 0:n.statsReporter){const s=function(o,r){var a,l;return{errorCode:o.errorCode,errorText:o.errorText,url:o.url,address:o.address,port:o.port,connectionState:r.connectionState,iceConnectionState:r.iceConnectionState,iceGatheringState:r.iceGatheringState,signalingState:r.signalingState,localDescriptionType:(a=r.localDescription)===null||a===void 0?void 0:a.type,remoteDescriptionType:(l=r.remoteDescription)===null||l===void 0?void 0:l.type}}(i,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",i=>{this.options.remoteStream=i.stream}),e.addEventListener("track",i=>{this.options.remoteStream=i.streams[0];const{remoteElement:n,remoteStream:s,screenShare:o}=this.options;o===!1&&ms(n,s,{callId:this.id,sessionId:this.session.sessionid,eventTarget:this.session.uuid})})}_onMediaError(e){const i=(e==null?void 0:e.name)||"UnknownError",n=(e==null?void 0:e.message)||"Unknown media error",s=(e==null?void 0:e.originalError)||e;this._dispatchNotification({type:st.userMediaError,error:s,call:this,errorName:i,errorMessage:n}),y.error(`Media error (${i}): ${n}`,e),B(P.Error,{error:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),this.hangup({initiator:"sdk:media-error"},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:st.peerConnectionFailureError,error:e.error}),y.error("Peer connection failure error"),e.warning&&B(P.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:st.signalingStateClosed},e)),y.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:st.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(B(P.Notification,e,this.id,!1)||B(P.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_registerInboundAnswerAttempt(){var e;if(this.options.attach||this._isRecovering)return!0;const i=(e=this.session.calls)===null||e===void 0?void 0:e[this.id];if(i&&i!==this){const n=Ne(d0);return B(P.Warning,{warning:n,callId:this.id,activeCallId:i.id,sessionId:this.session.sessionid},this.session.uuid),y.warn(`[${this.id}] answer() ignored: callID ${this.id} already has an active call (${i.id})`),!1}return!0}_init(){var e,i,n,s,o,r,a,l,c,u;const{id:d,userVariables:h,remoteCallerNumber:p,onNotification:_,recoveredCallId:v,wasHeldBeforeRecovery:b}=this.options;var w;this.options.id=d?d.toString():ki(),this.id=this.options.id,v&&(this.recoveredCallId=v,this._isRecovering=!0,this._wasHeldBeforeRecovery=!!b),h&&(w=h,Object.keys(w).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),p||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Ut(P.MediaError,this._onMediaError,this.id),Ut(P.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Ut(P.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Ri(_)&&Ut(P.Notification,_.bind(this),this.id);const C=this.session.options.enableCallReports!==!1,k=this.session.options.callReportInterval||5e3,L=(e=this.session.options.callReportFlushInterval)!==null&&e!==void 0?e:18e4,R=this.session.options.debugLogLevel||"debug",O=this.session.options.debugLogMaxEntries||1e3;if(C&&(this._callReportCollector=new le({enabled:!0,interval:k,intermediateReportInterval:L},{enabled:!0,level:R,maxEntries:O}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=T=>{var E,g,m,f;B(P.Warning,{warning:T,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),T.code===Cr&&this._state!==W.Held?(g=(E=this.session).reportNoRtp)===null||g===void 0||g.call(E,this.id,"inbound"):T.code===Wu&&this._state!==W.Held&&this._hasActiveUnmutedLocalAudioTrack()&&((f=(m=this.session).reportNoRtp)===null||f===void 0||f.call(m,this.id,"outbound"))}),this.session.options.enableCallRecording===!0){const T={enabled:!0,flushIntervalMs:(i=this.session.options.callRecordingFlushIntervalMs)!==null&&i!==void 0?i:15e3,maxBufferBytes:(n=this.session.options.callRecordingMaxBufferBytes)!==null&&n!==void 0?n:rh,sampleRate:(s=this.session.options.callRecordingSampleRate)!==null&&s!==void 0?s:48e3,tracks:(o=this.session.options.callRecordingTracks)!==null&&o!==void 0?o:["local","remote"],endpoint:(r=this.session.options.callRecordingEndpoint)!==null&&r!==void 0?r:"/call_recording"},E={callId:this.id,callReportId:(a=this.session.callReportId)!==null&&a!==void 0?a:"",voiceSdkId:this._getCallReportVoiceSdkId()};this._callRecorder=new je(T,E);const g=(l=this.session.connection)===null||l===void 0?void 0:l.host;g&&this._callRecorder._setHost(g),this._callRecorder.onWarning=m=>{B(P.Warning,{warning:m,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}this._isRecovering?this.setState(W.Recovering):this.setState(W.New),y.info(`New Call — region: ${(c=this.session.region)!==null&&c!==void 0?c:"unknown"}, dc: ${(u=this.session.dc)!==null&&u!==void 0?u:"unknown"}`,this.options)}_finalize(){var e,i,n;this._stopStats(),(e=this._mediaDeviceCollector)===null||e===void 0||e.stop(),this._mediaDeviceCollector=null,(i=this._callRecorder)===null||i===void 0||i.stop(),Fr(this.id),y.debug(`[${this.id}] Closing peer from _finalize`),(n=this.peer)===null||n===void 0||n.close();const{remoteStream:s,localStream:o,remoteElement:r,localElement:a}=this.options;_n(s),_n(o),vh(r,s),vh(a,o),bt(P.MediaError,null,this.id),bt(P.PeerConnectionFailureError,null,this.id),bt(P.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id];const l=this._postCallReport().catch(c=>{y.error("Unexpected error in _postCallReport",{error:c})});this.session.trackCallReportUpload(l)}_getCallReportVoiceSdkId(){return this.session.callReportVoiceSdkId||void 0}_getClientSummary(){var e,i,n,s,o,r,a,l,c,u,d,h;const p=this.session.options,_=p.anonymous_login;return{authentication:Object.assign({type:this._getAuthenticationType()},_?{anonymousLogin:{targetType:_.target_type,targetId:_.target_id,targetVersionId:_.target_version_id,targetParams:this._sanitizeClientOption(_.target_params)}}:{}),connection:{env:p.env,host:p.host,project:p.project,region:(e=this.session.region)!==null&&e!==void 0?e:p.region,dc:this.session.dc,rtcIp:p.rtcIp,rtcPort:p.rtcPort,autoReconnect:(i=p.autoReconnect)===null||i===void 0||i,maxReconnectAttempts:(n=p.maxReconnectAttempts)!==null&&n!==void 0?n:10,keepConnectionAliveOnSocketClose:(s=p.keepConnectionAliveOnSocketClose)!==null&&s!==void 0&&s,hangupOnBeforeUnload:p.hangupOnBeforeUnload!==!1,useCanaryRtcServer:(o=p.useCanaryRtcServer)!==null&&o!==void 0&&o,skipLastVoiceSdkId:(r=p.skipLastVoiceSdkId)!==null&&r!==void 0&&r,skipTrailing:(a=p.skipTrailing)!==null&&a!==void 0&&a},media:{audio:this._sanitizeClientOption(this.options.audio),video:this._sanitizeClientOption(this.options.video),mutedMicOnStart:(l=this.options.mutedMicOnStart)!==null&&l!==void 0&&l,prefetchIceCandidates:(c=this.options.prefetchIceCandidates)===null||c===void 0||c,forceRelayCandidate:(u=this.options.forceRelayCandidate)!==null&&u!==void 0&&u,trickleIce:(d=this.options.trickleIce)!==null&&d!==void 0&&d,iceServers:this._sanitizeIceServers(this.options.iceServers)},callReports:{enabled:p.enableCallReports!==!1,intervalMs:p.callReportInterval||5e3,flushIntervalMs:(h=p.callReportFlushInterval)!==null&&h!==void 0?h:18e4,debugLogLevel:p.debugLogLevel||"debug",debugLogMaxEntries:p.debugLogMaxEntries||1e3}}}_getAuthenticationType(){const e=this.session.options;return e.anonymous_login?"anonymous_login":e.login_token?"login_token":e.login&&(e.password||e.passwd)?"login_password":e.token?"token":"unknown"}_sanitizeIceServers(e){if(e&&e.length!==0)return e.map(({urls:i,username:n,credential:s})=>({urls:i,hasUsername:!!n,hasCredential:!!s}))}_sanitizeClientOption(e,i=0){if(e!==void 0){if(e===null)return null;if(typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="boolean")return e;if(typeof e!="function"){if(i>=4)return"[truncated]";if(Array.isArray(e))return e.map(n=>this._sanitizeClientOption(n,i+1)).filter(n=>n!==void 0);if(typeof e=="object"){const n=Object.entries(e).filter(([s])=>!this._isSensitiveClientOptionKey(s)).map(([s,o])=>[s,this._sanitizeClientOption(o,i+1)]).filter(s=>s[1]!==void 0);return Object.fromEntries(n)}}}}_isSensitiveClientOptionKey(e){return/(password|passwd|credential|secret|token|authorization|auth|api[_-]?key)/i.test(e)}flushIntermediateCallReport(e={type:"manual"}){this._flushIntermediateReport(e)}_flushIntermediateReport(e={type:"buffer-limit"}){var i;if(!this._callReportCollector)return;const n=this.session.callReportId;if(!n)return void y.debug("Cannot flush intermediate report: call_report_id not available");const s=(i=this.session.connection)===null||i===void 0?void 0:i.host;if(!s)return void y.debug("Cannot flush intermediate report: connection host not available");const o={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===_t.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ws,clientSummary:this._getClientSummary()},r=this._callReportCollector.flush(o,e);if(!r)return;y.info("Flushing intermediate call report",{callId:this.id,flushReason:e,segment:r.segment});const a=this._getCallReportVoiceSdkId(),l=e.type==="page-unload",c=this._callReportCollector.sendPayload(r,n,s,a,l).catch(u=>{y.error("Failed to post intermediate call report segment",{error:u})});this.session.trackCallReportUpload(c)}_postCallReport(){var e,i,n,s;return V(this,void 0,void 0,function*(){if(!this._callReportCollector)return void y.warn("Call report collector not initialized");if(yield this._callReportCollector.stop(),this._callRecorder){this._callRecorder.stop();const c=(e=this.session.connection)===null||e===void 0?void 0:e.host;c&&this._callRecorder._setHost(c),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const u=this._callRecorder.postFinalReport().catch(d=>{y.error("Failed to post final call recording",{error:d})}).finally(()=>{var d;(d=this._callRecorder)===null||d===void 0||d.cleanup()});this.session.trackCallReportUpload(u)}const o=this.session.callReportId;if(!o)return y.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const r={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===_t.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ws,clientSummary:this._getClientSummary()},a=(i=this.session.connection)===null||i===void 0?void 0:i.host;if(!a)return void y.error("Cannot post call report: connection host not available");const l=this._getCallReportVoiceSdkId();try{yield this._callReportCollector.postReport(r,o,a,l)}catch(c){throw y.error("Failed to post call report",{error:c}),c}finally{(n=this._callReportCollector)===null||n===void 0||n.cleanup(),(s=this._callRecorder)===null||s===void 0||s.cleanup()}})}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),y.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),y.debug("Stats stopped")}}Ah.setStateTelnyx=t=>{if(t){switch(t._state){case W.Recovering:t.state="recovering";break;case W.Requesting:case W.Trying:case W.Early:t.state="connecting";break;case W.Active:t.state="active";break;case W.Held:t.state="held";break;case W.Hangup:case W.Destroy:t.state="done";break;case W.Answering:t.state="ringing";break;case W.New:t.state="new"}return t}};class ni extends Ah{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,i)=>this.session.execute(new eb(e,i)),this.sendAIConversationMessage=e=>{if(!this.session.connected)throw new Error("Cannot send AI conversation message: session is not connected. sendAIConversationMessage requires an active WebSocket connection.");const i=new tb(e);this.session.connection.sendRawText(JSON.stringify(i.request))}}hangup(e={},i=!0){const n=Object.create(null,{hangup:{get:()=>super.hangup}});return V(this,void 0,void 0,function*(){this.screenShare instanceof ni&&(yield this.screenShare.hangup(e,i)),yield n.hangup.call(this,e,i)})}startScreenShare(e){return V(this,void 0,void 0,function*(){const i=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;i.getTracks().forEach(c=>{c.addEventListener("ended",()=>V(this,void 0,void 0,function*(){this.screenShare&&(yield this.screenShare.hangup({initiator:"sdk:screenshare-track-ended"}))}))});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:i,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new ni(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return V(this,void 0,void 0,function*(){this.screenShare instanceof ni&&(yield this.screenShare.hangup({initiator:"app:stopScreenShare"}))})}setAudioOutDevice(e){return V(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:i,speakerId:n}=this.options;return!(!i||!n)&&_h(i,n)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>V(this,void 0,void 0,function*(){const i=yield this.peer.instance.getStats(null);let n="";const s=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],o=["id","type","timestamp"];i.forEach(r=>{s.includes(r.type)||(n+=`
118
118
  ${r.type}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@telnyx/ai-agent-widget",
3
3
  "private": false,
4
- "version": "0.34.0",
4
+ "version": "0.34.1",
5
5
  "description": "A widget for Telnyx AI Agent",
6
6
  "type": "module",
7
7
  "author": "Telnyx",
@@ -22,7 +22,7 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@fontsource/inter": "^5.2.6",
25
- "@telnyx/ai-agent-lib": "0.6.0",
25
+ "@telnyx/ai-agent-lib": "0.6.1",
26
26
  "audiomotion-analyzer": "^4.5.1",
27
27
  "clsx": "^2.1.1",
28
28
  "jotai": "^2.12.5",