PageSourceSearch

https://app.voxhealth.ai/assets/LiveTranslateView-v5WMziLT.js

js voxhealth.ai collected 2026-10-05 13:15:16 UTC 302,339 bytes, 9 lines download raw bytes

1import{Ct as B,D as qn,F as Vs,G as $e,J as qs,Jt as J,R as At,T as ke,U as H,V as Gi,Wt as De,_ as le,b as se,et as be,ht as ie,i as Ys,j as Je,jt as Yn,l as Vi,m as xe,o as Ks,rt as Wt,st as Ci,ut as Js,v as L,vt as li,w as Se,x as G,y as zs}from"./vue.runtime.esm-bundler-DYdOdNtL.js";import{t as Qs}from"./client-DPrABKUY.js";import{l as Xs}from"./patients-BWQO6gDt.js";import{Fn as Zs}from"./main-DnpaWVIM.js";import{D as qi,v as pt,y as Yi}from"./format-CDnuUStP.js";import{t as eo}from"./useToast-m1WG9pkD.js";import{t as to}from"./ArrowsRightLeftIcon-dlSljDiY.js";import{t as io}from"./PauseIcon-V8F5Cs_E.js";import{t as no}from"./PhoneArrowDownLeftIcon-BW_bJKw3.js";import{t as Ki}from"./PhoneIcon-CBK_RVNX.js";import{t as so}from"./PlayIcon-B1bQzInh.js";import{t as oo}from"./Squares2X2Icon-C7Hye-1T.js";import{l as Gt,n as ro,t as ao}from"./phoneSeats-BVosUrm-.js";import{i as gt,n as vt,r as lo,t as Ji}from"./liveTranslateLanguages-CZA0aLf3.js";Je();function co(t,e){return H(),G("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24","stroke-width":"1.5",stroke:"currentColor","aria-hidden":"true","data-slot":"icon"},[L("path",{"stroke-linecap":"round","stroke-linejoin":"round",d:"M12 18.75a6 6 0 0 0 6-6v-1.5m-6 7.5a6 6 0 0 1-6-6v-1.5m6 7.5v3.75m-3.75 0h7.5M12 15.75a3 3 0 0 1-3-3V4.5a3 3 0 1 1 6 0v8.25a3 3 0 0 1-3 3Z"})])}Je();function Vt(t,e){return H(),G("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24","stroke-width":"1.5",stroke:"currentColor","aria-hidden":"true","data-slot":"icon"},[L("path",{"stroke-linecap":"round","stroke-linejoin":"round",d:"M15.75 3.75 18 6m0 0 2.25 2.25M18 6l2.25-2.25M18 6l-2.25 2.25m1.5 13.5c-8.284 0-15-6.716-15-15V4.5A2.25 2.25 0 0 1 4.5 2.25h1.372c.516 0 .966.351 1.091.852l1.106 4.423c.11.44-.054.902-.417 1.173l-1.293.97a1.062 1.062 0 0 0-.38 1.21 12.035 12.035 0 0 0 7.143 7.143c.441.162.928-.004 1.21-.38l.97-1.293a1.125 1.125 0 0 1 1.173-.417l4.423 1.106c.5.125.852.575.852 1.091V19.5a2.25 2.25 0 0 1-2.25 2.25h-2.25Z"})])}function Kn(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i}function R(t,e,i,n){return new(i||(i=Promise))((function(s,o){function r(h){try{l(n.next(h))}catch(p){o(p)}}function a(h){try{l(n.throw(h))}catch(p){o(p)}}function l(h){var p;h.done?s(h.value):(p=h.value,p instanceof i?p:new i((function(f){f(p)}))).then(r,a)}l((n=n.apply(t,e||[])).next())}))}var zi=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),uo=new Uint8Array(16);function ho(){if(!zi)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return zi(uo)}for(var Jn=[],ft=0;ft<256;++ft)Jn[ft]=(ft+256).toString(16).substr(1);function qe(t,e,i){var n=e&&i||0;typeof t=="string"&&(e=t==="binary"?new Array(16):null,t=null);var s=(t=t||{}).random||(t.rng||ho)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var o=0;o<16;++o)e[n+o]=s[o];return e||(function(r,a){var l=a||0,h=Jn;return[h[r[l++]],h[r[l++]],h[r[l++]],h[r[l++]],"-",h[r[l++]],h[r[l++]],"-",h[r[l++]],h[r[l++]],"-",h[r[l++]],h[r[l++]],"-",h[r[l++]],h[r[l++]],h[r[l++]],h[r[l++]],h[r[l++]],h[r[l++]]].join("")})(s)}var po={SDP_CREATE_OFFER_FAILED:40001,SDP_CREATE_ANSWER_FAILED:40002,SDP_SET_LOCAL_DESCRIPTION_FAILED:40003,SDP_SET_REMOTE_DESCRIPTION_FAILED:40004,SDP_SEND_FAILED:40005,MEDIA_MICROPHONE_PERMISSION_DENIED:42001,MEDIA_DEVICE_NOT_FOUND:42002,MEDIA_GET_USER_MEDIA_FAILED:42003,HOLD_FAILED:44001,INVALID_CALL_PARAMETERS:44002,BYE_SEND_FAILED:44003,SUBSCRIBE_FAILED:44004,PEER_CLOSED_DURING_INIT:44005,WEBSOCKET_CONNECTION_FAILED:45001,WEBSOCKET_ERROR:45002,RECONNECTION_EXHAUSTED:45003,GATEWAY_FAILED:45004,LOGIN_FAILED:46001,INVALID_CREDENTIALS:46002,AUTHENTICATION_REQUIRED:46003,ICE_RESTART_FAILED:47001,NETWORK_OFFLINE:48001,SESSION_NOT_REATTACHED:48501,UNEXPECTED_ERROR:49001},go={HIGH_RTT:31001,HIGH_JITTER:31002,HIGH_PACKET_LOSS:31003,LOW_MOS:31004,LOW_LOCAL_AUDIO:31005,LOW_INBOUND_AUDIO:31006,LOW_BYTES_RECEIVED:32001,LOW_BYTES_SENT:32002,RECORDING_UNAVAILABLE:32003,RECORDING_BUFFER_OVERFLOW:32004,ICE_CONNECTIVITY_LOST:33001,ICE_GATHERING_TIMEOUT:33002,ICE_GATHERING_EMPTY:33003,PEER_CONNECTION_FAILED:33004,ONLY_HOST_ICE_CANDIDATES:33005,ANSWER_WHILE_PEER_ACTIVE:33006,ICE_CANDIDATE_PAIR_CHANGED:33008,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:33009,MULTIPLE_ACTIVE_CALLS_DETECTED:33010,DUPLICATE_INBOUND_ANSWER:33007,SHARED_REMOTE_ELEMENT_OVERWRITE:33011,TOKEN_EXPIRING_SOON:34001,UNKNOWN_REATTACHED_
1SESSION:35002,SIGNALING_RECOVERY_REQUIRED:36003,MEDIA_RECOVERY_REQUIRED:36004,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:36005},{SDP_CREATE_OFFER_FAILED:vo,SDP_CREATE_ANSWER_FAILED:fo,SDP_SET_LOCAL_DESCRIPTION_FAILED:mo,SDP_SET_REMOTE_DESCRIPTION_FAILED:zn,SDP_SEND_FAILED:Qi,MEDIA_MICROPHONE_PERMISSION_DENIED:Qn,MEDIA_DEVICE_NOT_FOUND:Xn,MEDIA_GET_USER_MEDIA_FAILED:wi,HOLD_FAILED:_o,INVALID_CALL_PARAMETERS:yo,BYE_SEND_FAILED:bo,SUBSCRIBE_FAILED:So,PEER_CLOSED_DURING_INIT:qt,WEBSOCKET_CONNECTION_FAILED:Co,WEBSOCKET_ERROR:wo,RECONNECTION_EXHAUSTED:ci,GATEWAY_FAILED:ko,LOGIN_FAILED:Zn,INVALID_CREDENTIALS:Io,AUTHENTICATION_REQUIRED:Eo,ICE_RESTART_FAILED:To,NETWORK_OFFLINE:Ro,SESSION_NOT_REATTACHED:Xi,UNEXPECTED_ERROR:Zi}=po,{HIGH_RTT:Ao,HIGH_JITTER:Oo,HIGH_PACKET_LOSS:Do,LOW_MOS:en,LOW_LOCAL_AUDIO:mt,LOW_INBOUND_AUDIO:_t,LOW_BYTES_RECEIVED:di,LOW_BYTES_SENT:es,RECORDING_UNAVAILABLE:xo,RECORDING_BUFFER_OVERFLOW:No,ICE_CONNECTIVITY_LOST:Lo,ICE_GATHERING_TIMEOUT:Mo,ICE_GATHERING_EMPTY:Po,PEER_CONNECTION_FAILED:Fo,ONLY_HOST_ICE_CANDIDATES:Uo,ANSWER_WHILE_PEER_ACTIVE:$o,ICE_CANDIDATE_PAIR_CHANGED:jo,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:Bo,MULTIPLE_ACTIVE_CALLS_DETECTED:Ho,DUPLICATE_INBOUND_ANSWER:Wo,SHARED_REMOTE_ELEMENT_OVERWRITE:Go,TOKEN_EXPIRING_SOON:Vo,UNKNOWN_REATTACHED_SESSION:qo,SIGNALING_RECOVERY_REQUIRED:Yo,MEDIA_RECOVERY_REQUIRED:Ko,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:Jo}=go,tn="wss://rtc.telnyx.com",ts={NORMAL_CLOSURE:1e3,GOING_AWAY:1001,PROTOCOL_ERROR:1002,UNSUPPORTED_DATA:1003,NO_STATUS_RECEIVED:1005,ABNORMAL_CLOSURE:1006,INVALID_FRAME_PAYLOAD:1007,POLICY_VIOLATION:1008,MESSAGE_TOO_BIG:1009,INTERNAL_ERROR:1011},is={urls:"stun:stun.l.google.com:19302"},zo={urls:"stun:stun.telnyx.com:3478"},Qo={urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},Xo={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},Zo={urls:"turns:turn.telnyx.com:443",username:"testuser",credential:"testpassword"},er={urls:"turns:turn2.telnyx.com:443",username:"testuser",credential:"testpassword"},tr=[zo,is,Qo,Xo,Zo,er],ir=[{urls:"stun:stundev.telnyx.com:3478"},is,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},{urls:"turns:turndev.telnyx.com:443",username:"testuser",credential:"testpassword"}];var D;(function(t){t.SocketOpen="telnyx.socket.open",t.SocketClose="telnyx.socket.close",t.SocketError="telnyx.socket.error",t.SocketMessage="telnyx.socket.message",t.SpeedTest="telnyx.internal.speedtest",t.SocketActivity="telnyx.internal.socketActivity",t.Ready="telnyx.ready",t.Error="telnyx.error",t.Warning="telnyx.warning",t.Notification="telnyx.notification",t.StatsFrame="telnyx.stats.frame",t.StatsReport="telnyx.stats.report",t.Messages="telnyx.messages",t.Calls="telnyx.calls",t.MediaError="telnyx.rtc.mediaError",t.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError",t.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed",t.AIConversationMessage="telnyx.ai.conversation"})(D||(D={}));var nr={40001:{name:"SDP_CREATE_OFFER_FAILED",message:"Failed to create call offer",description:"The browser was unable to generate a local SDP offer. This typically indicates a WebRTC API error or invalid media constraints.",causes:["Browser WebRTC API error","Missing or invalid media constraints"],solutions:["Check getUserMedia permissions","Verify ICE server configuration"],fatal:!0},40002:{name:"SDP_CREATE_ANSWER_FAILED",message:"Failed to answer the call",description:"The browser was unable to generate a local SDP answer. The remote offer may be invalid or the browser state inconsistent.",causes:["Browser WebRTC API error","Invalid remote SDP offer"],solutions:["Retry the call","Check browser WebRTC compatibility"],fatal:!0},40003:{name:"SDP_SET_LOCAL_DESCRIPTION_FAILED",message:"Failed to apply local call settings",description:"setLocalDescription() was rejected by the browser. The generated SDP may be malformed or the browser state may be inconsistent.",causes:["Malformed SDP","Browser state inconsistency"],solutions:["Retry the call"],fatal:!0},40004:{name:"SDP_SET_REMOTE_DESCRIPTION_FAILED",message:"Failed to apply remote call settings",description:"setRemoteDescription() was rejected by the browser. The remote SDP may be malformed or contain unsupported codecs.",causes:["Malformed remote SDP","Browser codec mismatch"],solutions:["Retry the call","Check codec configuration"],fatal:!0},40005:{name:"SDP_SEND_FAILED",message:"Failed to send call data to server",description:"The Invite or Answer message could not be delivered via the signaling WebSocket. The connection may have been lost.",causes:["WebSocket connection lost","Server error"],solutions:["Check network connectivity","Retry the call"],fatal:!0},42001:{name:"MEDIA_MICROPHONE_PERMISSION_DENIED",message:"Microphone access denied",description:"The user or operating system denied microphone permission. The browser permission prompt was dismissed or OS-level access is disabled.",causes:["User denied browser permission prompt","OS-level microphone access disabled"],solutions:["Ask user to grant microphone permission in browser settings"],fatal:!0},42002:{name:"MEDIA_DEVICE_NOT_FOUND",message:"No microphone found",description:"The requested audio input device is not available. No microphone is connected, the device was disconnected, or an invali
1d deviceId was specified.",causes:["No microphone connected","Device was disconnected","Invalid deviceId"],solutions:["Check that a microphone is connected","Select a valid audio input device"],fatal:!0},42003:{name:"MEDIA_GET_USER_MEDIA_FAILED",message:"Failed to access microphone",description:"getUserMedia() was rejected for an unexpected reason. The device may be in use by another application or the browser encountered an internal error.",causes:["Browser error","Device in use by another application"],solutions:["Close other applications using the microphone","Retry"],fatal:!0},44001:{name:"HOLD_FAILED",message:"Failed to hold the call",description:"The server rejected or did not respond to the hold request. The WebSocket connection may have been lost during the operation.",causes:["Server error","WebSocket connection lost during hold"],solutions:["Retry the hold operation","Check network connectivity"],fatal:!1},44002:{name:"INVALID_CALL_PARAMETERS",message:"Invalid call parameters",description:"The call could not be initiated because required parameters are missing or invalid. For example, no destination number was provided to newCall().",causes:["Missing destinationNumber in call options","Invalid or empty call parameters"],solutions:["Provide a valid destinationNumber when calling newCall()","Check the call options object for required fields"],fatal:!0},44003:{name:"BYE_SEND_FAILED",message:"Failed to hang up cleanly",description:"The hangup signal could not be delivered to the server. The call was terminated locally but the server may not be aware.",causes:["WebSocket connection lost before BYE sent"],solutions:["No action needed — call is terminated locally","Check network connectivity"],fatal:!1},44004:{name:"SUBSCRIBE_FAILED",message:"Failed to subscribe to call events",description:"The Verto subscribe request for the call channel failed. This may prevent receiving call state updates from the server.",causes:["WebSocket connection lost during subscribe","Server rejected the subscription request"],solutions:["Check network connectivity","Retry the call"],fatal:!1},44005:{name:"PEER_CLOSED_DURING_INIT",message:"Call was closed during setup",description:"The PeerConnection was closed (e.g. by hangup()) while peer.init() was still running. This is a race condition: an async operation such as setRemoteDescription, getUserMedia, or the media recovery flow yielded control, and close() ran during that gap. The init() cannot continue because the underlying RTCPeerConnection has been destroyed.",causes:["call.hangup() or call.close() was called while the call was still setting up","A WebSocket Bye message arrived during getUserMedia prompt or SDP negotiation","User clicked hangup/decline before media permissions were granted"],solutions:["This is expected if the user intentionally hung up during setup — no action needed","If this happens frequently without user action, check for automatic hangup triggers that may fire too early"],fatal:!0},45001:{name:"WEBSOCKET_CONNECTION_FAILED",message:"Unable to connect to server",description:"The WebSocket connection to the signaling server could not be established. The server may be unreachable, the URL may be incorrect, or a firewall may be blocking the connection.",causes:["Server unreachable","Incorrect WebSocket URL","Firewall blocking WebSocket connections","Network interruption"],solutions:["Check network connectivity","Verify the signaling server URL","Ensure WebSocket connections are not blocked by a firewall"],fatal:!0},45002:{name:"WEBSOCKET_ERROR",message:"Connection to server lost",description:"An error occurred on the WebSocket connection after it was established. The connection may have been dropped due to network issues or server-side closure.",causes:["Network interruption","Server closed the connection","Idle timeout"],solutions:["Check network connectivity","SDK will attempt automatic reconnection if configured"],fatal:!1},45003:{name:"RECONNECTION_EXHAUSTED",message:"Unable to reconnect to server",description:"All automatic reconnection attempts have been exhausted. The SDK tried to re-establish the WebSocket connection multiple times but failed on every attempt.",causes:["Prolonged network outage","Server unreachable","Firewall or proxy blocking reconnection"],solutions:["Check network connectivity","Call client.disconnect() and client.connect() to manually retry","Notify the user that the connection was lost"],fatal:!0},45004:{name:"GATEWAY_FAILED",message:"Gateway connection failed",description:"The upstream gateway reported a FAILED, FAIL_WAIT, or TIMEOUT state. The signaling server could not establish or maintain a connection to the gateway. When autoReconnect is disabled, this is immediately fatal. When enabled, the SDK will retry until RECONNECTION_EXHAUSTED.",causes:["Gateway down or unreachable","Server-side infrastru
1cture issue","Network partition between signaling server and gateway"],solutions:["Wait for automatic reconnection (if autoReconnect is enabled)","Call client.disconnect() and client.connect() to manually retry","Check Telnyx service status"],fatal:!1},46001:{name:"LOGIN_FAILED",message:"Authentication failed",description:"The login request was rejected by the server. The credentials may be invalid, expired, or the account may be suspended.",causes:["Invalid credentials (username/password or token)","Expired authentication token","Account suspended or disabled"],solutions:["Verify credentials","Generate a new authentication token","Check account status"],fatal:!0},46002:{name:"INVALID_CREDENTIALS",message:"Invalid credential parameters",description:"The SDK rejected the login options before sending any request to the server. This is an internal client-side validation guard — the credentials object is missing required fields or has an invalid structure. No network request was made.",causes:["Missing login and password fields","Missing or malformed authentication token","Invalid combination of credential fields in the options object"],solutions:["Provide valid login/password or a valid authentication token","Check the TelnyxRTC constructor options against the documentation","Ensure the credential object matches one of the supported auth modes (credentials, token, or anonymous)"],fatal:!0},46003:{name:"AUTHENTICATION_REQUIRED",message:"Authentication required",description:"The server rejected a request because the session is not authenticated. This can happen when the client sends a message (e.g. Invite, Subscribe, or Ping) before login completes, after a token expires mid-session, or after the server drops the authenticated state for any reason.",causes:["Message sent before login completed","Authentication token expired during the session","Server-side session was invalidated","WebSocket reconnected but re-authentication did not complete"],solutions:["Ensure the client is fully logged in before sending messages","Re-authenticate using client.login() with fresh credentials","Listen for telnyx.ready before making calls or sending requests"],fatal:!1},47001:{name:"ICE_RESTART_FAILED",message:"ICE restart failed",description:"The ICE restart Modify request could not be sent or the server returned an error. The media path could not be recovered via ICE restart.",causes:["WebSocket connection lost during ICE restart","Server rejected the Modify request","Timeout waiting for server response"],solutions:["The call may recover via WebSocket reconnect + Attach","If the call does not recover, hang up and retry"],fatal:!1},48001:{name:"NETWORK_OFFLINE",message:"Device is offline",description:"The browser reported that the device has lost network connectivity (navigator.onLine === false). All WebSocket and media connections will fail until the network is restored.",causes:["Wi-Fi or ethernet disconnected","Airplane mode enabled","Network interface went down"],solutions:["Check network connectivity","Reconnect to Wi-Fi or ethernet","Disable airplane mode"],fatal:!1},48501:{name:"SESSION_NOT_REATTACHED",message:"Active call lost after reconnect",description:"The WebSocket reconnected successfully but the server did not reattach the active call session. The server no longer knows about the call, so any subsequent call-control operation (hangup, hold, etc.) will fail with CALL_DOES_NOT_EXIST. The call is unrecoverable and must be terminated locally.",causes:["Server-side session expired during the disconnection window","Reconnect token was invalidated","Backend restarted or lost in-memory call state"],solutions:["Terminate the local call and notify the user","Start a new call","Investigate why the session was not preserved on the server"],fatal:!0},49001:{name:"UNEXPECTED_ERROR",message:"An unexpected error occurred",description:"An error was thrown that does not match any known SDK error category. This is a catch-all for unclassified failures.",causes:["Unknown or unhandled error condition"],solutions:["Check the originalError property for the underlying cause","Report the issue if it persists"],fatal:!0}},sr={31001:{name:"HIGH_RTT",message:"High network latency detected",description:"Round-trip time (RTT) exceeded the threshold for multiple consecutive samples. High latency causes perceptible audio delays.",causes:["Poor network connection","Geographic distance to media server","Network congestion"],solutions:["Check network connectivity","Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications"]},31002:{name:"HIGH_JITTER",message:"High jitter detected",description:"Jitter (variability in packet arrival time) exceeded the threshold for multiple consecutive samples. High jitter causes crackling and choppy audio.",causes:["Network congestion","Unstable Wi-Fi connection","Overloaded network equipment"],solutions:["Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications","Check network equipment"]},31003:{name:"HIGH_PACKET_LOSS",message:"High packet loss detected",description:"Packet loss exceeded the threshold for multiple consecutive samples. High packet loss causes choppy audio or dropped calls.",causes:["Network congestion","Unstable connection","Firewall or QoS misconfiguration"],solutions:["Check network connectivity","Use a wired connection","Contact network administrator"]},31004:{name:"LOW_MOS",message:"Low call quality score",description:"Mean Opinion Score (MOS) dropped below the acceptable threshold for multiple consecutive samples. This is a composite indicator of overall call quality.",causes:["Combination of high latency, jitter, and/or packet loss","Poor network conditions"],solutions:["Check network connectivity","Use a wired connection","Close bandwidth-heavy applications"]},31005:{name:"LOW_LOCAL_AUDIO",message:"Low local microphone audio detected",description:"Local outbound audio level stayed below the acceptable threshold before the microphone produced real audio, or stayed silent for a long continuous window after audio was confirmed. This may indicate that the microphone is not capturing enough audio even while RTP is being sent.",causes:["Microphone input level is too low","Wrong microphone selected","Microphone is obstructed or too far from the speaker","Operating system input gain is muted or very low"],solutions:["Check the selected microphone","Increase microphone input gain","Move closer to the microphone","Verify the microphone is not muted at the operating system or hardware level"]},31006:{name:"LOW_INBOUND_AUDIO",message:"Low inbound audio detected",description:"Inbound (remote) audio level stayed below the acceptable threshold for multiple consecutive stats intervals while RTP packets continued to flow. This may indicate the remote party is sending silence or comfort-noise (e.g. one-way audio caused by a media bridge issue), as opposed to LOW_BYTES_RECEIVED which fires when no bytes arrive at all.",causes:["Remote party microphone is muted or capturing very low audio","Media bridge or PBX is injecting comfort-noise/silence instead of forwarding real audio","One
1-way audio where RTP flows but content is silent (server-side media issue)","Remote party is on hold or not speaking"],solutions:["Verify the remote party is not muted and is actively speaking","Check the media bridge / PBX for comfort-noise injection or transcoding issues","Inspect PCAP RTP payload uniqueness to distinguish real audio from comfort-noise","If the issue persists, report the call for server-side media investigation"]},32001:{name:"LOW_BYTES_RECEIVED",message:"No audio data received",description:"No bytes have been received from the remote party for multiple consecutive seconds. This may indicate a network interruption or remote-side issue.",causes:["Network interruption","Remote party microphone issue","Firewall blocking inbound media"],solutions:["Check network connectivity","Ask remote party to check their microphone","Check firewall rules for media ports"]},32002:{name:"LOW_BYTES_SENT",message:"No audio data being sent",description:"No bytes have been sent for multiple consecutive seconds. This may indicate a local microphone issue or network interruption.",causes:["Microphone muted or disconnected","Network interruption","Local media track ended"],solutions:["Check that the microphone is not muted","Verify the microphone is still connected","Check network connectivity"]},32003:{name:"RECORDING_UNAVAILABLE",message:"Call recording is not available in this browser",description:"Call recording was enabled (enableCallRecording is true), but the browser does not support MediaStreamTrackProcessor (required to capture raw audio PCM). Recording is disabled for this call; the call proceeds normally. Currently affects Firefox and older Chromium (< 94).",causes:["Browser does not implement MediaStreamTrackProcessor (Firefox, Safari)","Chromium version older than 94","Recording enabled on an unsupported platform"],solutions:["Use a recent Chromium-based browser (Chrome 94+, Edge 94+) to capture recordings","Disable enableCallRecording if recording is not required for this deployment","See the enableCallRecording JSDoc for platform support details"]},32004:{name:"RECORDING_BUFFER_OVERFLOW",message:"Call recording buffer overflow — oldest packets dropped",description:"The in-memory call recording buffer reached its maxBufferBytes cap before the next scheduled flush. The oldest captured RTP packets were dropped to keep memory bounded. This indicates the flush interval is too long for the call audio rate, or the upload endpoint is slow/unreachable. The recording continues with the remaining (newer) packets.",causes:["Flush interval (callRecordingFlushIntervalMs) is larger than the buffer can hold at the current audio rate","Upload endpoint (/call_recording) is slow or unreachable, so intermediate flushes back up","A very long call with high sample rate filling the buffer between flushes"],solutions:["Reduce callRecordingFlushIntervalMs so flushes happen more frequently","Increase callRecordingMaxBufferBytes if memory headroom allows","Check the /call_recording endpoint health and network path to voice-sdk-proxy"]},33001:{name:"ICE_CONNECTIVITY_LOST",message:"Connection interrupted",description:"The ICE connection transitioned to the disconnected state. The previously selected connection path was lost and renegotiation may be required. The connection may recover automatically.",causes:["Temporary network interruption","Network interface change (e.g. Wi-Fi to cellular)","NAT rebinding"],solutions:["Wait for automatic recovery","Check network connectivity"]},33002:{name:"ICE_GATHERING_TIMEOUT",message:"ICE gathering timed out",description:"ICE candidate gathering did not complete within the safety timeout. This is typically caused by network restrictions blocking STUN/TURN. The call may still succeed if candidates arrive late.",causes:["Firewall blocking STUN/TURN","Network unreachable","STUN/TURN server not responding"],solutions:["Check STUN/TURN server reachability","Ensure UDP traffic is not blocked","Try forceRelayCandidate option"]},33003:{name:"ICE_GATHERING_EMPTY",message:"No ICE candidates gathered",description:"No ICE candidates were gathered after sending the initial SDP. This may indicate a firewall blocking all STUN/TURN traffic or no available network interface.",causes:["Firewall blocking all STUN/TURN traffic","No network interface available","VPN blocking UDP"],solutions:["Check STUN/TURN server reachability","Ensure UDP traffic is not blocked","Use forceRelayCandidate option"]},33004:{name:"PEER_CONNECTION_FAILED",message:"Connection failed",description:"RTCPeerConnection entered the failed state. This is a recoverable condition — the SDK may attempt ICE restart or the connection may recover. If it does not recover, the call will eventually be terminated.",causes:["ICE failure","DTLS handshake failure","Prolonged network interruption"],solutions:["Wait for automatic recovery","Check network connectivity","Verify TURN server credentials"]},33005:{name:"ONLY_HOST_ICE_CANDIDATES",message:"Only local network candidates available",description:"ICE gathering completed with host (local network) candidates only. This is diagnostic evidence that no server-reflexive (srflx), peer-reflexive (prflx), or relay (TURN) candidates were found; connectivity may still succeed, but network traversal options can be limited
vendor: 8,634 bytes, line 1
1.",causes:["STUN/TURN servers unreachable","Firewall blocking UDP traffic to STUN/TURN servers","Incorrect TURN server configuration or credentials","Restrictive corporate network or VPN"],solutions:["Verify STUN/TURN server URLs and credentials","Ensure UDP traffic to STUN/TURN ports is not blocked","Check firewall or VPN settings","Try using TCP-based TURN as a fallback"]},33006:{name:"ANSWER_WHILE_PEER_ACTIVE",message:"Call answer ignored because a peer connection is already active",description:"answer() was called on a call that already has an active or connecting peer connection. Creating a second peer connection for the same call would duplicate media negotiation, confuse the remote party, and break call reporting. This is typically caused by application code invoking answer() multiple times (e.g. from multiple event handlers).",causes:["Application called answer() twice on the same call object","Multiple click handlers or event listeners triggering answer()"],solutions:["Ensure answer() is called only once per call","Disable the answer button after the first click","Check that answer() is not invoked from multiple event handlers"]},33008:{name:"ICE_CANDIDATE_PAIR_CHANGED",message:"ICE candidate pair changed mid-call",description:"The selected ICE candidate pair changed during an active call. This indicates a network path shift — for example, a Wi-Fi to cellular handoff, a NAT rebinding, or a relay fallback. The call may continue normally, but the path change can briefly affect audio quality.",causes:["Network interface change (e.g. Wi-Fi to cellular)","NAT rebinding or IP address change","Previous candidate pair failed and ICE selected an alternative","Network topology change"],solutions:["Monitor for audio quality degradation after the path change","Check network stability if changes are frequent","Verify TURN server configuration for relay fallback"]},33007:{name:"DUPLICATE_INBOUND_ANSWER",message:"Call answer ignored because another inbound call is already being answered",description:"answer() was called on an inbound call while another inbound call is already answering or active in this JavaScript runtime. Answering both legs can trigger SIP 486 USER_BUSY / LOSE_RACE when duplicate WebSocket registrations receive the same incoming call.",causes:["Multiple TelnyxRTC instances in the same page","Application code recreating a client without disconnecting the previous instance","Duplicate inbound call notifications produced by duplicate WebSocket registrations"],solutions:["Keep a single active TelnyxRTC instance for inbound call handling","Call disconnect() before replacing an SDK client instance","Only call answer() for one inbound call notification at a time"]},34001:{name:"TOKEN_EXPIRING_SOON",message:"Authentication token expiring soon",description:"The authentication token is approaching its expiration time. If the token expires the connection will be lost and calls will fail. A new token should be generated before expiration.",causes:["Token was issued with a limited lifetime"],solutions:["Generate a new authentication token","Reconnect with fresh credentials before the token expires"]},36003:{name:"SIGNALING_RECOVERY_REQUIRED",message:"Signaling recovery required",description:"The signaling (WebSocket) path has been detected as unhealthy and the SDK will force-close the socket and reconnect. The source field in the warning payload indicates what triggered the recovery (probe, request, peer_failure, or no_rtp). Active calls will be recovered via reattach after reconnection.",causes:["WebSocket probe timed out with no response","Critical signaling request timed out","Peer/media failure detected while signaling is also unhealthy"],solutions:["The SDK will automatically reconnect and recover the call","Check for network interface changes or interruptions","Verify firewall/NAT timeout settings"]},36004:{name:"MEDIA_RECOVERY_REQUIRED",message:"Media recovery required",description:"The peer connection or media flow has been detected as unhealthy while signaling is healthy. The SDK will attempt ICE restart to recover the media path. No socket reconnection is needed.",causes:["ICE connection state changed to failed","RTCPeerConnection state changed to failed","No RTP packets/bytes received while media should be active"],solutions:["The SDK will automatically attempt ICE restart","Check network connectivity and ICE candidate availability","Verify TURN server configuration"]},36005:{name:"RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT",message:"Reconnection failed — auto-reconnect disabled",description:"The WebSocket was closed and auto-reconnect is disabled, so the SDK will not attempt to reconnect. This typically occurs after the user called disconnect() or after reconnection attempts were exhausted.",causes:["Auto-reconnect was disabled by the application","Reconnection attempts were previously exhausted","The session was intentionally disconnected"],solutions:["Call connect() manually to re-establish the session","Check if disconnect() was called intentionally","Review maxReconnectAttempts configuration"]},33009:{name:"AUDIO_INPUT_DEVICE_CHANGE_SKIPPED",message:"Audio input device change skipped",description:"The SDK could not change the microphone because the active peer connection has no audio RTP sender to replace. The existing local media and mute state were left unchanged.",causes:["The call was created without an audio sender","The peer connection was not ready when setAudioInDevice was called","The call is already ending or the local media sender was removed"],solutions:["Retry after the call is active and local media is attached","Verify the call was started with audio enabled","Inspect call state and peer connection sender availability"]},33010:{name:"MULTIPLE_ACTIVE_CALLS_DETECTED",message:"Multiple active calls detected in one SDK session",description:"A new call was created or received while another call is still active (ringing, answering, active, held, or recovering) in the same SDK session. This may be intentional for some applications (e.g. call waiting, transfer) but is often abnormal and makes call reports and application behavior harder to reason about. The new call proceeds normally — this warning is diagnostic only.",causes:["Application created an outbound call while another call is active","An inbound call arrived while another call is already active","Application did not hang up the previous call before starting a new one","Call waiting or multi-call scenario (may be intentional)"],solutions:["Verify this is the expected behavior for your application","Ensure the previous call is hung up before creating a new one if only one call is expected","Use call.hold() before starting a new call if needed","Check the warning payload for call IDs to correlate which calls are involved"]},33011:{name:"SHARED_REMOTE_ELEMENT_OVERWRITE",message:"Remote media element overwritten by another call",description:"A new MediaStream was attached to an HTML media element (audio/video) that already held a different MediaStream from another active call. The SDK overwrote the existing stream (last-writer-wins), which disrupts the other call remote media playout. This happens when two concurrent calls share a single remoteElement instead of each having its own. Use a per-call remoteElement (client.newCall({ remoteElement }) or call.answer({ remoteElement })) so each call owns a distinct element.",causes:["Two concurrent calls share one remoteElement (legacy single-element app)","Application did not pass a per-call remoteElement to newCall() or answer()","A second inbound call rang into a session using one session-level remoteElement"],solutions:["Pass a distinct remoteElement per call via client.newCall({ remoteElement })","For inbound calls, override at answer time via call.answer({ remoteElement })","Give each call its own <audio>/<video> element so attach/detach lifecycles are independent"]},35002:{name:"UNKNOWN_REATTACHED_SESSION",message:"Unknown reattach session after reconnect",description:"The WebSocket reconnected successfully and the server sent an Attach message for a session that does not match any active SDK call. The unknown Attach is ACK'd and ignored.",causes:["Server sent an Attach for a call that no longer exists in the SDK","Multiple Attach messages arrived and only the first was recovered","Race condition between reconnection and new inbound call"],solutions:["Check application logic for multiple simultaneous calls","Inspect the Attach callID in the warning payload for details","If a call should be active, start a new call manually"]}};function 
1he(t,e){const i=sr[t];return{code:t,name:i.name,message:e||i.message,description:i.description,causes:[...i.causes],solutions:[...i.solutions]}}var Ge=class ns extends Error{constructor(e){super(e.message||`[${e.code}] ${e.name}`),this.name=e.name,this.code=e.code,this.description=e.description,this.causes=e.causes,this.solutions=e.solutions,this.originalError=e.originalError,this.fatal=e.fatal,Object.setPrototypeOf(this,ns.prototype)}toJSON(){return{code:this.code,name:this.name,description:this.description,message:this.message,causes:this.causes,solutions:this.solutions,originalError:this.originalError,fatal:this.fatal}}};function Ye(t){if(t instanceof DOMException){if(t.name==="NotAllowedError")return Qn;if(t.name==="NotFoundError"||t.name==="OverconstrainedError")return Xn}return wi}function Z(t,e,i,n){const s=nr[t],o=e instanceof Error?e:e!==void 0?new Error(String(e)):void 0;return new Ge({code:t,name:s.name,description:s.description,message:i||s.message,causes:[...s.causes],solutions:[...s.solutions],originalError:o,fatal:n??s.fatal})}var or=class extends Error{constructor(t,e,i=""){super(`Signaling request timed out (id=${t}, method=${i||"unknown"}, timeout=${e}ms)`),this.name="RequestTimeoutError",this.requestId=t,this.timeoutMs=e,this.method=i}},ui=class extends Error{constructor(t,e,i){super(`Stale request cancelled (id=${t}, gen=${e}, current=${i})`),this.name="StaleRequestError",this.requestId=t,this.staleGeneration=e,this.currentGeneration=i}},rr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ss(t,e){return t(e={exports:{}},e.exports),e.exports}var ar=ss((function(t){var e=rr,i=function(){var n=function(){},s="undefined",o=typeof window!==s&&typeof window.navigator!==s&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"];function a(S,E){var T=S[E];if(typeof T.bind=="function")return T.bind(S);try{return Function.prototype.bind.call(T,S)}catch{return function(){return Function.prototype.apply.apply(T,[S,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function h(S,E){for(var T=0;T<r.length;T++){var N=r[T];this[N]=T<S?n:this.methodFactory(N,S,E)}this.log=this.debug}function p(S,E,T){return function(){typeof console!==s&&(h.call(this,E,T),this[S].apply(this,arguments))}}function f(S,E,T){return(function(N){return N==="debug"&&(N="log"),typeof console!==s&&(N==="trace"&&o?l:console[N]!==void 0?a(console,N):console.log!==void 0?a(console,"log"):n)})(S)||p.apply(this,arguments)}function b(S,E,T){var N,$=this;E=E??"WARN";var j="loglevel";function q(){var M;if(typeof window!==s&&j){try{M=window.localStorage[j]}catch{}if(typeof M===s)try{var c=window.document.cookie,u=c.indexOf(encodeURIComponent(j)+"=");u!==-1&&(M=/^([^;]+)/.exec(c.slice(u))[1])}catch{}return $.levels[M]===void 0&&(M=void 0),M}}typeof S=="string"?j+=":"+S:typeof S=="symbol"&&(j=void 0),$.name=S,$.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},$.methodFactory=T||f,$.getLevel=function(){return N},$.setLevel=function(M,c){if(typeof M=="string"&&$.levels[M.toUpperCase()]!==void 0&&(M=$.levels[M.toUpperCase()]),!(typeof M=="number"&&M>=0&&M<=$.levels.SILENT))throw"log.setLevel() called with invalid level: "+M;if(N=M,c!==!1&&(function(u){var m=(r[u]||"silent").toUpperCase();if(typeof window!==s&&j){try{window.localStorage[j]=m;return}catch{}try{window.document.cookie=encodeURIComponent(j)+"="+m+";"}catch{}}})(M),h.call($,M,S),typeof console===s&&M<$.levels.SILENT)return"No console available for logging"},$.setDefaultLevel=function(M){E=M,q()||$.setLevel(M,!1)},$.resetLevel=function(){$.setLevel(E,!1),(function(){if(typeof window!==s&&j){try{window.localStorage.removeItem(j);return}catch{}try{window.document.cookie=encodeURIComponent(j)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}})()},$.enableAll=function(M){$.setLevel($.levels.TRACE,M)},$.disableAll=function(M){$.setLevel($.levels.SILENT,M)};var Y=q();Y??=E,$.setLevel(Y,!1)}var g=new b,v={};
1g.getLogger=function(S){if(typeof S!="symbol"&&typeof S!="string"||S==="")throw new TypeError("You must supply a name when creating a logger.");var E=v[S];return E||(E=v[S]=new b(S,g.getLevel(),g.methodFactory)),E};var y=typeof window!==s?window.log:void 0;return g.noConflict=function(){return typeof window!==s&&window.log===g&&(window.log=y),g},g.getLoggers=function(){return v},g.default=g,g};t.exports?t.exports=i():e.log=i()})),nn={debug:0,info:1,warn:2,error:3},lr=class{constructor(t={}){var e,i,n;this.buffer=[],this.isCapturing=!1,this.options={enabled:(e=t.enabled)!==null&&e!==void 0&&e,level:(i=t.level)!==null&&i!==void 0?i:"debug",maxEntries:(n=t.maxEntries)!==null&&n!==void 0?n:1e3}}start(){this.options.enabled&&(this.isCapturing=!0,this.buffer=[])}stop(){this.isCapturing=!1}addEntry(t,e,i){if(!this.isCapturing||!this.options.enabled||nn[t]<nn[this.options.level])return;const n=Object.assign({timestamp:new Date().toISOString(),level:t,message:e},i&&Object.keys(i).length>0?{context:i}:{});this.buffer.push(n),this.buffer.length>this.options.maxEntries&&this.buffer.shift()}getLogs(){return[...this.buffer]}getLogCount(){return this.buffer.length}drain(){const t=this.buffer;return this.buffer=[],t}clear(){this.buffer=[]}isActive(){return this.isCapturing}isEnabled(){return this.options.enabled}},os=null,d=ar.getLogger("telnyx"),Ot={trace:0,debug:1,info:2,warn:3,error:4},rs=Ot.info;function sn(t){if(t==null||typeof t!="object")return t;try{const i=JSON.stringify(t),n=JSON.parse(i);if(typeof n=="object"&&n!==null&&Object.keys(n).length>1)return n}catch{}const e={};for(const i in t)try{const n=t[i];if(typeof n=="function")continue;if(typeof n=="object"&&n!==null)try{e[i]=JSON.parse(JSON.stringify(n))}catch{e[i]=String(n)}else e[i]=n}catch{}return Object.keys(e).length>0?e:{value:String(t)}}var cr=d.methodFactory;d.methodFactory=(t,e,i)=>{const n=cr(t,e,i);return function(...s){if(Ot[t]>=rs){const r=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)r.push(a);n(...r)}const o=os;if(o?.isActive()){const[r,...a]=s,l=typeof r=="string"?r:JSON.stringify(r);let h;a.length>0&&(h=a.length===1&&typeof a[0]=="object"&&a[0]!==null?sn(a[0]):{args:a.map(sn)}),o.addEntry(t,l,h)}}},d.setLevel("debug",!1);var yt=t=>{const[e,i,n,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{d.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},as=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},Ut=t=>t instanceof Function||typeof t=="function",nt=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,dr=/^(ws|wss):\/\//,ls=(t,e=null)=>{const{result:i={},error:n}=t;if(n)return{error:n};const{result:s=null}=i;if(s===null)return e!==null&&(i.node_id=e),{result:i};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&o!=="200"?{error:s}:a?ls(a,r):{result:s}},Dt=({login:t,passwd:e,password:i,login_token:n})=>!!(t&&(e||i)||n),tt=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,ki=t=>{var e,i,n,s,o,r;let a="",l="";return(i=(e=t?.result)===null||e===void 0?void 0:e.params)!==null&&i!==void 0&&i.state&&(a=(s=(n=t?.result)===null||n===void 0?void 0:n.params)===null||s===void 0?void 0:s.state),(o=t?.params)!==null&&o!==void 0&&o.state&&(l=(r=t?.params)===null||r===void 0?void 0:r.state),a||l};function on({debounceTime:t}){let e,i;return{promise:new Promise(((n,s)=>{e=t?ur(n,t):n,i=s})),resolve:e,reject:i}}var ur=(t,e)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout((()=>{t(...n)}),e)}},Ii="telnyx-voice-sdk-id",xt="telnyx-voice-sdk-session-id",$t="telnyx-voice-sdk-session-id-stored-at",Ei="telnyx-voice-sdk-active-calls",hr=9e4;function rn(t=Date.now()){const e=(function(){const i=Number(sessionStorage.getItem($t));return Number.isFinite(i)?i:null})();return e!==null&&t-e<=hr}function st(){return sessionStorage.getItem(Ii)}function hi(t,e=Date.now()){sessionStorage.setItem(xt,t),sessionStorage.setItem($t,String(e))}function cs(){sessionStorage.removeItem(Ii),sessionStorage.removeItem(xt),sessionStorage.removeItem($t)}function Me(){(function(t){try{sessionStorage.removeItem(t)}catch(e){d.debug(`safeRemoveItem('${t}') failed: ${e instanceof Error?e.message:String(e)}`)}})(Ei)}function an(t=Date.now()){const e=(function(i){try{return sessionStorage.getItem(i)}catch(n){return d.debug(`safeGetItem('${i}') failed: ${n instanceof Error?n.message:String(n)}`),null}})(Ei);if(!e)return null;try{const i=JSON.parse(e);if(!i||typeof i!="object"||!Array.isArray(i.calls))return d.debug("Active-calls recovery marker payload was malformed — discarded."),Me(),null;const n=Number(i.storedAt);return!Number.isFinite(n)||t-n>9e5?(d.debug("Active-calls recovery marker was stale or had an invali
1d timestamp — discarded."),Me(),null):i.calls.length===0?(d.debug("Active-calls recovery marker had no call records — discarded."),Me(),null):i}catch(i){return d.debug(`Active-calls recovery marker JSON parse failed — discarded: ${i instanceof Error?i.message:String(i)}`),Me(),null}}function ds(t,e,i=Date.now()){if(!Array.isArray(t)||t.length===0)return void Me();(function(n,s){try{sessionStorage.setItem(n,s)}catch(o){d.info(`safeSetItem('${n}') failed: ${o instanceof Error?o.message:String(o)}`)}})(Ei,JSON.stringify({sessionId:e,calls:t,storedAt:i}))}var ue,Ee,Q;(function(t){t.Offer="offer",t.Answer="answer"})(ue||(ue={})),(function(t){t.Inbound="inbound",t.Outbound="outbound"})(Ee||(Ee={})),(function(t){t.Invite="telnyx_rtc.invite",t.Attach="telnyx_rtc.attach",t.Answer="telnyx_rtc.answer",t.Info="telnyx_rtc.info",t.Candidate="telnyx_rtc.candidate",t.EndOfCandidates="telnyx_rtc.endOfCandidates",t.Display="telnyx_rtc.display",t.Media="telnyx_rtc.media",t.Event="telnyx_rtc.event",t.Bye="telnyx_rtc.bye",t.Punt="telnyx_rtc.punt",t.Broadcast="telnyx_rtc.broadcast",t.Subscribe="telnyx_rtc.subscribe",t.Unsubscribe="telnyx_rtc.unsubscribe",t.ClientReady="telnyx_rtc.clientReady",t.Modify="telnyx_rtc.modify",t.Ringing="telnyx_rtc.ringing",t.GatewayState="telnyx_rtc.gatewayState",t.Ping="telnyx_rtc.ping",t.Pong="telnyx_rtc.pong"})(Q||(Q={}));var Ce={generic:"event",[Q.Display]:"participantData",[Q.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},pr={invalidCredentialsOptions:"InvalidCredentialsOptions"},us=8e6,ln={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0},mutedMicOnStart:!1,prefetchIceCandidates:!1},V,pi,_e,Te,de,Be;(function(t){t[t.New=0]="New",t[t.Requesting=1]="Requesting",t[t.Trying=2]="Trying",t[t.Recovering=3]="Recovering",t[t.Ringing=4]="Ringing",t[t.Answering=5]="Answering",t[t.Early=6]="Early",t[t.Active=7]="Active",t[t.Held=8]="Held",t[t.Hangup=9]="Hangup",t[t.Destroy=10]="Destroy",t[t.Purge=11]="Purge"})(V||(V={})),(function(t){t.Participant="participant",t.Moderator="moderator"})(pi||(pi={})),(function(t){t.Join="join",t.Leave="leave",t.Bootstrap="bootstrap",t.Add="add",t.Modify="modify",t.Delete="delete",t.Clear="clear",t.ChatMessage="chatMessage",t.LayerInfo="layerInfo",t.LogoInfo="logoInfo",t.LayoutInfo="layoutInfo",t.LayoutList="layoutList",t.ModCmdResponse="modCommandResponse"})(_e||(_e={})),(function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"})(Te||(Te={})),(function(t){t.REGED="REGED",t.UNREGED="UNREGED",t.NOREG="NOREG",t.FAILED="FAILED",t.FAIL_WAIT="FAIL_WAIT",t.TIMEOUT="TIMEOUT",t.REGISTER="REGISTER",t.TRYING="TRYING",t.EXPIRED="EXPIRED",t.UNREGISTER="UNREGISTER"})(de||(de={})),(function(t){t.Hold="hold",t.Unhold="unhold",t.ToggleHold="toggleHold",t.UpdateMedia="updateMedia"})(Be||(Be={}));var Ke="GLOBAL",me={},rt=(t,e)=>`${t}|${e}`,hs=(t,e=Ke)=>rt(t,e)in me,Ne=(t,e,i=Ke)=>{const n=rt(t,i);n in me||(me[n]=[]),me[n].push(e)},ps=(t,e,i=Ke)=>{const n=function(s){Re(t,n,i),e(s)};return n.prototype.targetRef=e,Ne(t,n,i)},Re=(t,e,i=Ke)=>{if(!hs(t,i))return!1;const n=rt(t,i);if(Ut(e))for(let s=me[n].length-1;s>=0;s--){const o=me[n][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&me[n].splice(s,1)}else me[n]=[];return me[n].length===0&&delete me[n],!0},F=(t,e,i=Ke,n=!0)=>{const s=n&&i!==Ke;if(!hs(t,i))return s&&F(t,e),!1;const o=rt(t,i),r=me[o].length;if(!r)return s&&F(t,e),!1;for(let a=r-1;a>=0;a--)me[o][a](e);return s&&F(t,e),!0},Yt=t=>{const e=rt(t,"");Object.keys(me).filter((i=>i.indexOf(e)===0)).forEach((i=>delete me[i]))},gr=typeof WebSocket<"u"?WebSocket:null,vr=0,fr=1,mr=2,cn=3,It=class{constructor(t){this.session=t,this.previousGatewayState="",this.lastInboundAt=0,this.socketGeneration=0,this._wsCl
1ient=null,this._host=tn,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this._safetyTimeoutId=null,this._pendingRequestIds=new Set,this._pendingRequestTimers=new Map,this._pendingRequestRejecters=new Map,this.upDur=null,this.downDur=null;const{host:e,env:i,region:n,useCanaryRtcServer:s}=t.options;d.debug("Creating new Connection",{host:this._host,env:i,region:n,useCanaryRtcServer:s}),i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":tn),e&&(this._host=(o=>`${dr.test(o)?"":"wss://"}${o}`)(e)),n&&(this._host=this._host.replace(/rtc(dev)?/,`${n}.rtc$1`)),s&&(this._useCanaryRtcServer=!0)}get connected(){return!!this._wsClient&&this._wsClient.readyState===fr}get connecting(){return!!this._wsClient&&this._wsClient.readyState===vr}get closing(){return!!this._wsClient&&this._wsClient.readyState===mr}get closed(){return!!this._wsClient&&this._wsClient.readyState===cn}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){d.debug("Connection.connect() called",{host:this._host,socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const t=new URL(this._host);let e=st();this.session.options.rtcIp&&this.session.options.rtcPort&&(e=null,this._useCanaryRtcServer=!1,t.searchParams.set("rtc_ip",this.session.options.rtcIp),t.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),e&&t.searchParams.set("voice_sdk_id",e),this._useCanaryRtcServer&&(t.searchParams.set("canary","true"),e&&!this._hasCanaryBeenUsed&&(t.searchParams.delete("voice_sdk_id"),d.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this.session.callReportVoiceSdkId=t.searchParams.get("voice_sdk_id"),this.session.options.skipLastVoiceSdkId&&t.searchParams.has("voice_sdk_id")&&t.searchParams.set("skip_last_voice_sdk_id","true"),this.session.options.skipTrailing&&t.searchParams.set("skip_trailing","true");try{const i=this.socketGeneration;this._wsClient=new gr(t.toString()),this.socketGeneration+=1,d.debug("WebSocket connection created",{sessionId:this.session.sessionid,voiceSdkId:this.session.callReportVoiceSdkId,socketGeneration:this.socketGeneration,reconnectCount:i}),this.lastInboundAt=0,this._cleanupPendingRequests(),this._registerSocketEvents(this._wsClient)}catch(i){d.error("WebSocket connection failed:",i);const n=Z(Co,i);F(D.Error,{error:n,sessionId:this.session.sessionid},this.session.uuid),this.session._terminateActiveCallsLocally()}}sendRawText(t){var e;(e=this._wsClient)===null||e===void 0||e.send(t)}send(t,e){var i;const{request:n}=t,s=this.socketGeneration,o=n.method||"",r=new Promise(((a,l)=>{if(n.hasOwnProperty("result"))return a();let h=!1,p=null;const f=b=>{if(p!==null&&(clearTimeout(p),this._pendingRequestTimers.delete(n.id),p=null),this._pendingRequestIds.delete(n.id),this._pendingRequestRejecters.delete(n.id),this.session.onOutboundConfirmed(),h)return;const{result:g,error:v}=ls(b);return v?l(v):a(g)};ps(n.id,f),this._pendingRequestIds.add(n.id),this._pendingRequestRejecters.set(n.id,{reject:l,generation:s}),e&&e>0&&(p=setTimeout((()=>{if(h=!0,p=null,this._pendingRequestTimers.delete(n.id),this._pendingRequestRejecters.delete(n.id),Re(n.id,f),this._pendingRequestIds.delete(n.id),this.socketGeneration!==s)return d.debug(`Stale request timeout for ${n.id} (gen ${s}, current ${this.socketGeneration}) — settling with StaleRequestError`),void l(new ui(n.id,s,this.socketGeneration));l(new or(n.id,e,o))}),e),this._pendingRequestTimers.set(n.id,p))}));return d.debug(`SEND: 
2`,JSON.stringify(n,null,2),`
3`),(i=this._wsClient)===null||i===void 0||i.send(JSON.stringify(n)),r}close(){if(d.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 t=this._wsClient;Ut(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout((()=>this._handleCloseTimeout(t)),5e3))}_registerSocketEvents(t){const e=this.socketGeneration;t.onopen=i=>(d.debug("WebSocket onopen",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid}),F(D.SocketOpen,i,this.session.uuid)),t.onclose=i=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(t,"close"),d.debug("WebSocket onclose",{c
3ode:i?.code,reason:i?.reason,wasClean:i?.wasClean,socketGeneration:e,sessionId:this.session.sessionid}),F(D.SocketClose,{event:i,socketGeneration:e},this.session.uuid)),t.onerror=i=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(t,"error"),d.debug("WebSocket onerror",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const n=Z(wo);return F(D.Error,{error:n,sessionId:this.session.sessionid},this.session.uuid),F(D.SocketError,{error:i,sessionId:this.session.sessionid,socketGeneration:e},this.session.uuid)},t.onmessage=i=>{var n,s;this.lastInboundAt=Date.now(),F(D.SocketActivity,{timestamp:this.lastInboundAt},this.session.uuid);const o=as(i.data);var r;if(typeof o!="string"){if(o.voice_sdk_id&&(this.session.callReportVoiceSdkId=o.voice_sdk_id,r=o.voice_sdk_id,sessionStorage.setItem(Ii,r)),this._unsetTimer(o.id),d.debug(`RECV: 
4`,JSON.stringify(o,null,2),`
5`),de[`${(s=(n=o?.result)===null||n===void 0?void 0:n.params)===null||s===void 0?void 0:s.state}`]||!F(o.id,o)){const a=ki(o);F(D.SocketMessage,o,this.session.uuid),a&&(this.previousGatewayState=a)}}else this._handleStringResponse(o)}}_deregisterSocketEvents(t){t.onopen=null,t.onclose=null,t.onerror=null,t.onmessage=null}_handleCloseTimeout(t){this._safetyTimeoutId=null,t&&t.readyState!==cn?(d.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(t),this._safetyCleanupSocket(t,"timeout"),this._wsClient&&this._wsClient!==t?d.debug("Safety timeout: socket was replaced, not emitting SocketClose",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===t}):(d.debug("Safety timeout: emitting SocketClose for stuck socket",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===t}),F(D.SocketClose,{code:ts.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))):d.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(d.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(t,e){this._wsClient===t?(d.debug(`Nulling socket reference (reason: ${e})`),this._wsClient=null):d.debug(`Skipping socket cleanup - old socket already replaced (reason: ${e})`)}_cleanupPendingRequests(){Array.from(this._pendingRequestIds).forEach((t=>{Re(t);
5const e=this._pendingRequestTimers.get(t),i=this._pendingRequestRejecters.get(t);e&&(clearTimeout(e),this._pendingRequestTimers.delete(t),i&&i.reject(new ui(t,i.generation,this.socketGeneration))),this._pendingRequestRejecters.delete(t)})),this._pendingRequestIds.clear()}_unsetTimer(t){clearTimeout(this._timers[t]),delete this._timers[t]}_handleStringResponse(t){if(/^#SP/.test(t))switch(t[3]){case"U":this.upDur=parseInt(t.substring(4));break;case"D":this.downDur=parseInt(t.substring(4)),F(D.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else d.warn("Unknown message from socket",t)}};It.DEFAULT_REQUEST_TIMEOUT_MS=1e4;var ze=class{buildRequest(t){this.request=Object.assign({jsonrpc:"2.0",id:qe()},t)}buildNotification(t){this.request=Object.assign({jsonrpc:"2.0"},t)}},dn={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"},ge=class extends ze{constructor(t={}){if(super(),t.hasOwnProperty("dialogParams")){const e=Kn(t.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const i in dn)i&&e.hasOwnProperty(i)&&(e[dn[i]]=e[i],delete e[i]);t.dialogParams=e}this.buildRequest({method:this.toString(),params:t})}},gs=class extends ge{constructor(t){super(),this.method=Q.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:t,params:{}})}},_r=class{constructor(t){this.pendingRequestId=null,this.onSocketMessage=e=>R(this,void 0,void 0,(function*(){e.id===this.pendingRequestId&&this.gatewayStateTask.resolve(ki(e))})),this.getIsRegistered=()=>R(this,void 0,void 0,(function*(){const e=new gs(st());this.pendingRequestId=e.request.id,this.gatewayStateTask=on({}),this.session.execute(e);const i=yield this.gatewayStateTask.promise;return!!i&&[de.REGISTER,de.REGED].includes(i)})),this.session=t,this.gatewayStateTask=on({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}},Ti=class extends ge{constructor(t){super(),this.method=Q.Ping,this.buildRequest({method:this.method,voice_sdk_id:t,params:{}})}},gi=class vi{constructor(e){this._session=e,this._lastInboundAt=0,this._lastOutboundConfirmedAt=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 vi.CRITICAL_METHODS.has(e)}start(){this._intervalId||(d.debug("Signaling health: monitor started"),this._lastInboundAt=Date.now(),this._lastOutboundConfirmedAt=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(),d.debug("Signaling health: monitor stopped")}get isRunning(){return this._intervalId!==null}get isProbeInFlight(){return this._probeInFlight}onSocketActivity(){this._lastInboundAt=Date.now()}onOutboundConfirmed(){this._lastOutboundConfirmedAt=Date.now()}_resolveProbe(){if(!this._probeInFlight)return;if(this._probeInFlight=!1,this._lastProbeSentAt=0,this._lastInboundAt=Date.now(),this._lastOutboundConfirmedAt=Date.now(),d.debug("Signaling health: probe resolved by matching Ping response"),!this._pendingMediaRecovery)return void d.debug("Signaling health: probe resolved but no pending media recovery");
5const e=this._pendingMediaRecovery;this._pendingMediaRecovery=null,this._getSignalingHealthState()==="healthy"&&(d.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?d.debug(`Signaling health: probe already in flight, skipping duplicate probe (${e})`):(d.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&&(vi.isCriticalMethod(n)?(d.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")):d.warn(`Non-critical signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms) — logging but not triggering signaling recovery`))}onPeerFailure(e,i){d.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){d.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&&(d.debug(`Signaling health: browser online — clearing browser offline state for session ${this._session.sessionid}`),this._browserWasOffline=!1)},this._offlineHandler=()=>{this._browserWasOffline=!0,d.debug(`Signaling health: browser offline signal received for session ${this._session.sessionid}`);const e=Z(Ro);F(D.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){d.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,s=i-this._lastOutboundConfirmedAt,o=n>=2e4;if(!o&&!(s>=45e3))return;if(!this._probeInFlight)return d.info(o?`Signaling health: no inbound WS activity for ${Math.round(n/1e3)}s during active call, sending health probe`:`Signaling health: inbound WS activity is flowing but no outbound request has been answered for ${Math.round(s/1e3)}s, sending health probe`),void this._sendProbe();const r=i-this._lastProbeSentAt;r>=5e3&&(d.warn(`Signaling health: probe timed out after ${r}ms (inbound silent for ${Math.round(n/1e3)}s, no outbound request answered for ${Math.round(s/1e3)}s) — declaring signaling unhealthy`),this._triggerSignalingRecovery(o?"Signaling health probe timed out: no inbound WS activity after probe":"Signaling health probe timed out: inbound WS activity is flowing but no outbound request is being answered","probe"))}_sendProbe(){var e;this._probeInFlight=!0,this._lastProbeSentAt=Date.now();const i=new Ti(st());(e=this._session.connection)===null||e===void 0||e.send(i).then((()=>this._resolveProbe())).catch((n=>{d.warn("Signaling health: probe Ping failed to send",n)}))}_recoverMediaOrSignaling(e,i,n,s){if(!this._session.hasActiveCall())return void d.debug(`Signaling health: ignoring ${s} recovery without an active call`);const o=this._getSignalingHealthState();o==="healthy"?(d.info(`Signaling health: signaling is healthy, triggering ICE restart for call ${e}`),this._triggerIceRestart(e,i)):o==="unknown"?(d.info(`Signaling health: signaling health is unknown, deferring ICE restart decision for call ${e}`),this._pendingMediaRecovery={callId:e,reason:i,source:s},this._probeIfNeeded(`${s} detected with stale/unknown signaling`)):(d.info("Signaling health: signaling is unhealthy, triggering socket reconnect instead of ICE restart"),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,d.debug(`Signaling recovery triggered (source=${i}, reason=${e})`);const r=he(Yo);F(D.Warning,{warning:r,reason:e,source:i,sessionId:this._session.sessionid},this._session.uuid),!((n=this._session.connection)===null||n===void 0)&&n.connected?(d.info("Signaling health: force-closing WebSocket to trigger reconnect"),this._session.socketDisconnect()):d.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){d.info(`Signaling health: triggering ICE restart for call ${e}`);const n=this._session.triggerIceRestart(e);if(!n.started)return void d.info(`Signaling health: ICE restart not started for call ${e}: ${n.reason}`);const s=he(Ko);F(D.Warning,{warning:s,reason:i,callId:e,sessionId:this._session.sessionid},this._session.uuid)}};
5gi.CRITICAL_METHODS=new Set([Q.Modify,Q.Bye,Q.Ping]);var vs="2.27.10",Ri=vs,yr=class extends ge{constructor(t,e,i,n,s={},o,r=!1){super(),this.method="login";const a={login:t,passwd:e,login_token:i,userVariables:s,reconnection:o,loginParams:{early_sdp_answer:r},"User-Agent":{sdkVersion:Ri,data:navigator.userAgent}};n&&(a.sessid=n),this.buildRequest({method:this.method,params:a})}},br=class extends ge{constructor(t,e){super(),this.buildRequest({id:t,result:{method:e}})}},un=class extends ge{toString(){return Q.Invite}},hn=class extends ge{toString(){return Q.Answer}},pn=class extends ge{toString(){return Q.Attach}},Sr=class extends ge{toString(){return Q.Bye}},Cr=class extends ge{toString(){return Q.Candidate}},wr=class extends ge{toString(){return Q.EndOfCandidates}},bt=class extends ge{toString(){return Q.Modify}},gn=class extends ge{toString(){return Q.Info}},kr=class extends ge{toString(){return Q.Broadcast}},Ir=class extends ge{toString(){return Q.Subscribe}},Er=class extends ge{toString(){return Q.Unsubscribe}},Tr=class extends ge{constructor(t){super(),this.method="anonymous_login";const{target_type:e,target_id:i,target_version_id:n,target_params:s,userVariables:o,sessionId:r,reconnection:a}=t,l={target_type:e,target_id:i,userVariables:o,reconnection:a,"User-Agent":{sdkVersion:Ri,data:navigator.userAgent}};r&&(l.sessid=r),n&&(l.target_version_id=n),s&&(l.target_params=s),this.buildRequest({method:this.method,params:l})}},fi=class Et{constructor(e){if(this.options=e,this.uuid=qe(),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 gi(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var i=e.debug?"debug":"info",n;rs=(n=Ot[i])!==null&&n!==void 0?n:Ot.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 It(this),this.registerAgent=new _r(this)}get __logger(){return d}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return R(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 d.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}),d.debug("Calling connect from execute since not currently connected."),this.connect()}));const n=gi.isCriticalMethod(((i=e.request)===null||i===void 0?void 0:i.method)||"")?It.DEFAULT_REQUEST_TIMEOUT_MS:void 0;return(n!=null?this.connection.send(e,n):this.connection.send(e)).catch((s=>R(this,void 0,void 0,(function*(){if(s instanceof ui)throw d.debug(`Stale request settled (id=${s.requestId}, gen=${s.staleGeneration}) — not triggering recovery`),s;if(s?.name==="RequestTimeoutError")throw this.onSignalingRequestTimeout(s.requestId,s.timeoutMs,s.method),s;if(s?.code===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const o=Z(Eo,s,void 0,!0);F(D.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((()=>
5this._pendingCallReportUploads.delete(e)),(()=>this._pendingCallReportUploads.delete(e)))}_drainCallReportUploads(){return R(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()}),Et.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS)))]),i&&d.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})}))}validateOptions(){return Dt(this.options)||tt(this.options)}broadcast(e){}disconnect(){return R(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(),d.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")}))}on(e,i){return Ne(e,i,this.uuid),this}off(e,i){return Re(e,i,this.uuid),this}connect(){return R(this,void 0,void 0,(function*(){this.connection||(d.debug("No existing connection found, creating a new one."),this.connection=new It(this)),this._attachListeners(),this._autoReconnect||(d.debug("autoReconnect was disabled, resetting reconnect attempts"),this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(d.debug("Connection wasn't alive, initiating connection to the server..."),this.connection.connect()),d.debug("Connect method called. Connection initiated.")}))}resetReconnectAttempts(){this._reconnectAttempts=0,this._reconnectCountedGeneration=-1}_handleLoginError(e){const i=Z(Zn,e);F(D.Error,{error:i,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){cs()}_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<=Et.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const o=1e3*(s-Et.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout((()=>{this._emitTokenExpiryWarning()}),o)}}catch{d.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=he(Vo);F(D.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 R(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)),Dt(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(tt(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const s="Invalid login options provided for authentication.";d.error(s);const o=Z(Io,void 0,s);F(D.Error,{error:o,type:pr.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid);return}}}))}_login({type:e,onSuccess:i,onError:n}){var s,o,r,a;return R(this,void 0,void 0,(function*(){let l;const h=!!st(),p=h&&(this.sessionid&&rn()?this.sessionid:(function(b=Date.now()){const g=sessionStorage.getItem(xt);return g?rn(b)?g:(sessionStorage.removeItem(xt),sessionStorage.removeItem($t),null):null})())||"";if(e==="login"){const b=(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,g=Object.assign(Object.assign({},this.options.userVariables),{push_when_active:b,pn_late_fanout:b}),v=(a=this.options.earlySdpAnswer)!==null&&a!==void 0&&a;
5l=new yr(this.options.login,this.options.password||this.options.passwd,this.options.login_token,p,g,h,v)}else l=new Tr({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:p,userVariables:this.options.userVariables,reconnection:h});const f=yield this.execute(l).catch((b=>{this._handleLoginError(b),n&&n(b)}));f&&(this.sessionid=f.sessid,this.sessionid&&hi(this.sessionid),this._checkTokenExpiry(),i&&i())}))}_onSocketOpen(){return R(this,void 0,void 0,(function*(){this.startSignalingHealthMonitor()}))}_flushIntermediateCallReports(e){const i=this.calls;i&&Object.values(i).forEach((n=>{if(n?.flushIntermediateCallReport)try{n.flushIntermediateCallReport(e)}catch(s){d.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(ts).find((([,n])=>n===e));return i?.[0]}_getSocketCloseError(e){if(e)return e instanceof Error?e.message:String(e)}_createSocketCloseFlushReason(e){return{type:e?.error?"socket-error":"socket-close",socketClose:{code:e?.code,codeName:this._getSocketCloseCodeName(e?.code),reason:e?.reason,wasClean:e?.wasClean,error:this._getSocketCloseError(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?.socketGeneration)!==null&&s!==void 0?s:r;if(a<r)d.debug(`Skipping stale onNetworkClose for socket generation ${a} (current generation is ${r})`);else if(a!==this._reconnectCountedGeneration){this._flushIntermediateCallReports(this._createSocketCloseFlushReason(e)),d.debug("onNetworkClose called",{closeCode:e?.code,closeReason:e?.reason,wasClean:e?.wasClean,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,autoReconnect:this._autoReconnect,reconnectAttempts:this._reconnectAttempts}),this.relayProtocol&&Yt(this.relayProtocol);for(const l in this.subscriptions)Yt(l);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.stopSignalingHealthMonitor(),this.sessionid&&this._autoReconnect&&hi(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){d.info(`Reconnection exhausted after ${l} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1,this._terminateActiveCallsLocally();const p=Z(ci);F(D.Error,{error:p,sessionId:this.sessionid},this.uuid);return}const h=this.reconnectDelay;d.debug(`Reconnect attempt ${this._reconnectAttempts}${l>0?` of ${l}`:""} (delay=${h}ms)`),this._reconnectTimeout=setTimeout((()=>{d.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()}),h)}else if(d.debug("auto_reconnect disabled, not reconnecting",{voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,intentionalClose:this._intentionalClose}),!this._intentionalClose){const l=he(Jo);F(D.Warning,{warning:l,reason:"auto_reconnect_disabled",sessionId:this.sessionid},this.uuid)}this._intentionalClose=!1}else d.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],Re(e,null,i)):(delete this.subscriptions[e],Yt(e)))}_addSubscription(e,i=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},Ut(i)&&Ne(e,i,n))}_existsSubscription(e,i){return!(!this.subscriptions.hasOwnProperty(e)||!(!i||i&&this.subscriptions[e].hasOwnProperty(i)))}_attachListeners(){this._detachListeners(),d.debug("Attaching socket event listeners"),this.on(D.SocketOpen,this._onSocketOpen),this.on(D.SocketClose,this.onNetworkClose),this.on(D.SocketError,this.onNetworkClose),this.on(D.SocketMessage,this._onSocketMessage),this.on(D.SocketActivity,this._onSocketActivity)}_detachListeners(){d.debug("Detaching socket event listeners"),this.off(D.SocketOpen,this._onSocketOpen),this.off(D.SocketClose,this.onNetworkClose),this.off(D.SocketError,this.onNetworkClose),this.off(D.SocketMessage,this._onSocketMessage),this.off(D.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(),d.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&&(d.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Ti(st()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout((()=>this._resetKeepAlive()),35e3)}setPingReceived(){d.debug("Ping received"),this._pong=!0}_onSocketActivity(){this._signalingHealthMonitor.onSocketActivity()}onOutboundConfirmed(){this._signalingHealthMonitor.onOutboundConfirmed()}hasActiveCall(){const e=this.calls;if(!e)return!1;const i=new Set([V.Early,V.Active,V.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){d.debug(`Reconnection exhausted — locally terminating ${i.length} active call(s) (no BYE): ${i.join(", ")}`);
5for(const n of i)e[n]?.hangup({},!1)}}startSignalingHealthMonitor(){this._signalingHealthMonitor.start()}stopSignalingHealthMonitor(){this._signalingHealthMonitor.stop()}triggerIceRestart(e){const i=this.calls,n=i?.[e];if(!n)return d.warn(`Signaling health: cannot trigger ICE restart — call ${e} not found`),{started:!1,reason:"call not found"};const s=n.peer;if(!s?.restartIce)return d.warn(`Signaling health: cannot trigger ICE restart — no peer for call ${e}`),{started:!1,reason:"no peer"};const o=s.restartIce();return o.started||d.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){Ne(e,i)}static off(e){Re(e)}static uuid(){return qe()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}};fi.TOKEN_EXPIRY_WARNING_SECONDS=120,fi.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;var Nt=t=>navigator.mediaDevices.getUserMedia(t),it=t=>t&&t instanceof MediaStream,Lt=(t,e,i)=>{const n=nt(t);if(n!==null){if(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject&&n.srcObject!==e&&(d.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=he(Go);F(D.Warning,{warning:s,callId:i.callId,sessionId:i.sessionId},i.eventTarget)}n.srcObject=e}},vn=(t,e)=>{const i=nt(t);if(i){if(e&&i.srcObject!==e)return;i.srcObject=null}},fs=(t,e)=>R(void 0,void 0,void 0,(function*(){const i=nt(t);if(i===null)return d.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return d.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield i.setSinkId(e),!0}catch{return!1}})),Rr=t=>{t&&t.readyState==="live"&&t.stop()},ot=t=>{it(t)&&t.getTracks().forEach(Rr),t=null},Mt=t=>R(void 0,void 0,void 0,(function*(){d.info("RTCService.getUserMedia",t);const{audio:e,video:i}=t;if(!e&&!i)return null;try{return yield Nt(t)}catch(n){if(d.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,h=r,p=a;if(typeof r=="object"&&r!==null&&"deviceId"in r){l=!0;const f=Object.assign({},r);delete f.deviceId,h=Object.keys(f).length===0||f}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const f=Object.assign({},a);delete f.deviceId,p=Object.keys(f).length===0||f}return l?{audio:h,video:p}:null})(t);if(s){d.warn("Device not found or not readable, falling back to default device");try{return yield Nt(s)}catch(o){throw d.error("Fallback getUserMedia also failed: ",o),n}}}throw n}})),Ze=(t=null,e=!1)=>R(void 0,void 0,void 0,(function*(){let i=[];const n=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===Te.AudioIn||s===Te.AudioOut,video:!s||s===Te.Video}))(t)).catch((s=>(d.error(s),null)));if(n){if(ot(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})),fn=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Pt=(t,e,i)=>R(void 0,void 0,void 0,(function*(){const n=yield Ze(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})),Ar=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map((i=>{e.hasOwnProperty(i)&&t[i]!==null&&t[i]!==void 0||delete t[i]}))},mi=t=>t?{id:t.id,kind:t.kind,enabled:t.enabled,muted:t.muted,readyState:t.readyState}:null,mn=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=>mi(a))):[]},_i=(t,e)=>{if(!t)return!1;const{subscribed:i,alreadySubscribed:n}=yi(t);return i.includes(e)||n.includes(e)},yi=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach((i=>{e[i]=t[`${i}Channels`]||[]})),e},He=(t,e=null,i=null)=>{if(!it(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}}))},Kt=t=>{He(t,"audio",!0)},Tt=t=>{He(t,"audio",!1)};function Or(){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 p=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),f=p[0],b=parseInt(p[1],10);
5return{browserInfo:navigator.userAgent,name:f,version:b,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const p=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),f=p[0],b=parseInt(p[1],10);return{browserInfo:navigator.userAgent,name:f,version:b,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const p=navigator.userAgent.match(/safari/gim)[0],f=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),b=parseInt(f[1],10);return{browserInfo:navigator.userAgent,name:p,version:b,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const p=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),f=p[0],b=parseInt(p[1],10);return{browserInfo:navigator.userAgent,name:f,version:b,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,h=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:i,supportWebRTC:!!(o&&r&&a&&l&&h),supportWebRTCAudio:n,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!Mt}}catch(t){return t.message}}var oe;function _n(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 yn(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then((()=>{t._playFulfilled=!0})).catch((e=>{d.error("playAudio",e),t._playFulfilled=!0})))}function bn(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"})(oe||(oe={}));var Sn=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}},Dr=class extends ze{constructor(t,e){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:qe(),type:"message",role:"user",content:[{type:"input_text",text:t},...e?.map((i=>({type:"image_url",image_url:{url:i}})))]}}})}},xr=class extends ze{constructor(t){super(),this.method="ai_conversation",this.buildNotification({method:this.method,params:{type:"conversation.item.create",item:t}})}},pe=class ce{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 lr(s)})(this.logCollectorOptions),this.logCollector.start(),n=this.logCollector,os=n)}start(e){var i,n;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._lastIntermediateFlushTime=this.intervalStartTime,this._stopped=!1,d.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:ce.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 R(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(),d.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,h=i?.type==="socket-close"||i?.type==="socket-error",p=a>0||l>0||h;if(this._flushing||!p)return d.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 f=this._segmentIndex++,b=this.statsBuffer;this.statsBuffer=[];const g=(r=(o=this.logCollector)===null||o===void 0?void 0:o.drain())!==null&&r!==void 0?r:[],v=new Date;this._lastIntermediateFlushTime=v;const y=Object.assign(Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(v.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:v.toISOString()}),stats:b},g.length>0?{logs:g}:{}),{segment:f}),i?{flushReason:i}:{});return d.info("CallReportCollector: Flushed intermediate segment",{segment:f,intervals:b.length,logEntries:g.length,callId:e.callId,flushReason:i}),y}finally{this._flushing=!1}}postReport(e,i,n,s){var o,r;return R(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 d.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void d.info("CallReportCollector: Skipping report — no stats or logs collected");const h=this._segmentIndex>0,p=this._segmentIndex,f=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}:{}),h?{segment:p}:{});yield this._sendPayload(f,i,n,s,!0)}))}sendPayload(e,i,n,s,o=!1){return R(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 R(this,void 0,void 0,(function*(){const h=new URL(n),p=`${h.protocol.replace(/^ws/,"http")}//${h.host}/call_report`,f=o?"final report":`intermediate segment ${e.segment}`;d.info(`CallReportCollector: Posting ${f}`,{endpoint:p,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 b={"Content-Type":"application/json","x-call-report-id":i,"x-call-id":e.summary.callId};s&&(b["x-voice-sdk-id"]=s);const g=JSON.stringify(e),v=(o||r)&&g.length<=ce.KEEPALIVE_BODY_LIMIT_BYTES;let y;for(let S=0;S<=ce.RETRY_DELAYS_MS.length;S++){try{const T=yield fetch(p,Object.assign({method:"POST",headers:b,body:g},v?{keepalive:!0}:{}));if(T.ok)return void d.info(`CallReportCollector: Successfully posted ${f}`,{attempt:S+1,status:T.status});{const N=yield T.text();y=new Error(`Call report POST failed with status ${T.status}`),d.error(`CallReportCollector: Failed to post ${f}`,{attempt:S+1,status:T.status,error:N})}}catch(T){y=T,d.warn(`CallReportCollector: Network error posting ${f}`,{attempt:S+1,error:T})}const E=ce.RETRY_DELAYS_MS[S];if(E===void 0)break;d.info(`CallReportCollector: Retrying ${f} in ${E}ms`,{attempt:S+2}),yield new Promise((T=>
5setTimeout(T,E)))}throw d.error(`CallReportCollector: Exhausted retries posting ${f}`,{error:y}),y instanceof Error?y:new Error("Call report POST failed after retries")}))}getStatsBuffer(){return this.statsBuffer}shouldForceRelayCandidateForRecovery(){var e,i,n,s,o,r,a,l,h,p,f,b,g,v,y,S;if(this.statsBuffer.length<2)return!1;const E=this.statsBuffer[this.statsBuffer.length-1],T=this.statsBuffer[this.statsBuffer.length-2],N=(e=E.ice)===null||e===void 0?void 0:e.local;if(!(N?.networkType==="vpn"&&N?.candidateType!=="relay"))return!1;const $=((i=E.ice)===null||i===void 0?void 0:i.writable)===!1,j=((n=E.transport)===null||n===void 0?void 0:n.iceState)==="disconnected"||((s=E.transport)===null||s===void 0?void 0:s.iceState)==="failed",q=this._positiveDelta((o=E.ice)===null||o===void 0?void 0:o.requestsSent,(r=T.ice)===null||r===void 0?void 0:r.requestsSent),Y=this._positiveDelta((a=E.ice)===null||a===void 0?void 0:a.responsesReceived,(l=T.ice)===null||l===void 0?void 0:l.responsesReceived),M=q>0&&Y===0,c=this._positiveDelta((p=(h=E.audio)===null||h===void 0?void 0:h.outbound)===null||p===void 0?void 0:p.bytesSent,(b=(f=T.audio)===null||f===void 0?void 0:f.outbound)===null||b===void 0?void 0:b.bytesSent),u=this._positiveDelta((v=(g=E.audio)===null||g===void 0?void 0:g.inbound)===null||v===void 0?void 0:v.bytesReceived,(S=(y=T.audio)===null||y===void 0?void 0:y.inbound)===null||S===void 0?void 0:S.bytesReceived);return $||j||M||c>0&&u===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(_t,!1),this._trackBreach(di,!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(ce.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 R(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,h=null,p=null,f=null;const b=[];let g=null;
5s.forEach((c=>{switch(c.type){case"outbound-rtp":c.kind==="audio"&&c.mediaType==="audio"&&(r=c);break;case"inbound-rtp":c.kind==="audio"&&c.mediaType==="audio"&&(a=c);break;case"media-playout":c.kind==="audio"&&(l=c);break;case"remote-inbound-rtp":c.kind==="audio"&&(h=c);break;case"remote-outbound-rtp":c.kind==="audio"&&(p=c);break;case"candidate-pair":(c.nominated||c.state==="succeeded")&&b.push(c);break;case"transport":g=c}}));const v=g?.selectedCandidatePairId,y=v?(n=(i=s).get)===null||n===void 0?void 0:n.call(i,v):void 0,S=this._getCodec(s,r?.codecId),E=this._getCodec(s,a?.codecId);if(f=y?.type==="candidate-pair"?y:v?b.find((c=>c.id===v))||b[b.length-1]||null:b[b.length-1]||null,r){const c=this._getOutboundAudioLevel(s,r);if(c!==null&&this.intervalAudioLevels.outbound.push(c),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const u=(r.bytesSent||0)-this.previousStats.outboundBytes,m=(r.timestamp||o.getTime())-this.previousStats.timestamp;if(m>0){const C=8*u*1e3/m;this.intervalBitrates.outbound.push(C)}}this.previousStats.outboundBytes=r.bytesSent}if(a){const c=this._getInboundAudioLevel(s,a);if(c!==null&&this.intervalAudioLevels.inbound.push(c),a.jitter!==void 0&&this.intervalJitters.push(1e3*a.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const u=(a.bytesReceived||0)-this.previousStats.inboundBytes,m=(a.timestamp||o.getTime())-this.previousStats.timestamp;if(m>0){const C=8*u*1e3/m;this.intervalBitrates.inbound.push(C)}}this.previousStats.inboundBytes=a.bytesReceived}let T,N,$,j,q;f&&f.currentRoundTripTime!==void 0&&this.intervalRTTs.push(f.currentRoundTripTime),f&&(T=this._resolveCandidate(s,f.localCandidateId),N=this._resolveCandidate(s,f.remoteCandidateId)),f&&($=Object.assign(Object.assign({id:f.id,localCandidateId:f.localCandidateId,remoteCandidateId:f.remoteCandidateId,state:f.state,nominated:f.nominated,writable:f.writable,currentRoundTripTime:f.currentRoundTripTime,requestsSent:f.requestsSent,responsesReceived:f.responsesReceived},T?{local:T}:{}),N?{remote:N}:{}),this.previousCandidatePairSnapshot!==null&&f.id!==this.previousCandidatePairSnapshot.id&&(d.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:$}),this._emitWarning(jo)),this.previousCandidatePairSnapshot=$),r&&(j=this._getLocalAudioTrackSnapshot(),q=this._getOutboundAudioSourceStats(s,r)),this._logLocalAudioTrackSnapshot(j,q),this.previousStats.timestamp=o.getTime();const Y=o.getTime()-this.intervalStartTime.getTime(),M=this._collectionIntervalFor();if(e||Y>=M){const c=this._createStatsEntry(this.intervalStartTime,o,r,a,f,T,N,g,j,q,l,h,p,S,E);this.statsBuffer.push(c),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),d.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(c,a),this._requestIntermediateFlushIfNeeded(o),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(s){d.error("CallReportCollector: Error collecting stats",{error:s})}}))}_getIntermediateReportInterval(){var e;return(e=this.options.intermediateReportInterval)!==null&&e!==void 0?e:ce.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 d.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>=ce.STATS_FLUSH_THRESHOLD||o>=ce.LOGS_FLUSH_THRESHOLD?l="buffer-limit":r>0&&a>=r&&(l="safety-interval"),l){d.info("CallReportCollector: Requesting intermediate report flush",{reason:l,statsIntervals:s,logEntries:o,msSinceLastFlush:a}),this._lastIntermediateFlushTime=e;try{this.onFlushNeeded()}catch(h){d.error("CallReportCollector: onFlushNeeded callback error",{error:h})}}}_checkQualityWarnings(e,i){var n,s,o,r,a,l,h,p,f,b,g,v,y,S,E;if(!this.onWarning)return;const T=(n=e.connection)===null||n===void 0?void 0:n.roundTripTimeAvg,N=(o=(s=e.audio)===null||s===void 0?void 0:s.inbound)===null||o===void 0?void 0:o.jitterAvg;let $;if(i){const j=(r=i.packetsReceived)!==null&&r!==void 0?r:0,q=(a=i.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const Y=j-this._prevPacketsReceived,M=q-this._prevPacketsLost,c=Y+M;c>0&&($=M/c*100)}this._prevPacketsReceived=j,this._prevPacketsLost=q}if(this._trackBreach(Ao,T!==void 0&&T>ce.THRESHOLD_RTT_MS),this._trackBreach(Oo,N!==void 0&&N>ce.THRESHOLD_JITTER_MS),this._trackBreach(Do,$!==void 0&&$>ce.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),this._isHeld?this._trackBreach(_t,!1):this._trackLowInboundAudio(e),T!==void 0&&N!==void 0&&$!==void 0){const j=93.2-.11*N-2.5*$-.01*(1e3*T),q=Math.max(1,Math.min(4.5,1+.035*j+j*(j-60)
5*(100-j)*7e-6));this._trackBreach(en,q<ce.THRESHOLD_MOS)}else this._trackBreach(en,!1);if(((h=(l=e.audio)===null||l===void 0?void 0:l.inbound)===null||h===void 0?void 0:h.bytesReceived)!==void 0){const j=(b=(f=(p=this._previousStatsEntryForWarnings)===null||p===void 0?void 0:p.audio)===null||f===void 0?void 0:f.inbound)===null||b===void 0?void 0:b.bytesReceived,q=e.audio.inbound.bytesReceived;this._trackBreach(di,!this._isHeld&&j!==void 0&&q-j==0)}if(((v=(g=e.audio)===null||g===void 0?void 0:g.outbound)===null||v===void 0?void 0:v.bytesSent)!==void 0){const j=(E=(S=(y=this._previousStatsEntryForWarnings)===null||y===void 0?void 0:y.audio)===null||S===void 0?void 0:S.outbound)===null||E===void 0?void 0:E.bytesSent,q=e.audio.outbound.bytesSent;this._trackBreach(es,j!==void 0&&q-j==0)}this._previousStatsEntryForWarnings=e}_trackLowLocalAudio(e){var i;const n=(i=e.audio)===null||i===void 0?void 0:i.outbound,s=n?.audioLevelAvg,o=n?.localTrack;if(s===void 0||o?.enabled===!1||o?.muted===!0)return void this._resetLowLocalAudioWarning();if(!(s<=ce.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(mt,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=ce.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(mt)):this._trackBreach(mt,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(mt,!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?.audioLevelAvg;if(s===void 0)return void this._trackBreach(_t,!1);const o=s<=ce.THRESHOLD_INBOUND_AUDIO_LEVEL;this._trackBreach(_t,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]>=ce.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=ce.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=he(e);d.warn(`CallReportCollector: warning ${n.code}: ${n.message}`),(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){d.error(`CallReportCollector: Failed to emit warning ${e}`,{error:n})}}_createStatsEntry(e,i,n,s,o,r,a,l,h,p,f,b,g,v,y){const S={intervalStartUtc:e.toISOString(),intervalEndUtc:i.toISOString(),audio:{}};if(n&&(S.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)},h?{localTrack:h}:{}),p?{mediaSource:p}:{}),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}:{}),v?{codec:this._buildCodecSnapshot(v,n.codecId)}:{})),s&&(S.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}:{}
5),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}:{}),y?{codec:this._buildCodecSnapshot(y,s.codecId)}:{})),o&&(S.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}),S.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&&(S.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}:{})),f&&(S.mediaPlayout=this._withoutUndefined({synthesizedSamplesEvents:f.synthesizedSamplesEvents,synthesizedSamplesDuration:f.synthesizedSamplesDuration,totalPlayoutDelay:f.totalPlayoutDelay,totalSamplesCount:f.totalSamplesCount,totalSamplesDuration:f.totalSamplesDuration})),b||g){const E={};if(b){const T=b.jitter!==void 0?1e3*b.jitter:void 0;let N;typeof b.totalRoundTripTime=="number"&&typeof b.roundTripTimeMeasurements=="number"&&b.roundTripTimeMeasurements>0&&(N=b.totalRoundTripTime/b.roundTripTimeMeasurements),E.inbound=this._withoutUndefined({packetsReceived:b.packetsReceived,packetsLost:b.packetsLost,fractionLost:b.fractionLost,jitter:T,roundTripTime:b.roundTripTime,totalRoundTripTime:b.totalRoundTripTime,roundTripTimeMeasurements:b.roundTripTimeMeasurements,roundTripTimeAvg:N,nackCount:b.nackCount,reportsReceived:b.reportsReceived,packetsDiscarded:b.packetsDiscarded})}g&&(E.outbound=this._withoutUndefined({packetsSent:g.packetsSent,bytesSent:g.bytesSent,reportsCount:g.reportsCount,roundTripTime:g.roundTripTime,totalPacketSendDelay:g.totalPacketSendDelay})),S.remoteRtcp=E}return S}_resolveCandidate(e,i){if(!i)return void d.debug("CallReportCollector: candidateId is empty, skipping resolve");const n=e.get(i);if(!n)return void d.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;d.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;
5return 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 h;return((h=l.track)===null||h===void 0?void 0:h.kind)==="audio"})),s=n?.track;if(!s)return;const o=(i=s.getSettings)===null||i===void 0?void 0:i.call(s),r=this._withoutUndefined({deviceId:o?.deviceId,groupId:o?.groupId,channelCount:o?.channelCount,sampleRate:o?.sampleRate,sampleSize:o?.sampleSize,latency:o?.latency,echoCancellation:o?.echoCancellation,noiseSuppression:o?.noiseSuppression,autoGainControl: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){d.debug("CallReportCollector: unable to snapshot local audio track",{error:n});return}}_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,d.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?.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,h=i-a;if(h<=0)return null;const p=Math.sqrt(l/h);return Math.min(1,Math.max(0,p))}_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:[]}}};pe.INITIAL_COLLECTION_INTERVAL_MS=1e3,pe.STATS_FLUSH_THRESHOLD=300,pe.LOGS_FLUSH_THRESHOLD=800,pe.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,pe.CONSECUTIVE_BREACHES_REQUIRED=3,pe.THRESHOLD_RTT_MS=.4,pe.THRESHOLD_JITTER_MS=30,pe.THRESHOLD_PACKET_LOSS_PCT=1,pe.THRESHOLD_MOS=3.5,pe.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,pe.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,pe.THRESHOLD_INBOUND_AUDIO_LEVEL=.001,pe.WARNING_THROTTLE_MS=15e3,pe.RETRY_DELAYS_MS=[500,1e3,2e3],pe.KEEPALIVE_BODY_LIMIT_BYTES=61440;var je=class Ie{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 d.warn("CallRecorder: MediaStreamTrackProcessor unavailable — recording disabled for this call"),this._emitWarning(xo),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 d.info("CallRecorder: no audio tracks available to re
5cord — recording idle for this call",{callId:this.callContext.callId}),void(this._started=!0);this._startedAt=new Date,this._started=!0,this._scheduleFlush(),d.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,d.info("CallRecorder: stopped",{callId:this.callContext.callId,packetsBuffered:this._buffers.local.length+this._buffers.remote.length}))}postFinalReport(){return R(this,void 0,void 0,(function*(){if(!this.options.enabled)return;if(this.stop(),!this._startedAt)return void d.debug("CallRecorder: postFinalReport skipped — never started");const e=this._resolveEndpointFromContext();if(!e)return void d.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 h=this._drain(l);if(h.length===0)return[];const p=this._buildEnvelope(h,l,"final",n,s);return[{envelope:p,bodyBytes:JSON.stringify(p).length}]})),r=o.reduce(((l,h)=>l+h.bodyBytes),0)<=Ie.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),R(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||d.warn("CallRecorder: reader loop error",{track:i,error:a})}}))}catch(n){d.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 h={rtpSeq:s.seq,rtpTs:l,rtpSsrc:s.ssrc,capturedAt:new Date().toISOString(),payloadBytes:a};this._pushPacket(h,e)}_pushPacket(e,i){const n=e.payloadBytes.length+Ie.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+Ie.PACKET_OVERHEAD_BYTES)}this._overflowWarnedThisWindow[i]||(this._overflowWarnedThisWindow[i]=!0,d.warn("CallRecorder: buffer overflow — oldest packets dropped",{track:i}),this._emitWarning(No))}}_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()*Ie.BYTES_PER_SAMPLE+Ie.FRAMES_PER_SECOND*Ie.PACKET_OVERHEAD_BYTES;return Math.max(1e3,this._maxBufferBytes()/e*500)}_maxBufferBytes(){var e;return(e=this.options.maxBufferBytes)!==null&&e!==void 0?e:us}_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=>{d.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 R(this,void 0,void 0,(function*(){if(!this._flushing&&!this._stopped){this._flushing=!0;try{const e=this._resolveEndpointFromContext();if(!e)return void d.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=>{d.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)}
5_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 R(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<=Ie.KEEPALIVE_BODY_LIMIT_BYTES,a=this.options.fetchImpl||fetch;let l;for(let h=0;h<=Ie.RETRY_DELAYS_MS.length;h++){try{const f=yield a(e,Object.assign({method:"POST",headers:s,body:o},r?{keepalive:!0}:{}));if(f.ok)return void d.info("CallRecorder: posted",{track:i.track,segment:i.segment,attempt:h+1,status:f.status,packets:i.packet_count});{const b=yield f.text().catch((()=>""));l=new Error(`Call recording POST failed with status ${f.status}`),d.error("CallRecorder: failed to post",{track:i.track,segment:i.segment,attempt:h+1,status:f.status,error:b})}}catch(f){l=f,d.warn("CallRecorder: network error posting",{track:i.track,segment:i.segment,attempt:h+1,error:f})}const p=Ie.RETRY_DELAYS_MS[h];if(p===void 0)break;d.info("CallRecorder: retrying",{track:i.track,segment:i.segment,inMs:p,attempt:h+2}),yield new Promise((f=>setTimeout(f,p)))}throw d.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=he(e);(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){d.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;var Nr=class{constructor(){this._rawDeviceCache=[],this._deviceChangeHandler=null,this._stopped=!1}logDevicesAtStart(){return R(this,void 0,void 0,(function*(){try{const t=yield this._enumerateAudioDevices();this._rawDeviceCache=t,d.debug("MediaDeviceCollector: devices at call start",{devices:t}),this._startDeviceChangeListener()}catch(t){d.debug("MediaDeviceCollector: failed to log devices at start",{error:t})}}))}stop(){this._stopped=!0,this._removeDeviceChangeListener()}_enumerateAudioDevices(){return R(this,void 0,void 0,(function*(){try{if(typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.enumerateDevices=="function")return(yield navigator.mediaDevices.enumerateDevices()).filter((t=>t.kind==="audioinput"||t.kind==="audiooutput"))}catch(t){d.debug("MediaDeviceCollector: enumerateDevices failed",{error:t})}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 R(this,void 0,void 0,(function*(){if(!this._stopped)try{const t=yield this._enumerateAudioDevices(),e=new Set(this._rawDeviceCache.map((o=>o.deviceId))),i=new Set(t.map((o=>o.deviceId))),n=t.filter((o=>!e.has(o.deviceId))),s=this._rawDeviceCache.filter((o=>!i.has(o.deviceId)));(n.length>0||s.length>0)&&d.debug("MediaDeviceCollector: devices changed during call",{connected:n,disconnected:s}),this._rawDeviceCache=t}catch(t){d.debug("MediaDeviceCollector: error handling devicechange",{error:t})}}))}},St,ms=ss((function(t,e){var i;function n(){}function s(){s.init.call(this)}function o(c){return c._maxListeners===void 0?s.defaultMaxListeners:c._maxListeners}function r(c,u,m,C){var k,O,A;if(typeof m!="function")throw new TypeError('"listener" argument must be a function');
5if((O=c._events)?(O.newListener&&(c.emit("newListener",u,m.listener?m.listener:m),O=c._events),A=O[u]):(O=c._events=new n,c._eventsCount=0),A){if(typeof A=="function"?A=O[u]=C?[m,A]:[A,m]:C?A.unshift(m):A.push(m),!A.warned&&(k=o(c))&&0<k&&A.length>k){A.warned=!0;var P=new Error("Possible EventEmitter memory leak detected. "+A.length+" "+u+" listeners added. Use emitter.setMaxListeners() to increase limit");P.name="MaxListenersExceededWarning",P.emitter=c,P.type=u,P.count=A.length,(function(W){typeof console.warn=="function"?console.warn(W):console.log(W)})(P)}}else A=O[u]=m,++c._eventsCount;return c}function a(c,u,m){function C(){c.removeListener(u,C),k||(k=!0,m.apply(c,arguments))}var k=!1;return C.listener=m,C}function l(c){var u=this._events;if(u){var m=u[c];if(typeof m=="function")return 1;if(m)return m.length}return 0}function h(c,u){for(var m=Array(u);u--;)m[u]=c[u];return m}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(c){if(typeof c!="number"||0>c||isNaN(c))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=c,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(c){var u,m,C,k,O,A,P,W=c==="error";if(A=this._events)W=W&&A.error==null;else if(!W)return!1;if(P=this.domain,W){if(u=arguments[1],!P){if(u instanceof Error)throw u;var ee=new Error('Uncaught, unspecified "error" event. ('+u+")");throw ee.context=u,ee}return u||(u=new Error('Uncaught, unspecified "error" event')),u.domainEmitter=this,u.domain=P,u.domainThrown=!1,P.emit("error",u),!1}if(!(m=A[c]))return!1;var te=typeof m=="function";switch(C=arguments.length){case 1:(function(I,x,K){if(x)I.call(K);else for(var z=I.length,ne=h(I,z),ae=0;ae<z;++ae)ne[ae].call(K)})(m,te,this);break;case 2:(function(I,x,K,z){if(x)I.call(K,z);else for(var ne=I.length,ae=h(I,ne),fe=0;fe<ne;++fe)ae[fe].call(K,z)})(m,te,this,arguments[1]);break;case 3:(function(I,x,K,z,ne){if(x)I.call(K,z,ne);else for(var ae=I.length,fe=h(I,ae),Oe=0;Oe<ae;++Oe)fe[Oe].call(K,z,ne)})(m,te,this,arguments[1],arguments[2]);break;case 4:(function(I,x,K,z,ne,ae){if(x)I.call(K,z,ne,ae);else for(var fe=I.length,Oe=h(I,fe),Le=0;Le<fe;++Le)Oe[Le].call(K,z,ne,ae)})(m,te,this,arguments[1],arguments[2],arguments[3]);break;default:for(k=Array(C-1),O=1;O<C;O++)k[O-1]=arguments[O];(function(I,x,K,z){if(x)I.apply(K,z);else for(var ne=I.length,ae=h(I,ne),fe=0;fe<ne;++fe)ae[fe].apply(K,z)})(m,te,this,k)}return!0},s.prototype.addListener=function(c,u){return r(this,c,u,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(c,u){return r(this,c,u,!0)},s.prototype.once=function(c,u){if(typeof u!="function")throw new TypeError('"listener" argument must be a function');return this.on(c,a(this,c,u)),this},s.prototype.prependOnceListener=function(c,u){if(typeof u!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(c,a(this,c,u)),this},s.prototype.removeListener=function(c,u){var m,C,k,O,A;if(typeof u!="function")throw new TypeError('"listener" argument must be a function');if(!(C=this._events))return this;if(!(m=C[c]))return this;if(m===u||m.listener&&m.listener===u)--this._eventsCount==0?this._events=new n:(delete C[c],C.removeListener&&this.emit("removeListener",c,m.listener||u));else if(typeof m!="function"){for(k=-1,O=m.length;0<O--;)if(m[O]===u||m[O].listener&&m[O].listener===u){A=m[O].listener,k=O;break}if(0>k)return this;if(m.length===1){if(m[0]=void 0,--this._eventsCount==0)return this._events=new n,this;delete C[c]}else(function(P,W){for(var ee=W,te=ee+1,I=P.length;te<I;ee+=1,te+=1)P[ee]=P[te];P.pop()})(m,k);
5C.removeListener&&this.emit("removeListener",c,A||u)}return this},s.prototype.removeAllListeners=function(c){var u,m;if(!(m=this._events))return this;if(!m.removeListener)return arguments.length===0?(this._events=new n,this._eventsCount=0):m[c]&&(--this._eventsCount==0?this._events=new n:delete m[c]),this;if(arguments.length===0){for(var C,k=Object.keys(m),O=0;O<k.length;++O)(C=k[O])!=="removeListener"&&this.removeAllListeners(C);return this.removeAllListeners("removeListener"),this._events=new n,this._eventsCount=0,this}if(typeof(u=m[c])=="function")this.removeListener(c,u);else if(u)do this.removeListener(c,u[u.length-1]);while(u[0]);return this},s.prototype.listeners=function(c){var u,m,C=this._events;return C?m=(u=C[c])?typeof u=="function"?[u.listener||u]:(function(k){for(var O=Array(k.length),A=0;A<O.length;++A)O[A]=k[A].listener||k[A];return O})(u):[]:m=[],m},s.listenerCount=function(c,u){return typeof c.listenerCount=="function"?c.listenerCount(u):l.call(c,u)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var p,f=new Uint8Array(16);function b(){if(!p&&!(p=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 p(f)}for(var g=/^(?:[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=[],y=0;256>y;++y)v.push((y+256).toString(16).substr(1));function S(c){var u=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,m=(v[c[u+0]]+v[c[u+1]]+v[c[u+2]]+v[c[u+3]]+"-"+v[c[u+4]]+v[c[u+5]]+"-"+v[c[u+6]]+v[c[u+7]]+"-"+v[c[u+8]]+v[c[u+9]]+"-"+v[c[u+10]]+v[c[u+11]]+v[c[u+12]]+v[c[u+13]]+v[c[u+14]]+v[c[u+15]]).toLowerCase();if(!(function(C){return typeof C=="string"&&g.test(C)})(m))throw TypeError("Stringified UUID is invalid");return m}function E(c,u,m){var C=(c=c||{}).random||(c.rng||b)();if(C[6]=64|15&C[6],C[8]=128|63&C[8],u){m=m||0;for(var k=0;16>k;++k)u[m+k]=C[k];return u}return S(C)}function T(c,u){if(!c||!u)return{};const m={...c};return m.localCandidateId&&(m.local={...u.get(m.localCandidateId)}),m.remoteCandidateId&&(m.remote={...u.get(m.remoteCandidateId)}),m}function N(c,u,m){return 8*(function(C,k,O){const A=C[O],P=k?k[O]:null;return A===null||P===null?null:(A-P)/(C.timestamp-k.timestamp)*1e3})(c,u,m)}function $(c){if(!c.entries)return c;const u={};return c.forEach((function(m,C){u[C]=m})),u}function j(c,u,m={}){if(!c)return null;let C={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};m.remote&&(C.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const k of c.values())switch(k.type){case"outbound-rtp":{const O=k.mediaType||k.kind,A={};let P={};if(!["audio","video"].includes(O))continue;if(k.codecId){const W=c.get(k.codecId);W&&(A.clockRate=W.clockRate,A.mimeType=W.mimeType,A.payloadType=W.payloadType)}P=c.get(k.mediaSourceId)||c.get(k.trackId)||{},C[O].outbound.push({...k,...A,track:{...P}});break}case"inbound-rtp":{let O=k.mediaType||k.kind,A={};const P={};if(!["audio","video"].includes(O))if(k.id.includes("Video"))O="video";else{if(!k.id.includes("Audio"))continue;O="audio"}if(k.codecId){const W=c.get(k.codecId);W&&(P.clockRate=W.clockRate,P.mimeType=W.mimeType,P.payloadType=W.payloadType)}if(!C.connection.id&&k.transportId){const W=c.get(k.transportId);if(W&&W.selectedCandidatePairId){const ee=c.get(W.selectedCandidatePairId);C.connection=T(ee,c)}}A=c.get(k.mediaSourceId)||c.get(k.trackId)||{},C[O].inbound.push({...k,...P,track:{...A}});break}case"peer-connection":C.connection.dataChannelsClosed=k.dataChannelsClosed,C.connection.dataChannelsOpened=k.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!m.remote)break;let O=k.mediaType||k.kind;const A={};if(!["audio","video"].includes(O))if(k.id.includes("Video"))O="video";else{if(!k.id.includes("Audio"))continue;O="audio"}if(k.codecId){const P=c.get(k.codecId);P&&(A.clockRate=P.clockRate,A.mimeType=P.mimeType,A.payloadType=P.payloadType)}if(!C.connection.id&&k.transportId){const P=c.get(k.transportId);if(P&&P.selectedCandidatePairId){const W=c.get(P.selectedCandidatePairId);C.connection=T(W,c)}}C.remote[O].inbound.push({...k,...A});break}case"remote-outbound-rtp":{if(!m.remote)break;const O=k.mediaType||k.kind,A={};if(!["audio","video"].includes(O))continue;if(k.codecId){const P=c.get(k.codecId);P&&(A.clockRate=P.clockRate,A.mimeType=P.mimeType,A.payloadType=P.payloadType)}C.remote[O].outbound.push({...k,...A});break}}if(!C.connection.id)for(const k of c.values())k.type==="candidate-pair"&&k.nominated&&k.state==="succeeded"&&(C.connection=T(k,c));return C=(function(k,O){return O&&(k.audio.inbound.map((A=>{let P=O.audio.inbound.find((W=>W.id===A.id));A.bitrate=N(A,P,"bytesReceived"),A.packetRate=N(A,P,"packetsReceived")})),k.audio.outbound.map((A=>{let P=O.audio.outbound.find((W=>W.id===A.id));A.bitrate=N(A,P,"bytesSent"),A.packetRate=N(A,P,"packetsSent")})),k.video.inbound.map((A=>{let P=O.video.inbound.find((W=>W.id===A.id));A.bitrate=N(A,P,"bytesReceived"),A.packetRate=N(A,P,"packetsReceived")})),k.video.outbound.map((A=>{let P=O.video.outbound.find((W=>W.id===A.id));A.bitrate=N(A,P,"bytesSent"),A.packetRate=N(A,P,"packetsSent")}))),k})(C,u),C}let q,Y={},M=[];e.WebRTCStats=class extends s{constructor(c){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>
5"u")throw new Error("WebRTCStats only works in browser");const u={...c};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=u.getStatsInterval||1e3,this.rawStats=!!u.rawStats,this.statsObject=!!u.statsObject,this.filteredStats=!!u.filteredStats,this.shouldWrapGetUserMedia=!!u.wrapGetUserMedia,typeof u.remote=="boolean"&&(this.remote=u.remote),this.debug=!!u.debug,this.logLevel=u.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(c,u){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:c,pc:u})}async addConnection(c){const{pc:u,peerId:m}=c;let{connectionId:C,remote:k}=c;if(k=typeof k=="boolean"?k:this.remote,!(u&&u instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!m)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[m]){if(C&&C in this.peersToMonitor[m])throw new Error(`We are already monitoring connection with id ${C}.`);for(let A in this.peersToMonitor[m]){const P=this.peersToMonitor[m][A];if(P.pc===u)throw new Error(`We are already monitoring peer with id ${m}.`);P.pc.connectionState==="closed"&&this.removeConnection({pc:P.pc})}}const O=u.getConfiguration();return O.iceServers&&O.iceServers.forEach((function(A){delete A.credential})),C||(C=E()),this.emitEvent({event:"addConnection",tag:"peer",peerId:m,connectionId:C,data:{options:c,peerConfiguration:O}}),this.monitorPeer({peerId:m,connectionId:C,pc:u,remote:k}),{connectionId:C}}getTimeline(c){return this.timeline=this.timeline.sort(((u,m)=>u.timestamp.getTime()-m.timestamp.getTime())),c?this.timeline.filter((u=>u.tag===c)):this.timeline}get logger(){const c=u=>{const m=["none","error","warn","info","debug"];return m.slice(0,m.indexOf(this.logLevel)+1).indexOf(u)>-1};return{error(...u){this.debug&&c("error")&&console.error("[webrtc-stats][error] ",...u)},warn(...u){this.debug&&c("warn")&&console.warn("[webrtc-stats][warn] ",...u)},info(...u){this.debug&&c("info")&&console.log("[webrtc-stats][info] ",...u)},debug(...u){this.debug&&c("debug")&&console.debug("[webrtc-stats][debug] ",...u)}}}
5removeConnection(c){let u,{connectionId:m,pc:C}=c;if(!C&&!m)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(m){if(typeof m!="string")throw new Error("connectionId must be a string.");for(let k in this.peersToMonitor)m in this.peersToMonitor[k]&&(C=this.peersToMonitor[k][m].pc,u=k)}else if(C){if(!(C instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let k in this.peersToMonitor)for(let O in this.peersToMonitor[k])this.peersToMonitor[k][O].pc===C&&(m=O,u=k)}if(!C||!m)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(m,C),delete this.peersToMonitor[u][m],Object.values(this.peersToMonitor[u]).length===0&&delete this.peersToMonitor[u],{connectionId:m}}removeAllPeers(){for(let c in this.peersToMonitor)this.removePeer(c)}removePeer(c){if(this.logger.info(`Removing PeerConnection with id ${c}.`),this.peersToMonitor[c]){for(let u in this.peersToMonitor[c]){let m=this.peersToMonitor[c][u].pc;this.removePeerConnectionEventListeners(u,m)}delete this.peersToMonitor[c]}}destroy(){this.removeAllPeers(),M.forEach((c=>{this.removeTrackEventListeners(c)})),M=[],this.shouldWrapGetUserMedia&&q&&(navigator.mediaDevices.getUserMedia=q)}monitorPeer(c){let{peerId:u,connectionId:m,pc:C,remote:k}=c;if(!C)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const O={pc:C,connectionId:m,stream:null,stats:{parsed:null,raw:null},options:{remote:k}};if(this.peersToMonitor[u]){if(m in this.peersToMonitor[u])return void this.logger.warn(`Already watching connection with ID ${m}`);this.peersToMonitor[u][m]=O}else this.peersToMonitor[u]={[m]:O};this.addPeerConnectionEventListeners(u,m,C),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then((c=>{c.forEach((u=>{this.emitEvent(u)}))}))}),this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(c=null){this.logger.info(c?`Getting stats from peer ${c}`:"Getting stats from all peers");let u={};if(c){if(!this.peersToMonitor[c])throw new Error(`Cannot get stats. Peer with id ${c} does not exist`);u[c]=this.peersToMonitor[c]}else u=this.peersToMonitor;let m=[];for(const C in u)for(const k in u[C]){const O=u[C][k],A=O.pc;if(A&&!this.checkIfConnectionIsClosed(C,k,A))try{const P=this.getTimestamp(),W=A.getStats(null);if(W){const ee=await W,te=this.getTimestamp(),I=$(ee),x={remote:O.options.remote},K=j(ee,O.stats.parsed,x),z={event:"stats",tag:"stats",peerId:C,connectionId:k,timeTaken:te-P,data:K};this.rawStats===!0&&(z.rawStats=ee),this.statsObject===!0&&(z.statsObject=I),this.filteredStats===!0&&(z.filteredStats=this.filteroutStats(I)),m.push(z),O.stats.parsed=K}else this.logger.error(`PeerConnection from peer ${C} did not return any stats data`)}catch(P){this.logger.error(P)}}return m}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const c in this.peersToMonitor)for(const u in this.peersToMonitor[c]){const m=this.peersToMonitor[c][u].pc;this.checkIfConnectionIsClosed(c,u,m)}}),this.connectionMonitoringInterval)}checkIfConnectionIsClosed(c,u,m){const C=this.isConnectionClosed(m);if(C){this.removeConnection({pc:m});let k=m.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:k,peerId:c,connectionId:u,tag:"connection",data:"closed"})}return C}isConnectionClosed(c){return c.connectionState==="closed"||c.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."),q=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const c=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=function(){return c({constraints:arguments[0]}),q.apply(navigator.mediaDevices,arguments).then((u=>(c({stream:u}),u)),(u=>(c({error:u}),Promise.reject(u))))}.bind(navigator.mediaDevices)}filteroutStats(c={}){const u={...c};for(const C in u){var m=u[C];this.statsToMonitor.includes(m.type)||delete u[C]}return u}get peerConnectionListeners(){return{icecandidate:(c,u,m,C)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",C),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:c,connectionId:u,data:C.candidate})},track:(c,u,m,C)=>{this.logger.debug(`[pc-event] track | peerId: ${c}`,C);const k=C.track,O=C.streams[0];c in this.peersToMonitor&&u in this.peersToMonitor[c]&&(this.peersToMonitor[c][u].stream=O),this.addTrackEventListeners(k,u),this.emitEvent({event:"ontrack",tag:"track",peerId:c,connectionId:u,data:{stream:O?this.get
5StreamDetails(O):null,track:k?this.getMediaTrackDetails(k):null,title:C.track.kind+":"+C.track.id+" "+C.streams.map((function(A){return"stream:"+A.id}))}})},signalingstatechange:(c,u,m)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${c}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:c,connectionId:u,data:{signalingState:m.signalingState,localDescription:m.localDescription,remoteDescription:m.remoteDescription}})},iceconnectionstatechange:(c,u,m)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${c}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:c,connectionId:u,data:m.iceConnectionState})},icegatheringstatechange:(c,u,m)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${c}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:c,connectionId:u,data:m.iceGatheringState})},icecandidateerror:(c,u,m,C)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${c}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:c,connectionId:u,error:{errorCode:C.errorCode}})},connectionstatechange:(c,u,m)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${c}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:c,connectionId:u,data:m.connectionState})},negotiationneeded:(c,u,m)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${c}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:c,connectionId:u})},datachannel:(c,u,m,C)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${c}`,C),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:c,connectionId:u,data:C.channel})}}}addPeerConnectionEventListeners(c,u,m){this.logger.debug(`Adding event listeners for peer ${c} and connection ${u}.`),Y[u]={},Object.keys(this.peerConnectionListeners).forEach((C=>{Y[u][C]=this.peerConnectionListeners[C].bind(this,c,u,m),m.addEventListener(C,Y[u][C],!1)}))}parseGetUserMedia(c){try{const u={event:"getUserMedia",tag:"getUserMedia",data:{...c}};c.stream&&(u.data.details=this.parseStream(c.stream),c.stream.getTracks().map((m=>{this.addTrackEventListeners(m),M.push(m)}))),this.emitEvent(u)}catch{}}parseStream(c){const u={audio:[],video:[]};return c.getTracks().forEach((m=>{u[m.kind].push(this.getMediaTrackDetails(m))})),u}getMediaTrackDetails(c){return{enabled:c.enabled,id:c.id,contentHint:c.contentHint,kind:c.kind,label:c.label,muted:c.muted,readyState:c.readyState,constructorName:c.constructor.name,capabilities:c.getCapabilities?c.getCapabilities():{},constraints:c.getConstraints?c.getConstraints():{},settings:c.getSettings?c.getSettings():{},_track:c}}getStreamDetails(c){return{active:c.active,id:c.id,_stream:c}}getTrackEventObject(c){return{mute:u=>{this.emitEvent({event:"mute",tag:"track",connectionId:c,data:{event:u}})},unmute:u=>{this.emitEvent({event:"unmute",tag:"track",connectionId:c,data:{event:u}})},overconstrained:u=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:c,data:{event:u}})},ended:u=>{this.emitEvent({event:"ended",tag:"track",connectionId:c,data:{event:u}}),this.removeTrackEventListeners(u.target)}}}addTrackEventListeners(c,u){Y[c.id]={};const m=this.getTrackEventObject(u);Object.keys(m).forEach((C=>{Y[c.id][C]=m[C].bind(this),c.addEventListener(C,Y[c.id][C])})),Y[c.id].readyState=setInterval((()=>{if(c.readyState==="ended"){let C=new CustomEvent("ended",{detail:{check:"readyState"}});c.dispatchEvent(C)}}),1e3)}removeTrackEventListeners(c){if(c.id in Y){const u=this.getTrackEventObject();Object.keys(u).forEach((m=>{c.removeEventListener(m,Y[c.id][m])})),clearInterval(Y[c.id].readyState),delete Y[c.id]}}addToTimeline(c){this.timeline.push(c),this.emit("timeline",c)}emitEvent(c){const u={...c,timestamp:new Date};this.addToTimeline(u),u.tag&&this.emit(u.tag,u)}set getStatsInterval(c){if(!Number.isInteger(c))throw new Error(`getStatsInterval should be an integer, got: ${c}`);this._getStatsInterval=c,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(c,u){c in Y&&(Object.keys(this.peerConnectionListeners).forEac
5h((m=>{u.removeEventListener(m,Y[c][m],!1)})),delete Y[c]),u.getSenders().forEach((m=>{m.track&&this.removeTrackEventListeners(m.track)})),u.getReceivers().forEach((m=>{m.track&&this.removeTrackEventListeners(m.track)}))}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const c=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const u=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),m=function(){return c.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),u.apply(navigator.mediaDevices,arguments).then((function(C){return C}),(function(C){return c.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,C.name),Promise.reject(C)}))};navigator.mediaDevices.getDisplayMedia=m.bind(navigator.mediaDevices)}}}}));(St=ms)&&St.__esModule&&Object.prototype.hasOwnProperty.call(St,"default")&&St.default;var Lr=ms.WebRTCStats;function Mr(t){const{packetsLost:e,packetsReceived:i,jitter:n,rtt:s}=t,o=(function(h){const{jitter:p,rtt:f}=h,b=p+f/2;return .024*b+.11*(b-177.3)*(b>177.3?1:0)})({rtt:s,jitter:n}),r=(function(h){const{packetsLost:p,packetsReceived:f}=h,b=p/(f+p)*100;return 20*Math.log(1+b)})({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 Pr(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"}var Fr=class extends ze{constructor(t,e){super(),this.buildRequest({type:"debug_report_start",debug_report_id:t,debug_report_version:1,call_id:e})}},Ur=class extends ze{constructor(t,e){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:t,debug_report_version:1,call_id:e})}},$r=class extends ze{constructor(t,e,i){super(),this.buildRequest({type:"debug_report_data",debug_report_id:t,debug_report_version:1,call_id:e,debug_report_data:i})}};function jr(t,e){const i=qe();let n=!1;const s=new Lr({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>R(this,void 0,void 0,(function*(){r.event==="stats"&&F(D.StatsFrame,(function({data:a}){var l,h,p,f,b,g,v,y;const{audio:S,remote:E}=a,{audio:T}=E,N=(h=(l=T.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&h!==void 0?h:1/0,$=(f=(p=T.inbound[0])===null||p===void 0?void 0:p.roundTripTime)!==null&&f!==void 0?f:1/0,j=(g=(b=S.inbound[0])===null||b===void 0?void 0:b.packetsReceived)!==null&&g!==void 0?g:-1,q=(y=(v=S.inbound[0])===null||v===void 0?void 0:v.packetsLost)!==null&&y!==void 0?y:-1,Y=Mr({jitter:1e3*N,rtt:1e3*$,packetsLost:q,packetsReceived:j});return{jitter:N,rtt:$,mos:Y,quality:Pr(Y),inboundAudio:S.inbound[0],outboundAudio:S.outbound[0],remoteInboundAudio:T.inbound[0],remoteOutboundAudio:T.outbound[0]}})(r),t.uuid),yield t.execute(new $r(i,e,r))}));return{get isRunning(){return n},start:(r,a,l)=>R(this,void 0,void 0,(function*(){if(n)d.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new Fr(i,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),n=!0}catch(h){d.error(`[${e}] Failed to start stats reporter:`,h),s.removeAllPeers(),s.destroy()}}})),stop:r=>R(this,void 0,void 0,(function*(){const a=s.getTimeline();F(D.StatsReport,a,t.uuid),r==="file"&&(function(l,h){const p=new Blob([JSON.stringify(l)],{type:"application/json"}),f=URL.createObjectURL(p),b=document.createElement("a");b.href=f,b.download=`${h}.json`,b.click(),URL.revokeObjectURL(f)})(a,`webrtc-stats-${i}-${Date.now()}`),yield t.execute(new Ur(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)}}}var _s=(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:Ce.conferenceUpdate,call:t.calls[s],canvasInfo:Br(o),currentLayerIdx:r};switch(i){case"layer-info":{const l=Object.assign({action:_e.LayerInfo},a);F(D.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:_e.LayoutInfo},a);F(D.Notification,l,t.uuid);break}}},Br=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return as(e)},ys=["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"],Hr={"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 X(t,e){return`telnyx:call:${t}:${e}`}function Cn(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}function bs(t,e,i){const n=Cn(X(t,"new-call-start"));if(n===void 0)return{mode:e,direction:i,steps:[]};const s=[];for(const a of ys){if(a==="new-call-start")continue;const l=Cn(X(t,a));l!==void 0&&s.push({label:Hr[a]||a,fromStart:l-n})}s.sort(((a,l)=>a.fromStart-l.fromStart));const o=[];let r=0;for(const a of s)o.push({label:a.label,fromStart:a.fromStart,delta:a.fromStart-r}),r=a.fromStart;return{mode:e,direction:i,steps:o}}function bi(t){for(const e of ys)try{performance.clearMarks(X(t,e))}catch{d.warn("Clearing performance marks is failed")}}var Ft=class Si{constructor(e,i,n,s,o){this.type=e,this.options=i,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=()=>R(this,void 0,void 0,(function*(){var r,a;if(!this.instance)return void d.debug("Connection state change ignored: instance is null");const{connectionState:l}=this.instance;if(d.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${l}`),l!=="failed"&&l!=="disconnected"||(this.isDebugEnabled&&this.statsReporter&&(function(h,p){return R(this,void 0,void 0,(function*(){const f={connectionState:h.connectionState,previousConnectionState:p,iceConnectionState:h.iceConnectionState,iceGatheringState:h.iceGatheringState,signalingState:h.signalingState},b=h.getTransceivers();if(b.length>0){const g=b[0].sender,v=g?.transport;v&&(f.dtlsState=v.state)}h.sctp&&(f.sctpState=h.sctp.state);try{const g=yield h.getStats();g.forEach((v=>{v.type==="candidate-pair"&&v.state==="succeeded"&&(f.candidatePairState=v.state,g.forEach((y=>{y.type==="local-candidate"&&y.id===v.localCandidateId&&(f.localCandidateType=y.candidateType,f.selectedCandidatePair=f.selectedCandidatePair||{local:{},remote:{}},f.selectedCandidatePair.local={address:y.address,port:y.port,protocol:y.protocol,candidateType:y.candidateType}),y.type==="remote-candidate"&&y.id===v.remoteCandidateId&&(f.remoteCandidateType=y.candidateType,f.selectedCandidatePair=f.selectedCandidatePair||{local:{},remote:{}},f.selectedCandidatePair.remote={address:y.address,port:y.port,protocol:y.protocol,candidateType:y.candidateType})}))),v.type==="transport"&&(f.dtlsCipher=v.dtlsCipher,f.srtpCipher=v.srtpCipher,f.tlsVersion=v.tlsVersion,v.dtlsState&&(f.dtlsState=v.dtlsState))}))}catch(g){d.error("Error gathering connection state details:",g)}return f}))})(this.instance,this._prevConnectionState).then((h=>{this.statsReporter.reportConnectionStateChange(h)})),(a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"connection_failed")),l==="disconnected"){const h=he(Lo);F(D.Warning,{warning:h,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(l==="failed"){const h=he(Fo);F(D.PeerConnectionFailureError,{warning:h,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(X(this.options.id,"dtls-connected")),this.tryCollectTimings(),this._restartedIceOnConnectionStateFailed=!1),this._isTrickleIce()&&(l==="connecting"&&performance.mark(X(this.options.id,"peer-connection-connecting")),l==="connected"&&(this._clearIceGatheringSafetyTimeout(),performance.mark(X(this.options.id,"peer-connection-connected"))))})),this._handleIceConnectionStateChange=()=>{var r,a;if(!this.instance)return void d.debug("ICE connection state change ignored: instance is null");const l=this.instance.iceConnectionState;d.debug(`[${new Date().toISOString()}] ICE Connection State`,l),l==="connected"&&performance.mark(X(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;d.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)},d.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!i.video},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?(d.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&&(d.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null}),Si.ICE_RESTART_TIMEOUT_MS),d.info("ICE restart: initiated by signaling health monitor"),{started:!0}):(d.debug("ICE restart: session not connected, skipping"),{started:!1,reason:"session not connected"}):(d.warn("ICE restart: no RTCPeerConnection instance"),{started:!1,reason:"no RTCPeerConnection instance"})}get isOffer(){return this.type===ue.Offer}get isAnswer(){return this.type===ue.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}get callEstablishmentTimings(){return this._callEstablishmentTimings}isConnectionHealthy(){return this.instance.connectionState==="connected"&&this.instance.iceConnectionState==="connected"&&this.instance.signalingState!=="closed"}startNegotiation(){performance.mark(X(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 R(this,void 0,void 0,(function*(){performance.mark(X(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 Ge&&F(D.Error,{error:e,sessionId:this._session.sessionid},this.options.id)}_logTransceivers(){this.instance?(d.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEac
5h(((e,i)=>{d.info(`>> Transceiver [${i}]:`,e.mid,e.direction,e.stopped),d.info(`>> Sender Params [${i}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))):d.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(d.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":F(D.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(d.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){d.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?d.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(X(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&&Lt(n,this.options.remoteStream,{callId:this.options.id,sessionId:this._session.sessionid,eventTarget:this._session.uuid})}tryCollectTimings(){if(this._timingsCollected||!(performance.getEntriesByName(X(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=bs(this.options.id,e,i);this._callEstablishmentTimings=n,(function(s){const{mode:o,direction:r,steps:a}=s,l=`[CallTimings][${r}][${o}]`;if(a.length===0)return void d.info(`${l} No timing data collected`);const h=Math.max(...a.map((v=>v.label.length)),4)+2,p=(v,y)=>{for(;v.length<y;)v+=" ";return v},f=(v,y)=>{for(;v.length<y;)v=" "+v;return v},b=p("Step",h)+f("Delta",14)+f("From Start",14);let g="";for(let v=0;v<b.length;v++)g+="-";d.info(`${l} Call establishment timing breakdown:`),d.info(`${l} ${b}`),d.info(`${l} ${g}`),d.info(`${l} ${p("Call Start",h)}${f("-",14)}${f("0.00ms",14)}`);for(const v of a){const y=v.delta.toFixed(2)+"ms",S=v.fromStart.toFixed(2)+"ms";d.info(`${l} ${p(v.label,h)}${f(y,14)}${f(S,14)}`)}d.info(`${l} ${g}`)})(n),bi(this.options.id)}createPeerConnection(){return R(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:ue.Offer}),performance.mark(X(this.options.id,"set-remote-description")),!this.instance))throw Z(qt);const i=!!this.options.receiveOnlyAudio&&!this.options.audio;let n=null;if(this.options.localStream=yield this._retrieveLocalStream().catch((s=>R(this,void 0,void 0,(function*(){const o=this._session.options.mediaPermissionsRecovery;if(o?.enabled&&this._isAnswer()){let r=null,a=null;return yield new Promise(((l,h)=>{a=setTimeout((()=>h(new Error("Media recovery flow timed out!"))),o.timeout),F(D.Error,{error:Z(Ye(s),s,void 0,!1),callId:this.options.id,sessionId:this._session.sessionid,recoverable:!0,retryDeadline:Date.now()+o.timeout,resume:()=>{l()},reject:()=>{h(new Error("Call was rejected during media recovery flow!"))}},this._session.uuid)})).then((()=>R(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)}
5)))).catch((l=>{var h;a&&(clearTimeout(a),a=null),n=l,(h=o.onError)===null||h===void 0||h.call(o,l)})),r}return n=s,null})))),!this.instance)throw Z(qt);if(!this.options.localStream&&!i)throw Z(n?Ye(n):wi,n??void 0);performance.mark(X(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&it(this.options.localStream)&&(d.info("Muting local audio tracks on start"),Tt(this.options.localStream)),this.options.applyDesiredAudioMuteState&&this.options.applyDesiredAudioMuteState(),performance.mark(X(this.options.id,"peer-creation-end"))}))}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout((()=>{if(this.instance){if(this._gatheredCandidatesCount===0){const e=he(Po);F(D.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=he(Mo);F(D.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}}),Si.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){this._iceGatheringSafetyTimeout!==null&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return R(this,void 0,void 0,(function*(){if(yield this.createPeerConnection(),!this.instance)throw Z(qt);this.isDebugEnabled&&(this.statsReporter=jr(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(it(n)){const o=n.getAudioTracks();let r=[...o];if(d.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach((h=>{d.info("Local audio tracks constraints: ",h.getConstraints())})),this.options.video){const h=n.getVideoTracks();r=[...o,...h],d.info("Local video tracks: ",h),typeof this.options.video=="object"&&h.forEach((p=>{d.info("Local video tracks constraints: ",p.getConstraints())}))}const{audioCodecs:a,videoCodecs:l}=Sn(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const h={direction:"sendrecv",streams:[n]};r.forEach((p=>{p.kind==="audio"&&(this.options.userVariables.microphoneLabel=p.label),p.kind==="video"&&(this.options.userVariables.cameraLabel=p.label);const f=this.instance.addTransceiver(p,h);p.kind==="audio"&&a.length>0&&this._setCodecs(f,a),p.kind==="video"&&l.length>0&&this._setCodecs(f,l)}))}else typeof this.instance.addTrack=="function"?(r.forEach((h=>{h.kind==="audio"&&(this.options.userVariables.microphoneLabel=h.label),h.kind==="video"&&(this.options.userVariables.cameraLabel=h.label),this.instance.addTrack(h,n)})),this.instance.getTransceivers().forEach((h=>{h.receiver.track.kind==="audio"&&a.length>0&&this._setCodecs(h,a),h.receiver.track.kind==="video"&&l.length>0&&this._setCodecs(h,l)}))):this.instance.addStream(n);s===!1&&Lt(i,n)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});d.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=Sn(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);d.info("Add transceiver",e,i)}}_createOffer(){return R(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,d.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark(X(this.options.id,"create-offer")),yield this._setLocalDescription(e),performance.mark(X(this.options.id,"set-local-description")),performance.mark(X(this.options.id,"ice-gathering-started")),e}catch(e){throw d.error("Peer _createOffer error:",e),e instanceof Ge?e:Z(vo,e)}}}))}_setRemoteDescription(e){return R(this,void 0,void 0,(function*(){d.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(i){throw d.error("Peer _setRemoteDescription error:",i),Z(zn,i)}}))}_createAnswer(){return R(this,void 0,void 0,(function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return d.debug("Skipping negotiation, state:",this.instance.signalingState),d.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:ue.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark(X(this.options.id,"create-answer")),yield this._setLocalDescription(e),performance.mark(X(this.options.id,"set-local-description")),performance.mark(X(this.options.id,"ice-gathering-started")),e}catch(e){throw d.error("Peer _createAnswer error:",e),e instanceof Ge?e:Z(fo,e)}}}))}_setLocalDescription(e){return R(this,void 0,void 0,(function*(){try{yield this.instance.setLocalDescription(e)}catch(i){throw d.error("Peer _setLocalDescription error:",i),Z(mo,i)}}))}_retrieveLocalStream(){return R(this,void 0,void 0,(function*(){if(it(this.options.localStream))return this.options.localStream;const e=yield(i=this.options,R(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 Pt(s,a,Te.AudioIn).catch((()=>null)),s&&(typeof n=="boolean"&&(n={}),n.deviceId={exact:s})),r&&(r=yield Pt(r,l,Te.Video).catch((()=>null)),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:n,video:o}})));var i;return Mt(e)}))}_isOffer(){return this.type===ue.Offer}_isAnswer(){return this.type===ue.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:i,iceServers:n}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?1:0,iceServers:n,iceTransportPolicy:i?"relay":"all"};return d.info("RTC config",s),s}restartStatsReporter(){return R(this,void 0,void 0,(function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?d.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(d.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):d.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))}))}close(){return R(this,void 0,void 0,(function*(){bi(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)}))}};Ft.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,Ft.ICE_RESTART_TIMEOUT_MS=15e3;var Ct=Ri,Ss=class{constructor(t,e){var i;this.session=t,this._callReportCollector=null,this._callRecorder=null,this._mediaDeviceCollector=null,this.id="",this.recoveredCallId="",this.state=V[V.New],this.prevState="",this.channels=[],this.role=pi.Participant,this.extension=null,this._state=V.New,this._prevState=V.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=S=>{const E=S<0||!this._lastSerno||this._lastSerno&&S===this._lastSerno+1;return E&&S>=0&&(this._lastSerno=S),E},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then((S=>
5{S.forEach((E=>{this._statsBindings.forEach((T=>{if(T.callback){if(T.constraints){for(const N in T.constraints)if(T.constraints.hasOwnProperty(N)&&T.constraints[N]!==E[N])return}T.callback(E)}}))}))}))};const{iceServers:n,speaker:s,micId:o,micLabel:r,camId:a,camLabel:l,localElement:h,remoteElement:p,options:f,mediaConstraints:{audio:b,video:g},ringtoneFile:v,ringbackFile:y}=t;this.options=Object.assign({},ln,{audio:b,video:g,iceServers:e?.iceServers&&Array.isArray(e.iceServers)?e.iceServers:n,localElement:h,remoteElement:p,micId:o,micLabel:r,camId:a,camLabel:l,speakerId:s,ringtoneFile:v,ringbackFile:y,debug:f.debug,debugOutput:f.debugOutput,trickleIce:f.trickleIce,prefetchIceCandidates:(i=f.prefetchIceCandidates)!==null&&i!==void 0?i:ln.prefetchIceCandidates,forceRelayCandidate:f.forceRelayCandidate,keepConnectionAliveOnSocketClose:f.keepConnectionAliveOnSocketClose,mutedMicOnStart:f.mutedMicOnStart},e),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=_n(this.options.ringtoneFile,"_ringtone"),this._ringback=_n(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}_captureHangupCallerStack(){const t=new Error("Call.hangup caller").stack;return t?t.split(`
6`).map((e=>e.trim())).filter(Boolean).slice(1,11):[]}get nodeId(){return this._targetNodeId}set nodeId(t){this._targetNodeId=t}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 t,e;return(e=(t=this.options.localStream)===null||t===void 0?void 0:t.getAudioTracks()[0])===null||e===void 0?void 0:e.id}_hasActiveUnmutedLocalAudioTrack(){const t=this.options.localStream;return!!t?.getAudioTracks&&t.getAudioTracks().some((e=>e.enabled===!0&&e.muted!==!0&&e.readyState==="live"))}shouldForceRelayCandidateForRecovery(){var t,e;return!!this.options.forceRelayCandidate||!!this.recoveredCallId&&(e=(t=this._callReportCollector)===null||t===void 0?void 0:t.shouldForceRelayCandidateForRecovery())!==null&&e!==void 0&&e}invite(){return R(this,void 0,void 0,(function*(){this._creatingPeer=!0,this.direction=Ee.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(X(this.id,"new-peer")),this.peer=new Ft(ue.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(t){d.error("Peer init failed, aborting call",t),this._creatingPeer=!1;const e=t instanceof Ge?t:Z(Zi,t instanceof Error?t:void 0);F(D.Error,{error:e,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),this.hangup({initiator:"sdk:peer-init-failed"},!1);return}this._creatingPeer=!1}))}answer(t={}){var e,i,n,s,o,r,a,l;return R(this,void 0,void 0,(function*(){const h=((n=(i=(e=this.session).getActiveCalls)===null||i===void 0?void 0:i.call(e))!==null&&n!==void 0?n:[]).filter((p=>p.id!==this.id));if(h.length>0&&d.debug(`[${this.id}] answer(): answering inbound call while ${h.length} other active call(s) exist in session ${this.session.sessionid}`),this._creatingPeer||((s=this.peer)===null||s===void 0?void 0:s.instance)&&this.peer.instance.signalingState!=="closed"){const p=he($o);F(D.Warning,{warning:p,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),d.warn(`[${this.id}] answer() ignored: peer connection already exists or is being created (signalingState: ${(a=(r=(o=this.peer)===null||o===void 0?void 0:o.instance)===null||r===void 0?void 0:r.signalingState)!==null&&a!==void 0?a:"creating"})`);return}if(this._registerInboundAnswerAttempt()){performance.mark(X(this.id,"answer-called")),this._creatingPeer=!0,this.stopRingtone(),this.direction=Ee.Inbound,((l=t?.customHeaders)===null||l===void 0?void 0:l.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:t.customHeaders})),t.remoteElement===void 0&&t.localElement===void 0||(this.options=Object.assign(Object.assign(Object.assign({},this.options),t.remoteElement!==void 0&&{remoteElement:t.remoteElement}),t.localElement!==void 0&&{localElement:t.localElement})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(X(this.id,"new-peer")),this.peer=new Ft(ue.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(p){d.error("Peer init failed, aborting call",p),this._creatingPeer=!1;const f=p instanceof Ge?p:Z(Zi,p instanceof Error?p:void 0);F(D.Error,{error:f,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),yield this.hangup({initiator:"sdk:peer-init-failed"},!0);return}this._creatingPeer=!1}}
6))}playRingtone(){yn(this._ringtone)}stopRingtone(){bn(this._ringtone)}playRingback(){yn(this._ringback)}stopRingback(){bn(this._ringback)}hangup(t,e){var i,n,s,o,r,a;return R(this,void 0,void 0,(function*(){const l=t||{},h=e!==!1,p=this.state,f=this.prevState,b=this._captureHangupCallerStack(),g=l.initiator||"app:call.hangup",v=this._state<V.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=l.cause||v.cause,this.causeCode=l.causeCode||v.causeCode,this.sipCode=l.sipCode||null,this.sipReason=l.sipReason||null,this.sipCallId=l.sip_call_id||null,this.options.customHeaders=[...(i=this.options.customHeaders)!==null&&i!==void 0?i:[],...(s=(n=l?.dialogParams)===null||n===void 0?void 0:n.customHeaders)!==null&&s!==void 0?s:[]],d.debug(`[${this.id}] hangup() invoked`,{callId:this.id,execute:h,state:p,prevState:f,cause:this.cause,causeCode:this.causeCode,initiator:g,sipCode:this.sipCode,sipReason:this.sipReason,sipCallId:this.sipCallId,isRecovering:!!l.isRecovering,hasDialogCustomHeaders:!!(!((r=(o=l.dialogParams)===null||o===void 0?void 0:o.customHeaders)===null||r===void 0)&&r.length),callerStack:b}),l.isRecovering)return this._isRecovering=!0,this.setState(V.Recovering),void this._finalize();if(this.setState(V.Hangup),this.stopRingtone(),this.stopRingback(),h){const y=new Sr({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});let S;try{yield Promise.race([this._execute(y),new Promise((E=>{S=setTimeout((()=>{d.warn(`[${this.id}] BYE execution timed out after 5000ms — proceeding to destroy.`),E()}),5e3)}))])}catch(E){d.error("telnyx_rtc.bye failed!",E);const T=Z(bo,E);F(D.Error,{error:T,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}finally{S&&clearTimeout(S)}}d.debug(`[${this.id}] Closing peer from hangup`),(a=this.peer)===null||a===void 0||a.close(),this.setState(V.Destroy)}))}hold(){const t=new bt({sessid:this.session.sessionid,action:Be.Hold,dialogParams:this.options});return this._execute(t).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const t=new bt({sessid:this.session.sessionid,action:Be.Unhold,dialogParams:this.options});return this._execute(t).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const t=new bt({sessid:this.session.sessionid,action:Be.ToggleHold,dialogParams:this.options});return this._execute(t).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(t){const e=new gn({sessid:this.session.sessionid,dtmf:t,dialogParams:this.options});this._execute(e)}message(t,e){const i={from:this.session.options.login,to:t,body:e},n=new gn({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(n)}muteAudio(){d.debug("muteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!0,Tt(this.options.localStream)}unmuteAudio(){d.debug("unmuteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!1,Kt(this.options.localStream)}_applyDesiredAudioMuteState(){d.debug("applyDesiredAudioMuteState called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted?Tt(this.options.localStream):Kt(this.options.localStream)}toggleAudioMute(){d.debug("toggleAudioMute called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!this._desiredAudioMuted,this._applyDesiredAudioMuteState()}setAudioInDevice(t,e=this._desiredAudioMuted){var i,n,s;return R(this,void 0,void 0,(function*(){const o=!!e,{instance:r}=this.peer,a=r.getSenders().find((({track:{kind:f}})=>f==="audio"));if(!a)return d.warn("Skipping audio input device change: no audio sender found",{callId:this.id,deviceId:t,audioMuted:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),void F(D.Warning,{warning:he(Bo),callId:this.id,deviceId:t,sessionId:this.session.sessionid},((i=this.options)===null||i===void 0?void 0:i.id)||this.id);let l;d.debug("Starting audio input device change",{callId:this.id,state:this.state,deviceId:t,previousDesiredAudioMuted:this._desiredAudioMuted,newDesiredMuted:o,currentSenderTrack:mi(a.track),localTracks:mn(this.options.localStream)});try{l=yield Nt({audio:{deviceId:{exact:t}}})}catch(f){const b=Z(Ye(f),f);F(D.MediaError,b,((n=this.options)===null||n===void 0?void 0:n.id)||this.id);return}const h=l.getAudioTracks()[0];h.enabled=!o;try{yield a.replaceTrack(h)}catch(f){const b=Z(Ye(f),f);F(D.MediaError,b,((s=this.options)===null||s===void 0?void 0:s.id)||this.id),l.getTracks().forEac
6h((g=>g.stop()));return}this._desiredAudioMuted=o,this.options.micId=t;const{localStream:p}=this.options;p.getAudioTracks().forEach((f=>f.stop())),p.getVideoTracks().forEach((f=>l.addTrack(f))),this.options.localStream=l,d.debug("Finished audio input device change",{callId:this.id,state:this.state,deviceId:t,desiredAudioMuted:this._desiredAudioMuted,senderTrack:mi(a.track),localTracks:mn(this.options.localStream)})}))}muteVideo(){var t=this.options.localStream;He(t,"video",!1)}unmuteVideo(){var t=this.options.localStream;He(t,"video",!0)}toggleVideoMute(){var t=this.options.localStream;He(t,"video",null)}setVideoDevice(t){return R(this,void 0,void 0,(function*(){const{instance:e}=this.peer,i=e.getSenders().find((({track:{kind:n}})=>n==="video"));if(i){const n=yield Nt({video:{deviceId:{exact:t}}}),s=n.getVideoTracks()[0];i.replaceTrack(s);const{localElement:o,localStream:r}=this.options;Lt(o,n),this.options.camId=t,r.getAudioTracks().forEach((a=>n.addTrack(a))),r.getVideoTracks().forEach((a=>a.stop())),this.options.localStream=n,this._applyDesiredAudioMuteState()}}))}deaf(){Tt(this.options.remoteStream)}undeaf(){Kt(this.options.remoteStream)}toggleDeaf(){var t=this.options.remoteStream;He(t,"audio",null)}setBandwidthEncodingsMaxBps(t,e){return R(this,void 0,void 0,(function*(){if(!this||!this.peer)return void d.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:i}=this.peer,n=i.getSenders();if(!n)return void d.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 s=n.find((({track:{kind:o}})=>o===e));if(s){const o=s.getParameters();o.encodings||(o.encodings=[{rid:"h"}]),d.info("Parameters: ",o),d.info("Setting max ",e==="audio"?"audio":"video"," bandwidth to: ",t," [bps]"),o.encodings[0].maxBitrate=t,yield s.setParameters(o).then((()=>{d.info(e==="audio"?"New audio":"New video"," bandwidth settings in use: ",s.getParameters())})).catch((r=>d.error(r)))}else d.error("Could not set bandwidth (reason: no "+e+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")}))}setAudioBandwidthEncodingsMaxBps(t){this.setBandwidthEncodingsMaxBps(t,"audio")}setVideoBandwidthEncodingsMaxBps(t){this.setBandwidthEncodingsMaxBps(t,"video")}_isTerminatingOrTerminated(){return[V.Hangup,V.Destroy,V.Purge].includes(this._state)}getStats(t,e){if(!t)return;const i={callback:t,constraints:e};this._statsBindings.push(i),!this._statsIntervalId&&this._startStats(2e3)}setState(t){var e,i,n,s,o,r,a;switch(this._prevState=this._state,this._state=t,this.state=V[this._state].toLowerCase(),this.prevState=V[this._prevState].toLowerCase(),d.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:Ce.callUpdate,call:this}),t){case V.Purge:d.info(`[${this.id}] Entering Purge state.`);break;case V.Active:if(performance.mark(X(this.id,"call-active")),(e=this.peer)===null||e===void 0||e.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,d.debug(`[${this.id}] Recovery complete, call is active`)),this._wasHeldBeforeRecovery&&(d.debug(`[${this.id}] Cleared held-before-recovery intent on transition to Active`),this._wasHeldBeforeRecovery=!1),(i=this._callReportCollector)===null||i===void 0||i.setHeld(!1),this.session.startSignalingHealthMonitor(),setTimeout((()=>{const{remoteElement:l,speakerId:h}=this.options;l&&h&&fs(l,h)}),0),this._callReportCollector&&(n=this.peer)!==null&&n!==void 0&&n.instance&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance),this._callRecorder){const l=(s=this.session.connection)===null||s===void 0?void 0:s.host;l&&this._callRecorder._setHost(l),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const h=(o=this.options.localStream)===null||o===void 0?void 0:o.getAudioTracks()[0],p=(r=this.options.remoteStream)===null||r===void 0?void 0:r.getAudioTracks()[0];this._callRecorder.start(h,p)}this._mediaDeviceCollector=new Nr,this._mediaDeviceCollector.logDevicesAtStart();break;case V.Held:(a=this._callReportCollector)===null||a===void 0||a.setHeld(!0);break;case V.Destroy:this._finalize()}}handleMessage(t){const{method:e,params:i}=t;switch(e){case Q.Answer:if(performance.mark(X(this.id,"telnyx-rtc-answer")),this.gotAnswer=!0,i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id
6),this._state>=V.Active)return;this._state>=V.Early&&this.setState(V.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case Q.Media:if(performance.mark(X(this.id,"telnyx-rtc-media")),this._state>=V.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case Q.Display:{const{display_name:s,display_number:o,display_direction:r}=i;this.extension=o;const a=r===Ee.Inbound?Ee.Outbound:Ee.Inbound,l={type:Ce[e],call:this,displayName:s,displayNumber:o,displayDirection:a};F(D.Notification,l,this.id)||F(D.Notification,l,this.session.uuid);break}case Q.Candidate:this._addIceCandidate(i);break;case Q.Info:case Q.Event:{const s=Object.assign(Object.assign({},i),{type:Ce.generic,call:this});F(D.Notification,s,this.id)||F(D.Notification,s,this.session.uuid);break}case Q.Ringing:performance.mark(X(this.id,"ringing")),this.playRingback(),i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id);break;case Q.Bye:const n=i.client_state||i.clientState;n&&(this.options.clientState=n),this.stopRingback(),this.stopRingtone(),this.hangup(Object.assign(Object.assign({},i),{initiator:"remote:telnyx_rtc.bye"}),!1)}}handleConferenceUpdate(t,e){return R(this,void 0,void 0,(function*(){if(!this._checkConferenceSerno(t.wireSerno)&&t.name!==e.laName)return d.error("ConferenceUpdate invalid wireSerno or packet name:",t),"INVALID_PACKET";const{action:i,data:n,hashKey:s=String(this._lastSerno),arrIndex:o}=t;switch(i){case"bootObj":{this._lastSerno=0;const{chatChannel:r,infoChannel:a,modChannel:l,laName:h,conferenceMemberID:p,role:f}=e;this._dispatchConferenceUpdate({action:_e.Join,conferenceName:h,participantId:Number(p),role:f}),r&&(yield this._subscribeConferenceChat(r)),a&&(yield this._subscribeConferenceInfo(a));const b=[];for(const g in n)b.push(Object.assign({callId:n[g][0],index:Number(g)},yt(n[g][1])));this._dispatchConferenceUpdate({action:_e.Bootstrap,participants:b});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:_e.Add,callId:s,index:o},yt(n)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:_e.Modify,callId:s,index:o},yt(n)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:_e.Delete,callId:s,index:o},yt(n)));break;case"clear":this._dispatchConferenceUpdate({action:_e.Clear});break;default:this._dispatchConferenceUpdate({action:i,data:n,callId:s,index:o})}}))}_addChannel(t){this.channels.includes(t)||this.channels.push(t);const e=this.session.relayProtocol;this.session._existsSubscription(e,t)&&(this.session.subscriptions[e][t]=Object.assign(Object.assign({},this.session.subscriptions[e][t]),{callId:this.id}))}_subscribeConferenceChat(t){return R(this,void 0,void 0,(function*(){const e={nodeId:this.nodeId,channels:[t],handler:n=>{const{direction:s,from:o,fromDisplay:r,message:a,type:l}=n.data;this._dispatchConferenceUpdate({action:_e.ChatMessage,direction:s,participantNumber:o,participantName:r,messageText:a,messageType:l,messageId:n.eventSerno})}},i=yield this.session.vertoSubscribe(e).catch((n=>{d.error("ConfChat subscription error:",n)}));_i(i,t)&&(this._addChannel(t),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(n,s)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:t,data:{action:"send",message:n,type:s}})}}}))}))}_subscribeConferenceInfo(t){return R(this,void 0,void 0,(function*(){const e={nodeId:this.nodeId,channels:[t],handler:n=>{const{eventData:s}=n;s.contentType==="layout-info"?(s.callID=this.id,_s(this.session,s)):d.error("Conference-Info unknown contentType",n)}},i=yield this.session.vertoSubscribe(e).catch((n=>{d.error("ConfInfo subscription error:",n)}));_i(i,t)&&this._addChannel(t)}))}_confControl(t,e={}){const i=Object.assign({application:"conf-control",callID:this.id,value:null},e);this.session.vertoBroadcast({nodeId:this.nodeId,channel:t,data:i})}_handleChangeHoldStateSuccess(t){return t.holdState==="active"?this.setState(V.Active):this.setState(V.Held),!0}_handleChangeHoldStateError(t){d.error(`Failed to ${t.action} on call ${this.id}`);const e=Z(_o,t);return F(D.Error,{error:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(t,e={}){const i=new bt(Object.assign(Object.assign({sessid:this.session.sessionid,action:Be.UpdateMedia,callID:this.options.id,sdp:t},e.trickle?{trickle:!0}:{}),{dialogParams:this.options}));d.info(`ICE restart: sending ${e.trickle?"trickle ":""}Modify with new offer SDP`),this._execute(i).then((n=>R(this,void 0,void 0,(function*(){var s;n?.sdp?(d.info("ICE restart Modify response received"),(s=this.peer)===null||s===void 0||s.finishIceRestart(),yield this._onRemoteSdp(n.sdp)):this._onIceRestartFailed("ICE restart Modify response missing SDP")}
6)))).catch((n=>{this._onIceRestartFailed("ICE restart Modify failed",n)}))}_onIceRestartFailed(t,e){var i,n,s;d.error(t,e),(i=this.peer)===null||i===void 0||i.finishIceRestart();const o=Z(To,e);F(D.Error,{error:o,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),(s=(n=this.session).reportIceRestartFailed)===null||s===void 0||s.call(n,this.id)}_onRemoteSdp(t){return R(this,void 0,void 0,(function*(){const e=new RTCSessionDescription({sdp:t,type:ue.Answer});yield this.peer.instance.setRemoteDescription(e).then((()=>{performance.mark(X(this.id,"set-remote-description")),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(V.Early),this.gotAnswer&&this._state!==V.Held&&this.setState(V.Active)})).catch((i=>R(this,void 0,void 0,(function*(){d.error("Call setRemoteDescription Error: ",i);const n=Z(zn,i);F(D.Error,{error:n,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(s){d.error("Error during hangup after setRemoteDescription failure:",s)}}))))}))}_warnIfOnlyHostIceCandidates(t){if(!(i=>{if(!i)return!1;const n=i.split(/\r?\n/).filter((s=>/^a=candidate:/i.test(s)));return n.length>0&&n.every((s=>/\styp\s+host(?:\s|$)/i.test(s)))})(t))return;const e=he(Uo);d.warn(`[${this.id}] Warning ${e.code}: ${e.message}`),F(D.Warning,{warning:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onIceSdp(t){var e,i,n;if(this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._isTerminatingOrTerminated())return;if(this.peer&&(this.peer.iceDone=!0),!t)return void d.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:s,type:o}=t;(i=(e=this.peer)===null||e===void 0?void 0:e.instance)===null||i===void 0||i.removeEventListener("icecandidate",this._onIce),this._warnIfOnlyHostIceCandidates(s),performance.mark(X(this.id,"ice-gathering-end"));let r=null;const a={sessid:this.session.sessionid,sdp:s,dialogParams:this.options,"User-Agent":`Web-${Ct}`};if(!((n=this.peer)===null||n===void 0)&&n.isIceRestarting)this._sendIceRestartModify(s);else{switch(o){case ue.Offer:this.setState(V.Requesting),r=new un(a);break;case ue.Answer:this._isRecovering||this.setState(V.Answering),r=this.options.attach===!0?new pn(a):new hn(a);break;default:d.error(`${this.id} - Unknown local SDP type:`,t),this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1);return}performance.mark(X(this.id,"send-sdp")),this._execute(r).then((l=>{if(this._isTerminatingOrTerminated())return void d.debug(`[${this.id}] Ignoring ${o} response because call is ${this.state}`);const{node_id:h=null}=l;this._targetNodeId=h,o===ue.Offer?this.setState(V.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(V.Held):this.setState(V.Active)})).catch((l=>R(this,void 0,void 0,(function*(){d.error(`${this.id} - Sending ${o} error:`,l);const h=Z(Qi,l);F(D.Error,{error:h,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(p){d.error("Error during hangup after SDP send failure:",p)}}))))}}_onTrickleIceSdp(t){var e;if(this._isTerminatingOrTerminated())return;if(!t)return d.error("No SDP data provided"),void this.hangup({initiator:"sdk:missing-local-sdp"},!1);const{sdp:i,type:n}=t;let s=null;const o={sessid:this.session.sessionid,sdp:i,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${Ct}`};if(!((e=this.peer)===null||e===void 0)&&e.isIceRestarting)this._sendIceRestartModify(i,{trickle:!0});else{switch(n){case ue.Offer:this.setState(V.Requesting),s=new un(o);break;case ue.Answer:this._isRecovering||this.setState(V.Answering),s=this.options.attach===!0?new pn(o):new hn(o);break;default:d.error(`${this.id} - Unknown local SDP type:`,t),this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1);return}performance.mark(X(this.id,"send-sdp")),this._execute(s).then((r=>{if(this._isTerminatingOrTerminated())return void d.debug(`[${this.id}] Ignoring ${n} response because call is ${this.state}`);const{node_id:a=null}=r;this._targetNodeId=a,n===ue.Offer?this.setState(V.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(V.Held):this.setState(V.Active)}
6)).catch((r=>R(this,void 0,void 0,(function*(){d.error(`${this.id} - Sending ${n} error:`,r);const a=Z(Qi,r);F(D.Error,{error:a,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(l){d.error("Error during hangup after SDP send failure:",l)}}))))}}_onIce(t){var e;if(this._isTerminatingOrTerminated())return;const{instance:i}=this.peer;if(this._iceTimeout===null){const n=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout((()=>this._onIceSdp(i.localDescription)),n)}t.candidate?(d.debug("RTCPeer Candidate:",t.candidate),(e=this.peer)===null||e===void 0||e.incrementGatheredCandidates(),this._trackCandidateMarks(t.candidate)):this._onIceSdp(i.localDescription)}_onTrickleIce(t){var e,i,n,s;this._isTerminatingOrTerminated()||(t.candidate&&t.candidate.candidate?(d.debug("RTCPeer Candidate:",t.candidate),(e=this.peer)===null||e===void 0||e.incrementGatheredCandidates(),this._trackCandidateMarks(t.candidate),this._sendIceCandidate(t.candidate)):(t.candidate===null&&this._warnIfOnlyHostIceCandidates((s=(n=(i=this.peer)===null||i===void 0?void 0:i.instance)===null||n===void 0?void 0:n.localDescription)===null||s===void 0?void 0:s.sdp),this._sendEndOfCandidates())
6)}_sendIceCandidate(t){const e=new Cr({sessid:this.session.sessionid,candidate:t.candidate,sdpMLineIndex:t.sdpMLineIndex,sdpMid:t.sdpMid,dialogParams:this.options});this._execute(e)}_addIceCandidate(t){if(!this._isRemoteDescriptionSet)return d.debug("Remote description not set. Queued ICE candidate.",t),void this._pendingIceCandidates.push(t);this._addIceCandidateToPeer(t)}_addIceCandidateToPeer(t){const e=this.peer.instance.addIceCandidate(t);Promise.resolve(e).then((()=>{d.debug("Successfully added ICE candidate:",t)})).catch((i=>{d.error("Failed to add ICE candidate:",i,t)}))}_sendEndOfCandidates(){const t=new wr({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(t)}_trackCandidateMarks(t){var e;if(this._firstCandidateSent||(performance.mark(X(this.id,"first-candidate")),this._firstCandidateSent=!0),!this._firstNonHostCandidateSent){const i=(e=t.candidate.match(/typ (\w+)/))===null||e===void 0?void 0:e[1];i&&i!=="host"&&(performance.mark(X(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 t=[...this._pendingIceCandidates];this._pendingIceCandidates=[],t.forEach((e=>{this._addIceCandidateToPeer(e)}))}_registerPeerEvents(t){t.onicecandidate=e=>{var i;this.options.trickleIce?this._onTrickleIce(e):(i=this.peer)!==null&&i!==void 0&&i.iceDone||this._onIce(e)},t.onicegatheringstatechange=e=>{d.debug("ICE gathering state changed:",t.iceGatheringState,e),t.iceGatheringState==="complete"&&(d.debug("Finished gathering candidates"),performance.mark(X(this.id,"ice-gathering-completed")))},t.onicecandidateerror=e=>{var i;if(d.debug("ICE candidate error:",e),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const n=(function(s,o){var r,a;return{errorCode:s.errorCode,errorText:s.errorText,url:s.url,address:s.address,port:s.port,connectionState:o.connectionState,iceConnectionState:o.iceConnectionState,iceGatheringState:o.iceGatheringState,signalingState:o.signalingState,localDescriptionType:(r=o.localDescription)===null||r===void 0?void 0:r.type,remoteDescriptionType:(a=o.remoteDescription)===null||a===void 0?void 0:a.type}})(e,t);this.peer.statsReporter.reportIceCandidateError(n)}},t.addEventListener("addstream",(e=>{this.options.remoteStream=e.stream})),t.addEventListener("track",(e=>{this.options.remoteStream=e.streams[0];const{remoteElement:i,remoteStream:n,screenShare:s}=this.options;s===!1&&Lt(i,n,{callId:this.id,sessionId:this.session.sessionid,eventTarget:this.session.uuid})}))}_onMediaError(t){const e=t?.name||"UnknownError",i=t?.message||"Unknown media error",n=t?.originalError||t;this._dispatchNotification({type:Ce.userMediaError,error:n,call:this,errorName:e,errorMessage:i}),d.error(`Media error (${e}): ${i}`,t),F(D.Error,{error:t,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),this.hangup({initiator:"sdk:media-error"},!1)}_onPeerConnectionFailureError(t){this._dispatchNotification({type:Ce.peerConnectionFailureError,error:t.error}),d.error("Peer connection failure error"),t.warning&&F(D.Warning,{warning:t.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(t){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:Ce.signalingStateClosed},t)),d.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(t){this._dispatchNotification(Object.assign({type:Ce.conferenceUpdate,call:this},t))}_dispatchNotification(t){this.options.screenShare!==!0&&(F(D.Notification,t,this.id,!1)||F(D.Notification,t,this.session.uuid))}_execute(t){return this.nodeId&&(t.targetNodeId=this.nodeId),this.session.execute(t)}_registerInboundAnswerAttempt(){var t;if(this.options.attach||this._isRecovering)return!0;const e=(t=this.session.calls)===null||t===void 0?void 0:t[this.id];if(e&&e!==this){const i=he(Wo);return F(D.Warning,{warning:i,callId:this.id,activeCallId:e.id,sessionId:this.session.sessionid},this.session.uuid),d.warn(`[${this.id}] answer() ignored: callID ${this.id} already has an active call (${e.id})`),!1}return!0}_init(){var t,e,i,n,s,o,r,a,l,h;const{id:p,userVariables:f,remoteCallerNumber:b,onNotification:g,recoveredCallId:v,wasHeldBeforeRecovery:y}=this.options;var S;this.options.id=p?p.toString():qe(),this.id=this.options.id,v&&(this.recoveredCallId=v,this._isRecovering=!0,this._wasHeldBeforeRecovery=!!y),f&&(S=f,Object.keys(S).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),b||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Ne(D.MediaError,this._onMediaError,this.id),Ne(D.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Ne(D.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Ut(g)&&Ne(D.Notification,g.bind(this),this.id);const E=this.session.options.enableCallReports!==!1,T=this.session.options.callReportInterval||5e3,N=(t=this.session.options.callReportFlushInterval)!==null&&t!==void 0?t:18e4,$=this.session.options.debugLogLevel||"debug",j=this.session.options.debugLogMaxEntries||1e3;if(E&&(this._callReportCollector=new pe({enabled:!0,interval:T,intermediateReportInterval:N},{enabled:!0,level:$,maxEntries:j}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=q=>{var Y,M,c,u;F(D.Warning,{warning:q,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),q.code===di&&this._state!==V.Held?(M=(Y=this.session).reportNoRtp)===null||M===void 0||M.call(Y,this.id,"inbound"):q.code===es&&this._state!==V.Held&&this._hasActiveUnmutedLocalAudioTrack()&&((u=(c=this.session).reportNoRtp)===null||u===void 0||u.call(c,this.id,"outbound"))}),this.session.options.enableCallRecording===!0){const q={enabled:!0,flushIntervalMs:(e=this.session.options.callRecordingFlushIntervalMs)!==null&&e!==void 0?e:15e3,maxBufferBytes:(i=this.session.options.callRecordingMaxBufferBytes)!==null&&i!==void 0?i:us,sampleRate:(n=this.session.options.callRecordingSampleRate)!==null&&n!==void 0?n:48e3,tracks:(s=this.session.options.callRecordingTracks)!==null&&s!==void 0?s:["local","remote"],endpoint:(o=this.session.options.callRecordingEndpoint)!==null&&o!==void 0?o:"/call_recording"},Y={callId:this.id,callReportId:(r=this.session.callReportId)!==null&&r!==void 0?r:"",voiceSdkId:this._getCallReportVoiceSdkId()};this._callRecorder=new je(q,Y);const M=(a=this.session.connection)===null||a===void 0?void 0:a.host;M&&this._callRecorder._setHost(M),this._callRecorder.onWarning=c=>{F(D.Warning,{warning:c,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}this._isRecovering?this.setState(V.Recovering):this.setState(V.New),d.info(`New Call — region: ${(l=this.session.region)!==null&&l!==void 0?l:"unknown"}, dc: ${(h=this.session.dc)!==null&&h!==void 0?h:"unknown"}`,this.options)}getEstablishmentTimings(){var t,e,i;const n=(t=this.peer)===null||t===void 0?void 0:t.callEstablishmentTimings;if(n)return n;const s=!((e=this.options)===null||e===void 0)&&e.trickleIce&&!(!((i=this.peer)===null||i===void 0)&&i.isIceRestarting)?"trickle":"non-trickle";return bs(this.id,s,this.direction)}_finalize(){var t,e,i;this._stopStats(),(t=this._mediaDeviceCollector)===null||t===void 0||t.stop(),this._mediaDeviceCollector=null,(e=this._callRecorder)===null||e===void 0||e.stop(),bi(this.id),d.debug(`[${this.id}] Closing peer from _finalize`),(i=this.peer)===null||i===void 0||i.close();
6const{remoteStream:n,localStream:s,remoteElement:o,localElement:r}=this.options;ot(n),ot(s),vn(o,n),vn(r,s),Re(D.MediaError,null,this.id),Re(D.PeerConnectionFailureError,null,this.id),Re(D.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id];const a=this._postCallReport().catch((l=>{d.error("Unexpected error in _postCallReport",{error:l})}));this.session.trackCallReportUpload(a)}_getCallReportVoiceSdkId(){return this.session.callReportVoiceSdkId||void 0}_getClientSummary(){var t,e,i,n,s,o,r,a,l,h,p,f;const b=this.session.options,g=b.anonymous_login;return{authentication:Object.assign({type:this._getAuthenticationType()},g?{anonymousLogin:{targetType:g.target_type,targetId:g.target_id,targetVersionId:g.target_version_id,targetParams:this._sanitizeClientOption(g.target_params)}}:{}),connection:{env:b.env,host:b.host,project:b.project,region:(t=this.session.region)!==null&&t!==void 0?t:b.region,dc:this.session.dc,rtcIp:b.rtcIp,rtcPort:b.rtcPort,autoReconnect:(e=b.autoReconnect)===null||e===void 0||e,maxReconnectAttempts:(i=b.maxReconnectAttempts)!==null&&i!==void 0?i:10,keepConnectionAliveOnSocketClose:(n=b.keepConnectionAliveOnSocketClose)!==null&&n!==void 0&&n,hangupOnBeforeUnload:b.hangupOnBeforeUnload!==!1,useCanaryRtcServer:(s=b.useCanaryRtcServer)!==null&&s!==void 0&&s,skipLastVoiceSdkId:(o=b.skipLastVoiceSdkId)!==null&&o!==void 0&&o,skipTrailing:(r=b.skipTrailing)!==null&&r!==void 0&&r},media:{audio:this._sanitizeClientOption(this.options.audio),video:this._sanitizeClientOption(this.options.video),mutedMicOnStart:(a=this.options.mutedMicOnStart)!==null&&a!==void 0&&a,prefetchIceCandidates:(l=this.options.prefetchIceCandidates)!==null&&l!==void 0&&l,forceRelayCandidate:(h=this.options.forceRelayCandidate)!==null&&h!==void 0&&h,trickleIce:(p=this.options.trickleIce)!==null&&p!==void 0&&p,iceServers:this._sanitizeIceServers(this.options.iceServers)},callReports:{enabled:b.enableCallReports!==!1,intervalMs:b.callReportInterval||5e3,flushIntervalMs:(f=b.callReportFlushInterval)!==null&&f!==void 0?f:18e4,debugLogLevel:b.debugLogLevel||"debug",debugLogMaxEntries:b.debugLogMaxEntries||1e3}}}_getAuthenticationType(){const t=this.session.options;return t.anonymous_login?"anonymous_login":t.login_token?"login_token":t.login&&(t.password||t.passwd)?"login_password":t.token?"token":"unknown"}_sanitizeIceServers(t){if(t&&t.length!==0)return t.map((({urls:e,username:i,credential:n})=>({urls:e,hasUsername:!!i,hasCredential:!!n})))}_sanitizeClientOption(t,e=0){if(t!==void 0){if(t===null)return null;if(typeof t=="string")return t;if(typeof t=="number")return Number.isFinite(t)?t:void 0;if(typeof t=="boolean")return t;if(typeof t!="function"){if(e>=4)return"[truncated]";if(Array.isArray(t))return t.map((i=>this._sanitizeClientOption(i,e+1))).filter((i=>i!==void 0));if(typeof t=="object"){const i=Object.entries(t).filter((([n])=>!this._isSensitiveClientOptionKey(n))).map((([n,s])=>[n,this._sanitizeClientOption(s,e+1)])).filter((n=>n[1]!==void 0));return Object.fromEntries(i)}}}}_isSensitiveClientOptionKey(t){return/(password|passwd|credential|secret|token|authorization|auth|api[_-]?key)/i.test(t)}flushIntermediateCallReport(t={type:"manual"}){this._flushIntermediateReport(t)}_flushIntermediateReport(t={type:"buffer-limit"}){var e;if(!this._callReportCollector)return;const i=this.session.callReportId;if(!i)return void d.debug("Cannot flush intermediate report: call_report_id not available");const n=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!n)return void d.debug("Cannot flush intermediate report: connection host not available");const s={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===Ee.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Ct,clientSummary:this._getClientSummary()},o=this._callReportCollector.flush(s,t);if(!o)return;d.info("Flushing intermediate call report",{callId:this.id,flushReason:t,segment:o.segment});const r=this._getCallReportVoiceSdkId(),a=t.type==="page-unload",l=this._callReportCollector.sendPayload(o,i,n,r,a).catch((h=>{d.error("Failed to post intermediate call report segment",{error:h})}));this.session.trackCallReportUpload(l)}_postCallReport(){var t,e,i,n;return R(this,void 0,void 0,(function*(){if(!this._callReportCollector)return void d.warn("Call report collector not initialized");if(yield this._callReportCollector.stop(),this._callRecorder){this._callRecorder.stop();const l=(t=this.session.connection)===null||t===void 0?void 0:t.host;l&&this._callRecorder._setHost(l),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const h=this._callRecorder.postFinalReport().catch((p=>{d.error("Failed to post final call recording",{error:p})})).finally((()=>{var p;(p=this._callRecorder)===null||p===void 0||p.cleanup()}));this.session.trackCallReportUpload(h)}const s=this.session.callReportId;if(!s)return d.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const o={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===Ee.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Ct,clientSummary:this._getClientSummary()},r=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!r)return void d.error("Cannot post call report: connection host not available");const a=this._getCallReportVoiceSdkId();try{yield this._callReportCollector.postReport(o,s,r,a)}catch(l){throw d.error("Failed to post call report",{error:l}),l}finally{(i=this._callReportCollector)===null||i===void 0||i.cleanup(),(n=this._callRecorder)===null||n===void 0||n.cleanup()}}))}_startStats(t){this._statsIntervalId=setInterval(this._doStats,t),d.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),d.debug("Stats stopped")}};
6Ss.setStateTelnyx=t=>{if(t){switch(t._state){case V.Recovering:t.state="recovering";break;case V.Requesting:case V.Trying:case V.Early:t.state="connecting";break;case V.Active:t.state="active";break;case V.Held:t.state="held";break;case V.Hangup:case V.Destroy:t.state="done";break;case V.Answering:t.state="ringing";break;case V.New:t.state="new"}return t}};var Ai=class Rt extends Ss{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,i)=>this.session.execute(new Dr(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 xr(e);this.session.connection.sendRawText(JSON.stringify(i.request))}}hangup(e={},i=!0){const n=Object.create(null,{hangup:{get:()=>super.hangup}});return R(this,void 0,void 0,(function*(){this.screenShare instanceof Rt&&(yield this.screenShare.hangup(e,i)),yield n.hangup.call(this,e,i)}))}startScreenShare(e){return R(this,void 0,void 0,(function*(){const i=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;i.getTracks().forEach((h=>{h.addEventListener("ended",(()=>R(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 Rt(this.session,l),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){return R(this,void 0,void 0,(function*(){this.screenShare instanceof Rt&&(yield this.screenShare.hangup({initiator:"app:stopScreenShare"}))}))}setAudioOutDevice(e){return R(this,void 0,void 0,(function*(){this.options.speakerId=e;const{remoteElement:i,speakerId:n}=this.options;return!(!i||!n)&&fs(i,n)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval((()=>R(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+=`
7${r.type}
8`,Object.keys(r).forEach((a=>{o.includes(a)||(n+=`	${a}: ${r[a]}
9`)})))})),d.info(n)}))),2e3)}},Cs=class ws extends fi{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._localElementId=null,this._remoteElement=null,this._remoteElementId=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile}getActiveCalls(){return Object.values(this.calls).filter((e=>ws.ACTIVE_CALL_STATE_NAMES.has(e.state)))}_extractSafeCallIdentifiers(e){var i,n;const s={callId:e.id,state:e.state,direction:e.direction};(i=e.options)!==null&&i!==void 0&&i.telnyxSessionId&&(s.telnyxSessionId=e.options.telnyxSessionId),(n=e.options)!==null&&n!==void 0&&n.telnyxLegId&&(s.telnyxLegId=e.options.telnyxLegId);const o=e.sipCallId;return typeof o=="string"&&o&&(s.sipCallId=o),s}emitMultipleActiveCallsWarning(e){const i=this.getActiveCalls().filter((r=>r.id!==e));if(i.length===0)return;const n=he(Ho),s=this.calls[e],o=s?this._extractSafeCallIdentifiers(s):{callId:e};F(D.Warning,{warning:n,callId:e,sessionId:this.sessionid,newCall:o,activeCalls:i.map((r=>this._extractSafeCallIdentifiers(r)))},this.uuid),d.warn(`MULTIPLE_ACTIVE_CALLS_DETECTED: new call ${e} created while ${i.length} other call(s) are active in session ${this.sessionid}`)}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return R(this,void 0,void 0,(function*(){return e.getIsRegistered.call(this)}))}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return R(this,void 0,void 0,(function*(){d.debug("BrowserSession.connect() called"),e.connect.call(this)}))}checkPermissions(e=!0,i=!0){return R(this,void 0,void 0,(function*(){try{const n=yield Mt({audio:e,video:i});return ot(n),!0}catch{return!1}}
9))}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return R(this,void 0,void 0,(function*(){d.info("[disconnect] Client-initiated disconnect — setting Purge with BYE on all active calls.");for(const i in this.calls){const n=this.calls[i];n.setState(V.Purge),d.info("Start hangup for ",n),yield n.hangup({initiator:"app:client.disconnect"},!0)}this.calls={},yield e.disconnect.call(this)}))}serverDisconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return R(this,void 0,void 0,(function*(){d.info("[serverDisconnect] Server-initiated disconnect — setting Purge without BYE on all active calls.");for(const i in this.calls){const n=this.calls[i];n.setState(V.Purge),n.hangup({initiator:"sdk:server-disconnect"},!1)}this.calls={},yield e.disconnect.call(this)}))}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise(((i,n)=>{if(ps(D.SpeedTest,(r=>{const{upDur:a,downDur:l}=r,h=l?8*e/(l/1e3)/1024:0;i({upDur:a,downDur:l,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:h.toFixed(0)})}),this.uuid),!(e=Number(e)))return n(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let s=e/1024;e%1024&&s++;const o=".".repeat(1024);for(let r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")}))}getDevices(){return Ze().catch((e=>{const i=Z(Ye(e),e);return F(D.MediaError,i,this.uuid),[]}))}getVideoDevices(){return Ze(Te.Video).catch((e=>(F(D.MediaError,e,this.uuid),[])))}getAudioInDevices(){return Ze(Te.AudioIn).catch((e=>{const i=Z(Ye(e),e);return F(D.MediaError,i,this.uuid),[]}))}getAudioOutDevices(){return Ze(Te.AudioOut).catch((e=>(d.error("getAudioOutDevices",e),F(D.MediaError,e,this.uuid),[])))}validateDeviceId(e,i,n){return Pt(e,i,n)}getDeviceResolutions(e){return R(this,void 0,void 0,(function*(){try{return yield(i=>R(void 0,void 0,void 0,(function*(){const n=[],s=yield Mt({video:{deviceId:{exact:i}}}),o=s.getVideoTracks()[0];for(let r=0;r<fn.length;r++){const[a,l]=fn[r];(yield o.applyConstraints({width:{exact:a},height:{exact:l}}).then((()=>!0)).catch((()=>!1)))&&n.push({resolution:`${a}x${l}`,width:a,height:l})}return ot(s),n})))(e)}catch(i){throw i}}))}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return R(this,void 0,void 0,(function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:i,micLabel:n}=e,s=Kn(e,["micId","micLabel"]);return Ar(s),this._audioConstraints=yield((o,r,a,l)=>R(void 0,void 0,void 0,(function*(){const{deviceId:h}=l;if(h===void 0&&(o||r)){const p=yield Pt(o,r,a).catch((()=>null));p&&(l.deviceId={exact:p})}return l})))(i,n,"audioinput",s),this.micId=i,this.micLabel=n,this._audioConstraints}))}disableMicrophone(){this._previousAudioConstraints=this._audioConstraints,this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=this._previousAudioConstraints||!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const i=this.options.env==="development";this._iceServers=i?ir:tr}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElementId=typeof e=="string"?e:null,this._localElement=nt(e)}get localElement(){return this._localElement}get localElementId(){return this._localElementId}set remoteElement(e){this._remoteElementId=typeof e=="string"?e:null,this._remoteElement=nt(e)}get remoteElement(){return this._remoteElement}get remoteElementId(){return this._remoteElementId}vertoBroadcast({nodeId:e,channel:i="",data:n}){if(!i)throw new Error(`Invalid channel for broadcast: ${i}`);const s=new kr({sessid:this.sessionid,eventChannel:i,data:n});e&&(s.targetNodeId=e),this.execute(s).catch((o=>o))}vertoSubscribe({nodeId:e,channels:i=[],handler:n}){return R(this,void 0,void 0,(function*(){if(!(i=i.filter((l=>l&&!this._existsSubscription(this.relayProtocol,l)))).length)return{};const s=new Ir({sessid:this.sessionid,eventChannel:i});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=yi(o);return r.length&&r.forEach((l=>this._removeSubscription(this.relayProtocol,l))),a.forEach((l=>this._addSubscription(this.relayProtocol,n,l))),o}))}
9vertoUnsubscribe({nodeId:e,channels:i=[]}){return R(this,void 0,void 0,(function*(){if(!(i=i.filter((a=>a&&this._existsSubscription(this.relayProtocol,a)))).length)return{};const n=new Er({sessid:this.sessionid,eventChannel:i});e&&(n.targetNodeId=e);const s=yield this.execute(n),{unsubscribed:o=[],notSubscribed:r=[]}=yi(s);return o.forEach((a=>this._removeSubscription(this.relayProtocol,a))),r.forEach((a=>this._removeSubscription(this.relayProtocol,a))),s}))}static telnyxStateCall(e){return Ai.setStateTelnyx(e)}};Cs.ACTIVE_CALL_STATE_NAMES=new Set(["new","requesting","trying","recovering","ringing","answering","early","active","held"]);var wn=class{constructor(t,e){this.code=e,this.message=t}},Wr=class{constructor(t){this.session=t,this.retriedConnect=0,this.retriedRegister=0}_ack(t,e){const i=new br(t,e);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*(t=2,e=6,Math.floor(Math.random()*(e-t+1)+t));var t,e}handleMessage(t){var e,i,n,s,o,r,a,l,h;const{session:p}=this;p.setPingReceived();const{id:f,method:b,params:g={},voice_sdk_id:v}=t,y=g?.callID,S=g?.eventChannel,E=g?.eventType,T=p.calls[y],N=(e=T?.peer)===null||e===void 0?void 0:e.isConnectionHealthy(),$=new Set(Object.keys(p.calls));if(Array.isArray(g?.reattached_sessions)&&$.size){d.debug(`Reattach: active call IDs before cleanup check: [${Array.from($).join(", ")}].`);const M=g.reattached_sessions.length===0,c=g.reattached_sessions.some((u=>$.has(u)));if(M||!c)for(const u of Object.keys(p.calls)){const m=p.calls[u];d.debug(`Session not reattached — terminating active call ${u} `);const C=Z(Xi);F(D.Error,{error:C,callId:u,sessionId:p.sessionid},p.uuid),m.hangup({},!1)}}if(Array.isArray(g?.reattached_sessions)&&p.sessionid){const M=an();if(M&&M.calls.length>0)if(M.sessionId!==p.sessionid)d.debug(`Recovery markers were saved for a different sessid (saved=${M.sessionId}, current=${p.sessionid}) — ignoring all.`),Me();else{const c=new Set(g.reattached_sessions),u=[];for(const m of M.calls)try{if(c.has(m.id)){d.debug(`Recovery marker for call ${m.id} was reattached — keeping for Attach element restore.`),u.push(m);continue}d.info(`Recovery marker for call ${m.id} (sessid=${p.sessionid}) was not reattached — emitting SESSION_NOT_REATTACHED.`);const C=Z(Xi);F(D.Error,{error:C,callId:m.id,sessionId:p.sessionid,customHeaders:m.customHeaders},p.uuid)}catch(C){d.debug(`Recovery marker for a saved call failed to process (callId=${m?.id}) — skipping: ${C instanceof Error?C.message:String(C)}`),u.push(m)}ds(u,M.sessionId,M.storedAt)}}if(E==="channelPvtData")return this._handlePvtEvent(g.pvtData);const j=({recoveredCallId:M,forceRelayCandidateForRecovery:c,mutedMicOnStart:u,remoteElement:m,localElement:C,wasHeldBeforeRecovery:k}={})=>{var O,A,P,W,ee,te;const I={audio:!0,video:p.options.video,remoteSdp:g.sdp,destinationNumber:g.callee_id_number,remoteCallerName:g.caller_id_name,remoteCallerNumber:g.caller_id_number,callerName:g.callee_id_name,callerNumber:g.callee_id_number,attach:b===Q.Attach,mediaSettings:g.mediaSettings,debug:(O=p.options.debug)!==null&&O!==void 0&&O,debugOutput:(A=p.options.debugOutput)!==null&&A!==void 0?A:"socket",trickleIce:(P=p.options.trickleIce)!==null&&P!==void 0&&P,prefetchIceCandidates:(W=p.options.prefetchIceCandidates)!==null&&W!==void 0&&W,forceRelayCandidate:typeof c=="boolean"?c:(ee=p.options.forceRelayCandidate)!==null&&ee!==void 0&&ee,keepConnectionAliveOnSocketClose:(te=p.options.keepConnectionAliveOnSocketClose)!==null&&te!==void 0&&te,mutedMicOnStart:u??p.options.mutedMicOnStart};y&&(I.id=y),g.telnyx_call_control_id&&(I.telnyxCallControlId=g.telnyx_call_control_id),g.telnyx_session_id&&(I.telnyxSessionId=g.telnyx_session_id),g.telnyx_leg_id&&(I.telnyxLegId=g.telnyx_leg_id),g.client_state&&(I.clientState=g.client_state),g.dialogParams&&g.dialogParams.custom_headers&&g.dialogParams.custom_headers.length&&(I.customHeaders=g.dialogParams.custom_headers),M&&(I.recoveredCallId=M),k&&(I.wasHeldBeforeRecovery=k),m!==void 0&&(I.remoteElement=m),C!==void 0&&(I.localElement=C),performance.mark(X(I.id,"new-call-start"));const x=new Ai(p,I);return x.nodeId=this.nodeId,x},q=new gs(v),Y=new Ti(v);switch(b){case Q.Answer:case Q.Display:case Q.Candidate:case Q.Ringing:case Q.Bye:case Q.Media:if(!y||!T)return void d.error(`Received ${b} for non existing call:`,g);T.handleMessage(t),this._ack(f,b);break;case Q.Ping:this.session.setPingReceived(),this.session.execute(Y);break;case Q.Punt:p.options.keepConnectionAliveOnSocketClose&&N?(d.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),p.socketDisconnect(),this._ack(f,b)):(d.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),p.serverDisconnect());break;case Q.Invite:{const u=j();u.direction=Ee.Inbound,u.playRingtone(),u.setState(V.Ringing),this.session.emitMultipleActiveCallsWarning(u.id),this._ack(f,b);break}case Q.Attach:{const u=T||null;if(Object.keys(p.calls).length===0){let m,C;d.warn(`[${new Date().toISOString()}][${y}] Attach: SDK doens't have any active call therefore we recover first arrived attach session ${y}`);let k=!1,O=!1;const A=an();if(A&&A.sessionId===p.sessionid){const W=A.calls.find((ee=>ee!==null&&typeof ee=="object"&&ee.id===y));W&&(m=W.remoteElement,C=W.localElement,k=W.wasHeld===!0,typeof W.forceRelayCandidate=="boolean"&&(O=W.forceRelayCandidate),(m||C)&&d.info(`[${y}] Attach: restoring per-call media elements from recovery marker (remoteElement=${m??"<none>"}, localElement=${C??"<none>"}).`),typeof W.forceRelayCandidate=="boolean"&&d.info(`[${y}] Attach: restoring forceRelayCandidate=${W.forceRelayCandidate} from recovery marker.`))}const P=j({recoveredCallId:y,forceRelayCandidateForRecovery:O,remoteElement:m,localElement:C,wasHeldBeforeRecovery:k});P.answer(),this.session.emitMultipleActiveCallsWarning(P.id),this._ack(f,b);break}
9if(u){const m=u.id,C=u.state==="held",k=u.shouldForceRelayCandidateForRecovery();k&&d.warn(`[${new Date().toISOString()}][${y}] Attach: forcing relay candidate for recovery`),d.info(`[${new Date().toISOString()}][${y}] Attach: recovering active call ${m}.`),u.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1);const O=j({recoveredCallId:m,forceRelayCandidateForRecovery:k,mutedMicOnStart:u.isAudioMuted,remoteElement:u.options.remoteElement,localElement:u.options.localElement,wasHeldBeforeRecovery:C});O.answer(),this.session.emitMultipleActiveCallsWarning(O.id),this._ack(f,b);break}d.warn(`Attach: callID ${y} does not match any active calls. `),F(D.Warning,{warning:he(qo),callId:y,params:g,sessionId:p.sessionid},p.uuid),this._ack(f,b);break}case Q.Event:case"webrtc.event":if(!S)return void d.error("Verto received an unknown event:",g);const M=p.relayProtocol,c=S.split(".")[0];p._existsSubscription(M,S)?F(M,g,S):S===p.sessionid?this._handleSessionEvent(g.eventData):p._existsSubscription(M,c)?F(M,g,c):p.calls.hasOwnProperty(S)?p.calls[S].handleMessage(t):F(D.Notification,g,p.uuid);break;case Q.Info:g.type=Ce.generic,F(D.Notification,g,p.uuid);break;case Q.ClientReady:this.session.execute(q);break;case"ai_conversation":F(D.AIConversationMessage,{method:"ai_conversation",params:g,voice_sdk_id:v},p.uuid);break;default:{const u=ki(t);if(u){switch(u){case de.REGISTER:case de.REGED:if(!this.isDuplicateGatewayState(u,[de.REGED,de.REGISTER])){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0,u===de.REGED&&this.session.resetReconnectAttempts();const m=(n=(i=t?.result)===null||i===void 0?void 0:i.params)===null||n===void 0?void 0:n.call_report_id;m&&(p.callReportId=m,d.debug("Captured call_report_id from REGED:",m));const C=(o=(s=t?.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.dc;C&&(p.dc=C);const k=(a=(r=t?.result)===null||r===void 0?void 0:r.params)===null||a===void 0?void 0:a.region;k&&(p.region=k),d.info(`Connected to Telnyx — region: ${(l=p.region)!==null&&l!==void 0?l:"unknown"}, dc: ${(h=p.dc)!==null&&h!==void 0?h:"unknown"}`),g.type=Ce.vertoClientReady,F(D.Ready,g,p.uuid)}break;case de.UNREGED:case de.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const m=new wn("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),C=Z(Zn,m);F(D.Error,{error:C,sessionId:p.sessionid},p.uuid);break}setTimeout((()=>{this.session.execute(q)}),this.reconnectDelay());break;case de.FAILED:case de.FAIL_WAIT:case de.TIMEOUT:if(!this.isDuplicateGatewayState(u,[de.FAILED,de.FAIL_WAIT,de.TIMEOUT])){const m=Z(ko,new Error(`Gateway state: ${u}`));if(F(D.Error,{error:m,sessionId:p.sessionid},p.uuid),p.options.skipLastVoiceSdkId=!0,d.debug(`Set skipLastVoiceSdkId=true on session options to avoid sticky reconnect to same b2bua-rtc instance (sessionId=${p.sessionid})`),!this.session.hasAutoReconnect()){this.retriedConnect=0;const C=new wn("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT|TIMEOUT");this.session._terminateActiveCallsLocally();const k=Z(ci,C);F(D.Error,{error:k,sessionId:p.sessionid},p.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0,this.session._terminateActiveCallsLocally();const C=Z(ci,new Error("Connection Retry Failed"));F(D.Error,{error:C,sessionId:p.sessionid},p.uuid);break}setTimeout((()=>{if(d.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(p.calls).some((C=>{var k;return((k=C.peer)===null||k===void 0?void 0:k.instance)&&!C.signalingStateClosed})))return d.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();d.debug("keepConnectionAliveOnSocketClose is set but all peer connections have signalingState closed, doing full reconnect")}this.session.disconnect().then((()=>{this.session.clearConnection(),this.session.connect()}))}),this.reconnectDelay())}break;default:d.warn("GatewayState message unknown method:",t)}break}d.debug("Verto message unknown method:",t);break}}}isDuplicateGatewayState(t,e){const{previousGatewayState:i}=this.session.connection,n=e.includes(i);return n&&d.debug(`Gateway state '${t}' received but previous state was '${i}' — guard condition met, skipping re-emission (sessionId=${this.session.sessionid})`),n}_retrieveCallId(t,e){const i=Object.keys(this.session.calls);if(t.action!=="bootObj")return i.find((n=>this.session.calls[n].channels.includes(e)));{const n=t.data.find((s=>i.includes(s[0])));if(n instanceof Array)return n[0]}}_handlePvtEvent(t){return R(this,void 0,void 0,(function*(){const{session:e}=this,i=e.relayProtocol,{action:n,laChannel:s,laName:o,chatChannel:r,infoChannel:a,modChannel:l,conferenceMemberID:h,role:p,callID:f}=t;switch(n){case"conference-liveArray-join":{const b=()=>{e.vertoBroadcast({nodeId:this.nodeId,channel:s,data:{liveArray:{command:"bootstrap",context:s,name:o}}})},g={nodeId:this.nodeId,channels:[s],handler:({data:y})=>{const S=f||this._retrieveCallId(y,s);if(S&&e.calls.hasOwnProperty(S)){const E=e.calls[S];E._addChannel(s),E.extension=o,E.handleConferenceUpdate(y,t).then((T=>{T==="INVALID_PACKET"&&b()}))}}},v=yield e.vertoSubscribe(g).catch((y=>{d.error("liveArray subscription error:",y);const S=Z(So,y);F(D.Error,{error:S,sessionId:e.sessionid},e.uuid)}));_i(v,s)&&b();break}case"conference-liveArray-part":{let b=null;
9if(s&&e._existsSubscription(i,s)){const{callId:v=null}=e.subscriptions[i][s];if(b=e.calls[v]||null,v!==null){const y={type:Ce.conferenceUpdate,action:_e.Leave,conferenceName:o,participantId:Number(h),role:p};F(D.Notification,y,v,!1)||F(D.Notification,y,e.uuid),b===null&&Re(D.Notification,null,v)}}const g=[s,r,a,l];e.vertoUnsubscribe({nodeId:this.nodeId,channels:g}).then((({unsubscribedChannels:v=[]})=>{b&&(b.channels=b.channels.filter((y=>!v.includes(y))))})).catch((v=>{d.error("liveArray unsubscribe error:",v)}));break}}}))}_handleSessionEvent(t){switch(t.contentType){case"layout-info":case"layer-info":_s(this.session,t);break;case"logo-info":{const e={type:Ce.conferenceUpdate,action:_e.LogoInfo,logo:t.logoURL};F(D.Notification,e,this.session.uuid);break}}}},Gr=class extends Cs{constructor(t){super(t),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>R(this,void 0,void 0,(function*(){this._idle=!1;const{autoReconnect:e=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=e}})})),this.handleAnonymousLoginOnSocketOpen=()=>R(this,void 0,void 0,(function*(){this._idle=!1,yield this.login()})),this._vertoHandler=new Wr(this),window.addEventListener("beforeunload",(e=>{if(d.debug("Window beforeunload triggered."),t.hangupOnBeforeUnload!==!1)return cs(),void(this.calls&&Object.keys(this.calls).forEach((i=>{this.calls[i]&&(d.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({initiator:"sdk:beforeunload"},!0))})));try{const i=this.getActiveCalls().map((n=>{const s={id:n.id,customHeaders:n.options.customHeaders,forceRelayCandidate:n.shouldForceRelayCandidateForRecovery()};return n.state==="held"&&(s.wasHeld=!0),typeof n.options.remoteElement=="string"?s.remoteElement=n.options.remoteElement:this.remoteElementId&&n.options.remoteElement===this.remoteElement&&(s.remoteElement=this.remoteElementId),typeof n.options.localElement=="string"?s.localElement=n.options.localElement:this.localElementId&&n.options.localElement===this.localElement&&(s.localElement=this.localElementId),s}));if(this.getActiveCalls().forEach((n=>{if(n.flushIntermediateCallReport)try{d.debug(`beforeunload: flushing call report for ${n.id}.`),n.flushIntermediateCallReport({type:"page-unload"})}catch(s){d.debug(`beforeunload: failed to flush call report for ${n.id}: ${s instanceof Error?s.message:String(s)}`)}})),!this.sessionid||i.length===0)return d.debug(`No sessionID ${this.sessionid} or activeCalls ${i.length} during saving calls recover marker!`),void Me();d.info(`Saving recovery marker for ${i.length} active call(s) before unload (sessid=${this.sessionid}): [${i.map((n=>n.id)).join(", ")}].`),ds(i,this.sessionid)}catch(i){const n=this.calls?Object.keys(this.calls):[];d.debug(`Failed to save active-calls recovery marker before unload (active call ids: [${n.join(", ")}]): ${i instanceof Error?i.message:String(i)}`)}})),document.addEventListener("visibilitychange",(()=>{document.visibilityState==="hidden"&&t.hangupOnBeforeUnload===!1&&this.sessionid&&this.hasActiveCall()&&(d.debug("visibilitychange → hidden: re-stamping reconnect session-id freshness."),hi(this.sessionid))}))}validateOptions(){return Dt(this.options)||tt(this.options)}newCall(t){if(!this.validateCallOptions(t))throw Z(yo,void 0,"Error: destinationNumber is required");const e=new Ai(this,t);return t.id||d.debug(`newCall: callId was not provided in options, SDK-generated ID: ${e.id}`),this.emitMultipleActiveCallsWarning(e.id),performance.mark(X(e.id,"new-call-start")),e.invite(),e}broadcast(t){return this.vertoBroadcast(t)}subscribe(t){return this.vertoSubscribe(t)}unsubscribe(t){return this.vertoUnsubscribe(t)}validateCallOptions(t){return!!tt(this.options)||!!t.destinationNumber}_onSocketOpen(){const t=Object.create(null,{_onSocketOpen:{get:()=>super._onSocketOpen}});return R(this,void 0,void 0,(function*(){return t._onSocketOpen.call(this),Dt(this.options)?this.handleLoginOnSocketOpen():tt(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0}))}_onSocketMessage(t){this._vertoHandler.handleMessage(t)}};function kn(t){return{options:t,statsSamples:[]}}function Vr(t){var e,i;const n=(i=(e=t.call)===null||e===void 0?void 0:e.peer)===null||i===void 0?void 0:i.instance,s=t.statsSamples[t.statsSamples.length-1];if(!n||!s)return;const o=(function(a,l){var h;const p=[],f=new Set,b=new Map,g=new Map,v={host:0,srflx:0,prflx:0,relay:0};a.forEach((M=>{switch(M.type){case"local-candidate":{const c=M;v[c.candidateType]++,g.set(c.id,c);break}case"remote-candidate":{const c=M;b.set(c.id,c);break}case"candidate-pair":{const c=M;p.push(c);break}case"transport":{const c=M;typeof c.selectedCandidatePairId=="string"&&f.add(c.selectedCandidatePairId);break}}}));const y=(function(M,c,u,m){var C,k;const O=M.find((te=>c.has(te.id))),A=M.find((te=>te.selected===!0)),P=M.find((te=>te.nominated===!0&&te.state==="succeeded")),W=M.filter((te=>te.state==="succeeded")),ee=(k=(C=O??A)!==null&&C!==void 0?C:P)!==null&&k!==void 0?k:W.length===1?W[0]:void 0;return ee?Object.assign(Object.assign({},ee),{localCandidate:u.get(ee.localCandidateId),remoteCandidate:m.get(ee.remoteCandidateId)}):null})(p,f,g,b),S=v.relay>0,E=v.srflx===0&&v.relay===0&&v.prflx===0,T=l.iceGatheringState,N=l.iceConnectionState,$=T==="complete",j=((h=y?.localCandidate)===null||h===void 0?void 0:h.candidateType)==="relay",{hasMultipleNetworkInterfaces:q,vpnDetected:Y}=(function(M){if(M.size===0)return{hasMultipleNetworkInterfaces:void 0,vpnDetected:void 0};const c=Array.from(M.values());return{hasMultipleNetworkInterfaces:new Set(c.filter((u=>u.candidateType==="host")).map((u=>u.address))).size>=2,vpnDetected:c.some((u=>u.networkType==="vpn"))}})(g);return{candidateGatheringCompleted:$,gatheringComplete:$,candidateCounts:v,candidates:Array.from(g.values()),hasRelayCandidate:S,onlyHostCandidates:E,isTurnRequired:j,hasMultipleNetworkInterfaces:q,vpnDetected:Y,hasSelectedPair:!!y,selectedPair:y??void 0,iceGatheringState:T,iceConnectionState:N}})(s,n),r=n.getConfiguration().iceServers;return r&&(o.serverCandidateComparison=(function(a,l){var h,p;if(!a||a.length===0)return;const f=[];for(const b of a){const g=Array.isArray(b.urls)?b.urls:[b.urls],v=l.filter((E=>g.some((T=>qr(E.url,T,E.protocol))))),y=(p=(h=v[0])===null||h===void 0?void 0:h.candidateType)!==null&&p!==void 0?p:null,S=v.length>0;f.push({urls:b.urls,hasCandidates:S,candidateType:y,candidates:v,candidateCount:v.length})}return f})(r,o.candidates)),o}function ks(t){return(Array.isArray(t.urls)?t.urls:[t.urls]).some((e=>/^turns?:/i.test(e)))}function In(t){var e;let i=t;const n=i.match(/^([a-z]+:)(\/\/)?([^@]*@)(.+)$/i);n&&(i=n[1]+((e=n[2])!==null&&e!==void 0?e:"")+n[4]);const s=i.indexOf("?transport=");return s!==-1&&(i=i.substring(0,s)),i}function En(t){const e=t.indexOf("?transport=");if(e===-1)return;const i=t.substring(e+11).toLowerCase(),n=i.indexOf("&");return n===-1?i:i.substring(0,n)}function qr(t,e,i){var n;if(!t||!e||In(t)!==In(e))return!1;const s=En(e);if(s===void 0)return!0;const o=(n=En(t))!==null&&n!==void 0?n:i?.toLowerCase();return o===void 0||o===s}var Jt=2e3,Yr=100,Tn=.01;function Kr(){var t;return R(this,void 0,void 0,(function*(){if(typeof navigator>"u"||typeof((t=navigator.mediaDevices)===null||t===void 0?void 0:t.getUserMedia)!="function")return{report:{activeCapturePerformed:!1,captureError:"not_supported",captureErrorMessage:"getUserMedia is not available in this environment"},stream:void 0};try{return{report:{deviceAvailable:!0},stream:yield navigator.mediaDevices.getUserMedia({audio:!0})}}catch(e){const{captureError:i,captureErrorMessage:n}=(function(s){const o=s&&typeof s=="object"&&"name"in s?String(s.name):"",r=s instanceof Error?s.message:String(s);return o==="NotAllowedError"||o==="PermissionDeniedError"||o==="SecurityError"?{captureError:"permission_denied",captureErrorMessage:`Microphone permission denied: ${r}`}:o==="NotFoundError"||o==="DevicesNotFoundError"||o==="OverconstrainedError"||o==="ConstraintNotSatisfiedError"?{captureError:"no_device",captureErrorMessage:`No microphone device found: ${r}`}:o==="TypeError"?{captureError:"not_supported",captureErrorMessage:`Microphone capture is not supported: ${r}`}:{captureError:"unknown",captureErrorMessage:r}})(e);return{report:{activeCapturePerformed:!1,captureError:i,captureErrorMessage:n,deviceAvailable:!1},stream:void 0}}}))}function Jr(t,e,i){return R(this,void 0,void 0,(function*(){if(typeof AudioContext>"u")return null;let n,s,o;try{n=new AudioContext,s=n.createAnalyser(),o=n.createMediaStreamSource(t),s.fftSize=2048,o.connect(s);const r=new Float32Array(s.fftSize),a=Date.now()+e;let l=0,h=0,p=0;for(;Date.now()<a;){s.getFloatTimeDomainData(r);let f=0;for(const v of r)f+=v*v;const b=Math.sqrt(f/r.length);l=Math.max(l,b),h+=b,p+=1;const g=a-Date.now();g>0&&(yield new Promise((v=>setTimeout(v,Math.min(Yr,g)))))}return{audioLevel:l,audioDetected:l>=i,audioLevelStats:{peak:l,average:p>0?h/p:0,samples:p}}}catch{return null}finally{try{o?.disconnect(),s?.disconnect(),yield n?.close()}catch{}}}))}function zr(t,e){return R(this,void 0,void 0,(function*(){if(typeof MediaRecorder<"u")try{const i=["audio/webm;codecs=opus","audio/webm"].find((r=>
9typeof MediaRecorder.isTypeSupported!="function"||MediaRecorder.isTypeSupported(r))),n=i?new MediaRecorder(t,{mimeType:i}):new MediaRecorder(t),s=[],o=Date.now();return yield new Promise((r=>{let a=!1;const l=f=>{a||(a=!0,clearTimeout(h),clearTimeout(p),r(f))};n.ondataavailable=({data:f})=>{f.size>0&&s.push(f)},n.onerror=()=>l(),n.onstop=()=>R(this,void 0,void 0,(function*(){const f=n.mimeType||i||"audio/webm",b=yield(g=new Blob(s,{type:f}),new Promise((v=>{try{const y=new FileReader;y.onloadend=()=>v(typeof y.result=="string"?y.result:void 0),y.onerror=()=>v(void 0),y.readAsDataURL(g)}catch{v(void 0)}})));var g;l(b?{recordingDataUrl:b,recordingMimeType:f,recordingDurationMs:Date.now()-o}:void 0)}));const h=setTimeout((()=>{try{n.state!=="inactive"&&n.stop()}catch{l()}}),e),p=setTimeout((()=>l()),e+1e3);n.start()}))}catch{return}}))}function Rn(t){var e,i;return R(this,void 0,void 0,(function*(){const n=(function(g){var v,y;const S=g&&typeof g=="object"?g:void 0;return{sampleDurationMs:Math.max(0,(v=S?.sampleDurationMs)!==null&&v!==void 0?v:Jt),silenceThreshold:Math.min(1,Math.max(0,(y=S?.silenceThreshold)!==null&&y!==void 0?y:Tn)),record:S?.record===!0,warnOnRecording:S?.warnOnRecording}})(t.options.microphone),s=yield(function(){var g;return R(this,void 0,void 0,(function*(){if(typeof navigator>"u"||typeof((g=navigator.permissions)===null||g===void 0?void 0:g.query)!="function")return"unknown";try{return(yield navigator.permissions.query({name:"microphone"})).state}catch{return"unknown"}}))})(),{report:o,stream:r}=yield Kr(),a=yield(function(){var g;return R(this,void 0,void 0,(function*(){if(typeof navigator<"u"&&typeof((g=navigator.mediaDevices)===null||g===void 0?void 0:g.enumerateDevices)=="function")try{const v=(yield navigator.mediaDevices.enumerateDevices()).filter((({kind:y})=>y==="audioinput")).map((({deviceId:y,label:S})=>({deviceId:y||"",label:S||"",kind:"audioinput"})));return{devices:v,deviceCount:v.length,deviceAvailable:v.length>0,labelsAccessible:v.some((({label:y})=>y.length>0))}}catch{return}}))})(),l=r?"granted":o.captureError==="permission_denied"?"denied":s,h={currentPermissionState:l,isPermissionGrantedCurrently:l==="granted",isGetUserMediaFailed:!r,deviceAvailable:a?.deviceAvailable||o.deviceAvailable||!1,deviceCount:(e=a?.deviceCount)!==null&&e!==void 0?e:0,devices:(i=a?.devices)!==null&&i!==void 0?i:[],labelsAccessible:a?.labelsAccessible,captureError:o.captureError,captureErrorMessage:o.captureErrorMessage,activeCapturePerformed:o.activeCapturePerformed};if(r)try{const g=yield(function(v,y,S){var E,T,N;return R(this,void 0,void 0,(function*(){v.activeCapturePerformed=!0,v.recordingPerformed=S.record,S.record&&S.warnOnRecording&&S.warnOnRecording("To check your microphone, we will be recorded your voice for a few seconds and played back to you so you can hear how it sounds.");const[$,j]=yield Promise.all([Jr(y,(E=S.sampleDurationMs)!==null&&E!==void 0?E:Jt,(T=S.silenceThreshold)!==null&&T!==void 0?T:Tn),S.record?zr(y,(N=S.sampleDurationMs)!==null&&N!==void 0?N:Jt):Promise.resolve(void 0)]);return $&&(v.audioLevel=$.audioLevel,v.audioDetected=$.audioDetected,v.audioLevelStats=$.audioLevelStats),j&&(v.recordingDataUrl=j.recordingDataUrl,v.recordingMimeType=j.recordingMimeType,v.recordingDurationMs=j.recordingDurationMs,v.recordingPerformed=!0),j}))})(h,r,n);g&&(h.playbackPerformed=yield(p=g.recordingDataUrl,f=g.recordingDurationMs+5e3,typeof Audio>"u"?Promise.resolve(!1):new Promise((v=>{let y,S=!1;const E=setTimeout((()=>T(!1)),f),T=N=>{S||(S=!0,clearTimeout(E),y&&(y.onended=null,y.onerror=null,y.paused||y.pause(),y.src=""),v(N))};try{y=new Audio(p),y.onended=()=>T(!0),y.onerror=()=>T(!1),y.play().catch((()=>T(!1)))}catch{T(!1)}}))))}finally{try{r.getTracks().forEach((g=>g.stop()))}catch{}}var p,f;const b=(function(g){const v=[],y=(E,T)=>v.push({code:E,message:T,source:"microphone"});g.currentPermissionState==="denied"&&y("microphone_permission_denied","Microphone permission has been denied by the user."),g.deviceAvailable===!1&&y("microphone_no_device","No audio input device is available.");const S=g.captureError?{permission_denied:["microphone_capture_permission_denied","Active microphone capture was denied permission."],no_device:["microphone_capture_no_device","No microphone device was found for active capture."],not_supported:["microphone_capture_not_supported","Active microphone capture is not supported."],unknown:["microphone_capture_failed","A
9ctive microphone capture failed."]}[g.captureError]:void 0;return S&&y(...S),g.activeCapturePerformed&&g.audioDetected===!1&&y("microphone_silent","No audio was detected above the silence threshold during active capture."),v})(h);return b.length>0&&(h.reasons=b),Object.keys(h).length>0?h:void 0}))}var zt=300,Qt=500,Xt=30,Zt=100,ei=.02,ti=.05,wt=8e3;function we(t){if(typeof t=="number"&&!Number.isNaN(t)&&Number.isFinite(t))return t}function ii(t){const e=t.filter((o=>we(o)!==void 0));if(e.length===0)return;let i=1/0,n=-1/0,s=0;for(const o of e)o<i&&(i=o),o>n&&(n=o),s+=o;return{min:i,max:n,average:s/e.length}}function ni(t){var e,i;const n=[],s=new Set;t.forEach((r=>{const a=r;n.push(a),a.type==="transport"&&typeof a.selectedCandidatePairId=="string"&&s.add(a.selectedCandidatePairId)}));const o=n.filter((r=>r.type==="candidate-pair"));return(i=(e=o.find((r=>s.has(r.id))))!==null&&e!==void 0?e:o.find((r=>r.selected===!0||r.nominated===!0&&r.state==="succeeded")))!==null&&i!==void 0?i:o.find((r=>r.state==="succeeded"))}function We(t,e){let i=0,n=!1;for(const s of t){const o=we(s[e]);o!==void 0&&(i+=o,n=!0)}return n?i:void 0}function Ve(t,e,i=!1){const n=[];return t.forEach((s=>{const o=s;o.type!==e||i&&!(function(r){var a;const l=(a=r.kind)!==null&&a!==void 0?a:r.mediaType;return l===void 0||l==="audio"})(o)||n.push(o)})),n}function Qr(t,e){const i=t.packets===void 0?e.packets!==void 0:e.packets!==void 0&&e.packets>t.packets,n=t.bytes===void 0?e.bytes!==void 0:e.bytes!==void 0&&e.bytes>t.bytes;return i||n}function An(t,e){if(t!==void 0&&e!==void 0)return we(e-t)}function On(t,e){var i,n;if(!t.some((h=>Ve(h,`${e}-rtp`,!0).length>0)))return;const s=t.map((h=>(function(p,f){const b=Ve(p,`${f}-rtp`,!0);return f==="outbound"?{packets:We(b,"packetsSent"),bytes:We(b,"bytesSent")}:{packets:We(b,"packetsReceived"),bytes:We(b,"bytesReceived")}})(h,e))).filter((({packets:h,bytes:p})=>h!==void 0||p!==void 0)),o=(i=s[0])!==null&&i!==void 0?i:{},r=(n=s[s.length-1])!==null&&n!==void 0?n:{},a=An(o.packets,r.packets),l=An(o.bytes,r.bytes);return Object.assign(Object.assign(Object.assign(Object.assign({flowing:s.length>1&&Qr(o,r)},r.packets!==void 0?{packets:r.packets}:{}),r.bytes!==void 0?{bytes:r.bytes}:{}),a!==void 0?{packetsDelta:a}:{}),l!==void 0?{bytesDelta:l}:{})}function Dn(t,e){const i=[];for(const n of t)for(const s of Ve(n,e,!0)){const o=we(s.jitter);if(o!==void 0){const r=1e3*o;r>=0&&i.push(r)}}return i}function xn(t){const e=We(t,"packetsReceived"),i=We(t,"packetsLost"),n=t.map((r=>we(r.fractionLost))).filter((r=>r!==void 0&&r>=0&&r<=1)),s=n.length>0?Math.max(...n):void 0,o=e!==void 0&&i!==void 0?e+i:void 0;return{packetsReceived:e,packetsLost:i,packetLossFraction:s??(i!==void 0&&o!==void 0&&o>0?i/o:void 0)}}function Nn(t){let e;return t.forEach((i=>{e===void 0&&(e=we(i.timestamp))})),e}function Xr(t){if(t.statsSamples.length===0)return{quality:"unknown",reasons:[]};const e=t.statsSamples,i=On(e,"inbound"),n=On(e,"outbound"),s=ii((function(g){var v;const y=[];for(const S of g){let E=!1;const T=Ve(S,"remote-inbound-rtp",!0);for(const N of T){const $=we(N.roundTripTime);if($!==void 0){const j=1e3*$;j>=0&&(y.push(j),E=!0)}}if(!E){const N=we((v=ni(S))===null||v===void 0?void 0:v.currentRoundTripTime);if(N!==void 0){const $=1e3*N;$>=0&&y.push($)}}}return y})(e)),o=(r=ii(Dn(e,"inbound-rtp")),a=ii(Dn(e,"remote-inbound-rtp")),r?.average===void 0?a:a?.average===void 0?r:a.average>r.average?a:r);var r,a;const l=(function(g,v,y){var S;if(g.length===0)return;const E=g[g.length-1],T=Ve(E,"inbound-rtp",!0),N=Ve(E,"remote-inbound-rtp",!0),$=(function(u,m){return u.packetLossFraction===void 0?m:m.packetLossFraction===void 0?u:m.packetLossFraction>u.packetLossFraction?m:u})(xn(T),xn(N));let j=y?.packets,q=(S=$.packetsReceived)!==null&&S!==void 0?S:v?.packets;const Y=$.packetsLost,M=$.packetLossFraction,c=ni(E);return j===void 0&&(j=we(c?.packetsSent)),q===void 0&&(q=we(c?.packetsReceived)),j!==void 0||q!==void 0||Y!==void 0?{packetsSent:j,packetsReceived:q,packetsLost:Y,packetLossFraction:M}:void 0})(e,i,n),h=(function(g,v,y){if(g.length===0)return;const S=g[g.length-1];let E=y?.bytes,T=v?.bytes;const N=ni(S);return E===void 0&&(E=we(N?.bytesSent)),T===void 0&&(T=we(N?.bytesReceived)),E!==void 0||T!==void 0?{bytesSent:E,bytesReceived:T}:void 0})(e,i,n),p=(function(g,v,y){if(g.length<2)return;const S=g[0],E=g[g.length-1],T=Nn(S),N=Nn(E);if(T===void 0||N===void 0)return;const $=(N-T)/1e3;if($<=0)return;const j=y?.bytesDelta!==void 0&&y.bytesDelta>=0?8*y.bytesDelta/$:void 0,q=v?.bytesDelta!==void 0&&v.bytesDelta>=0?8*v.bytesDelta/$:void 0;return j!==void 0||q!==void 0?{outbound:j,inbound:q}:void 0})(e,i,n),f=(function(g,v,y){let S=!1,E="good";return g?.average!==void 0&&(S=!0,g.average>=Qt?E="poor":g.average>=zt&&E==="good"&&(E="fair")),v?.average!==void 0&&(S=!0,v.average>=Zt?E="poor":v.average>=Xt&&E==="good"&&(E="fair")),y?.packetLossFraction!==void 0&&(S=!0,y.packetLossFraction>=ti?E="poor":y.packetLossFraction>=ei&&E==="good"&&(E="fair")),S?E:"unknown"})(s,o,l),b=(function(g,v,y,S){const E=[];return g?.average!==void 0&&(g.average>=Qt?E.push({code:"network_high_rtt",message:`Average RTT is ${Math.round(g.average)}ms (poor: ≥${Qt}ms threshold)`,source:"network"}):g.average>=zt&&E.push({code:"network_high_rtt",message:`Average RTT is ${Math.round(g.average)}ms (degraded: ≥${zt}ms threshold)`,source:"network"})),v?.average!==void 0&&(v.average>=Zt?E.push({code:"network_high_jitter",message:`Average jitter is ${Math.round(v.average)}ms (poor: ≥${Zt}ms threshold)`,source:"network"}):v.average>=Xt&&E.push({code:"network_high_jitter",message:`Average jitter is ${Math.round(v.average)}ms (degraded: ≥${Xt}ms threshold)`,source:"network"})),y?.packetLossFraction!==void 0&&(y.packetLossFraction>=ti?E.push({code:"network_packet_loss",message:`Packet loss is ${(100*y.packetLossFraction).toFixed(1)}% (poor: ≥${100*ti}% threshold)`,source:"network"}):y.packetLossFraction>=ei&&E.push({code:"network_packet_loss",message:`Packet loss is ${(100*y.packetLossFraction).toFixed(1)}% (degraded: ≥${100*ei}% threshold)`,source:"network"})),S&&(S.outbound!==void 0&&S.outbound<wt&&E.push({code:"network_low_bitrate",message:`Outbound audio bitrate is ${Math.round(S.outbound)} bps (<${wt} bps threshold)`,source:"network"}),S.inbound!==void 0&&S.inbound<wt&&E.push({code:"network_low_bitrate",message:`Inbound audio bitrate is ${Math.round(S.inbound)} bps (<${wt} bps threshold)`,source:"network"})),E})(s,o,l,t.options.mode==="network-only"?void 0:p);return{quality:f,rtt:s,jitter:o,packets:l,bytes:h,bitrate:p,inbound:i,outbound:n,reasons:b.length>0?b:void 0}}function Ln(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function si(t,e){return t.find((i=>i.label===e))}var Zr=class{constructor(){this.startedAtMonoMs=Mn()}build(t={}){var e,i;const n={};try{const s=(i=(e=t.call)===null||e===void 0?void 0:e.getEstablishmentTimings)===null||i===void 0?void 0:i.call(e);
9if(s){n.callEstablishment={mode:s.mode,direction:s.direction,steps:s.steps.map((p=>Object.assign({},p)))};const o=si(s.steps,"ICE candidate gathering started"),r=si(s.steps,"All ICE candidates gathered"),a=Ln(o&&r?r.fromStart-o.fromStart:void 0);a!==void 0&&(n.iceGatheringMs=a);const l=si(s.steps,"First server-reflexive/relay candidate found"),h=Ln(o&&l?l.fromStart-o.fromStart:void 0);h!==void 0&&(n.firstNonHostCandidateMs=h)}}catch{}return n}complete(t){const e=Mn()-this.startedAtMonoMs;Number.isFinite(e)&&e>=0&&(t.totalMs=e)}};function Mn(){try{if(typeof performance<"u"&&typeof performance.now=="function")return performance.now()}catch{}return Date.now()}function oi(){return new Zr}var Ae={NoCandidates:"ice_no_candidates",OnlyHostCandidates:"ice_only_host_candidates",GatheringTimeout:"ice_gathering_timeout",NoSelectedPair:"ice_no_selected_pair",TurnRequired:"ice_turn_required",OnlyRelayCandidates:"ice_only_relay_candidates",ServerNoCandidates:"ice_server_no_candidates",StrictNetwork:"ice_strict_network",MultipleInterfaces:"ice_multiple_interfaces",VpnDetected:"ice_vpn_detected"},Xe={HighJitter:"network_high_jitter",HighRtt:"network_high_rtt",PacketLoss:"network_packet_loss",LowBitrate:"network_low_bitrate",HighPacketLoss:"network_high_packet_loss",PoorQuality:"network_poor_quality",FairQuality:"network_fair_quality",NoAudioFlow:"network_no_audio_flow",OneWayAudio:"network_one_way_audio"},ri={PermissionDenied:"microphone_permission_denied",NoDevice:"microphone_no_device",CapturePermissionDenied:"microphone_capture_permission_denied",CaptureNoDevice:"microphone_capture_no_device",CaptureNotSupported:"microphone_capture_not_supported",CaptureFailed:"microphone_capture_failed",Silent:"microphone_silent",SilenceDetected:"microphone_silence_detected"},Pe=()=>({reasons:[],warnings:[]}),Pn={inconclusive:0,ready:1,degraded:2,blocked:3,permission_denied:4};function ve(t,e){return t?e?Pn[t]>=Pn[e]?t:e:t:e}function ye(t,e,i){return{code:t,message:e,source:i}}function et(t,e,i){return{code:t,message:e,source:i}}function Fn(t,e=!1){var i;if(!t)return Pe();const n=Pe(),{reasons:s,warnings:o}=n,r=t.candidates.length>0;r||(s.push(ye(Ae.NoCandidates,"No ICE candidates were gathered.","ice")),n.verdict="inconclusive"),r&&t.onlyHostCandidates&&(t.hasSelectedPair?o.push(et(Ae.OnlyHostCandidates,"Only host ICE candidates were found. Connectivity succeeded, but NAT traversal may not be possible.","ice")):(s.push(ye(Ae.OnlyHostCandidates,"Only host ICE candidates were found. NAT traversal may not be possible.","ice")),n.verdict=ve(n.verdict,"degraded"))),t.isTurnRequired&&!e&&(s.push(ye(Ae.TurnRequired,"The selected ICE candidate pair requires a TURN relay.","ice")),n.verdict=ve(n.verdict,"degraded"));const a=t.iceConnectionState!==void 0&&t.iceConnectionState!=="new";r&&!t.hasSelectedPair&&a&&(s.push(ye(Ae.NoSelectedPair,"No ICE candidate pair was selected. Connectivity failed.","ice")),n.verdict=ve(n.verdict,"blocked")),t.candidateGatheringCompleted===!1&&(s.push(ye(Ae.GatheringTimeout,"ICE gathering did not complete within the timeout.","ice")),n.verdict=ve(n.verdict,"degraded"));const l=((i=t.serverCandidateComparison)!==null&&i!==void 0?i:[]).filter((({hasCandidates:h})=>!h));return l.length>0&&o.push(et(Ae.ServerNoCandidates,`${l.length} configured ICE server${l.length===1?"":"s"} produced no candidates.`,"ice")),t.hasMultipleNetworkInterfaces&&o.push(et(Ae.MultipleInterfaces,"Multiple network interfaces were detected on the host.","ice")),t.vpnDetected&&o.push(et(Ae.VpnDetected,"A VPN appears to be active and may affect media routing.","ice")),!n.verdict&&r&&(n.verdict="ready"),n}function ea(t){if(t.established&&!t.error)return Pe();const e=Array.isArray(t.server.urls)?t.server.urls.join(", "):t.server.urls;return{verdict:"degraded",reasons:[ye("ice_server_failed",t.error?`ICE server [${e}] failed: ${t.error}`:`ICE server [${e}] did not establish a diagnostic call.`,"ice")],warnings:[]}}function Un(t,e=!0){var i;if(!t)return Pe();const n=Pe(),{reasons:s,warnings:o}=n,r=e?t.reasons:(i=t.reasons)===null||i===void 0?void 0:i.filter((({code:l})=>l!==Xe.LowBitrate));switch(r!=null&&r.length&&(s.push(...r),n.verdict="degraded"),t.quality){case"poor":s.push(ye(Xe.PoorQuality,"Network quality is poor.","network")),n.verdict=ve(n.verdict,"blocked");break;case"fair":o.push(et(Xe.FairQuality,"Network quality is fair.","network")),n.verdict=ve(n.verdict,"degraded");break;case"good":n.verdict=ve(n.verdict,"ready")}const a=[t.inbound,t.outbound].filter((l=>!!l));if(e&&a.length>0){const l=a.filter((({flowing:h})=>h)).length;a.length===2&&l===2?n.verdict=ve(n.verdict,"ready"):l>0?(s.push(ye(Xe.OneWayAudio,"Audio RTP is flowing in only one direction.","network")),n.verdict=ve(n.verdict,"blocked")):(s.push(ye(Xe.NoAudioFlow,"No inbound or outbound audio RTP is flowing.","network")),n.verdict=ve(n.verdict,"blocked"))}return n}function ta(t){var e;if(!t)return Pe();const i=Pe();(e=t.reasons)!==null&&e!==void 0&&e.length&&i.reasons.push(...t.reasons);const n=t.currentPermissionState==="denied"||t.isPermissionGrantedCurrently===!1||t.captureError==="permission_denied",s=t.deviceAvailable===!1||t.captureError!==void 0,o=t.activeCapturePerformed===!0&&t.audioDetected===!1;return n?i.verdict="permission_denied":s?i.verdict="blocked":o?i.verdict="degraded":(t.activeCapturePerformed===!0&&t.audioDetected===!0||t.activeCapturePerformed!==!0&&t.isPermissionGrantedCurrently===!0&&t.deviceAvailable!==!1)&&(i.verdict="ready"),i}var ai=class{constructor(t){this.options=t}run(){return R(this,void 0,void 0,(function*(){switch(this.options.mode){case"network-only":return this.runNetworkOnly();case"microphone-only":return this.runMicrophoneOnly(kn(this.options));
9default:return this.runFull()}}))}runFull(){return R(this,void 0,void 0,(function*(){const t=yield this.runTest({diagnosticOptions:this.options,modules:{ice:!!this.options.ice,network:!!this.options.network,microphone:!!this.options.microphone},autoHangup:this.options.autoHangup!==!1});return t.setupFailed?t.error?Ue({callId:t.callId,timings:t.timings},t.error):{version:1,verdict:"inconclusive",reasons:[{code:"call_setup_timeout",message:"The diagnostic call did not reach the established state",source:"diagnostic"}],callId:t.callId,timings:t.timings}:Ue({ice:t.ice,network:t.network,microphone:t.microphone,timings:t.timings,callId:t.callId,raw:t.raw},t.error)}))}runNetworkOnly(){var t,e,i;return R(this,void 0,void 0,(function*(){const n=this.options.client.iceServers,s=(function(l){const h=[];for(const p of l)(Array.isArray(p.urls)?p.urls:[p.urls]).forEach((f=>{h.push(Object.assign(Object.assign({},p),{urls:f}))}));return h})((i=(e=(t=this.options.rtcConfig)===null||t===void 0?void 0:t.iceServers)!==null&&e!==void 0?e:n)!==null&&i!==void 0?i:[]);let o=[];const r=oi();let a;try{return o=yield Promise.all(s.map((l=>R(this,void 0,void 0,(function*(){const h=yield this.runTest({diagnosticOptions:Object.assign(Object.assign({},this.options),{durationMs:3e3,statsSampleIntervalMs:500,rtcConfig:Object.assign(Object.assign({},this.options.rtcConfig),{iceServers:[l]})}),iceServers:[l],forceRelayCandidate:ks(l),modules:{ice:!0,network:!!this.options.network,microphone:!1},autoHangup:!0}),p=(function(f){if(f.error)return f.error.message;if(f.setupFailed)return"The diagnostic call did not reach the established state";if(!f.ice)return"No ICE report was produced";if(f.ice.candidates.length===0)return"No ICE candidates were gathered";if(!f.ice.hasSelectedPair)return"No ICE candidate pair was selected"})(h);return{server:l,established:p===void 0,callId:h.callId,ice:h.ice,network:h.network,timings:h.timings,error:p}}))))),a=Ue({serverTests:o,timings:r.build()},void 0,{networkOnly:!0}),a}catch(l){return a=Ue({timings:r.build()},kt(l),{networkOnly:!0}),a}finally{a!=null&&a.timings&&r.complete(a.timings)}}))}runTest(t){return R(this,void 0,void 0,(function*(){const e=kn(t.diagnosticOptions),i=oi();let n,s,o,r=!1;const a=l=>{l.callId===n?.id&&(s=kt(l.error))};t.diagnosticOptions.client.on("telnyx.error",a);try{if(n=this.createDiagnosticCall(t.diagnosticOptions,t.iceServers,t.forceRelayCandidate),e.call=n,r=yield this.waitForCallEstablishment(n),!r)return o={established:!1,setupFailed:!0,callId:n.id,timings:i.build({call:n}),error:s},o;yield this.collectSamples(n,e);const l=t.modules.ice?Vr(e):void 0,h=t.modules.network?Xr(e):void 0,p=t.modules.microphone?yield Rn(e):void 0;return o={established:!0,setupFailed:!1,callId:n.id,ice:l,network:h,microphone:p,timings:i.build({call:n}),raw:{samples:e.statsSamples.length?e.statsSamples:void 0}},o}catch(l){return e.error=kt(l),o={established:r,setupFailed:!1,callId:n?.id,timings:i.build({call:n}),error:e.error},o}finally{if(t.diagnosticOptions.client.off("telnyx.error",a),n&&t.autoHangup)try{yield n.hangup()}catch{}o!=null&&o.timings&&i.complete(o.timings)}}))}runMicrophoneOnly(t){return R(this,void 0,void 0,(function*(){const e=oi();let i;try{return i=Ue({microphone:this.options.microphone?yield Rn(t):void 0,timings:e.build()},t.error),i}catch(n){return t.error=kt(n),i=Ue({timings:e.build()},t.error),i}finally{i!=null&&i.timings&&e.complete(i.timings)}}))}waitForCallEstablishment(t){return R(this,void 0,void 0,(function*(){const e=Date.now()+3e4,i=()=>{var n,s;return t.state==="active"&&((s=(n=t.peer)===null||n===void 0?void 0:n.instance)===null||s===void 0?void 0:s.connectionState)==="connected"};for(;Date.now()<e;){if(i())return!0;if(["done","hangup","destroy"].includes(t.state))return!1;yield $n(500)}return i()}))}createDiagnosticCall(t,e,i=!1){const{client:n,destinationNumber:s,callerName:o,callerNumber:r,audio:a,debug:l,rtcConfig:h}=t;return n.newCall({destinationNumber:s,callerName:o,callerNumber:r,audio:a,debug:l===!0,iceServers:e??h?.iceServers,forceRelayCandidate:i})}collectSamples(t,e){var i,n,s;return R(this,void 0,void 0,(function*(){const o=(i=e.options.durationMs)!==null&&i!==void 0?i:5e3,r=(n=e.options.statsSampleIntervalMs)!==null&&n!==void 0?n:1e3,a=Date.now()+o;for(;Date.now()<a;){try{const l=yield(s=t.peer.instance)===null||s===void 0?void 0:s.getStats();l&&e.statsSamples.push(l)}catch{}yield $n(Math.min(r,Math.max(0,a-Date.now())))}}))}};function Ue(t,e,i){const{verdict:n,reasons:s,warnings:o}=(function(r,a,l={}){var h,p;const f=[Fn(r.ice),Un(r.network),ta(r.microphone),...((h=r.serverTests)!==null&&h!==void 0?h:[]).flatMap((y=>[Fn(y.ice,l.networkOnly&&ks(y.server)),Un(y.network,!l.networkOnly),ea(y)]))],b=f.flatMap((y=>y.reasons)),g=f.flatMap((y=>
9y.warnings));let v=f.reduce(((y,S)=>ve(y,S.verdict)),void 0);if(l.networkOnly&&(!((p=r.serverTests)===null||p===void 0)&&p.length)){const y=r.serverTests.filter((S=>S.established&&!S.error)).length;y===0?v="blocked":y<r.serverTests.length&&(v="degraded")}if(a)switch(a.code){case Qn:b.push(ye(ri.CapturePermissionDenied,"Microphone access was denied while establishing the diagnostic call.","microphone")),v=ve(v,"permission_denied");break;case Xn:b.push(ye(ri.CaptureNoDevice,"No microphone device was available while establishing the diagnostic call.","microphone")),v=ve(v,"blocked");break;case wi:b.push(ye(ri.CaptureFailed,"Microphone capture failed while establishing the diagnostic call.","microphone")),v=ve(v,"blocked");break;default:b.push(ye("diagnostic_run_error",`Diagnostic run encountered an error: ${a.message}`,"diagnostic")),v=ve(v,"blocked")}return{verdict:v??"inconclusive",reasons:b,warnings:g}})(t,e,i);return Object.assign(Object.assign({},t),{version:1,verdict:n??"inconclusive",reasons:s.length?s:void 0,warnings:o.length?o:void 0})}function kt(t){return t instanceof Error?t:new Error(String(t))}function $n(t){return new Promise((e=>setTimeout(e,t)))}var jn="+1-872-231-5806",ia=class extends Gr{constructor(t){super(t),d.info(`SDK version: ${vs}`)}newCall(t){return super.newCall(t)}runPreCall(t={}){var e,i;return R(this,void 0,void 0,(function*(){const n={client:this,destinationNumber:(e=t.destinationNumber)!==null&&e!==void 0?e:jn,durationMs:t.durationMs,ice:!0,network:!0,microphone:!0,mode:"full",rtcConfig:{iceServers:(i=t.iceServers)!==null&&i!==void 0?i:this.iceServers}};return new ai(n).run()}))}runNetworkCheck(t={}){var e;return R(this,void 0,void 0,(function*(){const i={client:this,destinationNumber:jn,ice:!0,network:!0,microphone:!1,mode:"network-only",rtcConfig:{iceServers:(e=t.iceServers)!==null&&e!==void 0?e:this.iceServers}};return new ai(i).run()}))}runMicrophoneCheck(t={}){var e;return R(this,void 0,void 0,(function*(){const i={client:this,ice:!1,network:!1,microphone:{sampleDurationMs:t.durationMs,silenceThreshold:t.silenceThreshold,record:(e=t.record)!==null&&e!==void 0&&e,warnOnRecording:t.warnOnRecording},mode:"microphone-only"};return new ai(i).run()}))}static webRTCInfo(){return Or()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:oe.full},{browserName:"Firefox",features:["audio"],supported:oe.partial},{browserName:"Safari",supported:oe.not_supported},{browserName:"Edge",supported:oe.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:oe.not_supported},{browserName:"Firefox",supported:oe.not_supported},{browserName:"Safari",features:["video","audio"],supported:oe.full},{browserName:"Edge",supported:oe.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:oe.full},{browserName:"Firefox",features:["audio"],supported:oe.partial},{browserName:"Safari",supported:oe.not_supported},{browserName:"Edge",supported:oe.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:oe.full},{browserName:"Firefox",features:["audio"],supported:oe.partial},{browserName:"Safari",features:["video","audio"],supported:oe.full},{browserName:"Edge",features:["audio"],supported:oe.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:oe.full},{browserName:"Firefox",features:["audio"],supported:oe.partial},{browserName:"Safari",supported:oe.not_supported},{browserName:"Edge",features:["audio"],supported:oe.partial}]}]}};async function at(t,e={}){const i=await Qs({functionName:"live-translate",body:t,keepalive:e.keepalive});if(i&&typeof i=="object"&&"error"in i)throw new Error(i.error.message);return i}var na=async()=>(await at({action:"lines"})).lines,sa=t=>at({action:"seat",lineId:t}),oa=t=>at({action:"translation",language:t}),ra=async t=>(await at({action:"handoff",...t})).handoff,Bn=(t,e,i={})=>at({action:"seat_client",lineId:t,registered:e},i);Je(),Ci();var aa="x-vox-handoff";function la(t){const e=t.options.customHeaders;if(!Array.isArray(e))return null;const i=e.find(n=>typeof n?.name=="string"&&n.name.toLowerCase()===aa);return typeof i?.value=="string"&&i.value?i.value:null}var ca=new Set(["hangup","destroy","purge"]),Hn=new Set(["active","held"]);function da(){const t=ie({}),e=ie(null),i=ie(null),n=ie([]),s=li(null),o=li(null),r=new Map;let a=null,l=null,h=null,p=null;function f(I,x){t.value={...t.value,[I]:x}}function b(I){const{[I]:x,...K}=t.value;t.value=K}function g(I,x,K){const z=Hn.has(x.state);return{id:x.id,lineId:I,state:x.state,remoteNumber:x.options.remoteCallerNumber||null,muted:x.isAudioMuted,held:x.state==="held",connectedAt:K?.connectedAt??(z?Date.now():null),handoffId:K?.handoffId??la(x)}}function v(){const I=a;if(!I){h=null,s.value=null,o.value=null,p&&(p.muted=!1);return}const x=h!==I.sdk.id;if(!Hn.has(I.sdk.state)||!I.sdk.remoteStream){x&&(h=null,s.value=null,o.value=null);return}h=I.sdk.id,s.value=I.sdk.remoteStream,x&&p&&(p.srcObject=I.sdk.remoteStream),(x||!o.value)&&(o.value=I.sdk.localStream?.getAudioTracks()[0]??null)}function y(I){const x={id:I.id,lineId:I.lineId,remoteNumber:I.remoteNumber,answered:I.connectedAt!==null,durationSeconds:I.c
9onnectedAt?Math.max(0,Math.floor((Date.now()-I.connectedAt)/1e3)):0,endedAt:Date.now()};n.value=[...n.value,x]}function S(I){if(l?.sdk.id===I){l=null,i.value&&y(i.value),i.value=null;return}a?.sdk.id===I&&(e.value&&y(e.value),a=l,e.value=i.value,l=null,i.value=null,v())}function E(I,x){if(ca.has(x.state)){S(x.id);return}if(a?.sdk.id===x.id){a={sdk:x,lineId:I},e.value=g(I,x,e.value),v();return}if(l?.sdk.id===x.id){l={sdk:x,lineId:I},i.value=g(I,x,i.value);return}if(!a){a={sdk:x,lineId:I},e.value=g(I,x,null),v();return}if(!l){l={sdk:x,lineId:I},i.value=g(I,x,null);return}x.hangup()}async function T(I){const x=r.get(I);r.delete(I);const K=[a,l].filter(z=>z?.lineId===I);for(const z of K)S(z.sdk.id);for(const z of K)try{await z.sdk.hangup()}catch{}if(x){x.client.off("telnyx.ready",x.onReady),x.client.off("telnyx.error",x.onError),x.client.off("telnyx.socket.close",x.onSocketClose),x.client.off("telnyx.notification",x.onNotification);try{await x.client.disconnect()}catch{}}}async function N(I,x){I in t.value&&(f(I,{status:"error",error:x}),await T(I))}async function $(I){f(I.id,{status:"connecting",error:null});try{const x=await sa(I.id);if(!(I.id in t.value))return;const K=new ia({login:x.login,password:x.password}),z={client:K,onReady:()=>f(I.id,{status:"ready",error:null}),onError:ne=>{ne.recoverable?f(I.id,{status:t.value[I.id]?.status??"connecting",error:ne.error.message}):N(I.id,ne.error.message||"Phone connection error")},onSocketClose:()=>{N(I.id,"Phone connection closed")},onNotification:ne=>{ne.type==="callUpdate"&&ne.call&&E(I.id,ne.call)}};r.set(I.id,z),p&&(K.remoteElement=p),K.on("telnyx.ready",z.onReady),K.on("telnyx.error",z.onError),K.on("telnyx.socket.close",z.onSocketClose),K.on("telnyx.notification",z.onNotification),await K.connect()}catch(x){await N(I.id,x instanceof Error?x.message:"Could not connect the phone")}}async function j(I,x){p=x,await Promise.all(I.filter(K=>!r.has(K.id)).map(K=>$(K)))}async function q(I){b(I),await T(I)}async function Y(){await Promise.all(Object.keys(t.value).map(I=>q(I)))}async function M(){await a?.sdk.answer({video:!1,remoteElement:p??void 0})}async function c(){await a?.sdk.hangup()}function u(){!a||!e.value||(a.sdk.toggleAudioMute(),e.value=g(a.lineId,a.sdk,e.value))}async function m(){a&&await a.sdk.toggleHold()}function C(I){return!a||!e.value?.connectedAt||e.value.held?!1:(a.sdk.dtmf(I),!0)}function k(I,x){a?.sdk.id!==I||l?.sdk.id!==x||([a,l]=[l,a],[e.value,i.value]=[i.value,e.value],v())}async function O(I){try{await I.sdk.unhold()}catch{}}async function A(){const I=a,x=l;if(!I||!x)return;let K=!1;I.sdk.state==="active"&&(await I.sdk.hold(),K=!0);try{x.sdk.state==="held"&&await x.sdk.unhold()}catch(z){throw K&&await O(I),z}k(I.sdk.id,x.sdk.id)}async function P(){const I=l;if(!I)return;const x=a;let K=!1;x?.sdk.state==="active"&&(await x.sdk.hold(),K=!0);try{await I.sdk.answer({video:!1,remoteElement:p??void 0})}catch(z){throw K&&x&&await O(x),z}if(l?.sdk.id!==I.sdk.id){K&&x&&a?.sdk.id===x.sdk.id&&await O(x);return}if(!x){a=l,l=null,e.value=i.value,i.value=null,v();return}k(x.sdk.id,I.sdk.id)}async function W(){await l?.sdk.hangup()}async function ee(I){const x=a?.sdk.peer?.instance.getSenders().find(z=>z.track?.kind==="audio"),K=I??o.value;x&&K&&x.track!==K&&await x.replaceTrack(K)}function te(I){p&&(p.muted=I)}return At(()=>{Y()}),{lines:t,call:e,other:i,ended:n,remoteStream:s,microphoneTrack:o,connect:j,disconnectLine:q,disconnect:Y,answer:M,hangup:c,toggleMute:u,toggleHold:m,sendDigit:C,swap:A,answerOther:P,hangupOther:W,setOutboundAudio:ee,setCallerAudioMuted:te}}Je();Yn();var ua={class:"grid grid-cols-3 gap-2",role:"group","aria-label":"Keypad"},ha=["aria-label","onClick"],pa={class:"text-sm font-semibold text-gray-900 dark:text-white tabular-nums"},ga={key:0,class:"text-[11px] tracking-wider text-gray-500 dark:text-gray-400"},va=qn({__name:"DialKeypad",emits:["digit"],setup(t,{emit:e}){const i=[{digit:"1",letters:""},{digit:"2",letters:"ABC"},{digit:"3",letters:"DEF"},{digit:"4",letters:"GHI"},{digit:"5",letters:"JKL"},{digit:"6",letters:"MNO"},{digit:"7",letters:"PQRS"},{digit:"8",letters:"TUV"},{digit:"9",letters:"WXYZ"},{digit:"*",letters:""},{digit:"0",letters:"+"},{digit:"#",letters:""}],n=e;return(s,o)=>(H(),G("div",ua,[(H(),G(xe,null,$e(i,r=>L("button",{key:r.digit,type:"button",class:"flex flex-col items-center justify-center rounded-md border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-800 py-2 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-primary-500","aria-label":r.letters?`${r.digit} ${r.letters}`:r.digit,onClick:a=>n("digit",r.digit)},[L("span",pa,J(r.digit),1),r.letters?(H(),G("span",ga,J(r.letters),1)):se("",!0)],8,ha)),64))]))}}),fa=va;function Wn(t,e,i,n){if(!i)return t;const s=t[t.length-1];if(!s||n-s.updatedAt>1500){const o={id:(s?.id??0)+1,original:"",translated:"",startedAt:n,updatedAt:n};
9return o[e]=i.trimStart(),[...t,o]}return[...t.slice(0,-1),{...s,[e]:s[e]+i,updatedAt:n}]}Je(),Ci();var ma="https://api.openai.com/v1/realtime/translations/calls";function Gn(){const t=ie("idle"),e=ie(null),i=ie([]),n=li(null),s=ie(!1);let o=null,r=null,a=0;function l(g){const v=JSON.parse(g.data);v.type==="session.input_transcript.delta"&&v.delta?i.value=Wn(i.value,"original",v.delta,Date.now()):v.type==="session.output_transcript.delta"&&v.delta&&!s.value?i.value=Wn(i.value,"translated",v.delta,Date.now()):v.type==="error"&&(e.value=v.error?.message??"Translation error")}async function h(g,v,y={}){f();const S=a;s.value=y.captionsOnly===!0,t.value="starting",e.value=null;try{const{clientSecret:E}=await oa(v);if(S!==a)return;const T=new RTCPeerConnection;o=T,T.addTrack(g,new MediaStream([g])),T.ontrack=q=>{o===T&&q.track.kind==="audio"&&!s.value&&(n.value=q.track)},T.onconnectionstatechange=()=>{o===T&&(T.connectionState==="connected"&&(t.value="live"),(T.connectionState==="failed"||T.connectionState==="closed")&&p("Translation connection failed"))};const N=T.createDataChannel("oai-events");r=N,N.onmessage=l,N.onclose=()=>{o===T&&p("Translation session ended")};const $=await T.createOffer();await T.setLocalDescription($);const j=await fetch(ma,{method:"POST",body:$.sdp,headers:{Authorization:`Bearer ${E}`,"Content-Type":"application/sdp"}});if(!j.ok)throw new Error(`Translation session was refused (${j.status})`);if(S!==a)return;await T.setRemoteDescription({type:"answer",sdp:await j.text()})}catch(E){if(S!==a)return;p(E instanceof Error?E.message:"Could not start translation")}}function p(g){f(),t.value="error",e.value=g}function f(){a++,r?.readyState==="open"&&r.send(JSON.stringify({type:"session.close"})),r=null,o?.close(),o=null,n.value=null,s.value=!1,t.value="idle"}function b(){i.value=[]}return At(f),{status:t,error:e,segments:i,outputTrack:n,captionsOnly:s,start:h,stop:f,clear:b}}Je();Ci(),Yn(),Ys();var _a={class:"container px-4 py-3"},ya={class:"space-y-4"},ba={class:"flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4"},Sa={class:"flex flex-wrap items-end gap-3"},Ca=["value"],wa=["value"],ka={class:"flex items-center gap-2 py-2 text-xs font-medium text-gray-700 dark:text-gray-300"},Ia={class:"grid grid-cols-1 lg:grid-cols-3 gap-4"},Ea={class:"space-y-4"},Ta={class:"card-base overflow-hidden","aria-labelledby":"call-heading"},Ra={class:"sr-only","aria-live":"assertive"},Aa={key:0,class:"bg-amber-50 dark:bg-amber-900/20 border-b border-amber-200 dark:border-amber-800/60 px-6 py-5"},Oa={class:"flex items-center gap-4"},Da={class:"relative flex h-11 w-11 shrink-0"},xa={class:"relative flex h-11 w-11 items-center justify-center rounded-full bg-amber-500 text-white"},Na={class:"min-w-0"},La=["href"],Ma={key:1,class:"text-xl font-bold text-gray-900 dark:text-white tabular-nums truncate"},Pa={key:2,class:"text-xs text-amber-900 dark:text-amber-200 tabular-nums truncate"},Fa={key:3,class:"text-xs text-amber-900 dark:text-amber-200 truncate"},Ua={class:"text-xs text-amber-800/80 dark:text-amber-300/80 truncate"},$a={class:"mt-4 grid grid-cols-2 gap-2"},ja={key:1,class:"bg-green-50 dark:bg-green-900/20 border-b border-green-200 dark:border-green-800/60 px-6 py-5"},Ba={class:"flex items-start justify-between gap-4"},Ha={class:"min-w-0"},Wa={class:"flex items-center gap-1.5 text-sm font-semibold text-green-800 dark:text-green-300"},Ga=["href"],Va={key:1,class:"text-xl font-bold text-gray-900 dark:text-white tabular-nums truncate"},qa={key:2,class:"text-xs text-green-900 dark:text-green-200 tabular-nums truncate"},Ya={key:3,class:"text-xs text-green-900 dark:text-green-200 truncate"},Ka={class:"text-xs text-green-900/70 dark:text-green-300/70 truncate"},Ja={key:0,class:"text-xl font-bold text-green-800 dark:text-green-300 tabular-nums"},za={class:"mt-4 grid grid-cols-2 gap-2"},Qa=["aria-pressed"],Xa=["aria-pressed","disabled"],Za=["aria-pressed","disabled"],el={key:0,class:"mt-3 text-sm font-medium text-amber-900 dark:text-amber-200"},tl={key:1,class:"mt-3 text-sm font-medium text-green-900 dark:text-green-200"},il={key:2,class:"mt-4 space-y-2"},nl={class:"text-[11px] font-medium text-green-900/70 dark:text-green-300/70"},sl={class:"tabular-nums"},ol={key:2,class:"bg-gray-100 dark:bg-gray-700/50 border-b border-gray-200 dark:border-gray-700 px-6 py-5"},rl={class:"flex items-center gap-4"},al={class:"flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-gray-600 dark:bg-gray-500 text-white"},ll={class:"min-w-0 flex-1"},cl={class:"text-sm font-semibold text-gray-900 dark:text-white"},dl=["href"],ul={key:1,class:"text-xl font-bold text-gray-900 dark:text-white tabular-nums truncate"},hl={key:2,class:"text-xs text-gray-700 dark:text-gray-300 tabular-nums truncate"},pl={class:"text-xs text-gray-600 dark:text-gray-400 tabular-nums"},gl={key:3,class:"px-6 py-5 flex items-center gap-4"},vl={class:"text-sm font-semibold text-gray-900 dark:text-white"},fl={class:"text-xs text-gray-500 dark:text-gray-400"},ml={key:4,class:"border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/60 px-6 py-3"},_l={class:"flex items-center justify-between gap-3"},yl={class:"min-w-0"},bl={class:"text-[11px] font-medium text-gray-600 dark:text-gray-400"},Sl={class:"text-xs font-semibold text-gray-900 dark:text-white truncate"},Cl={class:"text-[11px] text-gray-500 dark:text-gray-400 truncate"},wl={class:"flex shrink-0 gap-2"},kl={key:0,class:"mt-2 text-[11px] text-gray-500 dark:text-gray-400"},Il={class:"px-6 py-4 space-y-2"},El={key:0,class:"text-sm text-gray-700 dark:text-gray-300"},Tl={class:"card-base px-6 py-5 space-y-3"},Rl={key:0,class:"text-sm text-red-600 dark:text-red-400"},Al={key:1,class:"text-sm text-gray-500 dark:text-gray-400"},Ol={key:2,class:"text-sm text-gray-500 dark:text-gray-400"},Dl={key:3,class:"space-y-2"},xl={class:"flex items-start gap-2 min-w-0"},Nl=["checked","onChange"],Ll={class:"min-w-0"},Ml={class:"block text-xs font-medium text-gray-900 dark:text-white truncate"},Pl={key:0,class:"block text-xs text-gray-500 dark:text-gray-400 tabular-nums"},Fl={key:1,class:"block text-xs text-red-600 dark:text-red-400"},Ul={key:0,class:"shrink-0 inline-flex items-center gap-2"},$l=["value","disabled","onChange"],jl=["value"],Bl={class:"card-base px-6 py-5 lg:col-span-2 flex flex-col min-h-[24rem]"},Hl={class:"flex items-center justify-between mb-4"},Wl={class:"flex items-center gap-2"},Gl={key:0,class:"inline-flex items-center gap-1.5 rounded-full bg-green-100 dark:bg-green-900/40 px-2 py-0.5 text-[11px] font-medium text-green-800 dark:text-green-300"},Vl={key:1,class:"text-[11px] font-medium text-gray-500 dark:text-gray-400"},ql={key:0,class:"mb-3 text-sm text-red-600 dark:text-red-400"},Yl={key:0,class:"space-y-1"},Kl={key:0,class:"px-1 pb-1 text-[11px] font-medium text-gray-500 dark:text-gray-400"},Jl={class:"text-sm"},zl={key:0,role:"separator",class:"flex items-center gap-3 pt-5"},Ql={class:"inline-flex items-center gap-1.5 text-xs font-medium text-gray-600 dark:text-gray-300 tabular-nums"},Xl={key:1,class:"h-full flex flex-col items-center justify-center text-center py-12"},Zl={class:"text-sm text-gray-500 dark:text-gray-400 max-w-xs"},Vn="liveTranslate.staffLanguage",ec=qn({__name:"LiveTranslateView",setup(t){function e(){try{const _=localStorage.getItem(Vn);return vt.find(w=>w.code===_)?.code??"en"}catch{return"en"}}const i=da(),n=Gn(),s=Gn(),{showInfo:o,showWarning:r,showError:a}=eo(),l=Zs(),h=ie([]),p=ie(!0),f=ie(null),b=ie(e()),g=ie("auto"),v=ie(Ji),y=ie(!0),S=ie(null),E=ie(""),T=new Set,
9N=ie(!1),$=ie(""),j=ie(!1),q=new Map;let Y=!1;const M=ie(null),c=ie(null),u=ie(null),m=ie(null);Gi(async()=>{try{h.value=await na()}catch(_){f.value=_ instanceof Error?_.message:"Could not load phone lines"}finally{p.value=!1}}),be(b,_=>{try{localStorage.setItem(Vn,_)}catch{}});function C(_){return _.label??(_.phoneNumber?pt(_.phoneNumber):"Phone line")}function k(_){const w=h.value.find(U=>U.id===_);return w?C(w):"Phone line"}const O=ie(new Map);async function A(_){if(!_||O.value.has(_))return;const w=Yi(_);if(w)try{const U=(await Xs([w])).get(w);U&&(O.value=new Map(O.value).set(_,U))}catch{}}function P(_){return _?O.value.get(_)??null:null}function W(_){const w=P(_);return w?[w.first_name,w.last_name].filter(Boolean).join(" ")||"Patient":""}function ee(_){const w=P(_);if(!w||!_)return"";const U=pt(_);return w.medical_record_number?`${U}, MRN ${w.medical_record_number}`:U}function te(_){const w=P(_);return w?l.resolve({name:"ViewPatient",params:{patientId:String(w.id)}}).href:""}function I(_){return P(_)?W(_):x.value?.patientName?x.value.patientName:_?pt(_):"Unknown caller"}const x=ie(null);async function K(_){const w=_.remoteNumber?Yi(_.remoteNumber):null;if(!(!_.handoffId&&!w))try{const U=await ra({lineId:_.lineId,handoffId:_.handoffId,callerNumber:w});if(i.call.value?.id!==_.id||(x.value=U,!U))return;const re=vt.find(Gs=>Gs.code===U.language)?.code;re&&g.value==="auto"&&(g.value=re,Y=!0),U.translate&&(y.value=!0)}catch{}}const z=le(()=>{const _=x.value;if(!_)return"";const w=[];return _.reason&&w.push(`About ${_.reason.replace(/_/g," ")}`),_.language&&w.push(`speaks ${gt(_.language)}`),_.translate&&w.push("translation on"),w.join(" · ")}),ne=new Set,ae=new Map;function fe(_){return h.value.find(w=>w.id===_)?.mine===!0}function Oe(_){fe(_)&&(ne.add(_),Bn(_,!0).catch(()=>{}))}function Le(_,w={}){ne.delete(_)&&Bn(_,!1,w).catch(()=>{})}function Oi(_={}){for(const w of[...ne])Le(w,_)}const Di=()=>Oi({keepalive:!0});be(i.lines,_=>{for(const[w,U]of Object.entries(_)){const re=ae.get(w);ae.set(w,U.status),U.status==="ready"&&re!=="ready"?Oe(w):U.status!=="ready"&&re==="ready"&&Le(w)}for(const w of[...ae.keys()])w in _||(ae.delete(w),Le(w))},{deep:!0}),Gi(()=>window.addEventListener("pagehide",Di)),At(()=>{window.removeEventListener("pagehide",Di),Oi()});function xi(_){switch(_){case"ready":return{label:"Online",class:"bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300"};case"connecting":return{label:"Connecting",class:"bg-yellow-100 text-yellow-800 dark:bg-yellow-900/40 dark:text-yellow-300"};default:return{label:"Error",class:"bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300"}}}const jt=ie(!1);async function Is(_,w){if(!(!_.mine||w===_.presence)){jt.value=!0;try{await Gt(w),_.presence=w}catch(U){a(U instanceof Error?U.message:"Could not update presence")}finally{jt.value=!1}}}let lt=null;function Ni(){return h.value.find(_=>_.mine)}function Li(_){const w=Ni();!w||w.id!==_||lt||(lt=Gt("busy").then(({previous:U})=>(w.presence="busy",U)).catch(()=>null))}function Es(){const _=lt;lt=null,_&&_.then(async w=>{const U=Ni();if(U){if(w==="available"){try{await Gt("available"),U.presence="available"}catch(re){a(re instanceof Error?re.message:"Could not update presence")}return}w&&(U.presence=w)}})}function Ts(_,w){w?M.value&&i.connect([_],M.value):i.disconnectLine(_.id)}const Qe=le(()=>Object.values(i.lines.value).filter(_=>_.status==="ready").length),Mi=le(()=>k(i.call.value?.lineId)),Rs=le(()=>i.call.value?.state==="ringing"),ct=le(()=>i.other.value?.state==="ringing"),As=le(()=>k(i.other.value?.lineId)),Os=le(()=>{const _=i.call.value;return _?_.held?"On hold":_.connectedAt?"On call":"Connecting":""}),dt=le(()=>i.call.value?.held===!0);function Bt(_){return`${Math.floor(_/60)}:${String(_%60).padStart(2,"0")}`}function Ds(){i.answer()}function Pi(){i.call.value&&T.add(i.call.value.id),i.hangup()}function xs(){i.other.value&&T.add(i.other.value.id),i.hangupOther()}async function Ns(){if(!j.value){j.value=!0;try{await i.toggleHold()}catch(_){a(_ instanceof Error?_.message:"Could not hold the call")}finally{j.value=!1}}}async function Ls(){try{await i.answerOther()}catch(_){a(_ instanceof Error?_.message:"Could not answer the second call")}}async function Ms(){try{await i.swap()}catch(_){a(_ instanceof Error?_.message:"Could not swap the calls")}}function Ps(_){i.sendDigit(_)&&($.value=($.value+_).slice(-24))}const Fi=le(()=>{const _=S.value;return _?_.answered?_.endedByStaff?"You hung up":"Caller hung up":_.endedByStaff?"Call declined":"Missed call":""}),Ui=le(()=>{const _=S.value;if(!_)return"";const w=qi(_.endedAt);return _.answered?`Ended at ${w} after ${Bt(_.durationSeconds)} on ${_.lineName}`:`At ${w} on ${_.lineName}`});be(i.call,(_,w)=>{if(_&&_.id!==w?.id){S.value=null,x.value=null,N.value=!1,$.value="",w&&js(w.id),Bs(_.id),K(_),A(_.remoteNumber).finally(()=>{i.call.value?.state==="ringing"&&(E.value=`Incoming call from ${I(_.remoteNumber)}`)}),_.connectedAt&&Li(_.lineId);return}_&&w&&_.connectedAt&&!w.connectedAt&&(E.value="Call connected",Li(_.lineId))}),be(i.other,(_,w)=>{!_||_.id===w?.id||(A(_.remoteNumber).finally(()=>{i.other.value?.state==="ringing"&&(E.value=`Second call from ${I(_.remoteNumber)}`)}),_.state==="ringing"&&o(`Second call from ${I(_.remoteNumber)}`))}),be([i.call,i.other],([_,w])=>{!_&&!w&&Es()}),be(i.ended,_=>{if(_.length){i.ended.value=[];for(const w of _){i.lines.value[w.lineId]?.status==="ready"&&Oe(w.lineId),q.delete(w.id);const U={remoteNumber:w.remoteNumber,lineName:k(w.lineId),answered:w.answered,endedByStaff:T.delete(w.id),durationSeconds:w.durationSeconds,endedAt:w.endedAt};S.value=U,E.value=`${Fi.value}. ${Ui.value}`,!U.endedByStaff&&(U.answered?o(`Caller hung up after ${Bt(U.durationSeconds)}`):r(`Missed call from ${I(U.remoteNumber)}`))}}});const ut=le(()=>{if(g.value!=="auto")return g.value;const _=v.value.settled;return _?.kind==="supported"?_.code:null}),ht=le(()=>ut.value===b.value),Ht=le(()=>
9ht.value?null:ut.value),Fs=le(()=>{if(g.value==="auto"){const _=v.value.settled;if(!_)return"Listening for the caller's language. Until then they hear you directly.";if(_.kind==="unsupported")return`The caller seems to speak ${_.name}. You hear them translated, but they hear you directly; it cannot be translated into that language.`}return ht.value?`The caller speaks ${gt(b.value)}, so translation is off.`:`Caller speaks ${gt(ut.value??"")}. They hear you in ${gt(ut.value??"")}.`}),$i=le(()=>{const _=[n,s].filter(w=>!w.captionsOnly.value).map(w=>w.status.value).filter(w=>w!=="idle");return _.includes("error")?"error":_.includes("starting")?"starting":_.length&&_.every(w=>w==="live")?"live":"idle"}),ji=le(()=>n.error.value??s.error.value),Fe=le(()=>[...n.segments.value.map(_=>({key:`caller-${_.id}`,speaker:"caller",primary:n.captionsOnly.value?_.original:_.translated,secondary:n.captionsOnly.value?"":_.original,startedAt:_.startedAt})),...s.segments.value.map(_=>({key:`staff-${_.id}`,speaker:"staff",primary:_.original,secondary:_.translated,startedAt:_.startedAt}))].sort((_,w)=>_.startedAt-w.startedAt));function Bi(_){return _===0||Fe.value[_-1].speaker!==Fe.value[_].speaker}const Hi=ie(Date.now()),Us=setInterval(()=>{Hi.value=Date.now()},1e3);At(()=>clearInterval(Us));const $s=le(()=>{const _=i.call.value?.connectedAt;return _?Bt(Math.max(0,Math.floor((Hi.value-_)/1e3))):""});function Wi(){n.clear(),s.clear()}function js(_){q.set(_,{caller:n.segments.value,staff:s.segments.value,detection:v.value,callerLanguageChoice:g.value,languageFromHandoff:Y})}function Bs(_){const w=q.get(_);if(w){q.delete(_),n.segments.value=w.caller,s.segments.value=w.staff,v.value=w.detection,g.value=w.callerLanguageChoice,Y=w.languageFromHandoff;return}Wi(),v.value=Ji,Y&&(g.value="auto",Y=!1)}be(()=>n.segments.value,_=>{v.value.settled||(v.value=lo(v.value,_.map(w=>w.original).join(" ")))});function Hs(){const _=i.remoteStream.value?.getAudioTracks()[0];if(!y.value||!_||dt.value){n.stop();return}n.start(_,b.value,{captionsOnly:ht.value})}function Ws(){const _=i.microphoneTrack.value;if(!y.value||!_||dt.value){s.stop();return}s.start(_,Ht.value??b.value,{captionsOnly:Ht.value===null})}return be([i.remoteStream,y,b,ht,dt],Hs),be([i.microphoneTrack,y,b,Ht,dt],Ws),be(n.outputTrack,_=>{c.value&&(c.value.srcObject=_?new MediaStream([_]):null),i.setCallerAudioMuted(_!==null)}),be(s.outputTrack,_=>{u.value&&(u.value.srcObject=_?new MediaStream([_]):null),i.setOutboundAudio(_)}),be([Fe,S],async()=>{await Vs();const _=m.value;_&&(_.scrollTop=_.scrollHeight)}),(_,w)=>(H(),G("div",_a,[L("div",ya,[L("div",ba,[w[11]||(w[11]=L("div",null,[L("h1",{class:"text-xl font-bold text-gray-900 dark:text-white"},"Live Translate"),L("p",{class:"mt-1 text-sm text-gray-600 dark:text-gray-400"}," Answer calls here. You and the caller each hear the other in your own language. ")],-1)),L("div",Sa,[L("div",null,[w[7]||(w[7]=L("label",{for:"staff-language",class:"block text-[11px] font-medium text-gray-600 dark:text-gray-400"},"Your language",-1)),Wt(L("select",{id:"staff-language","onUpdate:modelValue":w[0]||(w[0]=U=>b.value=U),class:"form-select w-36"},[(H(!0),G(xe,null,$e(B(vt),U=>(H(),G("option",{key:U.code,value:U.code},J(U.label),9,Ca))),128))],512),[[Vi,b.value]])]),L("div",null,[w[9]||(w[9]=L("label",{for:"caller-language",class:"block text-[11px] font-medium text-gray-600 dark:text-gray-400"},"Caller language",-1)),Wt(L("select",{id:"caller-language","onUpdate:modelValue":w[1]||(w[1]=U=>g.value=U),class:"form-select w-40",onChange:w[2]||(w[2]=U=>Js(Y)?Y.value=!1:Y=!1)},[w[8]||(w[8]=L("option",{value:"auto"},"Auto-detect",-1)),(H(!0),G(xe,null,$e(B(vt),U=>(H(),G("option",{key:U.code,value:U.code},J(U.label),9,wa))),128))],544),[[Vi,g.value]])]),L("label",ka,[Wt(L("input",{"onUpdate:modelValue":w[3]||(w[3]=U=>y.value=U),type:"checkbox",class:"rounded border-gray-300 text-primary-600 focus:ring-primary-500"},null,512),[[Ks,y.value]]),w[10]||(w[10]=Se(" Translate ",-1))])])]),L("div",Ia,[L("div",Ea,[L("section",Ta,[w[20]||(w[20]=L("h2",{id:"call-heading",class:"sr-only"},"Call",-1)),L("p",Ra,J(E.value),1),B(i).call.value&&Rs.value?(H(),G("div",Aa,[L("div",Oa,[L("span",Da,[w[12]||(w[12]=L("span",{class:"absolute inset-0 rounded-full bg-amber-400/60 motion-safe:animate-ping"},null,-1)),L("span",xa,[ke(B(no),{class:"h-5 w-5","aria-hidden":"true"})])]),L("div",Na,[w[13]||(w[13]=L("p",{class:"text-sm font-semibold text-amber-900 dark:text-amber-200"},"Incoming call",-1)),P(B(i).call.value.remoteNumber)?(H(),G("a",{key:0,href:te(B(i).call.value.remoteNumber),target:"_blank",rel:"noopener",class:"block text-xl font-bold text-gray-900 dark:text-white truncate hover:underline"},J(W(B(i).call.value.remoteNumber)),9,La)):(H(),G("p",Ma,J(I(B(i).call.value.remoteNumber)),1)),P(B(i).call.value.remoteNumber)?(H(),G("p",Pa,J(ee(B(i).call.value.remoteNumber)),1)):se("",!0),z.value?(H(),G("p",Fa,J(z.value),1)):se("",!0),L("p",Ua,"On "+J(Mi.value),1)])]),L("div",$a,[L("button",{type:"button",class:"btn btn-primary justify-center",onClick:Ds},[ke(B(Ki),{class:"h-4 w-4 mr-1.5","aria-hidden":"true"}),w[14]||(w[14]=Se(" Answer ",-1))]),L("button",{type:"button",class:"btn btn-danger justify-center",onClick:Pi},"Decline")])])):B(i).call.value?(H(),G("div",ja,[L("div",Ba,[L("div",Ha,[L("p",Wa,[L("span",{class:De(["h-2 w-2 rounded-full",B(i).call.value.held?"bg-amber-500":"bg-green-500"]),"aria-hidden":"true"},null,2),Se(" "+J(Os.value),1)]),P(B(i).call.value.remoteNumber)?(H(),G("a",{key:0,href:te(B(i).call.value.remoteNumber),target:"_blank",rel:"noopener",class:"block text-xl font-bold text-gray-900 dark:text-white truncate hover:underline"},J(W(B(i).call.value.remoteNumber)),9,Ga)):(H(),G("p",Va,J(I(B(i).call.value.remoteNumber)),1)),P(B(i).call.value.remoteNumber)?(H(),G("p",qa,J(ee(B(i).call.value.remoteNumber)),1)):se("",!0),z.value?(H(),G("p",Ya,J(z.value),1)):se("",!0),L("p",Ka,"On "+J(Mi.value),1)]),B(i).call.value.connectedAt?(H(),G("p",Ja,J($s.value),1)):se("",!0)]),L("div",za,[L("button",{type:"button",class:"btn btn-secondary justify-center","aria-pressed":B(i).call.value.muted,onClick:w[4]||(w[4]=U=>B(i).toggleMute())},[ke(B(co),{class:"h-4 w-4 mr-1.5","aria-hidden":"true"}),Se(" "+J(B(i).call.value.muted?"Unmute":"Mute"),1)],8,Qa),L("button",{type:"button",class:"btn btn-secondary justify-center","aria-pressed":B(i).call.value.held,disabled:!B(i).call.value.connectedAt||j.value,onClick:Ns},[(H(),zs(qs(B(i).call.value.held?B(so):B(io)),{class:"h-4 w-4 mr-1.5","aria-hidden":"true"}
9)),Se(" "+J(B(i).call.value.held?"Resume":"Hold"),1)],8,Xa),L("button",{type:"button",class:"btn btn-secondary justify-center","aria-pressed":N.value,disabled:!B(i).call.value.connectedAt||B(i).call.value.held,onClick:w[5]||(w[5]=U=>N.value=!N.value)},[ke(B(oo),{class:"h-4 w-4 mr-1.5","aria-hidden":"true"}),w[15]||(w[15]=Se(" Keypad ",-1))],8,Za),L("button",{type:"button",class:"btn btn-danger justify-center",onClick:Pi},[ke(B(Vt),{class:"h-4 w-4 mr-1.5","aria-hidden":"true"}),w[16]||(w[16]=Se(" Hang up ",-1))])]),B(i).call.value.held?(H(),G("p",el," On hold. Neither of you can hear the other, and translation is paused. ")):B(i).call.value.muted?(H(),G("p",tl,"You are muted. The caller cannot hear you.")):se("",!0),N.value&&!B(i).call.value.held?(H(),G("div",il,[L("p",nl,[w[17]||(w[17]=Se(" Sent: ",-1)),L("span",sl,J($.value||"—"),1)]),ke(fa,{onDigit:Ps})])):se("",!0)])):S.value?(H(),G("div",ol,[L("div",rl,[L("span",al,[ke(B(Vt),{class:"h-5 w-5","aria-hidden":"true"})]),L("div",ll,[L("p",cl,J(Fi.value),1),P(S.value.remoteNumber)?(H(),G("a",{key:0,href:te(S.value.remoteNumber),target:"_blank",rel:"noopener",class:"block text-xl font-bold text-gray-900 dark:text-white truncate hover:underline"},J(W(S.value.remoteNumber)),9,dl)):(H(),G("p",ul,J(I(S.value.remoteNumber)),1)),P(S.value.remoteNumber)?(H(),G("p",hl,J(ee(S.value.remoteNumber)),1)):se("",!0),L("p",pl,J(Ui.value),1)])]),L("button",{type:"button",class:"btn btn-secondary w-full justify-center mt-4",onClick:w[6]||(w[6]=U=>S.value=null)},"Dismiss")])):(H(),G("div",gl,[L("span",{class:De(["flex h-11 w-11 shrink-0 items-center justify-center rounded-full",Qe.value?"bg-primary-50 text-primary-600 dark:bg-primary-900/30 dark:text-primary-400":"bg-gray-100 text-gray-400 dark:bg-gray-700"])},[ke(B(Ki),{class:"h-5 w-5","aria-hidden":"true"})],2),L("div",null,[L("p",vl,J(Qe.value?"Waiting for a call":"Not answering calls"),1),L("p",fl,J(Qe.value?`Calls to ${Qe.value===1?"your line":`your ${Qe.value} lines`} ring here.`:"Choose the lines this tab should answer."),1)])])),B(i).other.value?(H(),G("div",ml,[L("div",_l,[L("div",yl,[L("p",bl,J(ct.value?"Second call":"Waiting on hold"),1),L("p",Sl,J(I(B(i).other.value.remoteNumber)),1),L("p",Cl,"On "+J(As.value),1)]),L("div",wl,[ct.value?(H(),G("button",{key:0,type:"button",class:"btn btn-primary btn-xs",onClick:Ls},"Answer")):(H(),G("button",{key:1,type:"button",class:"btn btn-secondary btn-xs",onClick:Ms},[ke(B(to),{class:"h-3.5 w-3.5 mr-1","aria-hidden":"true"}),w[18]||(w[18]=Se(" Swap ",-1))])),L("button",{type:"button",class:"btn btn-danger btn-xs",onClick:xs},J(ct.value?"Decline":"Hang up"),1)])]),ct.value&&B(i).call.value?.connectedAt?(H(),G("p",kl," Answering puts "+J(I(B(i).call.value.remoteNumber))+" on hold. ",1)):se("",!0)])):se("",!0),L("div",Il,[B(i).call.value?.connectedAt&&y.value?(H(),G("p",El,J(Fs.value),1)):se("",!0),w[19]||(w[19]=L("p",{class:"text-sm text-gray-500 dark:text-gray-400"}," Use a headset, so the caller's translated voice is not picked up by your microphone. Translation is machine generated and not saved. Confirm names, dates and medications with the caller. ",-1))])]),L("section",Tl,[w[22]||(w[22]=L("h2",{class:"text-sm font-semibold text-gray-900 dark:text-white"},"Lines to answer",-1)),f.value?(H(),G("p",Rl,J(f.value),1)):p.value?(H(),G("p",Al,"Loading lines…")):h.value.length?(H(),G("ul",Dl,[(H(!0),G(xe,null,$e(h.value,U=>(H(),G("li",{key:U.id,class:"flex items-start justify-between gap-3"},[L("label",xl,[L("input",{type:"checkbox",class:"mt-0.5 rounded border-gray-300 text-primary-600 focus:ring-primary-500",checked:U.id in B(i).lines.value,onChange:re=>Ts(U,re.target.checked)},null,40,Nl),L("span",Ll,[L("span",Ml,J(C(U)),1),U.label&&U.phoneNumber?(H(),G("span",Pl,J(B(pt)(U.phoneNumber)),1)):se("",!0),B(i).lines.value[U.id]?.error?(H(),G("span",Fl,J(B(i).lines.value[U.id]?.error),1)):se("",!0)])]),U.id in B(i).lines.value?(H(),G("span",Ul,[U.mine&&B(i).lines.value[U.id].status==="ready"?(H(),G("select",{key:0,value:U.presence??"available",class:"form-input !py-0.5 !px-1.5 !text-[11px] !w-auto",disabled:jt.value,"aria-label":"My presence",onChange:re=>Is(U,re.target.value)},[(H(!0),G(xe,null,$e(B(ao),re=>(H(),G("option",{key:re,value:re},J(B(ro)[re]),9,jl))),128))],40,$l)):se("",!0),L("span",{class:De(["inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-[11px] font-medium",xi(B(i).lines.value[U.id].status).class])},[w[21]||(w[21]=L("span",{class:"h-1.5 w-1.5 rounded-full bg-current"},null,-1)),Se(" "+J(xi(B(i).lines.value[U.id].status).label),1)],2)])):se("",!0)]))),128))])):(H(),G("p",Ol," No phone lines are set up for this practice yet. "))])]),L("section",Bl,[L("div",Hl,[w[24]||(w[24]=L("h2",{class:"text-sm font-semibold text-gray-900 dark:text-white"},"Conversation",-1)),L("div",Wl,[$i.value==="live"?(H(),G("span",Gl,[...w[23]||(w[23]=[L("span",{class:"h-1.5 w-1.5 rounded-full bg-current"},null,-1),Se(" Translating ",-1)])])):$i.value==="starting"?(H(),G("span",Vl,"Starting translation…")):se("",!0),Fe.value.length&&!B(i).call.value?(H(),G("button",{key:2,type:"button",class:"btn btn-ghost btn-xs",onClick:Wi}," Clear ")):se("",!0)])]),ji.value?(H(),G("p",ql,J(ji.value),1)):se("",!0),L("div",{ref_key:"conversationScroller",ref:m,class:"flex-1 overflow-y-auto max-h-[60vh] pr-1"},[Fe.value.length?(H(),G("div",Yl,[(H(!0),G(xe,null,$e(Fe.value,(U,re)=>(H(),G("div",{key:U.key,class:De(["flex flex-col",U.speaker==="staff"?"items-end":"items-start",Bi(re)&&re>0?"pt-3":""])},[Bi(re)?(H(),G("span",Kl,J(U.speaker==="staff"?"You":"Caller"),1)):se("",!0),L("div",{class:De(["max-w-[75%] rounded-2xl px-4 py-2",U.speaker==="staff"?"bg-primary-600 text-white rounded-br-md":"bg-gray-100 text-gray-900 dark:bg-gray-700 dark:text-white rounded-bl-md"])},[U.primary?(H(),G(xe,{key:0},[L("p",Jl,J(U.primary),1),U.secondary?(H(),G("p",{key:0,class:De(["mt-0.5 text-xs",U.speaker==="staff"?"text-primary-100":"text-gray-500 dark:text-gray-400"])},J(U.secondary),3)):se("",!0)],64)):(H(),G(xe,{key:1},[L("p",{class:De(["text-sm",U.speaker==="staff"?"text-primary-100":"text-gray-500 dark:text-gray-400"])},J(U.secondary),3),L("p",{class:De(["mt-0.5 text-xs italic",U.speaker==="staff"?"text-primary-200":"text-gray-400"])},"Translating…",2)],64))],2)],2))),128)),S.value?.answered&&!B(i).call.value?(H(),G("div",zl,[w[25]||(w[25]=L("span",{class:"h-px flex-1 bg-gray-200 dark:bg-gray-700"},null,-1)),L("span",Ql,[ke(B(Vt),{class:"h-3.5 w-3.5","aria-hidden":"true"}),Se(" Call ended at "+J(B(qi)(S.value.endedAt)),1)]),w[26]||(w[26]=L("span",{class:"h-px flex-1 bg-gray-200 dark:bg-gray-700"},null,-1))])):se("",!0)])):(H(),G("div",Xl,[L("p",Zl,J(B(i).call.value?.connectedAt?"Start talking. What you and the caller say appears here.":"Answer a call to see the conversation, translated, as you talk."),1)]))],512)])])]),L("audio",{ref_key:"remoteAudio",ref:M,autoplay:"",class:"hidden"},null,512),L("audio",{ref_key:"callerTranslationAudio",ref:c,autoplay:"",class:"hidden"},null,512),L("audio",{ref_key:"staffTranslationAudio",ref:u,autoplay:"",muted:"",class:"hidden"},null,512)]))}}),vc=ec;export{vc as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.