@telnyx/webrtc 2.27.4-beta.0 → 2.27.4-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/bundle.mjs CHANGED
@@ -1 +1 @@
1
- function e(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}function t(e,t,i,n){return new(i||(i=Promise))((function(s,o){function r(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var i="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),n=new Uint8Array(16);function s(){if(!i)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return i(n)}for(var o=[],r=0;r<256;++r)o[r]=(r+256).toString(16).substr(1);function a(e,t,i){var n=t&&i||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var r=(e=e||{}).random||(e.rng||s)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t)for(var a=0;a<16;++a)t[n+a]=r[a];return t||function(e,t){var i=t||0,n=o;return[n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]]].join("")}(r)}const c={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},d={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,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,TOKEN_EXPIRING_SOON:34001,UNKNOWN_REATTACHED_SESSION:35002,SIGNALING_RECOVERY_REQUIRED:36003,MEDIA_RECOVERY_REQUIRED:36004,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:36005},{SDP_CREATE_OFFER_FAILED:l,SDP_CREATE_ANSWER_FAILED:u,SDP_SET_LOCAL_DESCRIPTION_FAILED:h,SDP_SET_REMOTE_DESCRIPTION_FAILED:p,SDP_SEND_FAILED:g,MEDIA_MICROPHONE_PERMISSION_DENIED:v,MEDIA_DEVICE_NOT_FOUND:m,MEDIA_GET_USER_MEDIA_FAILED:f,HOLD_FAILED:_,INVALID_CALL_PARAMETERS:y,BYE_SEND_FAILED:b,SUBSCRIBE_FAILED:S,PEER_CLOSED_DURING_INIT:I,WEBSOCKET_CONNECTION_FAILED:C,WEBSOCKET_ERROR:E,RECONNECTION_EXHAUSTED:k,GATEWAY_FAILED:w,LOGIN_FAILED:T,INVALID_CREDENTIALS:R,AUTHENTICATION_REQUIRED:A,ICE_RESTART_FAILED:O,NETWORK_OFFLINE:D,SESSION_NOT_REATTACHED:N,UNEXPECTED_ERROR:L}=c,{HIGH_RTT:P,HIGH_JITTER:M,HIGH_PACKET_LOSS:x,LOW_MOS:U,LOW_LOCAL_AUDIO:F,LOW_INBOUND_AUDIO:j,LOW_BYTES_RECEIVED:$,LOW_BYTES_SENT:H,ICE_CONNECTIVITY_LOST:W,ICE_GATHERING_TIMEOUT:B,ICE_GATHERING_EMPTY:G,PEER_CONNECTION_FAILED:V,ONLY_HOST_ICE_CANDIDATES:q,ANSWER_WHILE_PEER_ACTIVE:K,ICE_CANDIDATE_PAIR_CHANGED:Y,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:J,MULTIPLE_ACTIVE_CALLS_DETECTED:z,DUPLICATE_INBOUND_ANSWER:Q,TOKEN_EXPIRING_SOON:X,UNKNOWN_REATTACHED_SESSION:Z,SIGNALING_RECOVERY_REQUIRED:ee,MEDIA_RECOVERY_REQUIRED:te,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:ie}=d,ne=/^a=candidate:.+typ (srflx|prflx|relay)/m,se="wss://rtc.telnyx.com",oe={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},re={urls:"stun:stun.l.google.com:19302"},ae=[{urls:"stun:stun.telnyx.com:3478"},re,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],ce=[{urls:"stun:stundev.telnyx.com:3478"},re,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}];var de;!function(e){e.SocketOpen="telnyx.socket.open",e.SocketClose="telnyx.socket.close",e.SocketError="telnyx.socket.error",e.SocketMessage="telnyx.socket.message",e.SpeedTest="telnyx.internal.speedtest",e.SocketActivity="telnyx.internal.socketActivity",e.Ready="telnyx.ready",e.Error="telnyx.error",e.Warning="telnyx.warning",e.Notification="telnyx.notification",e.StatsFrame="telnyx.stats.frame",e.StatsReport="telnyx.stats.report",e.Messages="telnyx.messages",e.Calls="telnyx.calls",e.MediaError="telnyx.rtc.mediaError",e.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError",e.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed",e.AIConversationMessage="telnyx.ai.conversation"}(de||(de={}));const le={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 invalid 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 infrastructure 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}},ue={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-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"]},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 but only host (local network) candidates were collected — no server-reflexive (srflx) or relay (turn) candidates were found. This typically means the STUN/TURN servers are unreachable, which will prevent connections outside the local network.",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"]},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 he(e,t){const i=ue[e];return{code:e,name:i.name,message:t||i.message,description:i.description,causes:[...i.causes],solutions:[...i.solutions]}}class pe 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,pe.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 ge(e){return!0===e.recoverable}function ve(e){if(e instanceof DOMException){if("NotAllowedError"===e.name)return v;if("NotFoundError"===e.name||"OverconstrainedError"===e.name)return m}return f}function me(e,t,i,n){const s=le[e],o=t instanceof Error?t:void 0!==t?new Error(String(t)):void 0;return new pe({code:e,name:s.name,description:s.description,message:i||s.message,causes:[...s.causes],solutions:[...s.solutions],originalError:o,fatal:null!=n?n:s.fatal})}class fe extends Error{constructor(e,t,i=""){super(`Signaling request timed out (id=${e}, method=${i||"unknown"}, timeout=${t}ms)`),this.name="RequestTimeoutError",this.requestId=e,this.timeoutMs=t,this.method=i}}class _e extends Error{constructor(e,t,i){super(`Stale request cancelled (id=${e}, gen=${t}, current=${i})`),this.name="StaleRequestError",this.requestId=e,this.staleGeneration=t,this.currentGeneration=i}}var ye="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function be(e,t){return e(t={exports:{}},t.exports),t.exports}var Se=be((function(e){var t,i;t=ye,i=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"];function s(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function r(t,i){for(var s=0;s<n.length;s++){var o=n[s];this[o]=s<t?e:this.methodFactory(o,t,i)}this.log=this.debug}function a(e,i,n){return function(){typeof console!==t&&(r.call(this,i,n),this[e].apply(this,arguments))}}function c(n,r,c){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?o:void 0!==console[n]?s(console,n):void 0!==console.log?s(console,"log"):e)}(n)||a.apply(this,arguments)}function d(e,i,s){var o,a=this;i=null==i?"WARN":i;var d="loglevel";function l(){var e;if(typeof window!==t&&d){try{e=window.localStorage[d]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=i.indexOf(encodeURIComponent(d)+"=");-1!==n&&(e=/^([^;]+)/.exec(i.slice(n))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?d+=":"+e:"symbol"==typeof e&&(d=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=s||c,a.getLevel=function(){return o},a.setLevel=function(i,s){if("string"==typeof i&&void 0!==a.levels[i.toUpperCase()]&&(i=a.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(o=i,!1!==s&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+i+";"}catch(e){}}}(i),r.call(a,i,e),typeof console===t&&i<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){i=e,l()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(i,!1),function(){if(typeof window!==t&&d){try{return void window.localStorage.removeItem(d)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var u=l();null==u&&(u=i),a.setLevel(u,!1)}var l=new d,u={};l.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=u[e];return t||(t=u[e]=new d(e,l.getLevel(),l.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return l.noConflict=function(){return typeof window!==t&&window.log===l&&(window.log=h),l},l.getLoggers=function(){return u},l.default=l,l},e.exports?e.exports=i():t.log=i()}));const Ie={debug:0,info:1,warn:2,error:3};class Ce{constructor(e={}){var t,i,n;this.buffer=[],this.isCapturing=!1,this.options={enabled:null!==(t=e.enabled)&&void 0!==t&&t,level:null!==(i=e.level)&&void 0!==i?i:"debug",maxEntries:null!==(n=e.maxEntries)&&void 0!==n?n:1e3}}start(){this.options.enabled&&(this.isCapturing=!0,this.buffer=[])}stop(){this.isCapturing=!1}addEntry(e,t,i){if(!this.isCapturing||!this.options.enabled)return;if(Ie[e]<Ie[this.options.level])return;const n=Object.assign({timestamp:(new Date).toISOString(),level:e,message:t},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 e=this.buffer;return this.buffer=[],e}clear(){this.buffer=[]}isActive(){return this.isCapturing}isEnabled(){return this.options.enabled}}let Ee=null;const ke=Se.getLogger("telnyx"),we={trace:0,debug:1,info:2,warn:3,error:4};let Te=we.info;function Re(e){if(null==e)return e;if("object"!=typeof e)return e;try{const t=JSON.stringify(e),i=JSON.parse(t);if("object"==typeof i&&null!==i&&Object.keys(i).length>1)return i}catch(e){}const t={};for(const i in e)try{const n=e[i];if("function"==typeof n)continue;if("object"==typeof n&&null!==n)try{t[i]=JSON.parse(JSON.stringify(n))}catch(e){t[i]=String(n)}else t[i]=n}catch(e){}return Object.keys(t).length>0?t:{value:String(e)}}const Ae=ke.methodFactory;ke.methodFactory=(e,t,i)=>{const n=Ae(e,t,i);return function(...t){if(we[e]>=Te){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(const i of t)e.push(i);n(...e)}const i=Ee;if(null==i?void 0:i.isActive()){const[n,...s]=t,o="string"==typeof n?n:JSON.stringify(n);let r;s.length>0&&(r=1===s.length&&"object"==typeof s[0]&&null!==s[0]?Re(s[0]):{args:s.map(Re)}),i.addEntry(e,o,r)}}},ke.setLevel("debug",!1);const Oe=e=>{const[t,i,n,s,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){ke.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},De=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},Ne=e=>e instanceof Function||"function"==typeof e,Le=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,Pe=/^(ws|wss):\/\//,Me=(e,t=null)=>{const{result:i={},error:n}=e;if(n)return{error:n};const{result:s=null}=i;if(null===s)return null!==t&&(i.node_id=t),{result:i};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&"200"!==o?{error:s}:a?Me(a,r):{result:s}},xe=({login:e,passwd:t,password:i,login_token:n})=>Boolean(e&&(t||i)||n),Ue=({anonymous_login:e})=>Boolean(e)&&Boolean(e.target_id)&&Boolean(e.target_type),Fe=e=>{var t,i,n,s,o,r;let a="",c="";(null===(i=null===(t=null==e?void 0:e.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state)&&(a=null===(s=null===(n=null==e?void 0:e.result)||void 0===n?void 0:n.params)||void 0===s?void 0:s.state),(null===(o=null==e?void 0:e.params)||void 0===o?void 0:o.state)&&(c=null===(r=null==e?void 0:e.params)||void 0===r?void 0:r.state);return a||c};function je({debounceTime:e}){let t,i;return{promise:new Promise(((n,s)=>{t=e?$e(n,e):n,i=s})),resolve:t,reject:i}}const $e=(e,t)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout((()=>{e(...n)}),t)}},He="telnyx-voice-sdk-id",We="telnyx-voice-sdk-session-id",Be="telnyx-voice-sdk-session-id-stored-at",Ge="telnyx-voice-sdk-active-calls",Ve=9e4;function qe(e=Date.now()){const t=function(){const e=Number(sessionStorage.getItem(Be));return Number.isFinite(e)?e:null}();return null!==t&&e-t<=Ve}function Ke(){return sessionStorage.getItem(He)}function Ye(e,t=Date.now()){sessionStorage.setItem(We,e),sessionStorage.setItem(Be,String(t))}function Je(){sessionStorage.removeItem(He),sessionStorage.removeItem(We),sessionStorage.removeItem(Be)}function ze(){!function(e){try{sessionStorage.removeItem(e)}catch(t){ke.debug(`safeRemoveItem('${e}') failed: ${t instanceof Error?t.message:String(t)}`)}}(Ge)}function Qe(e=Date.now()){const t=function(e){try{return sessionStorage.getItem(e)}catch(t){return ke.debug(`safeGetItem('${e}') failed: ${t instanceof Error?t.message:String(t)}`),null}}(Ge);if(ze(),!t)return ke.debug("Active-calls recovery marker not found in storage — nothing to recover."),null;try{const i=JSON.parse(t);if(!i||"object"!=typeof i||!Array.isArray(i.calls))return ke.debug("Active-calls recovery marker payload was malformed — discarded."),null;const n=Number(i.storedAt);return!Number.isFinite(n)||e-n>9e5?(ke.debug("Active-calls recovery marker was stale or had an invalid timestamp — discarded."),null):0===i.calls.length?(ke.debug("Active-calls recovery marker had no call records — discarded."),null):i}catch(e){return ke.debug(`Active-calls recovery marker JSON parse failed — discarded: ${e instanceof Error?e.message:String(e)}`),null}}function Xe(e,t,i=Date.now()){if(!Array.isArray(e)||0===e.length)return void ze();const n={sessionId:t,calls:e,storedAt:i};!function(e,t){try{sessionStorage.setItem(e,t)}catch(t){ke.info(`safeSetItem('${e}') failed: ${t instanceof Error?t.message:String(t)}`)}}(Ge,JSON.stringify(n))}var Ze,et,tt;!function(e){e.Offer="offer",e.Answer="answer"}(Ze||(Ze={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(et||(et={})),function(e){e.Invite="telnyx_rtc.invite",e.Attach="telnyx_rtc.attach",e.Answer="telnyx_rtc.answer",e.Info="telnyx_rtc.info",e.Candidate="telnyx_rtc.candidate",e.EndOfCandidates="telnyx_rtc.endOfCandidates",e.Display="telnyx_rtc.display",e.Media="telnyx_rtc.media",e.Event="telnyx_rtc.event",e.Bye="telnyx_rtc.bye",e.Punt="telnyx_rtc.punt",e.Broadcast="telnyx_rtc.broadcast",e.Subscribe="telnyx_rtc.subscribe",e.Unsubscribe="telnyx_rtc.unsubscribe",e.ClientReady="telnyx_rtc.clientReady",e.Modify="telnyx_rtc.modify",e.Ringing="telnyx_rtc.ringing",e.GatewayState="telnyx_rtc.gatewayState",e.Ping="telnyx_rtc.ping",e.Pong="telnyx_rtc.pong"}(tt||(tt={}));const it={generic:"event",[tt.Display]:"participantData",[tt.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},nt={invalidCredentialsOptions:"InvalidCredentialsOptions"},st={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:!0};var ot,rt,at,ct,dt,lt;!function(e){e[e.New=0]="New",e[e.Requesting=1]="Requesting",e[e.Trying=2]="Trying",e[e.Recovering=3]="Recovering",e[e.Ringing=4]="Ringing",e[e.Answering=5]="Answering",e[e.Early=6]="Early",e[e.Active=7]="Active",e[e.Held=8]="Held",e[e.Hangup=9]="Hangup",e[e.Destroy=10]="Destroy",e[e.Purge=11]="Purge"}(ot||(ot={})),function(e){e.Participant="participant",e.Moderator="moderator"}(rt||(rt={})),function(e){e.Join="join",e.Leave="leave",e.Bootstrap="bootstrap",e.Add="add",e.Modify="modify",e.Delete="delete",e.Clear="clear",e.ChatMessage="chatMessage",e.LayerInfo="layerInfo",e.LogoInfo="logoInfo",e.LayoutInfo="layoutInfo",e.LayoutList="layoutList",e.ModCmdResponse="modCommandResponse"}(at||(at={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(ct||(ct={})),function(e){e.REGED="REGED",e.UNREGED="UNREGED",e.NOREG="NOREG",e.FAILED="FAILED",e.FAIL_WAIT="FAIL_WAIT",e.TIMEOUT="TIMEOUT",e.REGISTER="REGISTER",e.TRYING="TRYING",e.EXPIRED="EXPIRED",e.UNREGISTER="UNREGISTER"}(dt||(dt={})),function(e){e.Hold="hold",e.Unhold="unhold",e.ToggleHold="toggleHold",e.UpdateMedia="updateMedia"}(lt||(lt={}));const ut="GLOBAL",ht={},pt=(e,t)=>`${e}|${t}`,gt=(e,t=ut)=>pt(e,t)in ht,vt=(e,t,i=ut)=>{const n=pt(e,i);n in ht||(ht[n]=[]),ht[n].push(t)},mt=(e,t,i=ut)=>{const n=function(s){ft(e,n,i),t(s)};return n.prototype.targetRef=t,vt(e,n,i)},ft=(e,t,i=ut)=>{if(!gt(e,i))return!1;const n=pt(e,i);if(Ne(t)){for(let e=ht[n].length-1;e>=0;e--){const i=ht[n][e];(t===i||i.prototype&&t===i.prototype.targetRef)&&ht[n].splice(e,1)}}else ht[n]=[];return 0===ht[n].length&&delete ht[n],!0},_t=(e,t,i=ut,n=!0)=>{const s=n&&i!==ut;if(!gt(e,i))return s&&_t(e,t),!1;const o=pt(e,i),r=ht[o].length;if(!r)return s&&_t(e,t),!1;for(let e=r-1;e>=0;e--)ht[o][e](t);return s&&_t(e,t),!0},yt=e=>{const t=pt(e,"");Object.keys(ht).filter((e=>0===e.indexOf(t))).forEach((e=>delete ht[e]))};let bt="undefined"!=typeof WebSocket?WebSocket:null;const St=0,It=1,Ct=2,Et=3;class kt{constructor(e){this.session=e,this.previousGatewayState="",this.lastInboundAt=0,this.socketGeneration=0,this._wsClient=null,this._host=se,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:t,env:i,region:n,useCanaryRtcServer:s}=e.options;ke.debug("Creating new Connection",{host:this._host,env:i,region:n,useCanaryRtcServer:s}),i&&(this._host="development"===i?"wss://rtcdev.telnyx.com":se),t&&(this._host=(e=>`${Pe.test(e)?"":"wss://"}${e}`)(t)),n&&(this._host=this._host.replace(/rtc(dev)?/,`${n}.rtc$1`)),s&&(this._useCanaryRtcServer=!0)}get connected(){return!!this._wsClient&&this._wsClient.readyState===It}get connecting(){return!!this._wsClient&&this._wsClient.readyState===St}get closing(){return!!this._wsClient&&this._wsClient.readyState===Ct}get closed(){return!!this._wsClient&&this._wsClient.readyState===Et}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){ke.debug("Connection.connect() called",{host:this._host,socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const e=new URL(this._host);let t=Ke();this.session.options.rtcIp&&this.session.options.rtcPort&&(t=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),t&&e.searchParams.set("voice_sdk_id",t),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),t&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),ke.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this.session.callReportVoiceSdkId=e.searchParams.get("voice_sdk_id"),this.session.options.skipLastVoiceSdkId&&e.searchParams.has("voice_sdk_id")&&e.searchParams.set("skip_last_voice_sdk_id","true"),this.session.options.skipTrailing&&e.searchParams.set("skip_trailing","true");try{const t=this.socketGeneration;this._wsClient=new bt(e.toString()),this.socketGeneration+=1,ke.debug("WebSocket connection created",{sessionId:this.session.sessionid,voiceSdkId:this.session.callReportVoiceSdkId,socketGeneration:this.socketGeneration,reconnectCount:t}),this.lastInboundAt=0,this._cleanupPendingRequests(),this._registerSocketEvents(this._wsClient)}catch(e){ke.error("WebSocket connection failed:",e);const t=me(C,e);_t(de.Error,{error:t,sessionId:this.session.sessionid},this.session.uuid),this.session._terminateActiveCallsLocally()}}sendRawText(e){var t;null===(t=this._wsClient)||void 0===t||t.send(e)}send(e,t){var i;const{request:n}=e,s=this.socketGeneration,o=n.method||"",r=new Promise(((e,i)=>{if(n.hasOwnProperty("result"))return e();let r=!1,a=null;const c=t=>{if(null!==a&&(clearTimeout(a),this._pendingRequestTimers.delete(n.id),a=null),this._pendingRequestIds.delete(n.id),this._pendingRequestRejecters.delete(n.id),r)return;const{result:s,error:o}=Me(t);return o?i(o):e(s)};mt(n.id,c),this._pendingRequestIds.add(n.id),this._pendingRequestRejecters.set(n.id,{reject:i,generation:s}),t&&t>0&&(a=setTimeout((()=>{if(r=!0,a=null,this._pendingRequestTimers.delete(n.id),this._pendingRequestRejecters.delete(n.id),ft(n.id,c),this._pendingRequestIds.delete(n.id),this.socketGeneration!==s)return ke.debug(`Stale request timeout for ${n.id} (gen ${s}, current ${this.socketGeneration}) — settling with StaleRequestError`),void i(new _e(n.id,s,this.socketGeneration));i(new fe(n.id,t,o))}),t),this._pendingRequestTimers.set(n.id,a))}));return ke.debug("SEND: \n",JSON.stringify(n,null,2),"\n"),null===(i=this._wsClient)||void 0===i||i.send(JSON.stringify(n)),r}close(){if(ke.debug("Connection.close() called",{hasWsClient:!!this._wsClient,closing:this.closing,closed:this.closed,socketGeneration:this.socketGeneration,safetyTimeoutId:this._safetyTimeoutId,sessionId:this.session.sessionid}),!this._wsClient||this.closing)return;this._cleanupPendingRequests();const e=this._wsClient;Ne(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout((()=>this._handleCloseTimeout(e)),5e3))}_registerSocketEvents(e){const t=this.socketGeneration;e.onopen=e=>(ke.debug("WebSocket onopen",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid}),_t(de.SocketOpen,e,this.session.uuid)),e.onclose=i=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),ke.debug("WebSocket onclose",{code:null==i?void 0:i.code,reason:null==i?void 0:i.reason,wasClean:null==i?void 0:i.wasClean,socketGeneration:t,sessionId:this.session.sessionid}),_t(de.SocketClose,{event:i,socketGeneration:t},this.session.uuid)),e.onerror=i=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error"),ke.debug("WebSocket onerror",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const n=me(E);return _t(de.Error,{error:n,sessionId:this.session.sessionid},this.session.uuid),_t(de.SocketError,{error:i,sessionId:this.session.sessionid,socketGeneration:t},this.session.uuid)},e.onmessage=e=>{var t,i;this.lastInboundAt=Date.now(),_t(de.SocketActivity,{timestamp:this.lastInboundAt},this.session.uuid);const n=De(e.data);var s;if("string"!=typeof n){if(n.voice_sdk_id&&(this.session.callReportVoiceSdkId=n.voice_sdk_id,s=n.voice_sdk_id,sessionStorage.setItem(He,s)),this._unsetTimer(n.id),ke.debug("RECV: \n",JSON.stringify(n,null,2),"\n"),dt[`${null===(i=null===(t=null==n?void 0:n.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state}`]||!_t(n.id,n)){const e=Fe(n);_t(de.SocketMessage,n,this.session.uuid),Boolean(e)&&(this.previousGatewayState=e)}}else this._handleStringResponse(n)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(e){this._safetyTimeoutId=null,e&&e.readyState!==Et?(ke.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e?ke.debug("Safety timeout: socket was replaced, not emitting SocketClose",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}):(ke.debug("Safety timeout: emitting SocketClose for stuck socket",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}),_t(de.SocketClose,{code:oe.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))):ke.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(ke.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,t){this._wsClient===e?(ke.debug(`Nulling socket reference (reason: ${t})`),this._wsClient=null):ke.debug(`Skipping socket cleanup - old socket already replaced (reason: ${t})`)}_cleanupPendingRequests(){Array.from(this._pendingRequestIds).forEach((e=>{ft(e);const t=this._pendingRequestTimers.get(e),i=this._pendingRequestRejecters.get(e);t&&(clearTimeout(t),this._pendingRequestTimers.delete(e),i&&i.reject(new _e(e,i.generation,this.socketGeneration))),this._pendingRequestRejecters.delete(e)})),this._pendingRequestIds.clear()}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),_t(de.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else ke.warn("Unknown message from socket",e)}}kt.DEFAULT_REQUEST_TIMEOUT_MS=1e4;class wt{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:a()},e)}buildNotification(e){this.request=Object.assign({jsonrpc:"2.0"},e)}}const Tt={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class Rt extends wt{constructor(t={}){if(super(),t.hasOwnProperty("dialogParams")){const i=e(t.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const e in Tt)e&&i.hasOwnProperty(e)&&(i[Tt[e]]=i[e],delete i[e]);t.dialogParams=i}this.buildRequest({method:this.toString(),params:t})}}class At extends Rt{constructor(e){super(),this.method=tt.GatewayState;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Ot{constructor(e){this.pendingRequestId=null,this.onSocketMessage=e=>t(this,void 0,void 0,(function*(){e.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Fe(e))})),this.getIsRegistered=()=>t(this,void 0,void 0,(function*(){const e=new At(Ke());this.pendingRequestId=e.request.id,this.gatewayStateTask=je({}),this.session.execute(e);const t=yield this.gatewayStateTask.promise;return!!t&&[dt.REGISTER,dt.REGED].includes(t)})),this.session=e,this.gatewayStateTask=je({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Dt extends Rt{constructor(e){super(),this.method=tt.Ping;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Nt{constructor(e){this._session=e,this._lastInboundAt=0,this._lastProbeSentAt=0,this._probeInFlight=!1,this._intervalId=null,this._pendingMediaRecovery=null}static isCriticalMethod(e){return Nt.CRITICAL_METHODS.has(e)}start(){this._intervalId||(ke.debug("Signaling health: monitor started"),this._lastInboundAt=Date.now(),this._probeInFlight=!1,this._lastProbeSentAt=0,this._intervalId=setInterval((()=>this._check()),3e3))}stop(){this._intervalId&&(clearInterval(this._intervalId),this._intervalId=null,this._probeInFlight=!1,this._lastProbeSentAt=0),this._pendingMediaRecovery=null,ke.debug("Signaling health: monitor stopped")}get isRunning(){return null!==this._intervalId}get isProbeInFlight(){return this._probeInFlight}onSocketActivity(){this._lastInboundAt=Date.now()}_resolveProbe(){if(!this._probeInFlight)return;if(this._probeInFlight=!1,this._lastProbeSentAt=0,this._lastInboundAt=Date.now(),ke.debug("Signaling health: probe resolved by matching Ping response"),!this._pendingMediaRecovery)return void ke.debug("Signaling health: probe resolved but no pending media recovery");const e=this._pendingMediaRecovery;this._pendingMediaRecovery=null,"healthy"===this._getSignalingHealthState()&&(ke.info(`Signaling health: signaling probe resolved, triggering pending ICE restart for call ${e.callId}`),this._triggerIceRestart(e.callId,e.reason,e.source))}_probeIfNeeded(e){var t;(null===(t=this._session.connection)||void 0===t?void 0:t.connected)&&(this._probeInFlight?ke.debug(`Signaling health: probe already in flight, skipping duplicate probe (${e})`):(ke.info(`Signaling health: ${e}, sending signaling probe`),this._sendProbe()))}onRequestTimeout(e,t,i=""){var n;if(!(null===(n=this._session.connection)||void 0===n?void 0:n.connected))return;Nt.isCriticalMethod(i)?(ke.warn(`Critical signaling request timed out (id=${e}, method=${i}, timeout=${t}ms) — declaring signaling unhealthy`),this._triggerSignalingRecovery(`Critical signaling request timed out (method=${i}, id=${e}, timeout=${t}ms)`,"request")):ke.warn(`Non-critical signaling request timed out (id=${e}, method=${i||"unknown"}, timeout=${t}ms) — logging but not triggering signaling recovery`)}onPeerFailure(e,t){ke.warn(`Signaling health: peer failure reported (callId=${e}, evidence=${t})`),this._recoverMediaOrSignaling(e,`Peer connection failure (${t})`,`Peer failure detected (${t}) while signaling is unhealthy`,"peer_failure")}onNoRtp(e,t){ke.warn(`Signaling health: no RTP detected (callId=${e}, direction=${t})`),this._recoverMediaOrSignaling(e,`No RTP ${t} while media should be active`,`No RTP ${t} while signaling is unhealthy`,"no_rtp")}onIceRestartFailed(e){ke.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(!(null===(e=this._session.connection)||void 0===e?void 0:e.connected))return;const t=Date.now(),i=t-this._lastInboundAt;if(i<2e4)return;if(!this._probeInFlight)return ke.info(`Signaling health: no inbound WS activity for ${Math.round(i/1e3)}s during active call, sending health probe`),void this._sendProbe();const n=t-this._lastProbeSentAt;n>=5e3&&(ke.warn(`Signaling health: probe timed out after ${n}ms with no inbound activity — declaring signaling unhealthy`),this._triggerSignalingRecovery("Signaling health probe timed out: no inbound WS activity after probe","probe"))}_sendProbe(){var e;this._probeInFlight=!0,this._lastProbeSentAt=Date.now();const t=new Dt(Ke());null===(e=this._session.connection)||void 0===e||e.send(t).then((()=>this._resolveProbe())).catch((e=>{ke.warn("Signaling health: probe Ping failed to send",e)}))}_recoverMediaOrSignaling(e,t,i,n){if(!this._session.hasActiveCall())return void ke.debug(`Signaling health: ignoring ${n} recovery without an active call`);const s=this._getSignalingHealthState();return"healthy"===s?(ke.info(`Signaling health: signaling is healthy, triggering ICE restart for call ${e}`),void this._triggerIceRestart(e,t,n)):"unknown"===s?(ke.info(`Signaling health: signaling health is unknown, deferring ICE restart decision for call ${e}`),this._pendingMediaRecovery={callId:e,reason:t,source:n},void this._probeIfNeeded(`${n} detected with stale/unknown signaling`)):(ke.info("Signaling health: signaling is unhealthy, triggering socket reconnect instead of ICE restart"),void this._triggerSignalingRecovery(i,n))}_getSignalingHealthState(){var e;if(!(null===(e=this._session.connection)||void 0===e?void 0:e.connected))return"unhealthy";if(this._probeInFlight)return"unknown";const t=Date.now(),i=this._lastInboundAt||this._session.connection.lastInboundAt||0;return 0===i?"unknown":t-i<3e3?"healthy":"unknown"}_triggerSignalingRecovery(e,t="probe"){var i,n,s;this._pendingMediaRecovery=null,this._probeInFlight=!1,this._lastProbeSentAt=0,ke.debug(`Signaling recovery triggered (source=${t}, reason=${e})`);const o=he(ee);_t(de.Warning,{warning:o,reason:e,source:t,sessionId:this._session.sessionid},this._session.uuid),(null===(i=this._session.connection)||void 0===i?void 0:i.connected)?(ke.info("Signaling health: force-closing WebSocket to trigger reconnect"),this._session.socketDisconnect()):ke.debug("Signaling health: recovery triggered but connection not connected",{connected:null===(n=this._session.connection)||void 0===n?void 0:n.connected,hasConnection:!!this._session.connection,socketGeneration:null===(s=this._session.connection)||void 0===s?void 0:s.socketGeneration})}_triggerIceRestart(e,t,i){ke.info(`Signaling health: triggering ICE restart for call ${e}`);const n=this._session.triggerIceRestart(e);if(!n.started)return void ke.info(`Signaling health: ICE restart not started for call ${e}: ${n.reason}`);const s=he(te);_t(de.Warning,{warning:s,reason:t,callId:e,sessionId:this._session.sessionid},this._session.uuid)}}Nt.CRITICAL_METHODS=new Set([tt.Modify,tt.Bye,tt.Ping]);var Lt="2.27.4-beta.0",Pt=Lt;class Mt extends Rt{constructor(e,t,i,n,s={},o){super(),this.method="login";const r={login:e,passwd:t,login_token:i,userVariables:s,reconnection:o,loginParams:{},"User-Agent":{sdkVersion:Pt,data:navigator.userAgent}};n&&(r.sessid=n),this.buildRequest({method:this.method,params:r})}}class xt extends Rt{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Ut extends Rt{toString(){return tt.Invite}}class Ft extends Rt{toString(){return tt.Answer}}class jt extends Rt{toString(){return tt.Attach}}class $t extends Rt{toString(){return tt.Bye}}class Ht extends Rt{toString(){return tt.Candidate}}class Wt extends Rt{toString(){return tt.EndOfCandidates}}class Bt extends Rt{toString(){return tt.Modify}}class Gt extends Rt{toString(){return tt.Info}}class Vt extends Rt{toString(){return tt.Broadcast}}class qt extends Rt{toString(){return tt.Subscribe}}class Kt extends Rt{toString(){return tt.Unsubscribe}}class Yt extends Rt{constructor(e){super(),this.method="anonymous_login";const{target_type:t,target_id:i,target_version_id:n,target_params:s,userVariables:o,sessionId:r,reconnection:a}=e,c={target_type:t,target_id:i,userVariables:o,reconnection:a,"User-Agent":{sdkVersion:Pt,data:navigator.userAgent}};r&&(c.sessid=r),n&&(c.target_version_id=n),s&&(c.target_params=s),this.buildRequest({method:this.method,params:c})}}class Jt{constructor(e){if(this.options=e,this.uuid=a(),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 Nt(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var t,i;t=e.debug?"debug":"info",Te=null!==(i=we[t])&&void 0!==i?i:we.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 kt(this),this.registerAgent=new Ot(this)}get __logger(){return ke}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return t(this,void 0,void 0,(function*(){return this.registerAgent.getIsRegistered()}))}get reconnectDelay(){const e=this._reconnectAttempts,t=Math.min(1e3*Math.pow(2,e-1),3e4),i=Math.floor(.25*t*(2*Math.random()-1)),n=t+i;return ke.debug("Reconnect delay computed",{attempt:e,baseDelayMs:1e3,maxDelayMs:3e4,delayMs:t,jitterMs:i,totalDelay:n,sessionId:this.sessionid}),n}execute(e){var i;if(this._idle)return new Promise((t=>this._executeQueue.push({resolve:t,msg:e})));if(!this.connected)return new Promise((t=>{this._executeQueue.push({resolve:t,msg:e}),ke.debug("Calling connect from execute since not currently connected."),this.connect()}));const n=Nt.isCriticalMethod((null===(i=e.request)||void 0===i?void 0:i.method)||"")?kt.DEFAULT_REQUEST_TIMEOUT_MS:void 0;return(null!=n?this.connection.send(e,n):this.connection.send(e)).catch((e=>t(this,void 0,void 0,(function*(){if(e instanceof _e)throw ke.debug(`Stale request settled (id=${e.requestId}, gen=${e.staleGeneration}) — not triggering recovery`),e;if("RequestTimeoutError"===(null==e?void 0:e.name))throw this.onSignalingRequestTimeout(e.requestId,e.timeoutMs,e.method),e;if((null==e?void 0:e.code)===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const t=me(A,e,void 0,!0);_t(de.Error,{error:t,sessionId:this.sessionid},this.uuid)}yield this.login()}throw e}))))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}trackCallReportUpload(e){this._pendingCallReportUploads.add(e),e.then((()=>this._pendingCallReportUploads.delete(e)),(()=>this._pendingCallReportUploads.delete(e)))}_drainCallReportUploads(){return t(this,void 0,void 0,(function*(){if(0===this._pendingCallReportUploads.size)return;const e=Array.from(this._pendingCallReportUploads);let t=!1;yield Promise.race([Promise.all(e.map((e=>e.catch((()=>{}))))),new Promise((e=>setTimeout((()=>{t=!0,e()}),Jt.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS)))]),t&&ke.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})}))}validateOptions(){return xe(this.options)||Ue(this.options)}broadcast(e){}disconnect(){return t(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(),ke.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")}))}on(e,t){return vt(e,t,this.uuid),this}off(e,t){return ft(e,t,this.uuid),this}connect(){return t(this,void 0,void 0,(function*(){this.connection||(ke.debug("No existing connection found, creating a new one."),this.connection=new kt(this)),this._attachListeners(),this._autoReconnect||(ke.debug("autoReconnect was disabled, resetting reconnect attempts"),this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(ke.debug("Connection wasn't alive, initiating connection to the server..."),this.connection.connect()),ke.debug("Connect method called. Connection initiated.")}))}resetReconnectAttempts(){this._reconnectAttempts=0,this._reconnectCountedGeneration=-1}_handleLoginError(e){const t=me(T,e);_t(de.Error,{error:t,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){Je()}_checkTokenExpiry(){this._clearTokenExpiryTimeout();const e=this.options.login_token;if(e&&"string"==typeof e)try{const t=e.split(".");if(3!==t.length)return;const i=JSON.parse(atob(t[1])).exp;if("number"!=typeof i)return;const n=i-Math.floor(Date.now()/1e3);if(n<=0)return;if(n<=Jt.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const e=1e3*(n-Jt.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout((()=>{this._emitTokenExpiryWarning()}),e)}}catch(e){ke.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=he(X);_t(de.Warning,{warning:e,sessionId:this.sessionid},this.uuid)}_clearTokenExpiryTimeout(){null!==this._tokenExpiryTimeout&&(clearTimeout(this._tokenExpiryTimeout),this._tokenExpiryTimeout=null)}login({creds:e,onSuccess:i,onError:n}={}){return t(this,void 0,void 0,(function*(){if(this.connection&&this.connection.isAlive){if(e&&(void 0!==e.login&&(this.options.login=e.login),void 0!==e.password&&(this.options.password=e.password),void 0!==e.passwd&&(this.options.passwd=e.passwd),void 0!==e.login_token&&(this.options.login_token=e.login_token),void 0!==e.userVariables&&(this.options.userVariables=e.userVariables),void 0!==e.anonymous_login&&(this.options.anonymous_login=e.anonymous_login)),xe(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(Ue(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const e="Invalid login options provided for authentication.";ke.error(e);const t=me(R,void 0,e);return void _t(de.Error,{error:t,type:nt.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}}))}_login({type:e,onSuccess:i,onError:n}){return t(this,void 0,void 0,(function*(){let t;const s=!!Ke(),o=s&&(this.sessionid&&qe()?this.sessionid:function(e=Date.now()){const t=sessionStorage.getItem(We);return t?qe(e)?t:(sessionStorage.removeItem(We),sessionStorage.removeItem(Be),null):null}())||"";t="login"===e?new Mt(this.options.login,this.options.password||this.options.passwd,this.options.login_token,o,this.options.userVariables,s):new Yt({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:o,userVariables:this.options.userVariables,reconnection:s});const r=yield this.execute(t).catch((e=>{this._handleLoginError(e),n&&n(e)}));r&&(this.sessionid=r.sessid,this.sessionid&&Ye(this.sessionid),this._checkTokenExpiry(),i&&i())}))}_onSocketOpen(){return t(this,void 0,void 0,(function*(){this.startSignalingHealthMonitor()}))}_flushIntermediateCallReports(e){const t=this.calls;t&&Object.values(t).forEach((t=>{if(null==t?void 0:t.flushIntermediateCallReport)try{t.flushIntermediateCallReport(e)}catch(i){ke.error("Failed to flush intermediate call report",{callId:t.id,flushReason:e,error:i})}}))}_getSocketCloseCodeName(e){if(void 0===e)return;const t=Object.entries(oe).find((([,t])=>t===e));return null==t?void 0:t[0]}_getSocketCloseError(e){if(e)return e instanceof Error?e.message:String(e)}_createSocketCloseFlushReason(e){return{type:(null==e?void 0:e.error)?"socket-error":"socket-close",socketClose:{code:null==e?void 0:e.code,codeName:this._getSocketCloseCodeName(null==e?void 0:e.code),reason:null==e?void 0:e.reason,wasClean:null==e?void 0:e.wasClean,error:this._getSocketCloseError(null==e?void 0:e.error)}}}onNetworkClose(e){var t,i,n,s;const o=null!==(i=null===(t=this.connection)||void 0===t?void 0:t.socketGeneration)&&void 0!==i?i:0,r=null!==(n=null==e?void 0:e.socketGeneration)&&void 0!==n?n:o;if(r<o)ke.debug(`Skipping stale onNetworkClose for socket generation ${r} (current generation is ${o})`);else if(r!==this._reconnectCountedGeneration){this._flushIntermediateCallReports(this._createSocketCloseFlushReason(e)),ke.debug("onNetworkClose called",{closeCode:null==e?void 0:e.code,closeReason:null==e?void 0:e.reason,wasClean:null==e?void 0:e.wasClean,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,autoReconnect:this._autoReconnect,reconnectAttempts:this._reconnectAttempts}),this.relayProtocol&&yt(this.relayProtocol);for(const e in this.subscriptions)yt(e);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.stopSignalingHealthMonitor(),this.sessionid&&this._autoReconnect&&Ye(this.sessionid),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect){const e=null!==(s=this.options.maxReconnectAttempts)&&void 0!==s?s:10;if(this._reconnectCountedGeneration=r,this._reconnectAttempts+=1,e>0&&this._reconnectAttempts>e){ke.info(`Reconnection exhausted after ${e} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1,this._terminateActiveCallsLocally();const t=me(k);return void _t(de.Error,{error:t,sessionId:this.sessionid},this.uuid)}const t=this.reconnectDelay;ke.debug(`Reconnect attempt ${this._reconnectAttempts}${e>0?` of ${e}`:""} (delay=${t}ms)`),this._reconnectTimeout=setTimeout((()=>{ke.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()}),t)}else if(ke.debug("auto_reconnect disabled, not reconnecting",{voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,intentionalClose:this._intentionalClose}),!this._intentionalClose){const e=he(ie);_t(de.Warning,{warning:e,reason:"auto_reconnect_disabled",sessionId:this.sessionid},this.uuid)}this._intentionalClose=!1}else ke.debug(`Skipping duplicate onNetworkClose for socket generation ${r} (already handled, reconnect attempt ${this._reconnectAttempts})`)}_onSocketMessage(e){}_removeSubscription(e,t){this._existsSubscription(e,t)&&(t?(delete this.subscriptions[e][t],ft(e,null,t)):(delete this.subscriptions[e],yt(e)))}_addSubscription(e,t=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},Ne(t)&&vt(e,t,i))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),ke.debug("Attaching socket event listeners"),this.on(de.SocketOpen,this._onSocketOpen),this.on(de.SocketClose,this.onNetworkClose),this.on(de.SocketError,this.onNetworkClose),this.on(de.SocketMessage,this._onSocketMessage),this.on(de.SocketActivity,this._onSocketActivity)}_detachListeners(){ke.debug("Detaching socket event listeners"),this.off(de.SocketOpen,this._onSocketOpen),this.off(de.SocketClose,this.onNetworkClose),this.off(de.SocketError,this.onNetworkClose),this.off(de.SocketMessage,this._onSocketMessage),this.off(de.SocketActivity,this._onSocketActivity)}_emptyExecuteQueues(){this._executeQueue.forEach((({resolve:e,msg:t})=>{"string"==typeof t?this.executeRaw(t):e(this.execute(t))}))}_closeConnection(){var e,t;this._idle=!0,clearTimeout(this._keepAliveTimeout),this.stopSignalingHealthMonitor(),ke.debug("_closeConnection called",{connected:null===(e=this.connection)||void 0===e?void 0:e.connected,socketGeneration:null===(t=this.connection)||void 0===t?void 0:t.socketGeneration,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0}),this.connection&&this.connection.close()}_resetKeepAlive(){!1===this._pong&&(ke.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Dt(Ke()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout((()=>this._resetKeepAlive()),35e3)}setPingReceived(){ke.debug("Ping received"),this._pong=!0}_onSocketActivity(){this._signalingHealthMonitor.onSocketActivity()}hasActiveCall(){const e=this.calls;if(!e)return!1;const t=new Set([ot.Early,ot.Active,ot.Held]);return Object.values(e).some((e=>e&&null!=e._state&&t.has(e._state)))}_terminateActiveCallsLocally(){const e=this.calls;if(!e)return;const t=Object.keys(e);if(0!==t.length){ke.debug(`Reconnection exhausted — locally terminating ${t.length} active call(s) (no BYE): ${t.join(", ")}`);for(const i of t){const t=e[i];null==t||t.hangup({},!1)}}}startSignalingHealthMonitor(){this._signalingHealthMonitor.start()}stopSignalingHealthMonitor(){this._signalingHealthMonitor.stop()}triggerIceRestart(e){const t=this.calls,i=null==t?void 0:t[e];if(!i)return ke.warn(`Signaling health: cannot trigger ICE restart — call ${e} not found`),{started:!1,reason:"call not found"};const n=i.peer;if(!(null==n?void 0:n.restartIce))return ke.warn(`Signaling health: cannot trigger ICE restart — no peer for call ${e}`),{started:!1,reason:"no peer"};const s=n.restartIce();return s.started||ke.debug(`Signaling health: ICE restart skipped for call ${e}: ${s.reason}`),s}onSignalingRequestTimeout(e,t,i=""){this._signalingHealthMonitor.onRequestTimeout(e,t,i)}reportPeerFailure(e,t){this._signalingHealthMonitor.onPeerFailure(e,t)}reportNoRtp(e,t){this._signalingHealthMonitor.onNoRtp(e,t)}reportIceRestartFailed(e){this._signalingHealthMonitor.onIceRestartFailed(e)}static on(e,t){vt(e,t)}static off(e){ft(e)}static uuid(){return a()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}Jt.TOKEN_EXPIRY_WARNING_SECONDS=120,Jt.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;const zt=e=>navigator.mediaDevices.getUserMedia(e),Qt=e=>e&&e instanceof MediaStream,Xt=(e,t)=>{const i=Le(e);null!==i&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=t)},Zt=(e,t)=>{const i=Le(e);if(i){if(t&&i.srcObject!==t)return;i.srcObject=null}},ei=(e,i)=>t(void 0,void 0,void 0,(function*(){const t=Le(e);if(null===t)return ke.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof i)return ke.info(`Invalid speaker deviceId: '${i}'`),!1;try{return yield t.setSinkId(i),!0}catch(e){return!1}})),ti=e=>{e&&"live"===e.readyState&&e.stop()},ii=e=>{Qt(e)&&e.getTracks().forEach(ti),e=null},ni=e=>t(void 0,void 0,void 0,(function*(){ke.info("RTCService.getUserMedia",e);const{audio:t,video:i}=e;if(!t&&!i)return null;try{return yield zt(e)}catch(t){if(ke.error("getUserMedia error: ",t),(e=>"NotReadableError"===e.name||"NotFoundError"===e.name||"OverconstrainedError"===e.name)(t)){const i=(e=>{const{audio:t,video:i}=e;let n=!1,s=t,o=i;if("object"==typeof t&&null!==t&&"deviceId"in t){n=!0;const e=Object.assign({},t);delete e.deviceId,s=0===Object.keys(e).length||e}if("object"==typeof i&&null!==i&&"deviceId"in i){n=!0;const e=Object.assign({},i);delete e.deviceId,o=0===Object.keys(e).length||e}return n?{audio:s,video:o}:null})(e);if(i){ke.warn("Device not found or not readable, falling back to default device");try{return yield zt(i)}catch(e){throw ke.error("Fallback getUserMedia also failed: ",e),t}}}throw t}})),si=(e=null,i=!1)=>t(void 0,void 0,void 0,(function*(){let t=[];const n=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===ct.AudioIn||e===ct.AudioOut,video:!e||e===ct.Video}))(e)).catch((e=>(ke.error(e),null)));if(n){if(ii(n),t=yield navigator.mediaDevices.enumerateDevices(),e&&(t=t.filter((t=>t.kind===e))),!0===i)return t;const s=[];t=t.filter((e=>{if(!e.groupId)return!0;const t=`${e.kind}-${e.groupId}`;return!s.includes(t)&&(s.push(t),!0)}))}return t})),oi=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],ri=(e,i,n)=>t(void 0,void 0,void 0,(function*(){const t=yield si(n,!0);for(let n=0;n<t.length;n++){const{deviceId:s,label:o}=t[n];if(e===s||i===o)return s}return null})),ai=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((i=>{t.hasOwnProperty(i)&&null!==e[i]&&void 0!==e[i]||delete e[i]}))},ci=e=>e?{id:e.id,kind:e.kind,enabled:e.enabled,muted:e.muted,readyState:e.readyState}:null,di=e=>{var t,i,n,s,o,r;if(!e)return[];return(null!==(i=null===(t=e.getTracks)||void 0===t?void 0:t.call(e))&&void 0!==i?i:[...null!==(s=null===(n=e.getAudioTracks)||void 0===n?void 0:n.call(e))&&void 0!==s?s:[],...null!==(r=null===(o=e.getVideoTracks)||void 0===o?void 0:o.call(e))&&void 0!==r?r:[]]).map((e=>ci(e)))},li=(e,t)=>{if(!e)return!1;const{subscribed:i,alreadySubscribed:n}=ui(e);return i.includes(t)||n.includes(t)},ui=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((i=>{t[i]=e[`${i}Channels`]||[]})),t},hi=(e,t=null,i=null)=>{if(!Qt(e))return null;let n=[];switch(t){case"audio":n=e.getAudioTracks();break;case"video":n=e.getVideoTracks();break;default:n=e.getTracks()}n.forEach((e=>{switch(i){case"on":case!0:e.enabled=!0;break;case"off":case!1:e.enabled=!1;break;default:e.enabled=!e.enabled}}))},pi=e=>{hi(e,"audio",!0)},gi=e=>{hi(e,"audio",!1)};function vi(){try{const{browserInfo:e,name:t,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 e=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),t=e[0],i=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:i,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const e=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),t=e[0],i=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:i,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const e=navigator.userAgent.match(/safari/gim)[0],t=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),i=parseInt(t[1],10);return{browserInfo:navigator.userAgent,name:e,version:i,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const e=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),t=e[0],i=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:i,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,c=window.navigator&&window.navigator.mediaDevices,d=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:e,browserName:t,browserVersion:i,supportWebRTC:!!(o&&r&&a&&c&&d),supportWebRTCAudio:n,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!ni}}catch(e){return e.message}}var mi;function fi(e,t){const i=document.getElementById(t);if(i)return i;if(e&&t){const i=document.createElement("audio");return i.id=t,i.loop=!0,i.src=e,i.preload="auto",i.load(),document.body.appendChild(i),i}return null}function _i(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then((()=>{e._playFulfilled=!0})).catch((t=>{ke.error("playAudio",t),e._playFulfilled=!0})))}function yi(e){e&&(e._playFulfilled?(e.pause(),e.currentTime=0):e._promise&&e._promise.then?e._promise.then((()=>{e.pause(),e.currentTime=0})):setTimeout((()=>{e.pause(),e.currentTime=0}),1e3))}!function(e){e.not_supported="not supported",e.full="full",e.partial="partial"}(mi||(mi={}));const bi=e=>{const t=[],i=[];return e&&0!==e.length?(e.forEach((e=>{const n=e.mimeType.toLocaleLowerCase();n.startsWith("audio/")?t.push(e):n.startsWith("video/")&&i.push(e)})),{audioCodecs:t,videoCodecs:i}):{audioCodecs:t,videoCodecs:i}};class Si extends wt{constructor(e,t){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:a(),type:"message",role:"user",content:[{type:"input_text",text:e},...null==t?void 0:t.map((e=>({type:"image_url",image_url:{url:e}})))]}}})}}class Ii extends wt{constructor(e){super(),this.method="ai_conversation",this.buildNotification({method:this.method,params:{type:"conversation.item.create",item:e}})}}class Ci{constructor(e,t){var i;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._lastLocalAudioTrackSnapshotJson=null,this._hasConfirmedLocalAudio=!1,this._confirmedLocalAudioSilenceMs=0,this._segmentIndex=0,this._flushing=!1,this._stopped=!1,this.options=e,this.logCollectorOptions=t||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this._lastIntermediateFlushTime=this.callStartTime,this.logCollectorOptions.enabled&&(this.logCollector=function(e){return new Ce(e)}(this.logCollectorOptions),this.logCollector.start(),i=this.logCollector,Ee=i)}start(e){var t,i;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._lastIntermediateFlushTime=this.intervalStartTime,this._stopped=!1,ke.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:Ci.INITIAL_COLLECTION_INTERVAL_MS,logCollectorActive:null!==(i=null===(t=this.logCollector)||void 0===t?void 0:t.isActive())&&void 0!==i&&i}),this._scheduleNextCollection())}stop(){var e,i;return t(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 t=null!==(i=null===(e=this.logCollector)||void 0===e?void 0:e.getLogCount())&&void 0!==i?i:0;this.logCollector&&this.logCollector.stop(),ke.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:t,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})}))}flush(e,t){var i,n,s,o;const r=this.statsBuffer.length,a=null!==(n=null===(i=this.logCollector)||void 0===i?void 0:i.getLogCount())&&void 0!==n?n:0,c="socket-close"===(null==t?void 0:t.type)||"socket-error"===(null==t?void 0:t.type),d=r>0||a>0||c;if(this._flushing||!d)return ke.debug("CallReportCollector: Skipping intermediate flush",{reason:this._flushing?"already-flushing":"no-stats-or-logs",flushReason:t,statsIntervals:r,logEntries:a}),null;this._flushing=!0;try{const i=this._segmentIndex++,n=this.statsBuffer;this.statsBuffer=[];const r=null!==(o=null===(s=this.logCollector)||void 0===s?void 0:s.drain())&&void 0!==o?o:[],a=new Date;this._lastIntermediateFlushTime=a;const c=Object.assign(Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(a.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:a.toISOString()}),stats:n},r.length>0?{logs:r}:{}),{segment:i}),t?{flushReason:t}:{});return ke.info("CallReportCollector: Flushed intermediate segment",{segment:i,intervals:n.length,logEntries:r.length,callId:e.callId,flushReason:t}),c}finally{this._flushing=!1}}postReport(e,i,n,s){var o,r;return t(this,void 0,void 0,(function*(){const t=null===(o=this.logCollector)||void 0===o?void 0:o.getLogs(),a=t&&t.length>0;if(!this.options.enabled)return void ke.info("CallReportCollector: Skipping report — call reports disabled");if(0===this.statsBuffer.length&&!a)return void ke.info("CallReportCollector: Skipping report — no stats or logs collected");const c=this._segmentIndex>0,d=this._segmentIndex,l=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:null===(r=this.callEndTime)||void 0===r?void 0:r.toISOString()}),stats:this.statsBuffer},t&&t.length>0?{logs:t}:{}),c?{segment:d}:{});yield this._sendPayload(l,i,n,s,!0)}))}sendPayload(e,i,n,s){return t(this,void 0,void 0,(function*(){yield this._sendPayload(e,i,n,s,!1)}))}_sendPayload(e,i,n,s,o=!0){var r,a;return t(this,void 0,void 0,(function*(){const t=new URL(n),c=`${t.protocol.replace(/^ws/,"http")}//${t.host}/call_report`,d=o?"final report":`intermediate segment ${e.segment}`;ke.info(`CallReportCollector: Posting ${d}`,{endpoint:c,intervals:e.stats.length,logEntries:null!==(a=null===(r=e.logs)||void 0===r?void 0:r.length)&&void 0!==a?a:0,callId:e.summary.callId,segment:e.segment});const l={"Content-Type":"application/json","x-call-report-id":i,"x-call-id":e.summary.callId};s&&(l["x-voice-sdk-id"]=s);const u=JSON.stringify(e),h=o&&u.length<=Ci.KEEPALIVE_BODY_LIMIT_BYTES;let p;for(let e=0;e<=Ci.RETRY_DELAYS_MS.length;e++){try{const t=yield fetch(c,Object.assign({method:"POST",headers:l,body:u},h?{keepalive:!0}:{}));if(t.ok)return void ke.info(`CallReportCollector: Successfully posted ${d}`,{attempt:e+1,status:t.status});{const i=yield t.text();p=new Error(`Call report POST failed with status ${t.status}`),ke.error(`CallReportCollector: Failed to post ${d}`,{attempt:e+1,status:t.status,error:i})}}catch(t){p=t,ke.warn(`CallReportCollector: Network error posting ${d}`,{attempt:e+1,error:t})}const t=Ci.RETRY_DELAYS_MS[e];if(void 0===t)break;ke.info(`CallReportCollector: Retrying ${d} in ${t}ms`,{attempt:e+2}),yield new Promise((e=>setTimeout(e,t)))}throw ke.error(`CallReportCollector: Exhausted retries posting ${d}`,{error:p}),p instanceof Error?p:new Error("Call report POST failed after retries")}))}getStatsBuffer(){return this.statsBuffer}shouldForceRelayCandidateForRecovery(){var e,t,i,n,s,o,r,a,c,d,l,u,h,p,g,v;if(this.statsBuffer.length<2)return!1;const m=this.statsBuffer[this.statsBuffer.length-1],f=this.statsBuffer[this.statsBuffer.length-2],_=null===(e=m.ice)||void 0===e?void 0:e.local;if(!("vpn"===(null==_?void 0:_.networkType)&&"relay"!==(null==_?void 0:_.candidateType)))return!1;const y=!1===(null===(t=m.ice)||void 0===t?void 0:t.writable),b="disconnected"===(null===(i=m.transport)||void 0===i?void 0:i.iceState)||"failed"===(null===(n=m.transport)||void 0===n?void 0:n.iceState),S=this._positiveDelta(null===(s=m.ice)||void 0===s?void 0:s.requestsSent,null===(o=f.ice)||void 0===o?void 0:o.requestsSent),I=this._positiveDelta(null===(r=m.ice)||void 0===r?void 0:r.responsesReceived,null===(a=f.ice)||void 0===a?void 0:a.responsesReceived),C=S>0&&0===I,E=this._positiveDelta(null===(d=null===(c=m.audio)||void 0===c?void 0:c.outbound)||void 0===d?void 0:d.bytesSent,null===(u=null===(l=f.audio)||void 0===l?void 0:l.outbound)||void 0===u?void 0:u.bytesSent),k=this._positiveDelta(null===(p=null===(h=m.audio)||void 0===h?void 0:h.inbound)||void 0===p?void 0:p.bytesReceived,null===(v=null===(g=f.audio)||void 0===g?void 0:g.inbound)||void 0===v?void 0:v.bytesReceived);return y||b||C||E>0&&0===k}getLogs(){var e,t;return null!==(t=null===(e=this.logCollector)||void 0===e?void 0:e.getLogs())&&void 0!==t?t:[]}_positiveDelta(e,t){return void 0===e||void 0===t?0:Math.max(0,e-t)}cleanup(){this._lastLocalAudioTrackSnapshotJson=null,this.logCollector&&(this.logCollector.clear(),this.logCollector=null)}_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(Ci.INITIAL_COLLECTION_INTERVAL_MS,e)}_positiveInterval(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}_collectStats(e=!1){var i,n;return t(this,void 0,void 0,(function*(){if(this.peerConnection&&this.intervalStartTime)try{const t=yield this.peerConnection.getStats(),s=new Date;let o=null,r=null,a=null,c=null,d=null,l=null;const u=[];let h=null;t.forEach((e=>{switch(e.type){case"outbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(o=e);break;case"inbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(r=e);break;case"media-playout":"audio"===e.kind&&(a=e);break;case"remote-inbound-rtp":"audio"===e.kind&&(c=e);break;case"remote-outbound-rtp":"audio"===e.kind&&(d=e);break;case"candidate-pair":(e.nominated||"succeeded"===e.state)&&u.push(e);break;case"transport":h=e}}));const p=null==h?void 0:h.selectedCandidatePairId,g=p?null===(n=(i=t).get)||void 0===n?void 0:n.call(i,p):void 0,v=this._getCodec(t,null==o?void 0:o.codecId),m=this._getCodec(t,null==r?void 0:r.codecId);if(l="candidate-pair"===(null==g?void 0:g.type)?g:p?u.find((e=>e.id===p))||u[u.length-1]||null:u[u.length-1]||null,o){const e=this._getOutboundAudioLevel(t,o);if(null!==e&&this.intervalAudioLevels.outbound.push(e),void 0!==this.previousStats.outboundBytes&&void 0!==this.previousStats.timestamp){const e=(o.bytesSent||0)-this.previousStats.outboundBytes,t=(o.timestamp||s.getTime())-this.previousStats.timestamp;if(t>0){const i=8*e*1e3/t;this.intervalBitrates.outbound.push(i)}}this.previousStats.outboundBytes=o.bytesSent}if(r){const e=this._getInboundAudioLevel(t,r);if(null!==e&&this.intervalAudioLevels.inbound.push(e),void 0!==r.jitter&&this.intervalJitters.push(1e3*r.jitter),void 0!==this.previousStats.inboundBytes&&void 0!==this.previousStats.timestamp){const e=(r.bytesReceived||0)-this.previousStats.inboundBytes,t=(r.timestamp||s.getTime())-this.previousStats.timestamp;if(t>0){const i=8*e*1e3/t;this.intervalBitrates.inbound.push(i)}}this.previousStats.inboundBytes=r.bytesReceived}let f,_,y,b,S;l&&void 0!==l.currentRoundTripTime&&this.intervalRTTs.push(l.currentRoundTripTime),l&&(f=this._resolveCandidate(t,l.localCandidateId),_=this._resolveCandidate(t,l.remoteCandidateId)),l&&(y=Object.assign(Object.assign({id:l.id,localCandidateId:l.localCandidateId,remoteCandidateId:l.remoteCandidateId,state:l.state,nominated:l.nominated,writable:l.writable,currentRoundTripTime:l.currentRoundTripTime,requestsSent:l.requestsSent,responsesReceived:l.responsesReceived},f?{local:f}:{}),_?{remote:_}:{}),null!==this.previousCandidatePairSnapshot&&l.id!==this.previousCandidatePairSnapshot.id&&(ke.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:y}),this._emitWarning(Y)),this.previousCandidatePairSnapshot=y),o&&(b=this._getLocalAudioTrackSnapshot(),S=this._getOutboundAudioSourceStats(t,o)),this._logLocalAudioTrackSnapshot(b,S),this.previousStats.timestamp=s.getTime();const I=s.getTime()-this.intervalStartTime.getTime(),C=this._collectionIntervalFor();if(e||I>=C){const e=this._createStatsEntry(this.intervalStartTime,s,o,r,l,f,_,h,b,S,a,c,d,v,m);this.statsBuffer.push(e),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),ke.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(e,r),this._requestIntermediateFlushIfNeeded(s),this.intervalStartTime=s,this._resetIntervalAccumulators()}}catch(e){ke.error("CallReportCollector: Error collecting stats",{error:e})}}))}_getIntermediateReportInterval(){var e;return null!==(e=this.options.intermediateReportInterval)&&void 0!==e?e:Ci.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS}_requestIntermediateFlushIfNeeded(e){var t,i;const n=this.statsBuffer.length,s=null!==(i=null===(t=this.logCollector)||void 0===t?void 0:t.getLogCount())&&void 0!==i?i:0;if(!this.onFlushNeeded||this._flushing)return;if(0===n&&0===s)return void ke.debug("CallReportCollector: Skipping intermediate flush request — no stats or logs buffered");const o=this._getIntermediateReportInterval(),r=e.getTime()-this._lastIntermediateFlushTime.getTime();let a=null;if(n>=Ci.STATS_FLUSH_THRESHOLD||s>=Ci.LOGS_FLUSH_THRESHOLD?a="buffer-limit":o>0&&r>=o&&(a="safety-interval"),a){ke.info("CallReportCollector: Requesting intermediate report flush",{reason:a,statsIntervals:n,logEntries:s,msSinceLastFlush:r}),this._lastIntermediateFlushTime=e;try{this.onFlushNeeded()}catch(e){ke.error("CallReportCollector: onFlushNeeded callback error",{error:e})}}}_checkQualityWarnings(e,t){var i,n,s,o,r,a,c,d,l,u,h,p,g,v,m;if(!this.onWarning)return;const f=null===(i=e.connection)||void 0===i?void 0:i.roundTripTimeAvg,_=null===(s=null===(n=e.audio)||void 0===n?void 0:n.inbound)||void 0===s?void 0:s.jitterAvg;let y;if(t){const e=null!==(o=t.packetsReceived)&&void 0!==o?o:0,i=null!==(r=t.packetsLost)&&void 0!==r?r:0;if(null!==this._prevPacketsReceived&&null!==this._prevPacketsLost){const t=e-this._prevPacketsReceived,n=i-this._prevPacketsLost,s=t+n;s>0&&(y=n/s*100)}this._prevPacketsReceived=e,this._prevPacketsLost=i}if(this._trackBreach(P,void 0!==f&&f>Ci.THRESHOLD_RTT_MS),this._trackBreach(M,void 0!==_&&_>Ci.THRESHOLD_JITTER_MS),this._trackBreach(x,void 0!==y&&y>Ci.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),this._trackLowInboundAudio(e),void 0!==f&&void 0!==_&&void 0!==y){const e=93.2-.11*_-2.5*y-.01*(1e3*f),t=Math.max(1,Math.min(4.5,1+.035*e+e*(e-60)*(100-e)*7e-6));this._trackBreach(U,t<Ci.THRESHOLD_MOS)}else this._trackBreach(U,!1);if(void 0!==(null===(c=null===(a=e.audio)||void 0===a?void 0:a.inbound)||void 0===c?void 0:c.bytesReceived)){const t=null===(u=null===(l=null===(d=this._previousStatsEntryForWarnings)||void 0===d?void 0:d.audio)||void 0===l?void 0:l.inbound)||void 0===u?void 0:u.bytesReceived,i=e.audio.inbound.bytesReceived;this._trackBreach($,void 0!==t&&i-t==0)}if(void 0!==(null===(p=null===(h=e.audio)||void 0===h?void 0:h.outbound)||void 0===p?void 0:p.bytesSent)){const t=null===(m=null===(v=null===(g=this._previousStatsEntryForWarnings)||void 0===g?void 0:g.audio)||void 0===v?void 0:v.outbound)||void 0===m?void 0:m.bytesSent,i=e.audio.outbound.bytesSent;this._trackBreach(H,void 0!==t&&i-t==0)}this._previousStatsEntryForWarnings=e}_trackLowLocalAudio(e){var t;const i=null===(t=e.audio)||void 0===t?void 0:t.outbound,n=null==i?void 0:i.audioLevelAvg,s=null==i?void 0:i.localTrack;if(void 0===n||!1===(null==s?void 0:s.enabled)||!0===(null==s?void 0:s.muted))return void this._resetLowLocalAudioWarning();if(!(n<=Ci.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(F,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=Ci.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(F)):this._trackBreach(F,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(F,!1)}_getStatsIntervalDurationMs(e){const t=new Date(e.intervalStartUtc).getTime(),i=new Date(e.intervalEndUtc).getTime()-t;return Number.isFinite(i)&&i>0?i:this.options.interval}_trackLowInboundAudio(e){var t;const i=null===(t=e.audio)||void 0===t?void 0:t.inbound,n=null==i?void 0:i.audioLevelAvg;if(void 0===n)return void this._trackBreach(j,!1);const s=n<=Ci.THRESHOLD_INBOUND_AUDIO_LEVEL;this._trackBreach(j,s)}_trackBreach(e,t){var i,n;if(t){if(this._breachCounters[e]=(null!==(i=this._breachCounters[e])&&void 0!==i?i:0)+1,this._breachCounters[e]>=Ci.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const t=Date.now();t-(null!==(n=this._lastWarningEmitted[e])&&void 0!==n?n:0)>=Ci.WARNING_THROTTLE_MS&&(this._lastWarningEmitted[e]=t,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 t;try{const i=he(e);ke.warn(`CallReportCollector: warning ${i.code}: ${i.message}`),null===(t=this.onWarning)||void 0===t||t.call(this,i)}catch(t){ke.error(`CallReportCollector: Failed to emit warning ${e}`,{error:t})}}_createStatsEntry(e,t,i,n,s,o,r,a,c,d,l,u,h,p,g){const v={intervalStartUtc:e.toISOString(),intervalEndUtc:t.toISOString(),audio:{}};if(i&&(v.audio.outbound=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({packetsSent:i.packetsSent,bytesSent:i.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)},c?{localTrack:c}:{}),d?{mediaSource:d}:{}),void 0!==i.retransmittedPacketsSent?{retransmittedPacketsSent:i.retransmittedPacketsSent}:{}),void 0!==i.retransmittedBytesSent?{retransmittedBytesSent:i.retransmittedBytesSent}:{}),void 0!==i.headerBytesSent?{headerBytesSent:i.headerBytesSent}:{}),void 0!==i.nackCount?{nackCount:i.nackCount}:{}),void 0!==i.targetBitrate?{targetBitrate:i.targetBitrate}:{}),void 0!==i.totalPacketSendDelay?{totalPacketSendDelay:i.totalPacketSendDelay}:{}),void 0!==i.active?{active:i.active}:{}),p?{codec:this._buildCodecSnapshot(p,i.codecId)}:{})),n&&(v.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:n.packetsReceived,bytesReceived:n.bytesReceived,packetsLost:n.packetsLost,packetsDiscarded:n.packetsDiscarded,jitterBufferDelay:n.jitterBufferDelay,jitterBufferEmittedCount:n.jitterBufferEmittedCount,totalSamplesReceived:n.totalSamplesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,audioLevelAvg:this._average(this.intervalAudioLevels.inbound),jitterAvg:this._average(this.intervalJitters),bitrateAvg:this._average(this.intervalBitrates.inbound)},void 0!==n.nackCount?{nackCount:n.nackCount}:{}),void 0!==n.headerBytesReceived?{headerBytesReceived:n.headerBytesReceived}:{}),void 0!==n.fecPacketsReceived?{fecPacketsReceived:n.fecPacketsReceived}:{}),void 0!==n.fecPacketsDiscarded?{fecPacketsDiscarded:n.fecPacketsDiscarded}:{}),void 0!==n.jitterBufferTargetDelay?{jitterBufferTargetDelay:n.jitterBufferTargetDelay}:{}),void 0!==n.jitterBufferMinimumDelay?{jitterBufferMinimumDelay:n.jitterBufferMinimumDelay}:{}),void 0!==n.totalSamplesDecoded?{totalSamplesDecoded:n.totalSamplesDecoded}:{}),void 0!==n.samplesDecodedWithSilence?{samplesDecodedWithSilence:n.samplesDecodedWithSilence}:{}),void 0!==n.samplesDecodedWithConcealment?{samplesDecodedWithConcealment:n.samplesDecodedWithConcealment}:{}),void 0!==n.totalAudioEnergy?{totalAudioEnergy:n.totalAudioEnergy}:{}),void 0!==n.totalSamplesDuration?{totalSamplesDuration:n.totalSamplesDuration}:{}),g?{codec:this._buildCodecSnapshot(g,n.codecId)}:{})),s&&(v.connection=Object.assign(Object.assign({roundTripTimeAvg:this._average(this.intervalRTTs),currentRoundTripTime:s.currentRoundTripTime},void 0!==s.currentRoundTripTime?{roundTripTimeSource:"candidate-pair.currentRoundTripTime"}:{}),{packetsSent:s.packetsSent,packetsReceived:s.packetsReceived,bytesSent:s.bytesSent,bytesReceived:s.bytesReceived}),v.ice=Object.assign(Object.assign({id:s.id,localCandidateId:s.localCandidateId,remoteCandidateId:s.remoteCandidateId,state:s.state,nominated:s.nominated,writable:s.writable,currentRoundTripTime:s.currentRoundTripTime,requestsSent:s.requestsSent,responsesReceived:s.responsesReceived},o?{local:o}:{}),r?{remote:r}:{})),a&&(v.transport=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==a.iceState?{iceState:a.iceState}:{}),void 0!==a.dtlsState?{dtlsState:a.dtlsState}:{}),void 0!==a.srtpCipher?{srtpCipher:a.srtpCipher}:{}),void 0!==a.tlsVersion?{tlsVersion:a.tlsVersion}:{}),void 0!==a.selectedCandidatePairChanges?{selectedCandidatePairChanges:a.selectedCandidatePairChanges}:{}),void 0!==a.selectedCandidatePairId?{selectedCandidatePairId:a.selectedCandidatePairId}:{})),l&&(v.mediaPlayout=this._withoutUndefined({synthesizedSamples:l.synthesizedSamples,synthesizedDuration:l.synthesizedDuration,totalPlayoutDelay:l.totalPlayoutDelay,totalSampleCount:l.totalSampleCount})),u||h){const e={};if(u){const t=void 0!==u.jitter?1e3*u.jitter:void 0;let i;"number"==typeof u.totalRoundTripTime&&"number"==typeof u.roundTripTimeMeasurements&&u.roundTripTimeMeasurements>0&&(i=u.totalRoundTripTime/u.roundTripTimeMeasurements),e.inbound=this._withoutUndefined({packetsReceived:u.packetsReceived,packetsLost:u.packetsLost,fractionLost:u.fractionLost,jitter:t,roundTripTime:u.roundTripTime,totalRoundTripTime:u.totalRoundTripTime,roundTripTimeMeasurements:u.roundTripTimeMeasurements,roundTripTimeAvg:i,nackCount:u.nackCount,reportsReceived:u.reportsReceived,packetsDiscarded:u.packetsDiscarded})}h&&(e.outbound=this._withoutUndefined({packetsSent:h.packetsSent,bytesSent:h.bytesSent,reportsCount:h.reportsCount,roundTripTime:h.roundTripTime,totalPacketSendDelay:h.totalPacketSendDelay})),v.remoteRtcp=e}return v}_resolveCandidate(e,t){if(!t)return void ke.debug("CallReportCollector: candidateId is empty, skipping resolve");const i=e.get(t);if(!i)return void ke.debug("CallReportCollector: candidate not found in stats report",{candidateId:t});const n={};if(void 0!==i.id&&(n.id=i.id),void 0!==i.address?n.address=i.address:void 0!==i.ip&&(n.address=i.ip),void 0!==i.port&&(n.port=i.port),void 0!==i.candidateType&&(n.candidateType=i.candidateType),void 0!==i.protocol&&(n.protocol=i.protocol),void 0!==i.networkType&&(n.networkType=i.networkType),void 0!==i.url&&(n.url=i.url),void 0!==i.relayProtocol&&(n.relayProtocol=i.relayProtocol),0!==Object.keys(n).length)return n;ke.debug("CallReportCollector: candidate report has no usable fields",{candidateId:t})}_getCodec(e,t){if(!t)return;const i=e.get(t);return i&&"codec"===i.type?i:void 0}_buildCodecSnapshot(e,t){const i=this._withoutUndefined(Object.assign({mimeType:e.mimeType,clockRate:e.clockRate,channels:e.channels,payloadType:e.payloadType,sdpFmtpLine:e.sdpFmtpLine},void 0!==t?{codecId:t}:{}));return Object.keys(i).length>0?i:void 0}_getOutboundMediaSource(e,t){let i;return t.mediaSourceId&&(i=e.get(t.mediaSourceId)),i||e.forEach((e=>{i||"media-source"!==e.type||"audio"!==e.kind||(i=e)})),i}_getLocalAudioTrackSnapshot(){var e,t;try{const i=null===(e=this.peerConnection)||void 0===e?void 0:e.getSenders().find((e=>{var t;return"audio"===(null===(t=e.track)||void 0===t?void 0:t.kind)})),n=null==i?void 0:i.track;if(!n)return;const s=null===(t=n.getSettings)||void 0===t?void 0:t.call(n),o=this._withoutUndefined({deviceId:null==s?void 0:s.deviceId,groupId:null==s?void 0:s.groupId,channelCount:null==s?void 0:s.channelCount,sampleRate:null==s?void 0:s.sampleRate,sampleSize:null==s?void 0:s.sampleSize,latency:null==s?void 0:s.latency,echoCancellation:null==s?void 0:s.echoCancellation,noiseSuppression:null==s?void 0:s.noiseSuppression,autoGainControl:null==s?void 0:s.autoGainControl}),r=this._withoutUndefined(Object.assign({id:n.id,label:n.label,enabled:n.enabled,muted:n.muted,readyState:n.readyState,contentHint:n.contentHint},Object.keys(o).length>0?{settings:o}:{}));return Object.keys(r).length>0?r:void 0}catch(e){return void ke.debug("CallReportCollector: unable to snapshot local audio track",{error:e})}}_getOutboundAudioSourceStats(e,t){const i=this._getOutboundMediaSource(e,t);if(!i)return;const n=this._withoutUndefined({id:i.id,trackIdentifier:i.trackIdentifier,audioLevel:i.audioLevel,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration,echoReturnLoss:i.echoReturnLoss,echoReturnLossEnhancement:i.echoReturnLossEnhancement});return Object.keys(n).length>0?n:void 0}_logLocalAudioTrackSnapshot(e,t){if(!e||0===Object.keys(e).length)return;const i=this._stableStringify(e);i!==this._lastLocalAudioTrackSnapshotJson&&(this._lastLocalAudioTrackSnapshotJson=i,ke.debug("CallReportCollector: local audio track snapshot",{localTrack:e,mediaSource:t}))}_withoutUndefined(e){return Object.keys(e).reduce(((t,i)=>{const n=e[i];return void 0!==n&&(t[i]=n),t}),{})}_stableStringify(e){return JSON.stringify(this._sortObjectKeys(e))}_sortObjectKeys(e){return Array.isArray(e)?e.map((e=>this._sortObjectKeys(e))):e&&"object"==typeof e?Object.keys(e).sort().reduce(((t,i)=>(t[i]=this._sortObjectKeys(e[i]),t)),{}):e}_getOutboundAudioLevel(e,t){const i=this._getOutboundMediaSource(e,t);if(void 0!==(null==i?void 0:i.audioLevel))return i.audioLevel;if(i){const e=this._computeAudioLevelFromEnergy(i.totalAudioEnergy,i.totalSamplesDuration,"outbound");if(null!==e)return e}return this._getTrackAudioLevel(e,t.trackId)}_getInboundAudioLevel(e,t){if(void 0!==t.audioLevel)return t.audioLevel;const i=this._computeAudioLevelFromEnergy(t.totalAudioEnergy,t.totalSamplesDuration,"inbound");return null!==i?i:this._getTrackAudioLevel(e,t.trackId)}_computeAudioLevelFromEnergy(e,t,i){if(void 0===e||void 0===t)return null;const n="inbound"===i?"inboundAudioEnergy":"outboundAudioEnergy",s="inbound"===i?"inboundSamplesDuration":"outboundSamplesDuration",o=this.previousStats[n],r=this.previousStats[s];if(this.previousStats[n]=e,this.previousStats[s]=t,void 0===o||void 0===r)return null;const a=e-o,c=t-r;if(c<=0)return null;const d=Math.sqrt(a/c);return Math.min(1,Math.max(0,d))}_getTrackAudioLevel(e,t){var i;if(!t)return null;const n=e.get(t);return n&&null!==(i=n.audioLevel)&&void 0!==i?i:null}_average(e){if(0===e.length)return;const t=e.reduce(((e,t)=>e+t),0);return parseFloat((t/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}Ci.INITIAL_COLLECTION_INTERVAL_MS=1e3,Ci.STATS_FLUSH_THRESHOLD=300,Ci.LOGS_FLUSH_THRESHOLD=800,Ci.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,Ci.CONSECUTIVE_BREACHES_REQUIRED=3,Ci.THRESHOLD_RTT_MS=.4,Ci.THRESHOLD_JITTER_MS=30,Ci.THRESHOLD_PACKET_LOSS_PCT=1,Ci.THRESHOLD_MOS=3.5,Ci.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,Ci.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,Ci.THRESHOLD_INBOUND_AUDIO_LEVEL=.001,Ci.WARNING_THROTTLE_MS=15e3,Ci.RETRY_DELAYS_MS=[500,1e3,2e3],Ci.KEEPALIVE_BODY_LIMIT_BYTES=61440;class Ei{constructor(){this._rawDeviceCache=[],this._deviceChangeHandler=null,this._stopped=!1}logDevicesAtStart(){return t(this,void 0,void 0,(function*(){try{const e=yield this._enumerateAudioDevices();this._rawDeviceCache=e,ke.debug("MediaDeviceCollector: devices at call start",{devices:e}),this._startDeviceChangeListener()}catch(e){ke.debug("MediaDeviceCollector: failed to log devices at start",{error:e})}}))}stop(){this._stopped=!0,this._removeDeviceChangeListener()}_enumerateAudioDevices(){return t(this,void 0,void 0,(function*(){try{if("undefined"!=typeof navigator&&navigator.mediaDevices&&"function"==typeof navigator.mediaDevices.enumerateDevices){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind||"audiooutput"===e.kind))}}catch(e){ke.debug("MediaDeviceCollector: enumerateDevices failed",{error:e})}return[]}))}_startDeviceChangeListener(){"undefined"!=typeof navigator&&navigator.mediaDevices&&"function"==typeof navigator.mediaDevices.addEventListener&&(this._deviceChangeHandler=()=>{this._onDeviceChange()},navigator.mediaDevices.addEventListener("devicechange",this._deviceChangeHandler))}_removeDeviceChangeListener(){this._deviceChangeHandler&&"undefined"!=typeof navigator&&navigator.mediaDevices&&"function"==typeof navigator.mediaDevices.removeEventListener&&navigator.mediaDevices.removeEventListener("devicechange",this._deviceChangeHandler),this._deviceChangeHandler=null}_onDeviceChange(){return t(this,void 0,void 0,(function*(){if(!this._stopped)try{const e=yield this._enumerateAudioDevices(),t=new Set(this._rawDeviceCache.map((e=>e.deviceId))),i=new Set(e.map((e=>e.deviceId))),n=e.filter((e=>!t.has(e.deviceId))),s=this._rawDeviceCache.filter((e=>!i.has(e.deviceId)));(n.length>0||s.length>0)&&ke.debug("MediaDeviceCollector: devices changed during call",{connected:n,disconnected:s}),this._rawDeviceCache=e}catch(e){ke.debug("MediaDeviceCollector: error handling devicechange",{error:e})}}))}}var ki,wi=be((function(e,t){var i;function n(){}function s(){s.init.call(this)}function o(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function r(e,t,i,s){var r,a,c;if("function"!=typeof i)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),a=e._events),c=a[t]):(a=e._events=new n,e._eventsCount=0),c){if("function"==typeof c?c=a[t]=s?[i,c]:[c,i]:s?c.unshift(i):c.push(i),!c.warned&&((r=o(e))&&0<r&&c.length>r)){c.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=c.length,function(e){"function"==typeof console.warn?console.warn(e):console.log(e)}(d)}}else c=a[t]=i,++e._eventsCount;return e}function a(e,t,i){function n(){e.removeListener(t,n),s||(s=!0,i.apply(e,arguments))}var s=!1;return n.listener=i,n}function c(e){var t=this._events;if(t){var i=t[e];if("function"==typeof i)return 1;if(i)return i.length}return 0}function d(e,t){for(var i=Array(t);t--;)i[t]=e[t];return i}Object.defineProperty(t,"__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(e){if("number"!=typeof e||0>e||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(e){var t,i,n,s,o,r,a,c="error"===e;if(r=this._events)c=c&&null==r.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(i=r[e]))return!1;var u="function"==typeof i;switch(n=arguments.length){case 1:!function(e,t,i){if(t)e.call(i);else for(var n=e.length,s=d(e,n),o=0;o<n;++o)s[o].call(i)}(i,u,this);break;case 2:!function(e,t,i,n){if(t)e.call(i,n);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].call(i,n)}(i,u,this,arguments[1]);break;case 3:!function(e,t,i,n,s){if(t)e.call(i,n,s);else for(var o=e.length,r=d(e,o),a=0;a<o;++a)r[a].call(i,n,s)}(i,u,this,arguments[1],arguments[2]);break;case 4:!function(e,t,i,n,s,o){if(t)e.call(i,n,s,o);else for(var r=e.length,a=d(e,r),c=0;c<r;++c)a[c].call(i,n,s,o)}(i,u,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=Array(n-1),o=1;o<n;o++)s[o-1]=arguments[o];!function(e,t,i,n){if(t)e.apply(i,n);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].apply(i,n)}(i,u,this,s)}return!0},s.prototype.addListener=function(e,t){return r(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return r(this,e,t,!0)},s.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,a(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,a(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,s,o,r,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(s=this._events))return this;if(!(i=s[e]))return this;if(i===t||i.listener&&i.listener===t)0==--this._eventsCount?this._events=new n:(delete s[e],s.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(o=-1,r=i.length;0<r--;)if(i[r]===t||i[r].listener&&i[r].listener===t){a=i[r].listener,o=r;break}if(0>o)return this;if(1===i.length){if(i[0]=void 0,0==--this._eventsCount)return this._events=new n,this;delete s[e]}else!function(e,t){for(var i=t,n=i+1,s=e.length;n<s;i+=1,n+=1)e[i]=e[n];e.pop()}(i,o);s.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.removeAllListeners=function(e){var t,i;if(!(i=this._events))return this;if(!i.removeListener)return 0===arguments.length?(this._events=new n,this._eventsCount=0):i[e]&&(0==--this._eventsCount?this._events=new n:delete i[e]),this;if(0===arguments.length){for(var s,o=Object.keys(i),r=0;r<o.length;++r)"removeListener"!==(s=o[r])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=new n,this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},s.prototype.listeners=function(e){var t,i,n=this._events;return n?i=(t=n[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(t):[]:i=[],i},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):c.call(e,t)},s.prototype.listenerCount=c,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var l,u=new Uint8Array(16);function h(){if(!l&&!(l="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return l(u)}var p=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;for(var g=[],v=0;256>v;++v)g.push((v+256).toString(16).substr(1));function m(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:0,i=(g[e[t+0]]+g[e[t+1]]+g[e[t+2]]+g[e[t+3]]+"-"+g[e[t+4]]+g[e[t+5]]+"-"+g[e[t+6]]+g[e[t+7]]+"-"+g[e[t+8]]+g[e[t+9]]+"-"+g[e[t+10]]+g[e[t+11]]+g[e[t+12]]+g[e[t+13]]+g[e[t+14]]+g[e[t+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&p.test(e)}(i))throw TypeError("Stringified UUID is invalid");return i}function f(e,t,i){var n=(e=e||{}).random||(e.rng||h)();if(n[6]=64|15&n[6],n[8]=128|63&n[8],t){i=i||0;for(var s=0;16>s;++s)t[i+s]=n[s];return t}return m(n)}function _(e,t){if(!e||!t)return{};const i={...e};if(i.localCandidateId){const e=t.get(i.localCandidateId);i.local={...e}}if(i.remoteCandidateId){const e=t.get(i.remoteCandidateId);i.remote={...e}}return i}function y(e,t,i){return 8*function(e,t,i){const n=e[i],s=t?t[i]:null;return null===n||null===s?null:(n-s)/(e.timestamp-t.timestamp)*1e3}(e,t,i)}function b(e){if(!e.entries)return e;const t={};return e.forEach((function(e,i){t[i]=e})),t}function S(e,t,i={}){if(!e)return null;let n={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};i.remote&&(n.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const t of e.values())switch(t.type){case"outbound-rtp":{const i=t.mediaType||t.kind,s={};let o={};if(!["audio","video"].includes(i))continue;if(t.codecId){const i=e.get(t.codecId);i&&(s.clockRate=i.clockRate,s.mimeType=i.mimeType,s.payloadType=i.payloadType)}o=e.get(t.mediaSourceId)||e.get(t.trackId)||{},n[i].outbound.push({...t,...s,track:{...o}});break}case"inbound-rtp":{let i=t.mediaType||t.kind,s={};const o={};if(!["audio","video"].includes(i))if(t.id.includes("Video"))i="video";else{if(!t.id.includes("Audio"))continue;i="audio"}if(t.codecId){const i=e.get(t.codecId);i&&(o.clockRate=i.clockRate,o.mimeType=i.mimeType,o.payloadType=i.payloadType)}if(!n.connection.id&&t.transportId){const i=e.get(t.transportId);if(i&&i.selectedCandidatePairId){const t=e.get(i.selectedCandidatePairId);n.connection=_(t,e)}}s=e.get(t.mediaSourceId)||e.get(t.trackId)||{},n[i].inbound.push({...t,...o,track:{...s}});break}case"peer-connection":n.connection.dataChannelsClosed=t.dataChannelsClosed,n.connection.dataChannelsOpened=t.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!i.remote)break;let s=t.mediaType||t.kind;const o={};if(!["audio","video"].includes(s))if(t.id.includes("Video"))s="video";else{if(!t.id.includes("Audio"))continue;s="audio"}if(t.codecId){const i=e.get(t.codecId);i&&(o.clockRate=i.clockRate,o.mimeType=i.mimeType,o.payloadType=i.payloadType)}if(!n.connection.id&&t.transportId){const i=e.get(t.transportId);if(i&&i.selectedCandidatePairId){const t=e.get(i.selectedCandidatePairId);n.connection=_(t,e)}}n.remote[s].inbound.push({...t,...o});break}case"remote-outbound-rtp":{if(!i.remote)break;const s=t.mediaType||t.kind,o={};if(!["audio","video"].includes(s))continue;if(t.codecId){const i=e.get(t.codecId);i&&(o.clockRate=i.clockRate,o.mimeType=i.mimeType,o.payloadType=i.payloadType)}n.remote[s].outbound.push({...t,...o});break}}if(!n.connection.id)for(const t of e.values())"candidate-pair"===t.type&&t.nominated&&"succeeded"===t.state&&(n.connection=_(t,e));return n=function(e,t){return t?(e.audio.inbound.map((e=>{let i=t.audio.inbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesReceived"),e.packetRate=y(e,i,"packetsReceived")})),e.audio.outbound.map((e=>{let i=t.audio.outbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesSent"),e.packetRate=y(e,i,"packetsSent")})),e.video.inbound.map((e=>{let i=t.video.inbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesReceived"),e.packetRate=y(e,i,"packetsReceived")})),e.video.outbound.map((e=>{let i=t.video.outbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesSent"),e.packetRate=y(e,i,"packetsSent")})),e):e}(n,t),n}let I,C={},E=[];t.WebRTCStats=class extends s{constructor(e){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"],"undefined"==typeof window)throw new Error("WebRTCStats only works in browser");const t={...e};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=t.getStatsInterval||1e3,this.rawStats=!!t.rawStats,this.statsObject=!!t.statsObject,this.filteredStats=!!t.filteredStats,this.shouldWrapGetUserMedia=!!t.wrapGetUserMedia,"boolean"==typeof t.remote&&(this.remote=t.remote),this.debug=!!t.debug,this.logLevel=t.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(e,t){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:e,pc:t})}async addConnection(e){const{pc:t,peerId:i}=e;let{connectionId:n,remote:s}=e;if(s="boolean"==typeof s?s:this.remote,!(t&&t instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!i)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[i]){if(n&&n in this.peersToMonitor[i])throw new Error(`We are already monitoring connection with id ${n}.`);for(let e in this.peersToMonitor[i]){const n=this.peersToMonitor[i][e];if(n.pc===t)throw new Error(`We are already monitoring peer with id ${i}.`);"closed"===n.pc.connectionState&&this.removeConnection({pc:n.pc})}}const o=t.getConfiguration();return o.iceServers&&o.iceServers.forEach((function(e){delete e.credential})),n||(n=f()),this.emitEvent({event:"addConnection",tag:"peer",peerId:i,connectionId:n,data:{options:e,peerConfiguration:o}}),this.monitorPeer({peerId:i,connectionId:n,pc:t,remote:s}),{connectionId:n}}getTimeline(e){return this.timeline=this.timeline.sort(((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())),e?this.timeline.filter((t=>t.tag===e)):this.timeline}get logger(){const e=e=>{const t=["none","error","warn","info","debug"];return t.slice(0,t.indexOf(this.logLevel)+1).indexOf(e)>-1};return{error(...t){this.debug&&e("error")&&console.error("[webrtc-stats][error] ",...t)},warn(...t){this.debug&&e("warn")&&console.warn("[webrtc-stats][warn] ",...t)},info(...t){this.debug&&e("info")&&console.log("[webrtc-stats][info] ",...t)},debug(...t){this.debug&&e("debug")&&console.debug("[webrtc-stats][debug] ",...t)}}}removeConnection(e){let t,{connectionId:i,pc:n}=e;if(!n&&!i)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(i){if("string"!=typeof i)throw new Error("connectionId must be a string.");for(let e in this.peersToMonitor)i in this.peersToMonitor[e]&&(n=this.peersToMonitor[e][i].pc,t=e)}else if(n){if(!(n instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let e in this.peersToMonitor)for(let s in this.peersToMonitor[e])this.peersToMonitor[e][s].pc===n&&(i=s,t=e)}if(!n||!i)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(i,n),delete this.peersToMonitor[t][i],0===Object.values(this.peersToMonitor[t]).length&&delete this.peersToMonitor[t],{connectionId:i}}removeAllPeers(){for(let e in this.peersToMonitor)this.removePeer(e)}removePeer(e){if(this.logger.info(`Removing PeerConnection with id ${e}.`),this.peersToMonitor[e]){for(let t in this.peersToMonitor[e]){let i=this.peersToMonitor[e][t].pc;this.removePeerConnectionEventListeners(t,i)}delete this.peersToMonitor[e]}}destroy(){this.removeAllPeers(),E.forEach((e=>{this.removeTrackEventListeners(e)})),E=[],this.shouldWrapGetUserMedia&&I&&(navigator.mediaDevices.getUserMedia=I)}monitorPeer(e){let{peerId:t,connectionId:i,pc:n,remote:s}=e;if(!n)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const o={pc:n,connectionId:i,stream:null,stats:{parsed:null,raw:null},options:{remote:s}};if(this.peersToMonitor[t]){if(i in this.peersToMonitor[t])return void this.logger.warn(`Already watching connection with ID ${i}`);this.peersToMonitor[t][i]=o}else this.peersToMonitor[t]={[i]:o};this.addPeerConnectionEventListeners(t,i,n),1===this.numberOfMonitoredPeers&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then((e=>{e.forEach((e=>{this.emitEvent(e)}))}))}),this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(e=null){this.logger.info(e?`Getting stats from peer ${e}`:"Getting stats from all peers");let t={};if(e){if(!this.peersToMonitor[e])throw new Error(`Cannot get stats. Peer with id ${e} does not exist`);t[e]=this.peersToMonitor[e]}else t=this.peersToMonitor;let i=[];for(const e in t)for(const n in t[e]){const s=t[e][n],o=s.pc;if(o&&!this.checkIfConnectionIsClosed(e,n,o))try{const t=this.getTimestamp(),r=o.getStats(null);if(r){const o=await r,a=this.getTimestamp(),c=b(o),d={remote:s.options.remote},l=S(o,s.stats.parsed,d),u={event:"stats",tag:"stats",peerId:e,connectionId:n,timeTaken:a-t,data:l};!0===this.rawStats&&(u.rawStats=o),!0===this.statsObject&&(u.statsObject=c),!0===this.filteredStats&&(u.filteredStats=this.filteroutStats(c)),i.push(u),s.stats.parsed=l}else this.logger.error(`PeerConnection from peer ${e} did not return any stats data`)}catch(e){this.logger.error(e)}}return i}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const e in this.peersToMonitor)for(const t in this.peersToMonitor[e]){const i=this.peersToMonitor[e][t].pc;this.checkIfConnectionIsClosed(e,t,i)}}),this.connectionMonitoringInterval)}checkIfConnectionIsClosed(e,t,i){const n=this.isConnectionClosed(i);if(n){this.removeConnection({pc:i});let n="closed"===i.connectionState?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:n,peerId:e,connectionId:t,tag:"connection",data:"closed"})}return n}isConnectionClosed(e){return"closed"===e.connectionState||"closed"===e.iceConnectionState}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."),I=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const e=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=function(){return e({constraints:arguments[0]}),I.apply(navigator.mediaDevices,arguments).then((t=>(e({stream:t}),t)),(t=>(e({error:t}),Promise.reject(t))))}.bind(navigator.mediaDevices)}filteroutStats(e={}){const t={...e};for(const e in t){var i=t[e];this.statsToMonitor.includes(i.type)||delete t[e]}return t}get peerConnectionListeners(){return{icecandidate:(e,t,i,n)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",n),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:e,connectionId:t,data:n.candidate})},track:(e,t,i,n)=>{this.logger.debug(`[pc-event] track | peerId: ${e}`,n);const s=n.track,o=n.streams[0];e in this.peersToMonitor&&t in this.peersToMonitor[e]&&(this.peersToMonitor[e][t].stream=o),this.addTrackEventListeners(s,t),this.emitEvent({event:"ontrack",tag:"track",peerId:e,connectionId:t,data:{stream:o?this.getStreamDetails(o):null,track:s?this.getMediaTrackDetails(s):null,title:n.track.kind+":"+n.track.id+" "+n.streams.map((function(e){return"stream:"+e.id}))}})},signalingstatechange:(e,t,i)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${e}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:e,connectionId:t,data:{signalingState:i.signalingState,localDescription:i.localDescription,remoteDescription:i.remoteDescription}})},iceconnectionstatechange:(e,t,i)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${e}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:i.iceConnectionState})},icegatheringstatechange:(e,t,i)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${e}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:e,connectionId:t,data:i.iceGatheringState})},icecandidateerror:(e,t,i,n)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${e}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:e,connectionId:t,error:{errorCode:n.errorCode}})},connectionstatechange:(e,t,i)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${e}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:i.connectionState})},negotiationneeded:(e,t,i)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${e}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:e,connectionId:t})},datachannel:(e,t,i,n)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${e}`,n),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:e,connectionId:t,data:n.channel})}}}addPeerConnectionEventListeners(e,t,i){this.logger.debug(`Adding event listeners for peer ${e} and connection ${t}.`),C[t]={},Object.keys(this.peerConnectionListeners).forEach((n=>{C[t][n]=this.peerConnectionListeners[n].bind(this,e,t,i),i.addEventListener(n,C[t][n],!1)}))}parseGetUserMedia(e){try{const t={event:"getUserMedia",tag:"getUserMedia",data:{...e}};e.stream&&(t.data.details=this.parseStream(e.stream),e.stream.getTracks().map((e=>{this.addTrackEventListeners(e),E.push(e)}))),this.emitEvent(t)}catch(e){}}parseStream(e){const t={audio:[],video:[]};return e.getTracks().forEach((e=>{t[e.kind].push(this.getMediaTrackDetails(e))})),t}getMediaTrackDetails(e){return{enabled:e.enabled,id:e.id,contentHint:e.contentHint,kind:e.kind,label:e.label,muted:e.muted,readyState:e.readyState,constructorName:e.constructor.name,capabilities:e.getCapabilities?e.getCapabilities():{},constraints:e.getConstraints?e.getConstraints():{},settings:e.getSettings?e.getSettings():{},_track:e}}getStreamDetails(e){return{active:e.active,id:e.id,_stream:e}}getTrackEventObject(e){return{mute:t=>{this.emitEvent({event:"mute",tag:"track",connectionId:e,data:{event:t}})},unmute:t=>{this.emitEvent({event:"unmute",tag:"track",connectionId:e,data:{event:t}})},overconstrained:t=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:e,data:{event:t}})},ended:t=>{this.emitEvent({event:"ended",tag:"track",connectionId:e,data:{event:t}}),this.removeTrackEventListeners(t.target)}}}addTrackEventListeners(e,t){C[e.id]={};const i=this.getTrackEventObject(t);Object.keys(i).forEach((t=>{C[e.id][t]=i[t].bind(this),e.addEventListener(t,C[e.id][t])})),C[e.id].readyState=setInterval((()=>{if("ended"===e.readyState){let t=new CustomEvent("ended",{detail:{check:"readyState"}});e.dispatchEvent(t)}}),1e3)}removeTrackEventListeners(e){if(e.id in C){const t=this.getTrackEventObject();Object.keys(t).forEach((t=>{e.removeEventListener(t,C[e.id][t])})),clearInterval(C[e.id].readyState),delete C[e.id]}}addToTimeline(e){this.timeline.push(e),this.emit("timeline",e)}emitEvent(e){const t={...e,timestamp:new Date};this.addToTimeline(t),t.tag&&this.emit(t.tag,t)}set getStatsInterval(e){if(!Number.isInteger(e))throw new Error(`getStatsInterval should be an integer, got: ${e}`);this._getStatsInterval=e,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(e,t){e in C&&(Object.keys(this.peerConnectionListeners).forEach((i=>{t.removeEventListener(i,C[e][i],!1)})),delete C[e]),t.getSenders().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)})),t.getReceivers().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)}))}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const e=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const t=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),i=function(){return e.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),t.apply(navigator.mediaDevices,arguments).then((function(e){return e}),(function(t){return e.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,t.name),Promise.reject(t)}))};navigator.mediaDevices.getDisplayMedia=i.bind(navigator.mediaDevices)}}}}));(ki=wi)&&ki.__esModule&&Object.prototype.hasOwnProperty.call(ki,"default")&&ki.default;var Ti=wi.WebRTCStats;function Ri(e){const{packetsLost:t,packetsReceived:i,jitter:n,rtt:s}=e,o=function(e){const{jitter:t,rtt:i}=e,n=t+i/2;return.024*n+.11*(n-177.3)*(n>177.3?1:0)}({rtt:s,jitter:n}),r=function(e){const{packetsLost:t,packetsReceived:i}=e,n=t/(i+t)*100;return 20*Math.log(1+n)}({packetsLost:t,packetsReceived:i}),a=93.2-o-r+0,c=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(c,1),5)}function Ai(e){return isNaN(e)?null:e>4.2?"excellent":e>=4.1&&e<=4.2?"good":e>=3.7&&e<=4?"fair":e>=3.1&&e<=3.6?"poor":"bad"}class Oi extends wt{constructor(e,t){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:t})}}class Di extends wt{constructor(e,t){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:t})}}class Ni extends wt{constructor(e,t,i){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,call_id:t,debug_report_data:i})}}function Li(e,i){const n=a();let s=!1;const o=new Ti({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),r=s=>t(this,void 0,void 0,(function*(){"stats"===s.event&&_t(de.StatsFrame,function({data:e}){var t,i,n,s,o,r,a,c;const{audio:d,remote:l}=e,{audio:u}=l,h=null!==(i=null===(t=u.inbound[0])||void 0===t?void 0:t.jitter)&&void 0!==i?i:1/0,p=null!==(s=null===(n=u.inbound[0])||void 0===n?void 0:n.roundTripTime)&&void 0!==s?s:1/0,g=null!==(r=null===(o=d.inbound[0])||void 0===o?void 0:o.packetsReceived)&&void 0!==r?r:-1,v=null!==(c=null===(a=d.inbound[0])||void 0===a?void 0:a.packetsLost)&&void 0!==c?c:-1,m=Ri({jitter:1e3*h,rtt:1e3*p,packetsLost:v,packetsReceived:g});return{jitter:h,rtt:p,mos:m,quality:Ai(m),inboundAudio:d.inbound[0],outboundAudio:d.outbound[0],remoteInboundAudio:u.inbound[0],remoteOutboundAudio:u.outbound[0]}}(s),e.uuid),yield e.execute(new Ni(n,i,s))}));return{get isRunning(){return s},start:(a,c,d)=>t(this,void 0,void 0,(function*(){if(s)ke.debug(`[${i}] Stats reporter already running, skipping start`);else{yield e.execute(new Oi(n,i)),o.on("timeline",r);try{yield o.addConnection({pc:a,peerId:c,connectionId:d}),s=!0}catch(e){ke.error(`[${i}] Failed to start stats reporter:`,e),o.removeAllPeers(),o.destroy()}}})),stop:r=>t(this,void 0,void 0,(function*(){const t=o.getTimeline();if(_t(de.StatsReport,t,e.uuid),"file"===r){!function(e,t){const i=new Blob([JSON.stringify(e)],{type:"application/json"}),n=URL.createObjectURL(i),s=document.createElement("a");s.href=n,s.download=`${t}.json`,s.click(),URL.revokeObjectURL(n)}(t,`webrtc-stats-${n}-${Date.now()}`)}yield e.execute(new Di(n,i)),o.removeAllPeers(),o.destroy(),s=!1})),reportConnectionStateChange:e=>{const t={event:"connectionstatechange-detailed",tag:"connection",timestamp:(new Date).toISOString(),data:e};r(t)},reportIceCandidateError:e=>{const t={event:"icecandidateerror-detailed",tag:"connection",timestamp:(new Date).toISOString(),data:e};r(t)}}}const Pi=(e,t)=>{const{contentType:i,canvasType:n,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&"mcu-personal-canvas"!==n&&delete o.memberID;const a={type:it.conferenceUpdate,call:e.calls[s],canvasInfo:Mi(o),currentLayerIdx:r};switch(i){case"layer-info":{const t=Object.assign({action:at.LayerInfo},a);_t(de.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:at.LayoutInfo},a);_t(de.Notification,t,e.uuid);break}}},Mi=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return De(t)},xi=["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"],Ui={"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 Fi(e,t){return`telnyx:call:${e}:${t}`}function ji(e){try{const t=performance.getEntriesByName(e,"mark");return t.length>0?t[0].startTime:void 0}catch(e){return}}function $i(e){for(const t of xi)try{performance.clearMarks(Fi(e,t))}catch(e){ke.warn("Clearing performance marks is failed")}}class Hi{constructor(e,i,n,s,o){this.type=e,this.options=i,this.onSdpReadyTwice=null,this.statsReporter=null,this.isIceRestarting=!1,this.iceDone=!1,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this._iceGatheringSafetyTimeout=null,this._gatheredCandidatesCount=0,this._firstMediaTrackMarked=!1,this._timingsCollected=!1,this._iceRestartTimeoutId=null,this.handleConnectionStateChange=()=>t(this,void 0,void 0,(function*(){var e,i;if(!this.instance)return void ke.debug("Connection state change ignored: instance is null");const{connectionState:n}=this.instance;if(ke.info(`[${(new Date).toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${n}`),"failed"!==n&&"disconnected"!==n||(this.isDebugEnabled&&this.statsReporter&&function(e,i){return t(this,void 0,void 0,(function*(){const t={connectionState:e.connectionState,previousConnectionState:i,iceConnectionState:e.iceConnectionState,iceGatheringState:e.iceGatheringState,signalingState:e.signalingState},n=e.getTransceivers();if(n.length>0){const e=n[0].sender,i=null==e?void 0:e.transport;i&&(t.dtlsState=i.state)}e.sctp&&(t.sctpState=e.sctp.state);try{const i=yield e.getStats();i.forEach((e=>{"candidate-pair"===e.type&&"succeeded"===e.state&&(t.candidatePairState=e.state,i.forEach((i=>{"local-candidate"===i.type&&i.id===e.localCandidateId&&(t.localCandidateType=i.candidateType,t.selectedCandidatePair=t.selectedCandidatePair||{local:{},remote:{}},t.selectedCandidatePair.local={address:i.address,port:i.port,protocol:i.protocol,candidateType:i.candidateType}),"remote-candidate"===i.type&&i.id===e.remoteCandidateId&&(t.remoteCandidateType=i.candidateType,t.selectedCandidatePair=t.selectedCandidatePair||{local:{},remote:{}},t.selectedCandidatePair.remote={address:i.address,port:i.port,protocol:i.protocol,candidateType:i.candidateType})}))),"transport"===e.type&&(t.dtlsCipher=e.dtlsCipher,t.srtpCipher=e.srtpCipher,t.tlsVersion=e.tlsVersion,e.dtlsState&&(t.dtlsState=e.dtlsState))}))}catch(e){ke.error("Error gathering connection state details:",e)}return t}))}(this.instance,this._prevConnectionState).then((e=>{this.statsReporter.reportConnectionStateChange(e)})),null===(i=(e=this._session).reportPeerFailure)||void 0===i||i.call(e,this.options.id,"connection_failed")),"disconnected"===n){const e=he(W);_t(de.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if("failed"===n){const e=he(V);_t(de.PeerConnectionFailureError,{warning:e,error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${n}`),sessionId:this._session.sessionid},this.options.id)}this._prevConnectionState=n,"connected"===n&&(performance.mark(Fi(this.options.id,"dtls-connected")),this.tryCollectTimings(),this._restartedIceOnConnectionStateFailed=!1),this._isTrickleIce()&&("connecting"===n&&performance.mark(Fi(this.options.id,"peer-connection-connecting")),"connected"===n&&(this._clearIceGatheringSafetyTimeout(),performance.mark(Fi(this.options.id,"peer-connection-connected"))))})),this._handleIceConnectionStateChange=()=>{var e,t;if(!this.instance)return void ke.debug("ICE connection state change ignored: instance is null");const i=this.instance.iceConnectionState;ke.debug(`[${(new Date).toISOString()}] ICE Connection State`,i),"connected"===i&&performance.mark(Fi(this.options.id,"ice-connected")),"failed"===i&&(null===(t=(e=this._session).reportPeerFailure)||void 0===t||t.call(e,this.options.id,"ice_failed"))},this._handleIceGatheringStateChange=()=>{const e=this.instance.iceGatheringState;ke.debug(`[${(new Date).toISOString()}] ICE Gathering State`,e),"gathering"===e?(this._gatheredCandidatesCount=0,this._startIceGatheringSafetyTimeout()):"complete"===e&&this._clearIceGatheringSafetyTimeout()},this._setCodecs=(e,t)=>{if(e.setCodecPreferences)return e.setCodecPreferences(t)},ke.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!i.video},this._sdpReady=this._sdpReady.bind(this),this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this._session=n,this._trickleIceSdpFn=s,this._registerPeerEvents=o}finishIceRestart(){this.isIceRestarting&&(this.isIceRestarting=!1,this._iceRestartTimeoutId&&(clearTimeout(this._iceRestartTimeoutId),this._iceRestartTimeoutId=null))}restartIce(){return this.instance?this.isIceRestarting?(ke.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&&(ke.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null}),Hi.ICE_RESTART_TIMEOUT_MS),ke.info("ICE restart: initiated by signaling health monitor"),{started:!0}):(ke.debug("ICE restart: session not connected, skipping"),{started:!1,reason:"session not connected"}):(ke.warn("ICE restart: no RTCPeerConnection instance"),{started:!1,reason:"no RTCPeerConnection instance"})}get isOffer(){return this.type===Ze.Offer}get isAnswer(){return this.type===Ze.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get restartedIceOnConnectionStateFailed(){return this._restartedIceOnConnectionStateFailed}isConnectionHealthy(){return"connected"===this.instance.connectionState&&"connected"===this.instance.iceConnectionState&&"closed"!==this.instance.signalingState}startNegotiation(){performance.mark(Fi(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 t(this,void 0,void 0,(function*(){performance.mark(Fi(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 pe&&_t(de.Error,{error:e,sessionId:this._session.sessionid},this.options.id)}_logTransceivers(){this.instance?(ke.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach(((e,t)=>{ke.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),ke.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))):ke.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(ke.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":_t(de.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(ke.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){ke.info("Negotiation needed event"),"stable"!==this.instance.signalingState||this._negotiating?ke.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(Fi(this.options.id,"first-remote-media-track")),this._firstMediaTrackMarked=!0);const{streams:[t]}=e,{remoteElement:i,screenShare:n}=this.options;this.options.remoteStream=t,!1===n&&Xt(i,this.options.remoteStream)}tryCollectTimings(){if(this._timingsCollected)return;if(!(performance.getEntriesByName(Fi(this.options.id,"call-active"),"mark").length>0)||"connected"!==this.instance.connectionState)return;this._timingsCollected=!0;const e=this._isTrickleIce()?"trickle":"non-trickle",t=this.isOffer?"outbound":"inbound",i=function(e,t,i){const n=ji(Fi(e,"new-call-start"));if(void 0===n)return{mode:t,direction:i,steps:[]};const s=[];for(const t of xi){if("new-call-start"===t)continue;const i=ji(Fi(e,t));void 0!==i&&s.push({label:Ui[t]||t,fromStart:i-n})}s.sort(((e,t)=>e.fromStart-t.fromStart));const o=[];let r=0;for(const e of s)o.push({label:e.label,fromStart:e.fromStart,delta:e.fromStart-r}),r=e.fromStart;return{mode:t,direction:i,steps:o}}(this.options.id,e,t);!function(e){const{mode:t,direction:i,steps:n}=e,s=`[CallTimings][${i}][${t}]`;if(0===n.length)return void ke.info(`${s} No timing data collected`);const o=Math.max(...n.map((e=>e.label.length)),4)+2,r=(e,t)=>{for(;e.length<t;)e+=" ";return e},a=(e,t)=>{for(;e.length<t;)e=" "+e;return e},c=r("Step",o)+a("Delta",14)+a("From Start",14);let d="";for(let e=0;e<c.length;e++)d+="-";ke.info(`${s} Call establishment timing breakdown:`),ke.info(`${s} ${c}`),ke.info(`${s} ${d}`),ke.info(`${s} ${r("Call Start",o)}${a("-",14)}${a("0.00ms",14)}`);for(const e of n){const t=e.delta.toFixed(2)+"ms",i=e.fromStart.toFixed(2)+"ms";ke.info(`${s} ${r(e.label,o)}${a(t,14)}${a(i,14)}`)}ke.info(`${s} ${d}`)}(i),$i(this.options.id)}createPeerConnection(){return t(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",(e=>{this.options.remoteStream=e.stream})),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Ze.Offer}),performance.mark(Fi(this.options.id,"set-remote-description")),!this.instance))throw me(I);const i=Boolean(this.options.receiveOnlyAudio)&&!this.options.audio;let n=null;if(this.options.localStream=yield this._retrieveLocalStream().catch((e=>t(this,void 0,void 0,(function*(){const i=this._session.options.mediaPermissionsRecovery;if((null==i?void 0:i.enabled)&&this._isAnswer()){let s=null,o=null;return yield new Promise(((t,n)=>{o=setTimeout((()=>n(new Error("Media recovery flow timed out!"))),i.timeout),_t(de.Error,{error:me(ve(e),e,void 0,!1),callId:this.options.id,sessionId:this._session.sessionid,recoverable:!0,retryDeadline:Date.now()+i.timeout,resume:()=>{t()},reject:()=>{n(new Error("Call was rejected during media recovery flow!"))}},this._session.uuid)})).then((()=>t(this,void 0,void 0,(function*(){var e;o&&(clearTimeout(o),o=null),s=yield this._retrieveLocalStream(),null===(e=i.onSuccess)||void 0===e||e.call(i)})))).catch((e=>{var t;o&&(clearTimeout(o),o=null),n=e,null===(t=i.onError)||void 0===t||t.call(i,e)})),s}return n=e,null})))),!this.instance)throw me(I);if(!this.options.localStream&&!i){throw me(n?ve(n):f,null!=n?n:void 0)}performance.mark(Fi(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&Qt(this.options.localStream)&&(ke.info("Muting local audio tracks on start"),gi(this.options.localStream)),this.options.applyDesiredAudioMuteState&&this.options.applyDesiredAudioMuteState(),performance.mark(Fi(this.options.id,"peer-creation-end"))}))}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout((()=>{if(this.instance)if(0===this._gatheredCandidatesCount){const e=he(G);_t(de.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if("complete"!==this.instance.iceGatheringState){const e=he(B);_t(de.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}),Hi.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){null!==this._iceGatheringSafetyTimeout&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return t(this,void 0,void 0,(function*(){if(yield this.createPeerConnection(),!this.instance)throw me(I);this.isDebugEnabled&&(this.statsReporter=Li(this._session,this.options.id),yield null===(e=this.statsReporter)||void 0===e?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid));const{localElement:t,localStream:i=null,screenShare:n=!1}=this.options;if(Qt(i)){const e=i.getAudioTracks();let s=[...e];if(ke.info("Local audio tracks: ",e),"object"==typeof this.options.audio&&e.forEach((e=>{ke.info("Local audio tracks constraints: ",e.getConstraints())})),this.options.video){const t=i.getVideoTracks();s=[...e,...t],ke.info("Local video tracks: ",t),"object"==typeof this.options.video&&t.forEach((e=>{ke.info("Local video tracks constraints: ",e.getConstraints())}))}const{audioCodecs:o,videoCodecs:r}=bi(this.options.preferred_codecs);if(this.isOffer&&"function"==typeof this.instance.addTransceiver){const e={direction:"sendrecv",streams:[i]};s.forEach((t=>{"audio"===t.kind&&(this.options.userVariables.microphoneLabel=t.label),"video"===t.kind&&(this.options.userVariables.cameraLabel=t.label);const i=this.instance.addTransceiver(t,e);"audio"===t.kind&&o.length>0&&this._setCodecs(i,o),"video"===t.kind&&r.length>0&&this._setCodecs(i,r)}))}else"function"==typeof this.instance.addTrack?(s.forEach((e=>{"audio"===e.kind&&(this.options.userVariables.microphoneLabel=e.label),"video"===e.kind&&(this.options.userVariables.cameraLabel=e.label),this.instance.addTrack(e,i)})),this.instance.getTransceivers().forEach((e=>{"audio"===e.receiver.track.kind&&o.length>0&&this._setCodecs(e,o),"video"===e.receiver.track.kind&&r.length>0&&this._setCodecs(e,r)}))):this.instance.addStream(i);!1===n&&Xt(t,i)}else if(this.options.receiveOnlyAudio&&"function"==typeof this.instance.addTransceiver){const e=this.instance.addTransceiver("audio",{direction:"recvonly"});ke.info("Added recvonly audio transceiver for receive-only mode",e);const{audioCodecs:t}=bi(this.options.preferred_codecs);t.length>0&&this._setCodecs(e,t)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation().catch((e=>this._emitNegotiationError(e))),this._logTransceivers()}))}_getSenderByKind(e){return this.instance.getSenders().find((({track:t})=>t&&t.kind===e))}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const t=this.instance.addTransceiver(e);ke.info("Add transceiver",e,t)}}_createOffer(){return t(this,void 0,void 0,(function*(){if(this._isOffer()||this.isIceRestarting){this._constraints.offerToReceiveAudio=!1!==this.options.audio||Boolean(this.options.receiveOnlyAudio),this._constraints.offerToReceiveVideo=Boolean(this.options.video),ke.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark(Fi(this.options.id,"create-offer")),yield this._setLocalDescription(e),performance.mark(Fi(this.options.id,"set-local-description")),performance.mark(Fi(this.options.id,"ice-gathering-started")),this._isTrickleIce()||this._sdpReady(),e}catch(e){if(ke.error("Peer _createOffer error:",e),e instanceof pe)throw e;throw me(l,e)}}}))}_setRemoteDescription(e){return t(this,void 0,void 0,(function*(){ke.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(e){ke.error("Peer _setRemoteDescription error:",e);throw me(p,e)}}))}_createAnswer(){return t(this,void 0,void 0,(function*(){if(this._isAnswer()){if("stable"!==this.instance.signalingState&&"have-remote-offer"!==this.instance.signalingState)return ke.debug("Skipping negotiation, state:",this.instance.signalingState),ke.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:Ze.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark(Fi(this.options.id,"create-answer")),yield this._setLocalDescription(e),performance.mark(Fi(this.options.id,"set-local-description")),performance.mark(Fi(this.options.id,"ice-gathering-started")),e}catch(e){if(ke.error("Peer _createAnswer error:",e),e instanceof pe)throw e;throw me(u,e)}}}))}_setLocalDescription(e){return t(this,void 0,void 0,(function*(){try{yield this.instance.setLocalDescription(e)}catch(e){ke.error("Peer _setLocalDescription error:",e);throw me(h,e)}}))}_sdpReady(){Ne(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return t(this,void 0,void 0,(function*(){if(Qt(this.options.localStream))return this.options.localStream;const e=yield(i=this.options,t(void 0,void 0,void 0,(function*(){let{audio:e=!0,micId:t,video:n=!1,camId:s}=i;const{micLabel:o="",camLabel:r=""}=i;return t&&(t=yield ri(t,o,ct.AudioIn).catch((()=>null)),t&&("boolean"==typeof e&&(e={}),e.deviceId={exact:t})),s&&(s=yield ri(s,r,ct.Video).catch((()=>null)),s&&("boolean"==typeof n&&(n={}),n.deviceId={exact:s})),{audio:e,video:n}})));var i;return ni(e)}))}_isOffer(){return this.type===Ze.Offer}_isAnswer(){return this.type===Ze.Answer}_isTrickleIce(){return!0===this.options.trickleIce}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:t,iceServers:i}=this.options,n={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:i,iceTransportPolicy:t?"relay":"all"};return ke.info("RTC config",n),n}restartStatsReporter(){return t(this,void 0,void 0,(function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?ke.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(ke.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):ke.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))}))}close(){return t(this,void 0,void 0,(function*(){$i(this.options.id),this.finishIceRestart(),this._clearIceGatheringSafetyTimeout(),null!==this._sleepWakeupIntervalId&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)}))}}Hi.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,Hi.ICE_RESTART_TIMEOUT_MS=15e3;const Wi=Pt;class Bi{constructor(e,t){this.session=e,this._callReportCollector=null,this._mediaDeviceCollector=null,this.id="",this.recoveredCallId="",this.state=ot[ot.New],this.prevState="",this.channels=[],this.role=rt.Participant,this.extension=null,this._state=ot.New,this._prevState=ot.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._checkConferenceSerno=e=>{const t=e<0||!this._lastSerno||this._lastSerno&&e===this._lastSerno+1;return t&&e>=0&&(this._lastSerno=e),t},this._doStats=()=>{this.peer&&this.peer.instance&&0!==this._statsBindings.length&&this.peer.instance.getStats().then((e=>{e.forEach((e=>{this._statsBindings.forEach((t=>{if(t.callback){if(t.constraints)for(const i in t.constraints)if(t.constraints.hasOwnProperty(i)&&t.constraints[i]!==e[i])return;t.callback(e)}}))}))}))};const{iceServers:i,speaker:n,micId:s,micLabel:o,camId:r,camLabel:a,localElement:c,remoteElement:d,options:l,mediaConstraints:{audio:u,video:h},ringtoneFile:p,ringbackFile:g}=e;this.options=Object.assign({},st,{audio:u,video:h,iceServers:(null==t?void 0:t.iceServers)&&Array.isArray(t.iceServers)?t.iceServers:i,localElement:c,remoteElement:d,micId:s,micLabel:o,camId:r,camLabel:a,speakerId:n,ringtoneFile:p,ringbackFile:g,debug:l.debug,debugOutput:l.debugOutput,trickleIce:l.trickleIce,prefetchIceCandidates:l.prefetchIceCandidates,forceRelayCandidate:l.forceRelayCandidate,keepConnectionAliveOnSocketClose:l.keepConnectionAliveOnSocketClose,mutedMicOnStart:l.mutedMicOnStart},t),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=Boolean(this.options.mutedMicOnStart),this.options.applyDesiredAudioMuteState=this._applyDesiredAudioMuteState.bind(this),this._init(),this.options&&(this._ringtone=fi(this.options.ringtoneFile,"_ringtone"),this._ringback=fi(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}_captureHangupCallerStack(){const e=new Error("Call.hangup caller").stack;return e?e.split("\n").map((e=>e.trim())).filter(Boolean).slice(1,11):[]}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}get isVideoCall(){return!!this.options.video}get telnyxIDs(){return{telnyxCallControlId:this.options.telnyxCallControlId,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId}}get localStream(){return this.options.localStream}get remoteStream(){return this.options.remoteStream}get memberChannel(){return`conference-member.${this.id}`}get isAudioMuted(){return this._desiredAudioMuted}_getLocalAudioTrackId(){var e,t;return null===(t=null===(e=this.options.localStream)||void 0===e?void 0:e.getAudioTracks()[0])||void 0===t?void 0:t.id}_hasActiveUnmutedLocalAudioTrack(){const e=this.options.localStream;return!!(null==e?void 0:e.getAudioTracks)&&e.getAudioTracks().some((e=>!0===e.enabled&&!0!==e.muted&&"live"===e.readyState))}shouldForceRelayCandidateForRecovery(){var e,t;return!this.options.forceRelayCandidate&&(!!this.recoveredCallId&&(null!==(t=null===(e=this._callReportCollector)||void 0===e?void 0:e.shouldForceRelayCandidateForRecovery())&&void 0!==t&&t))}invite(){return t(this,void 0,void 0,(function*(){this._creatingPeer=!0,this.direction=et.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(Fi(this.id,"new-peer")),this.peer=new Hi(Ze.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){ke.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const t=e instanceof pe?e:me(L,e instanceof Error?e:void 0);return _t(de.Error,{error:t,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void this.hangup({initiator:"sdk:peer-init-failed"},!1)}this._creatingPeer=!1}))}answer(e={}){var i,n,s,o,r,a,c,d;return t(this,void 0,void 0,(function*(){const t=(null!==(s=null===(n=(i=this.session).getActiveCalls)||void 0===n?void 0:n.call(i))&&void 0!==s?s:[]).filter((e=>e.id!==this.id));if(t.length>0&&ke.debug(`[${this.id}] answer(): answering inbound call while ${t.length} other active call(s) exist in session ${this.session.sessionid}`),this._creatingPeer||(null===(o=this.peer)||void 0===o?void 0:o.instance)&&"closed"!==this.peer.instance.signalingState){const e=he(K);return _t(de.Warning,{warning:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void ke.warn(`[${this.id}] answer() ignored: peer connection already exists or is being created (signalingState: ${null!==(c=null===(a=null===(r=this.peer)||void 0===r?void 0:r.instance)||void 0===a?void 0:a.signalingState)&&void 0!==c?c:"creating"})`)}if(this._registerInboundAnswerAttempt()){performance.mark(Fi(this.id,"answer-called")),this._creatingPeer=!0,this.stopRingtone(),this.direction=et.Inbound,(null===(d=null==e?void 0:e.customHeaders)||void 0===d?void 0:d.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(Fi(this.id,"new-peer")),this.peer=new Hi(Ze.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){ke.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const t=e instanceof pe?e:me(L,e instanceof Error?e:void 0);return _t(de.Error,{error:t,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void(yield this.hangup({initiator:"sdk:peer-init-failed"},!0))}this._creatingPeer=!1}}))}playRingtone(){_i(this._ringtone)}stopRingtone(){yi(this._ringtone)}playRingback(){_i(this._ringback)}stopRingback(){yi(this._ringback)}hangup(e,i){var n,s,o,r,a,c;return t(this,void 0,void 0,(function*(){const t=e||{},d=!1!==i,l=this.state,u=this.prevState,h=this._captureHangupCallerStack(),p=t.initiator||"app:call.hangup",g=this._state<ot.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=t.cause||g.cause,this.causeCode=t.causeCode||g.causeCode,this.sipCode=t.sipCode||null,this.sipReason=t.sipReason||null,this.sipCallId=t.sip_call_id||null,this.options.customHeaders=[...null!==(n=this.options.customHeaders)&&void 0!==n?n:[],...null!==(o=null===(s=null==t?void 0:t.dialogParams)||void 0===s?void 0:s.customHeaders)&&void 0!==o?o:[]],ke.debug(`[${this.id}] hangup() invoked`,{callId:this.id,execute:d,state:l,prevState:u,cause:this.cause,causeCode:this.causeCode,initiator:p,sipCode:this.sipCode,sipReason:this.sipReason,sipCallId:this.sipCallId,isRecovering:Boolean(t.isRecovering),hasDialogCustomHeaders:Boolean(null===(a=null===(r=t.dialogParams)||void 0===r?void 0:r.customHeaders)||void 0===a?void 0:a.length),callerStack:h}),t.isRecovering)return this._isRecovering=!0,this.setState(ot.Recovering),void this._finalize();if(this.setState(ot.Hangup),this.stopRingtone(),this.stopRingback(),d){const e=new $t({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});let t;try{yield Promise.race([this._execute(e),new Promise((e=>{t=setTimeout((()=>{ke.warn(`[${this.id}] BYE execution timed out after 5000ms — proceeding to destroy.`),e()}),5e3)}))])}catch(e){ke.error("telnyx_rtc.bye failed!",e);const t=me(b,e);_t(de.Error,{error:t,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}finally{t&&clearTimeout(t)}}ke.debug(`[${this.id}] Closing peer from hangup`),null===(c=this.peer)||void 0===c||c.close(),this.setState(ot.Destroy)}))}hold(){const e=new Bt({sessid:this.session.sessionid,action:lt.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new Bt({sessid:this.session.sessionid,action:lt.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new Bt({sessid:this.session.sessionid,action:lt.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const t=new Gt({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(t)}message(e,t){const i={from:this.session.options.login,to:e,body:t},n=new Gt({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(n)}muteAudio(){ke.debug("muteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!0,gi(this.options.localStream)}unmuteAudio(){ke.debug("unmuteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!1,pi(this.options.localStream)}_applyDesiredAudioMuteState(){ke.debug("applyDesiredAudioMuteState called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted?gi(this.options.localStream):pi(this.options.localStream)}toggleAudioMute(){ke.debug("toggleAudioMute called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!this._desiredAudioMuted,this._applyDesiredAudioMuteState()}setAudioInDevice(e,i=this._desiredAudioMuted){var n,s,o;return t(this,void 0,void 0,(function*(){const t=Boolean(i),{instance:r}=this.peer,a=r.getSenders().find((({track:{kind:e}})=>"audio"===e));if(!a)return ke.warn("Skipping audio input device change: no audio sender found",{callId:this.id,deviceId:e,audioMuted:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),void _t(de.Warning,{warning:he(J),callId:this.id,deviceId:e,sessionId:this.session.sessionid},(null===(n=this.options)||void 0===n?void 0:n.id)||this.id);let c;ke.debug("Starting audio input device change",{callId:this.id,state:this.state,deviceId:e,previousDesiredAudioMuted:this._desiredAudioMuted,newDesiredMuted:t,currentSenderTrack:ci(a.track),localTracks:di(this.options.localStream)});try{c=yield zt({audio:{deviceId:{exact:e}}})}catch(e){const t=me(ve(e),e);return void _t(de.MediaError,t,(null===(s=this.options)||void 0===s?void 0:s.id)||this.id)}const d=c.getAudioTracks()[0];d.enabled=!t;try{yield a.replaceTrack(d)}catch(e){const t=me(ve(e),e);return _t(de.MediaError,t,(null===(o=this.options)||void 0===o?void 0:o.id)||this.id),void c.getTracks().forEach((e=>e.stop()))}this._desiredAudioMuted=t,this.options.micId=e;const{localStream:l}=this.options;l.getAudioTracks().forEach((e=>e.stop())),l.getVideoTracks().forEach((e=>c.addTrack(e))),this.options.localStream=c,ke.debug("Finished audio input device change",{callId:this.id,state:this.state,deviceId:e,desiredAudioMuted:this._desiredAudioMuted,senderTrack:ci(a.track),localTracks:di(this.options.localStream)})}))}muteVideo(){var e;e=this.options.localStream,hi(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,hi(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,hi(e,"video",null)}setVideoDevice(e){return t(this,void 0,void 0,(function*(){const{instance:t}=this.peer,i=t.getSenders().find((({track:{kind:e}})=>"video"===e));if(i){const t=yield zt({video:{deviceId:{exact:e}}}),n=t.getVideoTracks()[0];i.replaceTrack(n);const{localElement:s,localStream:o}=this.options;Xt(s,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t,this._applyDesiredAudioMuteState()}}))}deaf(){gi(this.options.remoteStream)}undeaf(){pi(this.options.remoteStream)}toggleDeaf(){var e;e=this.options.remoteStream,hi(e,"audio",null)}setBandwidthEncodingsMaxBps(e,i){return t(this,void 0,void 0,(function*(){if(!this||!this.peer)return void ke.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:t}=this.peer,n=t.getSenders();if(!n)return void ke.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:e}})=>e===i));if(s){const t=s.getParameters();t.encodings||(t.encodings=[{rid:"h"}]),ke.info("Parameters: ",t),ke.info("Setting max ","audio"===i?"audio":"video"," bandwidth to: ",e," [bps]"),t.encodings[0].maxBitrate=e,yield s.setParameters(t).then((()=>{ke.info("audio"===i?"New audio":"New video"," bandwidth settings in use: ",s.getParameters())})).catch((e=>ke.error(e)))}else ke.error("Could not set bandwidth (reason: no "+i+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")}))}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}_isTerminatingOrTerminated(){return[ot.Hangup,ot.Destroy,ot.Purge].includes(this._state)}getStats(e,t){if(!e)return;const i={callback:e,constraints:t};if(this._statsBindings.push(i),!this._statsIntervalId){const e=2e3;this._startStats(e)}}setState(e){var t,i;switch(this._prevState=this._state,this._state=e,this.state=ot[this._state].toLowerCase(),this.prevState=ot[this._prevState].toLowerCase(),ke.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:it.callUpdate,call:this}),e){case ot.Purge:ke.info(`[${this.id}] Entering Purge state.`);break;case ot.Active:performance.mark(Fi(this.id,"call-active")),null===(t=this.peer)||void 0===t||t.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,ke.debug(`[${this.id}] Recovery complete, call is active`)),this.session.startSignalingHealthMonitor(),setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&ei(e,t)}),0),this._callReportCollector&&(null===(i=this.peer)||void 0===i?void 0:i.instance)&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance),this._mediaDeviceCollector=new Ei,this._mediaDeviceCollector.logDevicesAtStart();break;case ot.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:i}=e;switch(t){case tt.Answer:if(performance.mark(Fi(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),this._state>=ot.Active)return;this._state>=ot.Early&&this.setState(ot.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case tt.Media:if(performance.mark(Fi(this.id,"telnyx-rtc-media")),this._state>=ot.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case tt.Display:{const{display_name:e,display_number:n,display_direction:s}=i;this.extension=n;const o=s===et.Inbound?et.Outbound:et.Inbound,r={type:it[t],call:this,displayName:e,displayNumber:n,displayDirection:o};_t(de.Notification,r,this.id)||_t(de.Notification,r,this.session.uuid);break}case tt.Candidate:this._addIceCandidate(i);break;case tt.Info:case tt.Event:{const e=Object.assign(Object.assign({},i),{type:it.generic,call:this});_t(de.Notification,e,this.id)||_t(de.Notification,e,this.session.uuid);break}case tt.Ringing:performance.mark(Fi(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 tt.Bye:const e=i.client_state||i.clientState;e&&(this.options.clientState=e),this.stopRingback(),this.stopRingtone(),this.hangup(Object.assign(Object.assign({},i),{initiator:"remote:telnyx_rtc.bye"}),!1)}}handleConferenceUpdate(e,i){return t(this,void 0,void 0,(function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==i.laName)return ke.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:t,data:n,hashKey:s=String(this._lastSerno),arrIndex:o}=e;switch(t){case"bootObj":{this._lastSerno=0;const{chatChannel:e,infoChannel:t,modChannel:s,laName:o,conferenceMemberID:r,role:a}=i;this._dispatchConferenceUpdate({action:at.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),t&&(yield this._subscribeConferenceInfo(t));const c=[];for(const e in n)c.push(Object.assign({callId:n[e][0],index:Number(e)},Oe(n[e][1])));this._dispatchConferenceUpdate({action:at.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:at.Add,callId:s,index:o},Oe(n)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:at.Modify,callId:s,index:o},Oe(n)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:at.Delete,callId:s,index:o},Oe(n)));break;case"clear":this._dispatchConferenceUpdate({action:at.Clear});break;default:this._dispatchConferenceUpdate({action:t,data:n,callId:s,index:o})}}))}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const t=this.session.relayProtocol;this.session._existsSubscription(t,e)&&(this.session.subscriptions[t][e]=Object.assign(Object.assign({},this.session.subscriptions[t][e]),{callId:this.id}))}_subscribeConferenceChat(e){return t(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{direction:t,from:i,fromDisplay:n,message:s,type:o}=e.data;this._dispatchConferenceUpdate({action:at.ChatMessage,direction:t,participantNumber:i,participantName:n,messageText:s,messageType:o,messageId:e.eventSerno})}},i=yield this.session.vertoSubscribe(t).catch((e=>{ke.error("ConfChat subscription error:",e)}));li(i,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(t,i)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:t,type:i}})}}}))}))}_subscribeConferenceInfo(e){return t(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{eventData:t}=e;if("layout-info"===t.contentType)t.callID=this.id,Pi(this.session,t);else ke.error("Conference-Info unknown contentType",e)}},i=yield this.session.vertoSubscribe(t).catch((e=>{ke.error("ConfInfo subscription error:",e)}));li(i,e)&&this._addChannel(e)}))}_confControl(e,t={}){const i=Object.assign({application:"conf-control",callID:this.id,value:null},t);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:i})}_handleChangeHoldStateSuccess(e){return"active"===e.holdState?this.setState(ot.Active):this.setState(ot.Held),!0}_handleChangeHoldStateError(e){ke.error(`Failed to ${e.action} on call ${this.id}`);const t=me(_,e);return _t(de.Error,{error:t,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e,i={}){const n=new Bt(Object.assign(Object.assign({sessid:this.session.sessionid,action:lt.UpdateMedia,callID:this.options.id,sdp:e},i.trickle?{trickle:!0}:{}),{dialogParams:this.options}));ke.info(`ICE restart: sending ${i.trickle?"trickle ":""}Modify with new offer SDP`),this._execute(n).then((e=>t(this,void 0,void 0,(function*(){var t;(null==e?void 0:e.sdp)?(ke.info("ICE restart Modify response received"),null===(t=this.peer)||void 0===t||t.finishIceRestart(),yield this._onRemoteSdp(e.sdp)):this._onIceRestartFailed("ICE restart Modify response missing SDP")})))).catch((e=>{this._onIceRestartFailed("ICE restart Modify failed",e)}))}_onIceRestartFailed(e,t){var i,n,s;ke.error(e,t),null===(i=this.peer)||void 0===i||i.finishIceRestart();const o=me(O,t);_t(de.Error,{error:o,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),null===(s=(n=this.session).reportIceRestartFailed)||void 0===s||s.call(n,this.id)}_onRemoteSdp(e){return t(this,void 0,void 0,(function*(){const i=new RTCSessionDescription({sdp:e,type:Ze.Answer});yield this.peer.instance.setRemoteDescription(i).then((()=>{performance.mark(Fi(this.id,"set-remote-description")),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(ot.Early),this.gotAnswer&&this.setState(ot.Active)})).catch((e=>t(this,void 0,void 0,(function*(){ke.error("Call setRemoteDescription Error: ",e);const t=me(p,e);_t(de.Error,{error:t,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(e){ke.error("Error during hangup after setRemoteDescription failure:",e)}}))))}))}_requestAnotherLocalDescription(){if(Ne(this.peer.onSdpReadyTwice)){const e=me(g,new Error("SDP without candidates for the second time!"));_t(de.Error,{error:e,sessionId:this.session.sessionid},this.session.uuid)}else Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this.peer.iceDone=!1,this.peer.startNegotiation()}_onIceSdp(e){var i,n,s;if(this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this.peer&&(this.peer.iceDone=!0),!e)return void ke.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:o,type:r}=e;if(-1===o.indexOf("candidate"))return ke.info("No candidate - retry \n"),void this._requestAnotherLocalDescription();if(null===(n=null===(i=this.peer)||void 0===i?void 0:i.instance)||void 0===n||n.removeEventListener("icecandidate",this._onIce),!ne.test(o)){const e=he(q);ke.warn(`[${this.id}] Warning ${e.code}: ${e.message}`),_t(de.Warning,{warning:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}performance.mark(Fi(this.id,"ice-gathering-end"));let a=null;const c={sessid:this.session.sessionid,sdp:o,dialogParams:this.options,"User-Agent":`Web-${Wi}`};if(null===(s=this.peer)||void 0===s?void 0:s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case Ze.Offer:this.setState(ot.Requesting),a=new Ut(c);break;case Ze.Answer:this._isRecovering||this.setState(ot.Answering),a=!0===this.options.attach?new jt(c):new Ft(c);break;default:return ke.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(Fi(this.id,"send-sdp")),this._execute(a).then((e=>{if(this._isTerminatingOrTerminated())return void ke.debug(`[${this.id}] Ignoring ${r} response because call is ${this.state}`);const{node_id:t=null}=e;this._targetNodeId=t,r===Ze.Offer?this.setState(ot.Trying):this.setState(ot.Active)})).catch((e=>t(this,void 0,void 0,(function*(){ke.error(`${this.id} - Sending ${r} error:`,e);const t=me(g,e);_t(de.Error,{error:t,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(e){ke.error("Error during hangup after SDP send failure:",e)}}))))}}_onTrickleIceSdp(e){var i;if(!e)return ke.error("No SDP data provided"),void this.hangup({initiator:"sdk:missing-local-sdp"},!1);const{sdp:n,type:s}=e;let o=null;const r={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${Wi}`};if(null===(i=this.peer)||void 0===i?void 0:i.isIceRestarting)this._sendIceRestartModify(n,{trickle:!0});else{switch(s){case Ze.Offer:this.setState(ot.Requesting),o=new Ut(r);break;case Ze.Answer:this._isRecovering||this.setState(ot.Answering),o=!0===this.options.attach?new jt(r):new Ft(r);break;default:return ke.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(Fi(this.id,"send-sdp")),this._execute(o).then((e=>{if(this._isTerminatingOrTerminated())return void ke.debug(`[${this.id}] Ignoring ${s} response because call is ${this.state}`);const{node_id:t=null}=e;this._targetNodeId=t,s===Ze.Offer?this.setState(ot.Trying):this.setState(ot.Active)})).catch((e=>t(this,void 0,void 0,(function*(){ke.error(`${this.id} - Sending ${s} error:`,e);const t=me(g,e);_t(de.Error,{error:t,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(e){ke.error("Error during hangup after SDP send failure:",e)}}))))}}_onIce(e){var t;const{instance:i}=this.peer;if(null===this._iceTimeout){const e=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout((()=>this._onIceSdp(i.localDescription)),e)}e.candidate?(ke.debug("RTCPeer Candidate:",e.candidate),null===(t=this.peer)||void 0===t||t.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate)):this._onIceSdp(i.localDescription)}_onTrickleIce(e){var t;e.candidate&&e.candidate.candidate?(ke.debug("RTCPeer Candidate:",e.candidate),null===(t=this.peer)||void 0===t||t.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const t=new Ht({sessid:this.session.sessionid,candidate:e.candidate,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,dialogParams:this.options});this._execute(t)}_addIceCandidate(e){if(!this._isRemoteDescriptionSet)return ke.debug("Remote description not set. Queued ICE candidate.",e),void this._pendingIceCandidates.push(e);this._addIceCandidateToPeer(e)}_addIceCandidateToPeer(e){const t=this.peer.instance.addIceCandidate(e);Promise.resolve(t).then((()=>{ke.debug("Successfully added ICE candidate:",e)})).catch((t=>{ke.error("Failed to add ICE candidate:",t,e)}))}_sendEndOfCandidates(){const e=new Wt({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var t;if(this._firstCandidateSent||(performance.mark(Fi(this.id,"first-candidate")),this._firstCandidateSent=!0),!this._firstNonHostCandidateSent){const i=null===(t=e.candidate.match(/typ (\w+)/))||void 0===t?void 0:t[1];i&&"host"!==i&&(performance.mark(Fi(this.id,"first-non-host-candidate")),this._firstNonHostCandidateSent=!0)}}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach((e=>{this._addIceCandidateToPeer(e)}))}_registerPeerEvents(e){e.onicecandidate=e=>{var t;this.options.trickleIce?this._onTrickleIce(e):(null===(t=this.peer)||void 0===t?void 0:t.iceDone)||this._onIce(e)},e.onicegatheringstatechange=t=>{ke.debug("ICE gathering state changed:",e.iceGatheringState,t),"complete"===e.iceGatheringState&&(ke.debug("Finished gathering candidates"),performance.mark(Fi(this.id,"ice-gathering-completed")))},e.onicecandidateerror=t=>{var i;if(ke.debug("ICE candidate error:",t),null===(i=this.peer)||void 0===i?void 0:i.statsReporter){const i=function(e,t){var i,n;return{errorCode:e.errorCode,errorText:e.errorText,url:e.url,address:e.address,port:e.port,connectionState:t.connectionState,iceConnectionState:t.iceConnectionState,iceGatheringState:t.iceGatheringState,signalingState:t.signalingState,localDescriptionType:null===(i=t.localDescription)||void 0===i?void 0:i.type,remoteDescriptionType:null===(n=t.remoteDescription)||void 0===n?void 0:n.type}}(t,e);this.peer.statsReporter.reportIceCandidateError(i)}},e.addEventListener("addstream",(e=>{this.options.remoteStream=e.stream})),e.addEventListener("track",(e=>{this.options.remoteStream=e.streams[0];const{remoteElement:t,remoteStream:i,screenShare:n}=this.options;!1===n&&Xt(t,i)}))}_onMediaError(e){const t=(null==e?void 0:e.name)||"UnknownError",i=(null==e?void 0:e.message)||"Unknown media error",n=(null==e?void 0:e.originalError)||e;this._dispatchNotification({type:it.userMediaError,error:n,call:this,errorName:t,errorMessage:i}),ke.error(`Media error (${t}): ${i}`,e),_t(de.Error,{error:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),this.hangup({initiator:"sdk:media-error"},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:it.peerConnectionFailureError,error:e.error}),ke.error("Peer connection failure error"),e.warning&&_t(de.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:it.signalingStateClosed},e)),ke.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:it.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(_t(de.Notification,e,this.id,!1)||_t(de.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_registerInboundAnswerAttempt(){if(this.options.attach||this._isRecovering)return!0;for(const e of this._getSessionInboundAnswerCalls()){if(e.id===this.id)continue;if(!e._isBlockingInboundAnswer())continue;const t=he(Q);return _t(de.Warning,{warning:t,callId:this.id,activeCallId:e.id,sessionId:this.session.sessionid,activeSessionId:e.session.sessionid},this.session.uuid),ke.warn(`[${this.id}] answer() ignored: inbound call ${e.id} is already answering or active`),!1}return!0}_getSessionInboundAnswerCalls(){return Object.values(this.session.calls).filter((e=>Boolean(e))).filter((e=>!e.options.attach&&!e._isRecovering&&e.direction===et.Inbound))}_isBlockingInboundAnswer(){var e;if([ot.Hangup,ot.Destroy,ot.Purge].includes(this._state))return!1;const t=[ot.Answering,ot.Early,ot.Active,ot.Held].includes(this._state);return!(!this._creatingPeer&&!t)&&(!(!this._creatingPeer||(null===(e=this.peer)||void 0===e?void 0:e.instance))||this._hasUsablePeerConnection())}_hasUsablePeerConnection(){var e;const t=null===(e=this.peer)||void 0===e?void 0:e.instance;return!!t&&("closed"!==t.signalingState&&("closed"!==t.connectionState&&"closed"!==t.iceConnectionState))}_init(){var e,t,i;const{id:n,userVariables:s,remoteCallerNumber:o,onNotification:r,recoveredCallId:c}=this.options;var d;this.options.id=n?n.toString():a(),this.id=this.options.id,c&&(this.recoveredCallId=c,this._isRecovering=!0),s&&(d=s,0!==Object.keys(d).length)||(this.options.userVariables=this.session.options.userVariables||{}),o||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,vt(de.MediaError,this._onMediaError,this.id),vt(de.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),vt(de.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Ne(r)&&vt(de.Notification,r.bind(this),this.id);const l=!1!==this.session.options.enableCallReports,u=this.session.options.callReportInterval||5e3,h=null!==(e=this.session.options.callReportFlushInterval)&&void 0!==e?e:18e4,p=this.session.options.debugLogLevel||"debug",g=this.session.options.debugLogMaxEntries||1e3;l&&(this._callReportCollector=new Ci({enabled:!0,interval:u,intermediateReportInterval:h},{enabled:!0,level:p,maxEntries:g}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=e=>{var t,i,n,s;_t(de.Warning,{warning:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),e.code===$?null===(i=(t=this.session).reportNoRtp)||void 0===i||i.call(t,this.id,"inbound"):e.code===H&&this._hasActiveUnmutedLocalAudioTrack()&&(null===(s=(n=this.session).reportNoRtp)||void 0===s||s.call(n,this.id,"outbound"))}),this._isRecovering?this.setState(ot.Recovering):this.setState(ot.New),ke.info(`New Call — region: ${null!==(t=this.session.region)&&void 0!==t?t:"unknown"}, dc: ${null!==(i=this.session.dc)&&void 0!==i?i:"unknown"}`,this.options)}_finalize(){var e,t;this._stopStats(),null===(e=this._mediaDeviceCollector)||void 0===e||e.stop(),this._mediaDeviceCollector=null,$i(this.id),ke.debug(`[${this.id}] Closing peer from _finalize`),null===(t=this.peer)||void 0===t||t.close();const{remoteStream:i,localStream:n,remoteElement:s,localElement:o}=this.options;ii(i),ii(n),Zt(s,i),Zt(o,n),ft(de.MediaError,null,this.id),ft(de.PeerConnectionFailureError,null,this.id),ft(de.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id];const r=this._postCallReport().catch((e=>{ke.error("Unexpected error in _postCallReport",{error:e})}));this.session.trackCallReportUpload(r)}_getCallReportVoiceSdkId(){return this.session.callReportVoiceSdkId||void 0}_getClientSummary(){var e,t,i,n,s,o,r,a,c,d,l,u;const h=this.session.options,p=h.anonymous_login;return{authentication:Object.assign({type:this._getAuthenticationType()},p?{anonymousLogin:{targetType:p.target_type,targetId:p.target_id,targetVersionId:p.target_version_id,targetParams:this._sanitizeClientOption(p.target_params)}}:{}),connection:{env:h.env,host:h.host,project:h.project,region:null!==(e=this.session.region)&&void 0!==e?e:h.region,dc:this.session.dc,rtcIp:h.rtcIp,rtcPort:h.rtcPort,autoReconnect:null===(t=h.autoReconnect)||void 0===t||t,maxReconnectAttempts:null!==(i=h.maxReconnectAttempts)&&void 0!==i?i:10,keepConnectionAliveOnSocketClose:null!==(n=h.keepConnectionAliveOnSocketClose)&&void 0!==n&&n,hangupOnBeforeUnload:!1!==h.hangupOnBeforeUnload,useCanaryRtcServer:null!==(s=h.useCanaryRtcServer)&&void 0!==s&&s,skipLastVoiceSdkId:null!==(o=h.skipLastVoiceSdkId)&&void 0!==o&&o,skipTrailing:null!==(r=h.skipTrailing)&&void 0!==r&&r},media:{audio:this._sanitizeClientOption(this.options.audio),video:this._sanitizeClientOption(this.options.video),mutedMicOnStart:null!==(a=this.options.mutedMicOnStart)&&void 0!==a&&a,prefetchIceCandidates:null===(c=this.options.prefetchIceCandidates)||void 0===c||c,forceRelayCandidate:null!==(d=this.options.forceRelayCandidate)&&void 0!==d&&d,trickleIce:null!==(l=this.options.trickleIce)&&void 0!==l&&l,iceServers:this._sanitizeIceServers(this.options.iceServers)},callReports:{enabled:!1!==h.enableCallReports,intervalMs:h.callReportInterval||5e3,flushIntervalMs:null!==(u=h.callReportFlushInterval)&&void 0!==u?u:18e4,debugLogLevel:h.debugLogLevel||"debug",debugLogMaxEntries:h.debugLogMaxEntries||1e3}}}_getAuthenticationType(){const e=this.session.options;return e.anonymous_login?"anonymous_login":e.login_token?"login_token":e.login&&(e.password||e.passwd)?"login_password":e.token?"token":"unknown"}_sanitizeIceServers(e){if(e&&0!==e.length)return e.map((({urls:e,username:t,credential:i})=>({urls:e,hasUsername:Boolean(t),hasCredential:Boolean(i)})))}_sanitizeClientOption(e,t=0){if(void 0!==e){if(null===e)return null;if("string"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?e:void 0;if("boolean"==typeof e)return e;if("function"!=typeof e){if(t>=4)return"[truncated]";if(Array.isArray(e))return e.map((e=>this._sanitizeClientOption(e,t+1))).filter((e=>void 0!==e));if("object"==typeof e){const i=Object.entries(e).filter((([e])=>!this._isSensitiveClientOptionKey(e))).map((([e,i])=>[e,this._sanitizeClientOption(i,t+1)])).filter((e=>void 0!==e[1]));return Object.fromEntries(i)}}}}_isSensitiveClientOptionKey(e){return/(password|passwd|credential|secret|token|authorization|auth|api[_-]?key)/i.test(e)}flushIntermediateCallReport(e={type:"manual"}){this._flushIntermediateReport(e)}_flushIntermediateReport(e={type:"buffer-limit"}){var t;if(!this._callReportCollector)return;const i=this.session.callReportId;if(!i)return void ke.debug("Cannot flush intermediate report: call_report_id not available");const n=null===(t=this.session.connection)||void 0===t?void 0:t.host;if(!n)return void ke.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===et.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Wi,clientSummary:this._getClientSummary()},o=this._callReportCollector.flush(s,e);if(!o)return;ke.info("Flushing intermediate call report",{callId:this.id,flushReason:e,segment:o.segment});const r=this._getCallReportVoiceSdkId(),a=this._callReportCollector.sendPayload(o,i,n,r).catch((e=>{ke.error("Failed to post intermediate call report segment",{error:e})}));this.session.trackCallReportUpload(a)}_postCallReport(){var e,i;return t(this,void 0,void 0,(function*(){if(!this._callReportCollector)return void ke.warn("Call report collector not initialized");yield this._callReportCollector.stop();const t=this.session.callReportId;if(!t)return ke.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const n={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===et.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Wi,clientSummary:this._getClientSummary()},s=null===(e=this.session.connection)||void 0===e?void 0:e.host;if(!s)return void ke.error("Cannot post call report: connection host not available");const o=this._getCallReportVoiceSdkId();try{yield this._callReportCollector.postReport(n,t,s,o)}catch(e){throw ke.error("Failed to post call report",{error:e}),e}finally{null===(i=this._callReportCollector)||void 0===i||i.cleanup()}}))}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),ke.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),ke.debug("Stats stopped")}}Bi.setStateTelnyx=e=>{if(e){switch(e._state){case ot.Recovering:e.state="recovering";break;case ot.Requesting:case ot.Trying:case ot.Early:e.state="connecting";break;case ot.Active:e.state="active";break;case ot.Held:e.state="held";break;case ot.Hangup:case ot.Destroy:e.state="done";break;case ot.Answering:e.state="ringing";break;case ot.New:e.state="new"}return e}};class Gi extends Bi{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,t)=>this.session.execute(new Si(e,t)),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 t=new Ii(e);this.session.connection.sendRawText(JSON.stringify(t.request))}}hangup(e={},i=!0){const n=Object.create(null,{hangup:{get:()=>super.hangup}});return t(this,void 0,void 0,(function*(){this.screenShare instanceof Gi&&(yield this.screenShare.hangup(e,i)),yield n.hangup.call(this,e,i)}))}startScreenShare(e){return t(this,void 0,void 0,(function*(){const i=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;i.getTracks().forEach((e=>{e.addEventListener("ended",(()=>t(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,c=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 Gi(this.session,c),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){return t(this,void 0,void 0,(function*(){this.screenShare instanceof Gi&&(yield this.screenShare.hangup({initiator:"app:stopScreenShare"}))}))}setAudioOutDevice(e){return t(this,void 0,void 0,(function*(){this.options.speakerId=e;const{remoteElement:t,speakerId:i}=this.options;return!(!t||!i)&&ei(t,i)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval((()=>t(this,void 0,void 0,(function*(){const e=yield this.peer.instance.getStats(null);let t="";const i=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],n=["id","type","timestamp"];e.forEach((e=>{i.includes(e.type)||(t+=`\n${e.type}\n`,Object.keys(e).forEach((i=>{n.includes(i)||(t+=`\t${i}: ${e[i]}\n`)})))})),ke.info(t)}))),2e3)}}class Vi extends Jt{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._onlineHandler=null,this._offlineHandler=null,this._wasOffline=!1,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile,this._setupNetworkListeners()}getActiveCalls(){return Object.values(this.calls).filter((e=>Vi.ACTIVE_CALL_STATE_NAMES.has(e.state)))}_extractSafeCallIdentifiers(e){var t,i;const n={callId:e.id,state:e.state,direction:e.direction};(null===(t=e.options)||void 0===t?void 0:t.telnyxSessionId)&&(n.telnyxSessionId=e.options.telnyxSessionId),(null===(i=e.options)||void 0===i?void 0:i.telnyxLegId)&&(n.telnyxLegId=e.options.telnyxLegId);const s=e.sipCallId;return"string"==typeof s&&s&&(n.sipCallId=s),n}emitMultipleActiveCallsWarning(e){const t=this.getActiveCalls().filter((t=>t.id!==e));if(0===t.length)return;const i=he(z),n=this.calls[e],s=n?this._extractSafeCallIdentifiers(n):{callId:e};_t(de.Warning,{warning:i,callId:e,sessionId:this.sessionid,newCall:s,activeCalls:t.map((e=>this._extractSafeCallIdentifiers(e)))},this.uuid),ke.warn(`MULTIPLE_ACTIVE_CALLS_DETECTED: new call ${e} created while ${t.length} other call(s) are active in session ${this.sessionid}`)}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return t(this,void 0,void 0,(function*(){return e.getIsRegistered.call(this)}))}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return t(this,void 0,void 0,(function*(){ke.debug("BrowserSession.connect() called"),e.connect.call(this)}))}checkPermissions(e=!0,i=!0){return t(this,void 0,void 0,(function*(){try{const t=yield ni({audio:e,video:i});return ii(t),!0}catch(e){return!1}}))}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return t(this,void 0,void 0,(function*(){ke.info("[disconnect] Client-initiated disconnect — setting Purge with BYE on all active calls.");for(const e in this.calls){const t=this.calls[e];t.setState(ot.Purge),ke.info("Start hangup for ",t),yield t.hangup({initiator:"app:client.disconnect"},!0)}this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)}))}serverDisconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return t(this,void 0,void 0,(function*(){ke.info("[serverDisconnect] Server-initiated disconnect — setting Purge without BYE on all active calls.");for(const e in this.calls){const t=this.calls[e];t.setState(ot.Purge),t.hangup({initiator:"sdk:server-disconnect"},!1)}this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)}))}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise(((t,i)=>{if(mt(de.SpeedTest,(i=>{const{upDur:n,downDur:s}=i,o=s?8*e/(s/1e3)/1024:0;t({upDur:n,downDur:s,upKps:(n?8*e/(n/1e3)/1024:0).toFixed(0),downKps:o.toFixed(0)})}),this.uuid),!(e=Number(e)))return i(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let n=e/1024;e%1024&&n++;const s=".".repeat(1024);for(let e=0;e<n;e++)this.executeRaw(`#SPB ${s}`);this.executeRaw("#SPE")}))}getDevices(){return si().catch((e=>{const t=me(ve(e),e);return _t(de.MediaError,t,this.uuid),[]}))}getVideoDevices(){return si(ct.Video).catch((e=>(_t(de.MediaError,e,this.uuid),[])))}getAudioInDevices(){return si(ct.AudioIn).catch((e=>{const t=me(ve(e),e);return _t(de.MediaError,t,this.uuid),[]}))}getAudioOutDevices(){return si(ct.AudioOut).catch((e=>(ke.error("getAudioOutDevices",e),_t(de.MediaError,e,this.uuid),[])))}validateDeviceId(e,t,i){return ri(e,t,i)}getDeviceResolutions(e){return t(this,void 0,void 0,(function*(){try{return yield(e=>t(void 0,void 0,void 0,(function*(){const t=[],i=yield ni({video:{deviceId:{exact:e}}}),n=i.getVideoTracks()[0];for(let e=0;e<oi.length;e++){const[i,s]=oi[e];(yield n.applyConstraints({width:{exact:i},height:{exact:s}}).then((()=>!0)).catch((()=>!1)))&&t.push({resolution:`${i}x${s}`,width:i,height:s})}return ii(i),t})))(e)}catch(e){throw e}}))}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(i){return t(this,void 0,void 0,(function*(){if(!i)throw new Error("You need to provide the settings object");const{micId:n,micLabel:s}=i,o=e(i,["micId","micLabel"]);return ai(o),this._audioConstraints=yield((e,i,n,s)=>t(void 0,void 0,void 0,(function*(){const{deviceId:t}=s;if(void 0===t&&(e||i)){const t=yield ri(e,i,n).catch((()=>null));t&&(s.deviceId={exact:t})}return s})))(n,s,"audioinput",o),this.micId=n,this.micLabel=s,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 e="development"===this.options.env;this._iceServers=e?ce:ae}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=Le(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=Le(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:t="",data:i}){if(!t)throw new Error(`Invalid channel for broadcast: ${t}`);const n=new Vt({sessid:this.sessionid,eventChannel:t,data:i});e&&(n.targetNodeId=e),this.execute(n).catch((e=>e))}vertoSubscribe({nodeId:e,channels:i=[],handler:n}){return t(this,void 0,void 0,(function*(){if(!(i=i.filter((e=>e&&!this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new qt({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const s=yield this.execute(t),{unauthorized:o=[],subscribed:r=[]}=ui(s);return o.length&&o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),r.forEach((e=>this._addSubscription(this.relayProtocol,n,e))),s}))}vertoUnsubscribe({nodeId:e,channels:i=[]}){return t(this,void 0,void 0,(function*(){if(!(i=i.filter((e=>e&&this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new Kt({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const n=yield this.execute(t),{unsubscribed:s=[],notSubscribed:o=[]}=ui(n);return s.forEach((e=>this._removeSubscription(this.relayProtocol,e))),o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),n}))}_setupNetworkListeners(){"undefined"!=typeof window&&(this._onlineHandler=()=>{this._wasOffline&&(ke.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,ke.debug(`Network connectivity lost for session ${this.sessionid}`);const e=me(D);_t(de.Error,{error:e,sessionId:this.sessionid},this.uuid)},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupNetworkListeners(){"undefined"!=typeof window&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null)}static telnyxStateCall(e){return Gi.setStateTelnyx(e)}}Vi.ACTIVE_CALL_STATE_NAMES=new Set(["new","requesting","trying","recovering","ringing","answering","early","active","held"]);class qi{constructor(e,t){this.code=t,this.message=e}}class Ki{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,t){const i=new xt(e,t);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*(e=2,t=6,Math.floor(Math.random()*(t-e+1)+e));var e,t}handleMessage(e){var t,i,n,s,o,r,a,c,d,l,u;const{session:h}=this;h.setPingReceived();const{id:p,method:g,params:v={},voice_sdk_id:m}=e,f=null==v?void 0:v.callID,_=null==v?void 0:v.eventChannel,y=null==v?void 0:v.eventType,b=h.calls[f],S=null===(t=null==b?void 0:b.peer)||void 0===t?void 0:t.isConnectionHealthy(),I=new Set(Object.keys(h.calls));if(Array.isArray(null==v?void 0:v.reattached_sessions)&&I.size){ke.debug(`Reattach: active call IDs before cleanup check: [${Array.from(I).join(", ")}].`);const e=0===v.reattached_sessions.length,t=v.reattached_sessions.some((e=>I.has(e)));if(e||!t)for(const e of Object.keys(h.calls)){const t=h.calls[e];ke.debug(`Session not reattached — terminating active call ${e} `);const i=me(N);_t(de.Error,{error:i,callId:e,sessionId:h.sessionid},h.uuid),t.hangup({},!1)}}if(Array.isArray(null==v?void 0:v.reattached_sessions)&&h.sessionid){const e=Qe();if(e&&e.calls.length>0)if(e.sessionId!==h.sessionid)ke.debug(`Recovery markers were saved for a different sessid (saved=${e.sessionId}, current=${h.sessionid}) — ignoring all.`);else{const t=new Set(v.reattached_sessions);for(const i of e.calls)try{if(t.has(i.id)){ke.debug(`Recovery marker for call ${i.id} was reattached — no notification.`);continue}ke.info(`Recovery marker for call ${i.id} (sessid=${h.sessionid}) was not reattached — emitting SESSION_NOT_REATTACHED.`);const e=me(N);_t(de.Error,{error:e,callId:i.id,sessionId:h.sessionid,customHeaders:i.customHeaders},h.uuid)}catch(e){ke.debug(`Recovery marker for a saved call failed to process (callId=${null==i?void 0:i.id}) — skipping: ${e instanceof Error?e.message:String(e)}`)}}}if("channelPvtData"===y)return this._handlePvtEvent(v.pvtData);const C=({recoveredCallId:e,forceRelayCandidateForRecovery:t,mutedMicOnStart:i}={})=>{var n,s,o,r,a;const c={audio:!0,video:h.options.video,remoteSdp:v.sdp,destinationNumber:v.callee_id_number,remoteCallerName:v.caller_id_name,remoteCallerNumber:v.caller_id_number,callerName:v.callee_id_name,callerNumber:v.callee_id_number,attach:g===tt.Attach,mediaSettings:v.mediaSettings,debug:null!==(n=h.options.debug)&&void 0!==n&&n,debugOutput:null!==(s=h.options.debugOutput)&&void 0!==s?s:"socket",trickleIce:null!==(o=h.options.trickleIce)&&void 0!==o&&o,prefetchIceCandidates:null===(r=h.options.prefetchIceCandidates)||void 0===r||r,forceRelayCandidate:t||h.options.forceRelayCandidate||!1,keepConnectionAliveOnSocketClose:null!==(a=h.options.keepConnectionAliveOnSocketClose)&&void 0!==a&&a,mutedMicOnStart:null!=i?i:h.options.mutedMicOnStart};f&&(c.id=f),v.telnyx_call_control_id&&(c.telnyxCallControlId=v.telnyx_call_control_id),v.telnyx_session_id&&(c.telnyxSessionId=v.telnyx_session_id),v.telnyx_leg_id&&(c.telnyxLegId=v.telnyx_leg_id),v.client_state&&(c.clientState=v.client_state),v.dialogParams&&v.dialogParams.custom_headers&&v.dialogParams.custom_headers.length&&(c.customHeaders=v.dialogParams.custom_headers),e&&(c.recoveredCallId=e),performance.mark(Fi(c.id,"new-call-start"));const d=new Gi(h,c);return d.nodeId=this.nodeId,d},E=new At(m),R=new Dt(m);switch(g){case tt.Answer:case tt.Display:case tt.Candidate:case tt.Ringing:case tt.Bye:case tt.Media:if(!f||!b)return void ke.error(`Received ${g} for non existing call:`,v);b.handleMessage(e),this._ack(p,g);break;case tt.Ping:this.session.setPingReceived(),this.session.execute(R);break;case tt.Punt:h.options.keepConnectionAliveOnSocketClose&&S?(ke.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),h.socketDisconnect(),this._ack(p,g)):(ke.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),h.serverDisconnect());break;case tt.Invite:{const e=C();e.direction=et.Inbound,e.playRingtone(),e.setState(ot.Ringing),this.session.emitMultipleActiveCallsWarning(e.id),this._ack(p,g);break}case tt.Attach:{const e=b||null;if(0===Object.keys(h.calls).length){ke.warn(`[${(new Date).toISOString()}][${f}] Attach: SDK doens't have any active call therefore we recover first arrived attach session ${f}`);const e=C({recoveredCallId:f});e.answer(),this.session.emitMultipleActiveCallsWarning(e.id),this._ack(p,g);break}if(e){const t=e.id,s=null!==(n=null===(i=e.shouldForceRelayCandidateForRecovery)||void 0===i?void 0:i.call(e))&&void 0!==n&&n;s&&ke.warn(`[${(new Date).toISOString()}][${f}] Attach: forcing relay candidate because recovered VPN media path is still stalled`),ke.info(`[${(new Date).toISOString()}][${f}] Attach: recovering active call ${t}.`),e.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1);const o=C({recoveredCallId:t,forceRelayCandidateForRecovery:s,mutedMicOnStart:e.isAudioMuted});o.answer(),this.session.emitMultipleActiveCallsWarning(o.id),this._ack(p,g);break}ke.warn(`Attach: callID ${f} does not match any active calls. `),_t(de.Warning,{warning:he(Z),callId:f,params:v,sessionId:h.sessionid},h.uuid),this._ack(p,g);break}case tt.Event:case"webrtc.event":if(!_)return void ke.error("Verto received an unknown event:",v);const t=h.relayProtocol,y=_.split(".")[0];h._existsSubscription(t,_)?_t(t,v,_):_===h.sessionid?this._handleSessionEvent(v.eventData):h._existsSubscription(t,y)?_t(t,v,y):h.calls.hasOwnProperty(_)?h.calls[_].handleMessage(e):_t(de.Notification,v,h.uuid);break;case tt.Info:v.type=it.generic,_t(de.Notification,v,h.uuid);break;case tt.ClientReady:this.session.execute(E);break;case"ai_conversation":_t(de.AIConversationMessage,{method:"ai_conversation",params:v,voice_sdk_id:m},h.uuid);break;default:{const t=Fe(e);if(t){switch(t){case dt.REGISTER:case dt.REGED:if(!this.isDuplicateGatewayState(t,[dt.REGED,dt.REGISTER])){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0,t===dt.REGED&&this.session.resetReconnectAttempts();const i=null===(o=null===(s=null==e?void 0:e.result)||void 0===s?void 0:s.params)||void 0===o?void 0:o.call_report_id;i&&(h.callReportId=i,ke.debug("Captured call_report_id from REGED:",i));const n=null===(a=null===(r=null==e?void 0:e.result)||void 0===r?void 0:r.params)||void 0===a?void 0:a.dc;n&&(h.dc=n);const p=null===(d=null===(c=null==e?void 0:e.result)||void 0===c?void 0:c.params)||void 0===d?void 0:d.region;p&&(h.region=p),ke.info(`Connected to Telnyx — region: ${null!==(l=h.region)&&void 0!==l?l:"unknown"}, dc: ${null!==(u=h.dc)&&void 0!==u?u:"unknown"}`),v.type=it.vertoClientReady,_t(de.Ready,v,h.uuid)}break;case dt.UNREGED:case dt.NOREG:if(this.retriedRegister+=1,5===this.retriedRegister){this.retriedRegister=0;const e=new qi("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),t=me(T,e);_t(de.Error,{error:t,sessionId:h.sessionid},h.uuid);break}setTimeout((()=>{this.session.execute(E)}),this.reconnectDelay());break;case dt.FAILED:case dt.FAIL_WAIT:case dt.TIMEOUT:if(!this.isDuplicateGatewayState(t,[dt.FAILED,dt.FAIL_WAIT,dt.TIMEOUT])){const e=me(w,new Error(`Gateway state: ${t}`));if(_t(de.Error,{error:e,sessionId:h.sessionid},h.uuid),h.options.skipLastVoiceSdkId=!0,ke.debug(`Set skipLastVoiceSdkId=true on session options to avoid sticky reconnect to same b2bua-rtc instance (sessionId=${h.sessionid})`),!this.session.hasAutoReconnect()){this.retriedConnect=0;const e=new qi("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT|TIMEOUT");this.session._terminateActiveCallsLocally();const t=me(k,e);_t(de.Error,{error:t,sessionId:h.sessionid},h.uuid);break}if(this.retriedConnect+=1,5===this.retriedConnect){this.retriedConnect=0,this.session._terminateActiveCallsLocally();const e=me(k,new Error("Connection Retry Failed"));_t(de.Error,{error:e,sessionId:h.sessionid},h.uuid);break}setTimeout((()=>{if(ke.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){const e=Object.values(h.calls).some((e=>{var t;return(null===(t=e.peer)||void 0===t?void 0:t.instance)&&!e.signalingStateClosed}));if(e)return ke.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();ke.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:ke.warn("GatewayState message unknown method:",e)}break}ke.debug("Verto message unknown method:",e);break}}}isDuplicateGatewayState(e,t){const{previousGatewayState:i}=this.session.connection,n=t.includes(i);return n&&ke.debug(`Gateway state '${e}' received but previous state was '${i}' — guard condition met, skipping re-emission (sessionId=${this.session.sessionid})`),n}_retrieveCallId(e,t){const i=Object.keys(this.session.calls);if("bootObj"!==e.action)return i.find((e=>this.session.calls[e].channels.includes(t)));{const t=e.data.find((e=>i.includes(e[0])));if(t instanceof Array)return t[0]}}_handlePvtEvent(e){return t(this,void 0,void 0,(function*(){const{session:t}=this,i=t.relayProtocol,{action:n,laChannel:s,laName:o,chatChannel:r,infoChannel:a,modChannel:c,conferenceMemberID:d,role:l,callID:u}=e;switch(n){case"conference-liveArray-join":{const i=()=>{t.vertoBroadcast({nodeId:this.nodeId,channel:s,data:{liveArray:{command:"bootstrap",context:s,name:o}}})},n={nodeId:this.nodeId,channels:[s],handler:({data:n})=>{const r=u||this._retrieveCallId(n,s);if(r&&t.calls.hasOwnProperty(r)){const a=t.calls[r];a._addChannel(s),a.extension=o,a.handleConferenceUpdate(n,e).then((e=>{"INVALID_PACKET"===e&&i()}))}}},r=yield t.vertoSubscribe(n).catch((e=>{ke.error("liveArray subscription error:",e);const i=me(S,e);_t(de.Error,{error:i,sessionId:t.sessionid},t.uuid)}));li(r,s)&&i();break}case"conference-liveArray-part":{let e=null;if(s&&t._existsSubscription(i,s)){const{callId:n=null}=t.subscriptions[i][s];if(e=t.calls[n]||null,null!==n){const i={type:it.conferenceUpdate,action:at.Leave,conferenceName:o,participantId:Number(d),role:l};_t(de.Notification,i,n,!1)||_t(de.Notification,i,t.uuid),null===e&&ft(de.Notification,null,n)}}const n=[s,r,a,c];t.vertoUnsubscribe({nodeId:this.nodeId,channels:n}).then((({unsubscribedChannels:t=[]})=>{e&&(e.channels=e.channels.filter((e=>!t.includes(e))))})).catch((e=>{ke.error("liveArray unsubscribe error:",e)}));break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":Pi(this.session,e);break;case"logo-info":{const t={type:it.conferenceUpdate,action:at.LogoInfo,logo:e.logoURL};_t(de.Notification,t,this.session.uuid);break}}}}class Yi extends Vi{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>t(this,void 0,void 0,(function*(){this._idle=!1;const{autoReconnect:e=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=e}})})),this.handleAnonymousLoginOnSocketOpen=()=>t(this,void 0,void 0,(function*(){this._idle=!1,yield this.login()})),this._vertoHandler=new Ki(this),window.addEventListener("beforeunload",(t=>{if(ke.debug("Window beforeunload triggered."),!1!==e.hangupOnBeforeUnload)return Je(),void(this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&(ke.info(`Hanging up call due to window unload: ${e}`),this.calls[e].hangup({initiator:"sdk:beforeunload"},!0))})));try{const e=(this.calls?Object.keys(this.calls):[]).filter((e=>!!this.calls[e])).map((e=>this.calls[e])).map((e=>({id:e.id,customHeaders:e.options.customHeaders})));if(!this.sessionid||0===e.length)return ke.debug(`No sessionID ${this.sessionid} or activeCalls ${e.length} during saving calls recover marker!`),void ze();ke.info(`Saving recovery marker for ${e.length} active call(s) before unload (sessid=${this.sessionid}): [${e.map((e=>e.id)).join(", ")}].`),Xe(e,this.sessionid)}catch(e){const t=this.calls?Object.keys(this.calls):[];ke.debug(`Failed to save active-calls recovery marker before unload (active call ids: [${t.join(", ")}]): ${e instanceof Error?e.message:String(e)}`)}})),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&!1===e.hangupOnBeforeUnload&&this.sessionid&&this.hasActiveCall()&&(ke.debug("visibilitychange → hidden: re-stamping reconnect session-id freshness."),Ye(this.sessionid))}))}validateOptions(){return xe(this.options)||Ue(this.options)}newCall(e){if(!this.validateCallOptions(e)){throw me(y,void 0,"Error: destinationNumber is required")}const t=new Gi(this,e);return e.id||ke.debug(`newCall: callId was not provided in options, SDK-generated ID: ${t.id}`),this.emitMultipleActiveCallsWarning(t.id),performance.mark(Fi(t.id,"new-call-start")),t.invite(),t}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!Ue(this.options)||Boolean(e.destinationNumber)}_onSocketOpen(){const e=Object.create(null,{_onSocketOpen:{get:()=>super._onSocketOpen}});return t(this,void 0,void 0,(function*(){return e._onSocketOpen.call(this),xe(this.options)?this.handleLoginOnSocketOpen():Ue(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0}))}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class Ji extends Yi{constructor(e){super(e),ke.info(`SDK version: ${Lt}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return vi()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:mi.full},{browserName:"Firefox",features:["audio"],supported:mi.partial},{browserName:"Safari",supported:mi.not_supported},{browserName:"Edge",supported:mi.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:mi.not_supported},{browserName:"Firefox",supported:mi.not_supported},{browserName:"Safari",features:["video","audio"],supported:mi.full},{browserName:"Edge",supported:mi.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:mi.full},{browserName:"Firefox",features:["audio"],supported:mi.partial},{browserName:"Safari",supported:mi.not_supported},{browserName:"Edge",supported:mi.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:mi.full},{browserName:"Firefox",features:["audio"],supported:mi.partial},{browserName:"Safari",features:["video","audio"],supported:mi.full},{browserName:"Edge",features:["audio"],supported:mi.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:mi.full},{browserName:"Firefox",features:["audio"],supported:mi.partial},{browserName:"Safari",supported:mi.not_supported},{browserName:"Edge",features:["audio"],supported:mi.partial}]}]}}class zi{static run(e){return t(this,void 0,void 0,(function*(){const t=je({}),i=je({}),n=new Ji(e.credentials);yield n.connect(),n.on(de.Ready,t.resolve),n.on(de.Error,t.reject),n.on(de.MediaError,t.reject),n.on(de.MediaError,t.reject),n.on(de.Notification,(e=>{e.call&&e.call.sipCode>=400&&i.reject(new Error(e.call.sipReason))})),vt(de.StatsReport,(e=>{i.resolve(zi.mapReport(e))})),yield t.promise,yield n.newCall({destinationNumber:e.texMLApplicationNumber,debug:!0});const s=yield i.promise;return yield n.disconnect(),s}))}static mapReport(e){var t,i,n,s,o,r,a,c,d,l,u,h,p;const g=[],v=[];for(const t of e)switch(t.event){case"onicecandidate":t.data&&g.push(t.data);break;case"stats":v.push(t.data)}let m=0,f=1/0,_=-1/0,y=0,b=1/0,S=-1/0,I=0;v.forEach((e=>{var t,i,n;if(!(null===(t=e.remote.audio.inbound)||void 0===t?void 0:t[0]))return;m+=1;const s=null!==(i=e.remote.audio.inbound[0].jitter)&&void 0!==i?i:0,o=null!==(n=e.remote.audio.inbound[0].roundTripTime)&&void 0!==n?n:0;y+=s,I+=o,_=Math.max(_,s),f=Math.min(f,s),S=Math.max(S,o),b=Math.min(b,o)}));const C=I/m,E=y/m,k=v[v.length-1],w=Ri({jitter:1e3*E,rtt:1e3*C,packetsReceived:null!==(n=null===(i=null===(t=k.audio.inbound)||void 0===t?void 0:t[0])||void 0===i?void 0:i.packetsReceived)&&void 0!==n?n:0,packetsLost:null!==(r=null===(o=null===(s=k.audio.inbound)||void 0===s?void 0:s[0])||void 0===o?void 0:o.packetsLost)&&void 0!==r?r:0});return{iceCandidatePairStats:v[v.length-1].connection,summaryStats:{mos:w,jitter:{average:E,max:_,min:f},rtt:{average:C,max:S,min:b},quality:Ai(w)},sessionStats:{packetsSent:null!==(a=k.connection.packetsSent)&&void 0!==a?a:0,bytesSent:null!==(c=k.connection.bytesSent)&&void 0!==c?c:0,bytesReceived:null!==(d=k.connection.bytesReceived)&&void 0!==d?d:0,packetsLost:null!==(h=null===(u=null===(l=k.remote.audio.inbound)||void 0===l?void 0:l[0])||void 0===u?void 0:u.packetsLost)&&void 0!==h?h:0,packetsReceived:null!==(p=k.connection.packetsReceived)&&void 0!==p?p:0},iceCandidateStats:g}}getTelnyxIds(){return{telnyxCallControlId:"",telnyxSessionId:"",telnyxLegId:""}}}function Qi(e){if(!e||"object"!=typeof e)return!1;if("conversation.item.created"!==e.type)return!1;const t=e.item;if("object"!=typeof t||null===t)return!1;const i=t;return"function_call"===i.type&&"string"==typeof i.call_id&&"string"==typeof i.name&&"string"==typeof i.arguments}function Xi(e){if(!e||"object"!=typeof e)return!1;if("conversation.item.create"!==e.type)return!1;const t=e.item;if("object"!=typeof t||null===t)return!1;const i=t;return"function_call_output"===i.type&&"string"==typeof i.call_id&&"string"==typeof i.output}export{Gi as Call,nt as ERROR_TYPE,it as NOTIFICATION_TYPE,zi as PreCallDiagnosis,le as SDK_ERRORS,ue as SDK_WARNINGS,de as SwEvent,c as TELNYX_ERROR_CODES,d as TELNYX_WARNING_CODES,pe as TelnyxError,Ji as TelnyxRTC,Xi as isFunctionCallOutputParams,Qi as isFunctionCallParams,ge as isMediaRecoveryErrorEvent};
1
+ function e(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}function t(e,t,i,n){return new(i||(i=Promise))((function(s,o){function r(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var i="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),n=new Uint8Array(16);function s(){if(!i)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return i(n)}for(var o=[],r=0;r<256;++r)o[r]=(r+256).toString(16).substr(1);function a(e,t,i){var n=t&&i||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var r=(e=e||{}).random||(e.rng||s)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t)for(var a=0;a<16;++a)t[n+a]=r[a];return t||function(e,t){var i=t||0,n=o;return[n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]]].join("")}(r)}const c={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},l={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,TOKEN_EXPIRING_SOON:34001,UNKNOWN_REATTACHED_SESSION:35002,SIGNALING_RECOVERY_REQUIRED:36003,MEDIA_RECOVERY_REQUIRED:36004,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:36005},{SDP_CREATE_OFFER_FAILED:d,SDP_CREATE_ANSWER_FAILED:u,SDP_SET_LOCAL_DESCRIPTION_FAILED:h,SDP_SET_REMOTE_DESCRIPTION_FAILED:p,SDP_SEND_FAILED:g,MEDIA_MICROPHONE_PERMISSION_DENIED:v,MEDIA_DEVICE_NOT_FOUND:m,MEDIA_GET_USER_MEDIA_FAILED:f,HOLD_FAILED:_,INVALID_CALL_PARAMETERS:y,BYE_SEND_FAILED:b,SUBSCRIBE_FAILED:S,PEER_CLOSED_DURING_INIT:I,WEBSOCKET_CONNECTION_FAILED:C,WEBSOCKET_ERROR:E,RECONNECTION_EXHAUSTED:k,GATEWAY_FAILED:w,LOGIN_FAILED:T,INVALID_CREDENTIALS:R,AUTHENTICATION_REQUIRED:A,ICE_RESTART_FAILED:O,NETWORK_OFFLINE:D,SESSION_NOT_REATTACHED:N,UNEXPECTED_ERROR:L}=c,{HIGH_RTT:M,HIGH_JITTER:P,HIGH_PACKET_LOSS:x,LOW_MOS:U,LOW_LOCAL_AUDIO:F,LOW_INBOUND_AUDIO:$,LOW_BYTES_RECEIVED:j,LOW_BYTES_SENT:B,RECORDING_UNAVAILABLE:W,RECORDING_BUFFER_OVERFLOW:H,ICE_CONNECTIVITY_LOST:G,ICE_GATHERING_TIMEOUT:V,ICE_GATHERING_EMPTY:q,PEER_CONNECTION_FAILED:K,ONLY_HOST_ICE_CANDIDATES:Y,ANSWER_WHILE_PEER_ACTIVE:J,ICE_CANDIDATE_PAIR_CHANGED:z,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:Q,MULTIPLE_ACTIVE_CALLS_DETECTED:X,DUPLICATE_INBOUND_ANSWER:Z,TOKEN_EXPIRING_SOON:ee,UNKNOWN_REATTACHED_SESSION:te,SIGNALING_RECOVERY_REQUIRED:ie,MEDIA_RECOVERY_REQUIRED:ne,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:se}=l,oe=/^a=candidate:.+typ (srflx|prflx|relay)/m,re="wss://rtc.telnyx.com",ae={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},ce={urls:"stun:stun.l.google.com:19302"},le=[{urls:"stun:stun.telnyx.com:3478"},ce,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],de=[{urls:"stun:stundev.telnyx.com:3478"},ce,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}];var ue;!function(e){e.SocketOpen="telnyx.socket.open",e.SocketClose="telnyx.socket.close",e.SocketError="telnyx.socket.error",e.SocketMessage="telnyx.socket.message",e.SpeedTest="telnyx.internal.speedtest",e.SocketActivity="telnyx.internal.socketActivity",e.Ready="telnyx.ready",e.Error="telnyx.error",e.Warning="telnyx.warning",e.Notification="telnyx.notification",e.StatsFrame="telnyx.stats.frame",e.StatsReport="telnyx.stats.report",e.Messages="telnyx.messages",e.Calls="telnyx.calls",e.MediaError="telnyx.rtc.mediaError",e.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError",e.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed",e.AIConversationMessage="telnyx.ai.conversation"}(ue||(ue={}));const he={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 invalid 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 infrastructure 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}},pe={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-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 but only host (local network) candidates were collected — no server-reflexive (srflx) or relay (turn) candidates were found. This typically means the STUN/TURN servers are unreachable, which will prevent connections outside the local network.",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"]},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 ge(e,t){const i=pe[e];return{code:e,name:i.name,message:t||i.message,description:i.description,causes:[...i.causes],solutions:[...i.solutions]}}class ve 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,ve.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 me(e){return!0===e.recoverable}function fe(e){if(e instanceof DOMException){if("NotAllowedError"===e.name)return v;if("NotFoundError"===e.name||"OverconstrainedError"===e.name)return m}return f}function _e(e,t,i,n){const s=he[e],o=t instanceof Error?t:void 0!==t?new Error(String(t)):void 0;return new ve({code:e,name:s.name,description:s.description,message:i||s.message,causes:[...s.causes],solutions:[...s.solutions],originalError:o,fatal:null!=n?n:s.fatal})}class ye extends Error{constructor(e,t,i=""){super(`Signaling request timed out (id=${e}, method=${i||"unknown"}, timeout=${t}ms)`),this.name="RequestTimeoutError",this.requestId=e,this.timeoutMs=t,this.method=i}}class be extends Error{constructor(e,t,i){super(`Stale request cancelled (id=${e}, gen=${t}, current=${i})`),this.name="StaleRequestError",this.requestId=e,this.staleGeneration=t,this.currentGeneration=i}}var Se="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Ie(e,t){return e(t={exports:{}},t.exports),t.exports}var Ce=Ie((function(e){var t,i;t=Se,i=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"];function s(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,arguments])}}}function o(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function r(t,i){for(var s=0;s<n.length;s++){var o=n[s];this[o]=s<t?e:this.methodFactory(o,t,i)}this.log=this.debug}function a(e,i,n){return function(){typeof console!==t&&(r.call(this,i,n),this[e].apply(this,arguments))}}function c(n,r,c){return function(n){return"debug"===n&&(n="log"),typeof console!==t&&("trace"===n&&i?o:void 0!==console[n]?s(console,n):void 0!==console.log?s(console,"log"):e)}(n)||a.apply(this,arguments)}function l(e,i,s){var o,a=this;i=null==i?"WARN":i;var l="loglevel";function d(){var e;if(typeof window!==t&&l){try{e=window.localStorage[l]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=i.indexOf(encodeURIComponent(l)+"=");-1!==n&&(e=/^([^;]+)/.exec(i.slice(n))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?l+=":"+e:"symbol"==typeof e&&(l=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=s||c,a.getLevel=function(){return o},a.setLevel=function(i,s){if("string"==typeof i&&void 0!==a.levels[i.toUpperCase()]&&(i=a.levels[i.toUpperCase()]),!("number"==typeof i&&i>=0&&i<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+i;if(o=i,!1!==s&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&l){try{return void(window.localStorage[l]=i)}catch(e){}try{window.document.cookie=encodeURIComponent(l)+"="+i+";"}catch(e){}}}(i),r.call(a,i,e),typeof console===t&&i<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){i=e,d()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(i,!1),function(){if(typeof window!==t&&l){try{return void window.localStorage.removeItem(l)}catch(e){}try{window.document.cookie=encodeURIComponent(l)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var u=d();null==u&&(u=i),a.setLevel(u,!1)}var d=new l,u={};d.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=u[e];return t||(t=u[e]=new l(e,d.getLevel(),d.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return d.noConflict=function(){return typeof window!==t&&window.log===d&&(window.log=h),d},d.getLoggers=function(){return u},d.default=d,d},e.exports?e.exports=i():t.log=i()}));const Ee={debug:0,info:1,warn:2,error:3};class ke{constructor(e={}){var t,i,n;this.buffer=[],this.isCapturing=!1,this.options={enabled:null!==(t=e.enabled)&&void 0!==t&&t,level:null!==(i=e.level)&&void 0!==i?i:"debug",maxEntries:null!==(n=e.maxEntries)&&void 0!==n?n:1e3}}start(){this.options.enabled&&(this.isCapturing=!0,this.buffer=[])}stop(){this.isCapturing=!1}addEntry(e,t,i){if(!this.isCapturing||!this.options.enabled)return;if(Ee[e]<Ee[this.options.level])return;const n=Object.assign({timestamp:(new Date).toISOString(),level:e,message:t},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 e=this.buffer;return this.buffer=[],e}clear(){this.buffer=[]}isActive(){return this.isCapturing}isEnabled(){return this.options.enabled}}let we=null;const Te=Ce.getLogger("telnyx"),Re={trace:0,debug:1,info:2,warn:3,error:4};let Ae=Re.info;function Oe(e){if(null==e)return e;if("object"!=typeof e)return e;try{const t=JSON.stringify(e),i=JSON.parse(t);if("object"==typeof i&&null!==i&&Object.keys(i).length>1)return i}catch(e){}const t={};for(const i in e)try{const n=e[i];if("function"==typeof n)continue;if("object"==typeof n&&null!==n)try{t[i]=JSON.parse(JSON.stringify(n))}catch(e){t[i]=String(n)}else t[i]=n}catch(e){}return Object.keys(t).length>0?t:{value:String(e)}}const De=Te.methodFactory;Te.methodFactory=(e,t,i)=>{const n=De(e,t,i);return function(...t){if(Re[e]>=Ae){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(const i of t)e.push(i);n(...e)}const i=we;if(null==i?void 0:i.isActive()){const[n,...s]=t,o="string"==typeof n?n:JSON.stringify(n);let r;s.length>0&&(r=1===s.length&&"object"==typeof s[0]&&null!==s[0]?Oe(s[0]):{args:s.map(Oe)}),i.addEntry(e,o,r)}}},Te.setLevel("debug",!1);const Ne=e=>{const[t,i,n,s,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){Te.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},Le=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},Me=e=>e instanceof Function||"function"==typeof e,Pe=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,xe=/^(ws|wss):\/\//,Ue=(e,t=null)=>{const{result:i={},error:n}=e;if(n)return{error:n};const{result:s=null}=i;if(null===s)return null!==t&&(i.node_id=t),{result:i};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&"200"!==o?{error:s}:a?Ue(a,r):{result:s}},Fe=({login:e,passwd:t,password:i,login_token:n})=>Boolean(e&&(t||i)||n),$e=({anonymous_login:e})=>Boolean(e)&&Boolean(e.target_id)&&Boolean(e.target_type),je=e=>{var t,i,n,s,o,r;let a="",c="";(null===(i=null===(t=null==e?void 0:e.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state)&&(a=null===(s=null===(n=null==e?void 0:e.result)||void 0===n?void 0:n.params)||void 0===s?void 0:s.state),(null===(o=null==e?void 0:e.params)||void 0===o?void 0:o.state)&&(c=null===(r=null==e?void 0:e.params)||void 0===r?void 0:r.state);return a||c};function Be({debounceTime:e}){let t,i;return{promise:new Promise(((n,s)=>{t=e?We(n,e):n,i=s})),resolve:t,reject:i}}const We=(e,t)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout((()=>{e(...n)}),t)}},He="telnyx-voice-sdk-id",Ge="telnyx-voice-sdk-session-id",Ve="telnyx-voice-sdk-session-id-stored-at",qe="telnyx-voice-sdk-active-calls",Ke=9e4;function Ye(e=Date.now()){const t=function(){const e=Number(sessionStorage.getItem(Ve));return Number.isFinite(e)?e:null}();return null!==t&&e-t<=Ke}function Je(){return sessionStorage.getItem(He)}function ze(e,t=Date.now()){sessionStorage.setItem(Ge,e),sessionStorage.setItem(Ve,String(t))}function Qe(){sessionStorage.removeItem(He),sessionStorage.removeItem(Ge),sessionStorage.removeItem(Ve)}function Xe(){!function(e){try{sessionStorage.removeItem(e)}catch(t){Te.debug(`safeRemoveItem('${e}') failed: ${t instanceof Error?t.message:String(t)}`)}}(qe)}function Ze(e=Date.now()){const t=function(e){try{return sessionStorage.getItem(e)}catch(t){return Te.debug(`safeGetItem('${e}') failed: ${t instanceof Error?t.message:String(t)}`),null}}(qe);if(Xe(),!t)return Te.debug("Active-calls recovery marker not found in storage — nothing to recover."),null;try{const i=JSON.parse(t);if(!i||"object"!=typeof i||!Array.isArray(i.calls))return Te.debug("Active-calls recovery marker payload was malformed — discarded."),null;const n=Number(i.storedAt);return!Number.isFinite(n)||e-n>9e5?(Te.debug("Active-calls recovery marker was stale or had an invalid timestamp — discarded."),null):0===i.calls.length?(Te.debug("Active-calls recovery marker had no call records — discarded."),null):i}catch(e){return Te.debug(`Active-calls recovery marker JSON parse failed — discarded: ${e instanceof Error?e.message:String(e)}`),null}}function et(e,t,i=Date.now()){if(!Array.isArray(e)||0===e.length)return void Xe();const n={sessionId:t,calls:e,storedAt:i};!function(e,t){try{sessionStorage.setItem(e,t)}catch(t){Te.info(`safeSetItem('${e}') failed: ${t instanceof Error?t.message:String(t)}`)}}(qe,JSON.stringify(n))}var tt,it,nt;!function(e){e.Offer="offer",e.Answer="answer"}(tt||(tt={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(it||(it={})),function(e){e.Invite="telnyx_rtc.invite",e.Attach="telnyx_rtc.attach",e.Answer="telnyx_rtc.answer",e.Info="telnyx_rtc.info",e.Candidate="telnyx_rtc.candidate",e.EndOfCandidates="telnyx_rtc.endOfCandidates",e.Display="telnyx_rtc.display",e.Media="telnyx_rtc.media",e.Event="telnyx_rtc.event",e.Bye="telnyx_rtc.bye",e.Punt="telnyx_rtc.punt",e.Broadcast="telnyx_rtc.broadcast",e.Subscribe="telnyx_rtc.subscribe",e.Unsubscribe="telnyx_rtc.unsubscribe",e.ClientReady="telnyx_rtc.clientReady",e.Modify="telnyx_rtc.modify",e.Ringing="telnyx_rtc.ringing",e.GatewayState="telnyx_rtc.gatewayState",e.Ping="telnyx_rtc.ping",e.Pong="telnyx_rtc.pong"}(nt||(nt={}));const st={generic:"event",[nt.Display]:"participantData",[nt.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},ot={invalidCredentialsOptions:"InvalidCredentialsOptions"},rt=24e4,at=8e6,ct={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:!0};var lt,dt,ut,ht,pt,gt;!function(e){e[e.New=0]="New",e[e.Requesting=1]="Requesting",e[e.Trying=2]="Trying",e[e.Recovering=3]="Recovering",e[e.Ringing=4]="Ringing",e[e.Answering=5]="Answering",e[e.Early=6]="Early",e[e.Active=7]="Active",e[e.Held=8]="Held",e[e.Hangup=9]="Hangup",e[e.Destroy=10]="Destroy",e[e.Purge=11]="Purge"}(lt||(lt={})),function(e){e.Participant="participant",e.Moderator="moderator"}(dt||(dt={})),function(e){e.Join="join",e.Leave="leave",e.Bootstrap="bootstrap",e.Add="add",e.Modify="modify",e.Delete="delete",e.Clear="clear",e.ChatMessage="chatMessage",e.LayerInfo="layerInfo",e.LogoInfo="logoInfo",e.LayoutInfo="layoutInfo",e.LayoutList="layoutList",e.ModCmdResponse="modCommandResponse"}(ut||(ut={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(ht||(ht={})),function(e){e.REGED="REGED",e.UNREGED="UNREGED",e.NOREG="NOREG",e.FAILED="FAILED",e.FAIL_WAIT="FAIL_WAIT",e.TIMEOUT="TIMEOUT",e.REGISTER="REGISTER",e.TRYING="TRYING",e.EXPIRED="EXPIRED",e.UNREGISTER="UNREGISTER"}(pt||(pt={})),function(e){e.Hold="hold",e.Unhold="unhold",e.ToggleHold="toggleHold",e.UpdateMedia="updateMedia"}(gt||(gt={}));const vt="GLOBAL",mt={},ft=(e,t)=>`${e}|${t}`,_t=(e,t=vt)=>ft(e,t)in mt,yt=(e,t,i=vt)=>{const n=ft(e,i);n in mt||(mt[n]=[]),mt[n].push(t)},bt=(e,t,i=vt)=>{const n=function(s){St(e,n,i),t(s)};return n.prototype.targetRef=t,yt(e,n,i)},St=(e,t,i=vt)=>{if(!_t(e,i))return!1;const n=ft(e,i);if(Me(t)){for(let e=mt[n].length-1;e>=0;e--){const i=mt[n][e];(t===i||i.prototype&&t===i.prototype.targetRef)&&mt[n].splice(e,1)}}else mt[n]=[];return 0===mt[n].length&&delete mt[n],!0},It=(e,t,i=vt,n=!0)=>{const s=n&&i!==vt;if(!_t(e,i))return s&&It(e,t),!1;const o=ft(e,i),r=mt[o].length;if(!r)return s&&It(e,t),!1;for(let e=r-1;e>=0;e--)mt[o][e](t);return s&&It(e,t),!0},Ct=e=>{const t=ft(e,"");Object.keys(mt).filter((e=>0===e.indexOf(t))).forEach((e=>delete mt[e]))};let Et="undefined"!=typeof WebSocket?WebSocket:null;const kt=0,wt=1,Tt=2,Rt=3;class At{constructor(e){this.session=e,this.previousGatewayState="",this.lastInboundAt=0,this.socketGeneration=0,this._wsClient=null,this._host=re,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:t,env:i,region:n,useCanaryRtcServer:s}=e.options;Te.debug("Creating new Connection",{host:this._host,env:i,region:n,useCanaryRtcServer:s}),i&&(this._host="development"===i?"wss://rtcdev.telnyx.com":re),t&&(this._host=(e=>`${xe.test(e)?"":"wss://"}${e}`)(t)),n&&(this._host=this._host.replace(/rtc(dev)?/,`${n}.rtc$1`)),s&&(this._useCanaryRtcServer=!0)}get connected(){return!!this._wsClient&&this._wsClient.readyState===wt}get connecting(){return!!this._wsClient&&this._wsClient.readyState===kt}get closing(){return!!this._wsClient&&this._wsClient.readyState===Tt}get closed(){return!!this._wsClient&&this._wsClient.readyState===Rt}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){Te.debug("Connection.connect() called",{host:this._host,socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const e=new URL(this._host);let t=Je();this.session.options.rtcIp&&this.session.options.rtcPort&&(t=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),t&&e.searchParams.set("voice_sdk_id",t),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),t&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),Te.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this.session.callReportVoiceSdkId=e.searchParams.get("voice_sdk_id"),this.session.options.skipLastVoiceSdkId&&e.searchParams.has("voice_sdk_id")&&e.searchParams.set("skip_last_voice_sdk_id","true"),this.session.options.skipTrailing&&e.searchParams.set("skip_trailing","true");try{const t=this.socketGeneration;this._wsClient=new Et(e.toString()),this.socketGeneration+=1,Te.debug("WebSocket connection created",{sessionId:this.session.sessionid,voiceSdkId:this.session.callReportVoiceSdkId,socketGeneration:this.socketGeneration,reconnectCount:t}),this.lastInboundAt=0,this._cleanupPendingRequests(),this._registerSocketEvents(this._wsClient)}catch(e){Te.error("WebSocket connection failed:",e);const t=_e(C,e);It(ue.Error,{error:t,sessionId:this.session.sessionid},this.session.uuid),this.session._terminateActiveCallsLocally()}}sendRawText(e){var t;null===(t=this._wsClient)||void 0===t||t.send(e)}send(e,t){var i;const{request:n}=e,s=this.socketGeneration,o=n.method||"",r=new Promise(((e,i)=>{if(n.hasOwnProperty("result"))return e();let r=!1,a=null;const c=t=>{if(null!==a&&(clearTimeout(a),this._pendingRequestTimers.delete(n.id),a=null),this._pendingRequestIds.delete(n.id),this._pendingRequestRejecters.delete(n.id),r)return;const{result:s,error:o}=Ue(t);return o?i(o):e(s)};bt(n.id,c),this._pendingRequestIds.add(n.id),this._pendingRequestRejecters.set(n.id,{reject:i,generation:s}),t&&t>0&&(a=setTimeout((()=>{if(r=!0,a=null,this._pendingRequestTimers.delete(n.id),this._pendingRequestRejecters.delete(n.id),St(n.id,c),this._pendingRequestIds.delete(n.id),this.socketGeneration!==s)return Te.debug(`Stale request timeout for ${n.id} (gen ${s}, current ${this.socketGeneration}) — settling with StaleRequestError`),void i(new be(n.id,s,this.socketGeneration));i(new ye(n.id,t,o))}),t),this._pendingRequestTimers.set(n.id,a))}));return Te.debug("SEND: \n",JSON.stringify(n,null,2),"\n"),null===(i=this._wsClient)||void 0===i||i.send(JSON.stringify(n)),r}close(){if(Te.debug("Connection.close() called",{hasWsClient:!!this._wsClient,closing:this.closing,closed:this.closed,socketGeneration:this.socketGeneration,safetyTimeoutId:this._safetyTimeoutId,sessionId:this.session.sessionid}),!this._wsClient||this.closing)return;this._cleanupPendingRequests();const e=this._wsClient;Me(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout((()=>this._handleCloseTimeout(e)),5e3))}_registerSocketEvents(e){const t=this.socketGeneration;e.onopen=e=>(Te.debug("WebSocket onopen",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid}),It(ue.SocketOpen,e,this.session.uuid)),e.onclose=i=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),Te.debug("WebSocket onclose",{code:null==i?void 0:i.code,reason:null==i?void 0:i.reason,wasClean:null==i?void 0:i.wasClean,socketGeneration:t,sessionId:this.session.sessionid}),It(ue.SocketClose,{event:i,socketGeneration:t},this.session.uuid)),e.onerror=i=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error"),Te.debug("WebSocket onerror",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const n=_e(E);return It(ue.Error,{error:n,sessionId:this.session.sessionid},this.session.uuid),It(ue.SocketError,{error:i,sessionId:this.session.sessionid,socketGeneration:t},this.session.uuid)},e.onmessage=e=>{var t,i;this.lastInboundAt=Date.now(),It(ue.SocketActivity,{timestamp:this.lastInboundAt},this.session.uuid);const n=Le(e.data);var s;if("string"!=typeof n){if(n.voice_sdk_id&&(this.session.callReportVoiceSdkId=n.voice_sdk_id,s=n.voice_sdk_id,sessionStorage.setItem(He,s)),this._unsetTimer(n.id),Te.debug("RECV: \n",JSON.stringify(n,null,2),"\n"),pt[`${null===(i=null===(t=null==n?void 0:n.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state}`]||!It(n.id,n)){const e=je(n);It(ue.SocketMessage,n,this.session.uuid),Boolean(e)&&(this.previousGatewayState=e)}}else this._handleStringResponse(n)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(e){this._safetyTimeoutId=null,e&&e.readyState!==Rt?(Te.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e?Te.debug("Safety timeout: socket was replaced, not emitting SocketClose",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}):(Te.debug("Safety timeout: emitting SocketClose for stuck socket",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}),It(ue.SocketClose,{code:ae.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))):Te.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(Te.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,t){this._wsClient===e?(Te.debug(`Nulling socket reference (reason: ${t})`),this._wsClient=null):Te.debug(`Skipping socket cleanup - old socket already replaced (reason: ${t})`)}_cleanupPendingRequests(){Array.from(this._pendingRequestIds).forEach((e=>{St(e);const t=this._pendingRequestTimers.get(e),i=this._pendingRequestRejecters.get(e);t&&(clearTimeout(t),this._pendingRequestTimers.delete(e),i&&i.reject(new be(e,i.generation,this.socketGeneration))),this._pendingRequestRejecters.delete(e)})),this._pendingRequestIds.clear()}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),It(ue.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else Te.warn("Unknown message from socket",e)}}At.DEFAULT_REQUEST_TIMEOUT_MS=1e4;class Ot{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:a()},e)}buildNotification(e){this.request=Object.assign({jsonrpc:"2.0"},e)}}const Dt={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class Nt extends Ot{constructor(t={}){if(super(),t.hasOwnProperty("dialogParams")){const i=e(t.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const e in Dt)e&&i.hasOwnProperty(e)&&(i[Dt[e]]=i[e],delete i[e]);t.dialogParams=i}this.buildRequest({method:this.toString(),params:t})}}class Lt extends Nt{constructor(e){super(),this.method=nt.GatewayState;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Mt{constructor(e){this.pendingRequestId=null,this.onSocketMessage=e=>t(this,void 0,void 0,(function*(){e.id===this.pendingRequestId&&this.gatewayStateTask.resolve(je(e))})),this.getIsRegistered=()=>t(this,void 0,void 0,(function*(){const e=new Lt(Je());this.pendingRequestId=e.request.id,this.gatewayStateTask=Be({}),this.session.execute(e);const t=yield this.gatewayStateTask.promise;return!!t&&[pt.REGISTER,pt.REGED].includes(t)})),this.session=e,this.gatewayStateTask=Be({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Pt extends Nt{constructor(e){super(),this.method=nt.Ping;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class xt{constructor(e){this._session=e,this._lastInboundAt=0,this._lastProbeSentAt=0,this._probeInFlight=!1,this._intervalId=null,this._pendingMediaRecovery=null,this._browserWasOffline=!1,this._onlineHandler=null,this._offlineHandler=null}static isCriticalMethod(e){return xt.CRITICAL_METHODS.has(e)}start(){this._intervalId||(Te.debug("Signaling health: monitor started"),this._lastInboundAt=Date.now(),this._probeInFlight=!1,this._lastProbeSentAt=0,this._setupBrowserListeners(),this._intervalId=setInterval((()=>this._check()),3e3))}stop(){this._intervalId&&(clearInterval(this._intervalId),this._intervalId=null,this._probeInFlight=!1,this._lastProbeSentAt=0),this._pendingMediaRecovery=null,this._cleanupBrowserListeners(),Te.debug("Signaling health: monitor stopped")}get isRunning(){return null!==this._intervalId}get isProbeInFlight(){return this._probeInFlight}onSocketActivity(){this._lastInboundAt=Date.now()}_resolveProbe(){if(!this._probeInFlight)return;if(this._probeInFlight=!1,this._lastProbeSentAt=0,this._lastInboundAt=Date.now(),Te.debug("Signaling health: probe resolved by matching Ping response"),!this._pendingMediaRecovery)return void Te.debug("Signaling health: probe resolved but no pending media recovery");const e=this._pendingMediaRecovery;this._pendingMediaRecovery=null,"healthy"===this._getSignalingHealthState()&&(Te.info(`Signaling health: signaling probe resolved, triggering pending ICE restart for call ${e.callId}`),this._triggerIceRestart(e.callId,e.reason))}_probeIfNeeded(e){var t;(null===(t=this._session.connection)||void 0===t?void 0:t.connected)&&(this._probeInFlight?Te.debug(`Signaling health: probe already in flight, skipping duplicate probe (${e})`):(Te.info(`Signaling health: ${e}, sending signaling probe`),this._sendProbe()))}onRequestTimeout(e,t,i=""){var n;if(!(null===(n=this._session.connection)||void 0===n?void 0:n.connected))return;xt.isCriticalMethod(i)?(Te.warn(`Critical signaling request timed out (id=${e}, method=${i}, timeout=${t}ms) — declaring signaling unhealthy`),this._triggerSignalingRecovery(`Critical signaling request timed out (method=${i}, id=${e}, timeout=${t}ms)`,"request")):Te.warn(`Non-critical signaling request timed out (id=${e}, method=${i||"unknown"}, timeout=${t}ms) — logging but not triggering signaling recovery`)}onPeerFailure(e,t){Te.warn(`Signaling health: peer failure reported (callId=${e}, evidence=${t})`),this._recoverMediaOrSignaling(e,`Peer connection failure (${t})`,`Peer failure detected (${t}) while signaling is unhealthy`,"peer_failure")}onNoRtp(e,t){Te.warn(`Signaling health: no RTP detected (callId=${e}, direction=${t})`),this._recoverMediaOrSignaling(e,`No RTP ${t} while media should be active`,`No RTP ${t} while signaling is unhealthy`,"no_rtp")}_setupBrowserListeners(){"undefined"==typeof window||this._onlineHandler||(this._onlineHandler=()=>{this._browserWasOffline&&(Te.debug(`Signaling health: browser online — clearing browser offline state for session ${this._session.sessionid}`),this._browserWasOffline=!1)},this._offlineHandler=()=>{this._browserWasOffline=!0,Te.debug(`Signaling health: browser offline signal received for session ${this._session.sessionid}`);const e=_e(D);It(ue.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(){"undefined"!=typeof window&&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){Te.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(!(null===(e=this._session.connection)||void 0===e?void 0:e.connected))return;const t=Date.now(),i=t-this._lastInboundAt;if(i<2e4)return;if(!this._probeInFlight)return Te.info(`Signaling health: no inbound WS activity for ${Math.round(i/1e3)}s during active call, sending health probe`),void this._sendProbe();const n=t-this._lastProbeSentAt;n>=5e3&&(Te.warn(`Signaling health: probe timed out after ${n}ms with no inbound activity — declaring signaling unhealthy`),this._triggerSignalingRecovery("Signaling health probe timed out: no inbound WS activity after probe","probe"))}_sendProbe(){var e;this._probeInFlight=!0,this._lastProbeSentAt=Date.now();const t=new Pt(Je());null===(e=this._session.connection)||void 0===e||e.send(t).then((()=>this._resolveProbe())).catch((e=>{Te.warn("Signaling health: probe Ping failed to send",e)}))}_recoverMediaOrSignaling(e,t,i,n){if(!this._session.hasActiveCall())return void Te.debug(`Signaling health: ignoring ${n} recovery without an active call`);const s=this._getSignalingHealthState();return"healthy"===s?(Te.info(`Signaling health: signaling is healthy, triggering ICE restart for call ${e}`),void this._triggerIceRestart(e,t)):"unknown"===s?(Te.info(`Signaling health: signaling health is unknown, deferring ICE restart decision for call ${e}`),this._pendingMediaRecovery={callId:e,reason:t,source:n},void this._probeIfNeeded(`${n} detected with stale/unknown signaling`)):(Te.info("Signaling health: signaling is unhealthy, triggering socket reconnect instead of ICE restart"),void this._triggerSignalingRecovery(i,n))}_getSignalingHealthState(){var e;if(!(null===(e=this._session.connection)||void 0===e?void 0:e.connected))return"unhealthy";if(this._probeInFlight)return"unknown";const t=Date.now(),i=this._lastInboundAt||this._session.connection.lastInboundAt||0;return 0===i?"unknown":t-i<3e3?"healthy":"unknown"}_triggerSignalingRecovery(e,t="probe"){var i,n,s;this._pendingMediaRecovery=null,this._probeInFlight=!1,this._lastProbeSentAt=0,Te.debug(`Signaling recovery triggered (source=${t}, reason=${e})`);const o=ge(ie);It(ue.Warning,{warning:o,reason:e,source:t,sessionId:this._session.sessionid},this._session.uuid),(null===(i=this._session.connection)||void 0===i?void 0:i.connected)?(Te.info("Signaling health: force-closing WebSocket to trigger reconnect"),this._session.socketDisconnect()):Te.debug("Signaling health: recovery triggered but connection not connected",{connected:null===(n=this._session.connection)||void 0===n?void 0:n.connected,hasConnection:!!this._session.connection,socketGeneration:null===(s=this._session.connection)||void 0===s?void 0:s.socketGeneration})}_triggerIceRestart(e,t){Te.info(`Signaling health: triggering ICE restart for call ${e}`);const i=this._session.triggerIceRestart(e);if(!i.started)return void Te.info(`Signaling health: ICE restart not started for call ${e}: ${i.reason}`);const n=ge(ne);It(ue.Warning,{warning:n,reason:t,callId:e,sessionId:this._session.sessionid},this._session.uuid)}}xt.CRITICAL_METHODS=new Set([nt.Modify,nt.Bye,nt.Ping]);var Ut="2.27.4-beta.2",Ft=Ut;class $t extends Nt{constructor(e,t,i,n,s={},o){super(),this.method="login";const r={login:e,passwd:t,login_token:i,userVariables:s,reconnection:o,loginParams:{},"User-Agent":{sdkVersion:Ft,data:navigator.userAgent}};n&&(r.sessid=n),this.buildRequest({method:this.method,params:r})}}class jt extends Nt{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Bt extends Nt{toString(){return nt.Invite}}class Wt extends Nt{toString(){return nt.Answer}}class Ht extends Nt{toString(){return nt.Attach}}class Gt extends Nt{toString(){return nt.Bye}}class Vt extends Nt{toString(){return nt.Candidate}}class qt extends Nt{toString(){return nt.EndOfCandidates}}class Kt extends Nt{toString(){return nt.Modify}}class Yt extends Nt{toString(){return nt.Info}}class Jt extends Nt{toString(){return nt.Broadcast}}class zt extends Nt{toString(){return nt.Subscribe}}class Qt extends Nt{toString(){return nt.Unsubscribe}}class Xt extends Nt{constructor(e){super(),this.method="anonymous_login";const{target_type:t,target_id:i,target_version_id:n,target_params:s,userVariables:o,sessionId:r,reconnection:a}=e,c={target_type:t,target_id:i,userVariables:o,reconnection:a,"User-Agent":{sdkVersion:Ft,data:navigator.userAgent}};r&&(c.sessid=r),n&&(c.target_version_id=n),s&&(c.target_params=s),this.buildRequest({method:this.method,params:c})}}class Zt{constructor(e){if(this.options=e,this.uuid=a(),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 xt(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var t,i;t=e.debug?"debug":"info",Ae=null!==(i=Re[t])&&void 0!==i?i:Re.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 At(this),this.registerAgent=new Mt(this)}get __logger(){return Te}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return t(this,void 0,void 0,(function*(){return this.registerAgent.getIsRegistered()}))}get reconnectDelay(){const e=this._reconnectAttempts,t=Math.min(1e3*Math.pow(2,e-1),3e4),i=Math.floor(.25*t*(2*Math.random()-1)),n=t+i;return Te.debug("Reconnect delay computed",{attempt:e,baseDelayMs:1e3,maxDelayMs:3e4,delayMs:t,jitterMs:i,totalDelay:n,sessionId:this.sessionid}),n}execute(e){var i;if(this._idle)return new Promise((t=>this._executeQueue.push({resolve:t,msg:e})));if(!this.connected)return new Promise((t=>{this._executeQueue.push({resolve:t,msg:e}),Te.debug("Calling connect from execute since not currently connected."),this.connect()}));const n=xt.isCriticalMethod((null===(i=e.request)||void 0===i?void 0:i.method)||"")?At.DEFAULT_REQUEST_TIMEOUT_MS:void 0;return(null!=n?this.connection.send(e,n):this.connection.send(e)).catch((e=>t(this,void 0,void 0,(function*(){if(e instanceof be)throw Te.debug(`Stale request settled (id=${e.requestId}, gen=${e.staleGeneration}) — not triggering recovery`),e;if("RequestTimeoutError"===(null==e?void 0:e.name))throw this.onSignalingRequestTimeout(e.requestId,e.timeoutMs,e.method),e;if((null==e?void 0:e.code)===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const t=_e(A,e,void 0,!0);It(ue.Error,{error:t,sessionId:this.sessionid},this.uuid)}yield this.login()}throw e}))))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}trackCallReportUpload(e){this._pendingCallReportUploads.add(e),e.then((()=>this._pendingCallReportUploads.delete(e)),(()=>this._pendingCallReportUploads.delete(e)))}_drainCallReportUploads(){return t(this,void 0,void 0,(function*(){if(0===this._pendingCallReportUploads.size)return;const e=Array.from(this._pendingCallReportUploads);let t=!1;yield Promise.race([Promise.all(e.map((e=>e.catch((()=>{}))))),new Promise((e=>setTimeout((()=>{t=!0,e()}),Zt.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS)))]),t&&Te.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})}))}validateOptions(){return Fe(this.options)||$e(this.options)}broadcast(e){}disconnect(){return t(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(),Te.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")}))}on(e,t){return yt(e,t,this.uuid),this}off(e,t){return St(e,t,this.uuid),this}connect(){return t(this,void 0,void 0,(function*(){this.connection||(Te.debug("No existing connection found, creating a new one."),this.connection=new At(this)),this._attachListeners(),this._autoReconnect||(Te.debug("autoReconnect was disabled, resetting reconnect attempts"),this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(Te.debug("Connection wasn't alive, initiating connection to the server..."),this.connection.connect()),Te.debug("Connect method called. Connection initiated.")}))}resetReconnectAttempts(){this._reconnectAttempts=0,this._reconnectCountedGeneration=-1}_handleLoginError(e){const t=_e(T,e);It(ue.Error,{error:t,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){Qe()}_checkTokenExpiry(){this._clearTokenExpiryTimeout();const e=this.options.login_token;if(e&&"string"==typeof e)try{const t=e.split(".");if(3!==t.length)return;const i=JSON.parse(atob(t[1])).exp;if("number"!=typeof i)return;const n=i-Math.floor(Date.now()/1e3);if(n<=0)return;if(n<=Zt.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const e=1e3*(n-Zt.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout((()=>{this._emitTokenExpiryWarning()}),e)}}catch(e){Te.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=ge(ee);It(ue.Warning,{warning:e,sessionId:this.sessionid},this.uuid)}_clearTokenExpiryTimeout(){null!==this._tokenExpiryTimeout&&(clearTimeout(this._tokenExpiryTimeout),this._tokenExpiryTimeout=null)}login({creds:e,onSuccess:i,onError:n}={}){return t(this,void 0,void 0,(function*(){if(this.connection&&this.connection.isAlive){if(e&&(void 0!==e.login&&(this.options.login=e.login),void 0!==e.password&&(this.options.password=e.password),void 0!==e.passwd&&(this.options.passwd=e.passwd),void 0!==e.login_token&&(this.options.login_token=e.login_token),void 0!==e.userVariables&&(this.options.userVariables=e.userVariables),void 0!==e.anonymous_login&&(this.options.anonymous_login=e.anonymous_login)),Fe(this.options))return this._login({type:"login",onSuccess:i,onError:n});if($e(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const e="Invalid login options provided for authentication.";Te.error(e);const t=_e(R,void 0,e);return void It(ue.Error,{error:t,type:ot.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}}))}_login({type:e,onSuccess:i,onError:n}){return t(this,void 0,void 0,(function*(){let t;const s=!!Je(),o=s&&(this.sessionid&&Ye()?this.sessionid:function(e=Date.now()){const t=sessionStorage.getItem(Ge);return t?Ye(e)?t:(sessionStorage.removeItem(Ge),sessionStorage.removeItem(Ve),null):null}())||"";t="login"===e?new $t(this.options.login,this.options.password||this.options.passwd,this.options.login_token,o,this.options.userVariables,s):new Xt({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:o,userVariables:this.options.userVariables,reconnection:s});const r=yield this.execute(t).catch((e=>{this._handleLoginError(e),n&&n(e)}));r&&(this.sessionid=r.sessid,this.sessionid&&ze(this.sessionid),this._checkTokenExpiry(),i&&i())}))}_onSocketOpen(){return t(this,void 0,void 0,(function*(){this.startSignalingHealthMonitor()}))}_flushIntermediateCallReports(e){const t=this.calls;t&&Object.values(t).forEach((t=>{if(null==t?void 0:t.flushIntermediateCallReport)try{t.flushIntermediateCallReport(e)}catch(i){Te.error("Failed to flush intermediate call report",{callId:t.id,flushReason:e,error:i})}}))}_getSocketCloseCodeName(e){if(void 0===e)return;const t=Object.entries(ae).find((([,t])=>t===e));return null==t?void 0:t[0]}_getSocketCloseError(e){if(e)return e instanceof Error?e.message:String(e)}_createSocketCloseFlushReason(e){return{type:(null==e?void 0:e.error)?"socket-error":"socket-close",socketClose:{code:null==e?void 0:e.code,codeName:this._getSocketCloseCodeName(null==e?void 0:e.code),reason:null==e?void 0:e.reason,wasClean:null==e?void 0:e.wasClean,error:this._getSocketCloseError(null==e?void 0:e.error)}}}onNetworkClose(e){var t,i,n,s;const o=null!==(i=null===(t=this.connection)||void 0===t?void 0:t.socketGeneration)&&void 0!==i?i:0,r=null!==(n=null==e?void 0:e.socketGeneration)&&void 0!==n?n:o;if(r<o)Te.debug(`Skipping stale onNetworkClose for socket generation ${r} (current generation is ${o})`);else if(r!==this._reconnectCountedGeneration){this._flushIntermediateCallReports(this._createSocketCloseFlushReason(e)),Te.debug("onNetworkClose called",{closeCode:null==e?void 0:e.code,closeReason:null==e?void 0:e.reason,wasClean:null==e?void 0:e.wasClean,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,autoReconnect:this._autoReconnect,reconnectAttempts:this._reconnectAttempts}),this.relayProtocol&&Ct(this.relayProtocol);for(const e in this.subscriptions)Ct(e);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.stopSignalingHealthMonitor(),this.sessionid&&this._autoReconnect&&ze(this.sessionid),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect){const e=null!==(s=this.options.maxReconnectAttempts)&&void 0!==s?s:10;if(this._reconnectCountedGeneration=r,this._reconnectAttempts+=1,e>0&&this._reconnectAttempts>e){Te.info(`Reconnection exhausted after ${e} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1,this._terminateActiveCallsLocally();const t=_e(k);return void It(ue.Error,{error:t,sessionId:this.sessionid},this.uuid)}const t=this.reconnectDelay;Te.debug(`Reconnect attempt ${this._reconnectAttempts}${e>0?` of ${e}`:""} (delay=${t}ms)`),this._reconnectTimeout=setTimeout((()=>{Te.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()}),t)}else if(Te.debug("auto_reconnect disabled, not reconnecting",{voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,intentionalClose:this._intentionalClose}),!this._intentionalClose){const e=ge(se);It(ue.Warning,{warning:e,reason:"auto_reconnect_disabled",sessionId:this.sessionid},this.uuid)}this._intentionalClose=!1}else Te.debug(`Skipping duplicate onNetworkClose for socket generation ${r} (already handled, reconnect attempt ${this._reconnectAttempts})`)}_onSocketMessage(e){}_removeSubscription(e,t){this._existsSubscription(e,t)&&(t?(delete this.subscriptions[e][t],St(e,null,t)):(delete this.subscriptions[e],Ct(e)))}_addSubscription(e,t=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},Me(t)&&yt(e,t,i))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),Te.debug("Attaching socket event listeners"),this.on(ue.SocketOpen,this._onSocketOpen),this.on(ue.SocketClose,this.onNetworkClose),this.on(ue.SocketError,this.onNetworkClose),this.on(ue.SocketMessage,this._onSocketMessage),this.on(ue.SocketActivity,this._onSocketActivity)}_detachListeners(){Te.debug("Detaching socket event listeners"),this.off(ue.SocketOpen,this._onSocketOpen),this.off(ue.SocketClose,this.onNetworkClose),this.off(ue.SocketError,this.onNetworkClose),this.off(ue.SocketMessage,this._onSocketMessage),this.off(ue.SocketActivity,this._onSocketActivity)}_emptyExecuteQueues(){this._executeQueue.forEach((({resolve:e,msg:t})=>{"string"==typeof t?this.executeRaw(t):e(this.execute(t))}))}_closeConnection(){var e,t;this._idle=!0,clearTimeout(this._keepAliveTimeout),this.stopSignalingHealthMonitor(),Te.debug("_closeConnection called",{connected:null===(e=this.connection)||void 0===e?void 0:e.connected,socketGeneration:null===(t=this.connection)||void 0===t?void 0:t.socketGeneration,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0}),this.connection&&this.connection.close()}_resetKeepAlive(){!1===this._pong&&(Te.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Pt(Je()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout((()=>this._resetKeepAlive()),35e3)}setPingReceived(){Te.debug("Ping received"),this._pong=!0}_onSocketActivity(){this._signalingHealthMonitor.onSocketActivity()}hasActiveCall(){const e=this.calls;if(!e)return!1;const t=new Set([lt.Early,lt.Active,lt.Held]);return Object.values(e).some((e=>e&&null!=e._state&&t.has(e._state)))}_terminateActiveCallsLocally(){const e=this.calls;if(!e)return;const t=Object.keys(e);if(0!==t.length){Te.debug(`Reconnection exhausted — locally terminating ${t.length} active call(s) (no BYE): ${t.join(", ")}`);for(const i of t){const t=e[i];null==t||t.hangup({},!1)}}}startSignalingHealthMonitor(){this._signalingHealthMonitor.start()}stopSignalingHealthMonitor(){this._signalingHealthMonitor.stop()}triggerIceRestart(e){const t=this.calls,i=null==t?void 0:t[e];if(!i)return Te.warn(`Signaling health: cannot trigger ICE restart — call ${e} not found`),{started:!1,reason:"call not found"};const n=i.peer;if(!(null==n?void 0:n.restartIce))return Te.warn(`Signaling health: cannot trigger ICE restart — no peer for call ${e}`),{started:!1,reason:"no peer"};const s=n.restartIce();return s.started||Te.debug(`Signaling health: ICE restart skipped for call ${e}: ${s.reason}`),s}onSignalingRequestTimeout(e,t,i=""){this._signalingHealthMonitor.onRequestTimeout(e,t,i)}reportPeerFailure(e,t){this._signalingHealthMonitor.onPeerFailure(e,t)}reportNoRtp(e,t){this._signalingHealthMonitor.onNoRtp(e,t)}reportIceRestartFailed(e){this._signalingHealthMonitor.onIceRestartFailed(e)}static on(e,t){yt(e,t)}static off(e){St(e)}static uuid(){return a()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}Zt.TOKEN_EXPIRY_WARNING_SECONDS=120,Zt.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;const ei=e=>navigator.mediaDevices.getUserMedia(e),ti=e=>e&&e instanceof MediaStream,ii=(e,t)=>{const i=Pe(e);null!==i&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=t)},ni=(e,t)=>{const i=Pe(e);if(i){if(t&&i.srcObject!==t)return;i.srcObject=null}},si=(e,i)=>t(void 0,void 0,void 0,(function*(){const t=Pe(e);if(null===t)return Te.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof i)return Te.info(`Invalid speaker deviceId: '${i}'`),!1;try{return yield t.setSinkId(i),!0}catch(e){return!1}})),oi=e=>{e&&"live"===e.readyState&&e.stop()},ri=e=>{ti(e)&&e.getTracks().forEach(oi),e=null},ai=e=>t(void 0,void 0,void 0,(function*(){Te.info("RTCService.getUserMedia",e);const{audio:t,video:i}=e;if(!t&&!i)return null;try{return yield ei(e)}catch(t){if(Te.error("getUserMedia error: ",t),(e=>"NotReadableError"===e.name||"NotFoundError"===e.name||"OverconstrainedError"===e.name)(t)){const i=(e=>{const{audio:t,video:i}=e;let n=!1,s=t,o=i;if("object"==typeof t&&null!==t&&"deviceId"in t){n=!0;const e=Object.assign({},t);delete e.deviceId,s=0===Object.keys(e).length||e}if("object"==typeof i&&null!==i&&"deviceId"in i){n=!0;const e=Object.assign({},i);delete e.deviceId,o=0===Object.keys(e).length||e}return n?{audio:s,video:o}:null})(e);if(i){Te.warn("Device not found or not readable, falling back to default device");try{return yield ei(i)}catch(e){throw Te.error("Fallback getUserMedia also failed: ",e),t}}}throw t}})),ci=(e=null,i=!1)=>t(void 0,void 0,void 0,(function*(){let t=[];const n=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===ht.AudioIn||e===ht.AudioOut,video:!e||e===ht.Video}))(e)).catch((e=>(Te.error(e),null)));if(n){if(ri(n),t=yield navigator.mediaDevices.enumerateDevices(),e&&(t=t.filter((t=>t.kind===e))),!0===i)return t;const s=[];t=t.filter((e=>{if(!e.groupId)return!0;const t=`${e.kind}-${e.groupId}`;return!s.includes(t)&&(s.push(t),!0)}))}return t})),li=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],di=(e,i,n)=>t(void 0,void 0,void 0,(function*(){const t=yield ci(n,!0);for(let n=0;n<t.length;n++){const{deviceId:s,label:o}=t[n];if(e===s||i===o)return s}return null})),ui=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((i=>{t.hasOwnProperty(i)&&null!==e[i]&&void 0!==e[i]||delete e[i]}))},hi=e=>e?{id:e.id,kind:e.kind,enabled:e.enabled,muted:e.muted,readyState:e.readyState}:null,pi=e=>{var t,i,n,s,o,r;if(!e)return[];return(null!==(i=null===(t=e.getTracks)||void 0===t?void 0:t.call(e))&&void 0!==i?i:[...null!==(s=null===(n=e.getAudioTracks)||void 0===n?void 0:n.call(e))&&void 0!==s?s:[],...null!==(r=null===(o=e.getVideoTracks)||void 0===o?void 0:o.call(e))&&void 0!==r?r:[]]).map((e=>hi(e)))},gi=(e,t)=>{if(!e)return!1;const{subscribed:i,alreadySubscribed:n}=vi(e);return i.includes(t)||n.includes(t)},vi=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((i=>{t[i]=e[`${i}Channels`]||[]})),t},mi=(e,t=null,i=null)=>{if(!ti(e))return null;let n=[];switch(t){case"audio":n=e.getAudioTracks();break;case"video":n=e.getVideoTracks();break;default:n=e.getTracks()}n.forEach((e=>{switch(i){case"on":case!0:e.enabled=!0;break;case"off":case!1:e.enabled=!1;break;default:e.enabled=!e.enabled}}))},fi=e=>{mi(e,"audio",!0)},_i=e=>{mi(e,"audio",!1)};function yi(){try{const{browserInfo:e,name:t,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 e=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),t=e[0],i=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:i,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const e=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),t=e[0],i=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:i,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const e=navigator.userAgent.match(/safari/gim)[0],t=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),i=parseInt(t[1],10);return{browserInfo:navigator.userAgent,name:e,version:i,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const e=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),t=e[0],i=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:i,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,c=window.navigator&&window.navigator.mediaDevices,l=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:e,browserName:t,browserVersion:i,supportWebRTC:!!(o&&r&&a&&c&&l),supportWebRTCAudio:n,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!ai}}catch(e){return e.message}}var bi;function Si(e,t){const i=document.getElementById(t);if(i)return i;if(e&&t){const i=document.createElement("audio");return i.id=t,i.loop=!0,i.src=e,i.preload="auto",i.load(),document.body.appendChild(i),i}return null}function Ii(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then((()=>{e._playFulfilled=!0})).catch((t=>{Te.error("playAudio",t),e._playFulfilled=!0})))}function Ci(e){e&&(e._playFulfilled?(e.pause(),e.currentTime=0):e._promise&&e._promise.then?e._promise.then((()=>{e.pause(),e.currentTime=0})):setTimeout((()=>{e.pause(),e.currentTime=0}),1e3))}!function(e){e.not_supported="not supported",e.full="full",e.partial="partial"}(bi||(bi={}));const Ei=e=>{const t=[],i=[];return e&&0!==e.length?(e.forEach((e=>{const n=e.mimeType.toLocaleLowerCase();n.startsWith("audio/")?t.push(e):n.startsWith("video/")&&i.push(e)})),{audioCodecs:t,videoCodecs:i}):{audioCodecs:t,videoCodecs:i}};class ki extends Ot{constructor(e,t){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:a(),type:"message",role:"user",content:[{type:"input_text",text:e},...null==t?void 0:t.map((e=>({type:"image_url",image_url:{url:e}})))]}}})}}class wi extends Ot{constructor(e){super(),this.method="ai_conversation",this.buildNotification({method:this.method,params:{type:"conversation.item.create",item:e}})}}class Ti{constructor(e,t){var i;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._lastLocalAudioTrackSnapshotJson=null,this._hasConfirmedLocalAudio=!1,this._confirmedLocalAudioSilenceMs=0,this._segmentIndex=0,this._flushing=!1,this._stopped=!1,this.options=e,this.logCollectorOptions=t||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this._lastIntermediateFlushTime=this.callStartTime,this.logCollectorOptions.enabled&&(this.logCollector=function(e){return new ke(e)}(this.logCollectorOptions),this.logCollector.start(),i=this.logCollector,we=i)}start(e){var t,i;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._lastIntermediateFlushTime=this.intervalStartTime,this._stopped=!1,Te.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:Ti.INITIAL_COLLECTION_INTERVAL_MS,logCollectorActive:null!==(i=null===(t=this.logCollector)||void 0===t?void 0:t.isActive())&&void 0!==i&&i}),this._scheduleNextCollection())}stop(){var e,i;return t(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 t=null!==(i=null===(e=this.logCollector)||void 0===e?void 0:e.getLogCount())&&void 0!==i?i:0;this.logCollector&&this.logCollector.stop(),Te.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:t,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})}))}flush(e,t){var i,n,s,o;const r=this.statsBuffer.length,a=null!==(n=null===(i=this.logCollector)||void 0===i?void 0:i.getLogCount())&&void 0!==n?n:0,c="socket-close"===(null==t?void 0:t.type)||"socket-error"===(null==t?void 0:t.type),l=r>0||a>0||c;if(this._flushing||!l)return Te.debug("CallReportCollector: Skipping intermediate flush",{reason:this._flushing?"already-flushing":"no-stats-or-logs",flushReason:t,statsIntervals:r,logEntries:a}),null;this._flushing=!0;try{const i=this._segmentIndex++,n=this.statsBuffer;this.statsBuffer=[];const r=null!==(o=null===(s=this.logCollector)||void 0===s?void 0:s.drain())&&void 0!==o?o:[],a=new Date;this._lastIntermediateFlushTime=a;const c=Object.assign(Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(a.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:a.toISOString()}),stats:n},r.length>0?{logs:r}:{}),{segment:i}),t?{flushReason:t}:{});return Te.info("CallReportCollector: Flushed intermediate segment",{segment:i,intervals:n.length,logEntries:r.length,callId:e.callId,flushReason:t}),c}finally{this._flushing=!1}}postReport(e,i,n,s){var o,r;return t(this,void 0,void 0,(function*(){const t=null===(o=this.logCollector)||void 0===o?void 0:o.getLogs(),a=t&&t.length>0;if(!this.options.enabled)return void Te.info("CallReportCollector: Skipping report — call reports disabled");if(0===this.statsBuffer.length&&!a)return void Te.info("CallReportCollector: Skipping report — no stats or logs collected");const c=this._segmentIndex>0,l=this._segmentIndex,d=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:this.callEndTime&&this.callStartTime?(this.callEndTime.getTime()-this.callStartTime.getTime())/1e3:void 0,startTimestamp:this.callStartTime.toISOString(),endTimestamp:null===(r=this.callEndTime)||void 0===r?void 0:r.toISOString()}),stats:this.statsBuffer},t&&t.length>0?{logs:t}:{}),c?{segment:l}:{});yield this._sendPayload(d,i,n,s,!0)}))}sendPayload(e,i,n,s,o=!1){return t(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,c;return t(this,void 0,void 0,(function*(){const t=new URL(n),l=`${t.protocol.replace(/^ws/,"http")}//${t.host}/call_report`,d=o?"final report":`intermediate segment ${e.segment}`;Te.info(`CallReportCollector: Posting ${d}`,{endpoint:l,intervals:e.stats.length,logEntries:null!==(c=null===(a=e.logs)||void 0===a?void 0:a.length)&&void 0!==c?c:0,callId:e.summary.callId,segment:e.segment});const u={"Content-Type":"application/json","x-call-report-id":i,"x-call-id":e.summary.callId};s&&(u["x-voice-sdk-id"]=s);const h=JSON.stringify(e),p=(o||r)&&h.length<=Ti.KEEPALIVE_BODY_LIMIT_BYTES;let g;for(let e=0;e<=Ti.RETRY_DELAYS_MS.length;e++){try{const t=yield fetch(l,Object.assign({method:"POST",headers:u,body:h},p?{keepalive:!0}:{}));if(t.ok)return void Te.info(`CallReportCollector: Successfully posted ${d}`,{attempt:e+1,status:t.status});{const i=yield t.text();g=new Error(`Call report POST failed with status ${t.status}`),Te.error(`CallReportCollector: Failed to post ${d}`,{attempt:e+1,status:t.status,error:i})}}catch(t){g=t,Te.warn(`CallReportCollector: Network error posting ${d}`,{attempt:e+1,error:t})}const t=Ti.RETRY_DELAYS_MS[e];if(void 0===t)break;Te.info(`CallReportCollector: Retrying ${d} in ${t}ms`,{attempt:e+2}),yield new Promise((e=>setTimeout(e,t)))}throw Te.error(`CallReportCollector: Exhausted retries posting ${d}`,{error:g}),g instanceof Error?g:new Error("Call report POST failed after retries")}))}getStatsBuffer(){return this.statsBuffer}shouldForceRelayCandidateForRecovery(){var e,t,i,n,s,o,r,a,c,l,d,u,h,p,g,v;if(this.statsBuffer.length<2)return!1;const m=this.statsBuffer[this.statsBuffer.length-1],f=this.statsBuffer[this.statsBuffer.length-2],_=null===(e=m.ice)||void 0===e?void 0:e.local;if(!("vpn"===(null==_?void 0:_.networkType)&&"relay"!==(null==_?void 0:_.candidateType)))return!1;const y=!1===(null===(t=m.ice)||void 0===t?void 0:t.writable),b="disconnected"===(null===(i=m.transport)||void 0===i?void 0:i.iceState)||"failed"===(null===(n=m.transport)||void 0===n?void 0:n.iceState),S=this._positiveDelta(null===(s=m.ice)||void 0===s?void 0:s.requestsSent,null===(o=f.ice)||void 0===o?void 0:o.requestsSent),I=this._positiveDelta(null===(r=m.ice)||void 0===r?void 0:r.responsesReceived,null===(a=f.ice)||void 0===a?void 0:a.responsesReceived),C=S>0&&0===I,E=this._positiveDelta(null===(l=null===(c=m.audio)||void 0===c?void 0:c.outbound)||void 0===l?void 0:l.bytesSent,null===(u=null===(d=f.audio)||void 0===d?void 0:d.outbound)||void 0===u?void 0:u.bytesSent),k=this._positiveDelta(null===(p=null===(h=m.audio)||void 0===h?void 0:h.inbound)||void 0===p?void 0:p.bytesReceived,null===(v=null===(g=f.audio)||void 0===g?void 0:g.inbound)||void 0===v?void 0:v.bytesReceived);return y||b||C||E>0&&0===k}getLogs(){var e,t;return null!==(t=null===(e=this.logCollector)||void 0===e?void 0:e.getLogs())&&void 0!==t?t:[]}_positiveDelta(e,t){return void 0===e||void 0===t?0:Math.max(0,e-t)}cleanup(){this._lastLocalAudioTrackSnapshotJson=null,this.logCollector&&(this.logCollector.clear(),this.logCollector=null)}_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(Ti.INITIAL_COLLECTION_INTERVAL_MS,e)}_positiveInterval(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}_collectStats(e=!1){var i,n;return t(this,void 0,void 0,(function*(){if(this.peerConnection&&this.intervalStartTime)try{const t=yield this.peerConnection.getStats(),s=new Date;let o=null,r=null,a=null,c=null,l=null,d=null;const u=[];let h=null;t.forEach((e=>{switch(e.type){case"outbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(o=e);break;case"inbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(r=e);break;case"media-playout":"audio"===e.kind&&(a=e);break;case"remote-inbound-rtp":"audio"===e.kind&&(c=e);break;case"remote-outbound-rtp":"audio"===e.kind&&(l=e);break;case"candidate-pair":(e.nominated||"succeeded"===e.state)&&u.push(e);break;case"transport":h=e}}));const p=null==h?void 0:h.selectedCandidatePairId,g=p?null===(n=(i=t).get)||void 0===n?void 0:n.call(i,p):void 0,v=this._getCodec(t,null==o?void 0:o.codecId),m=this._getCodec(t,null==r?void 0:r.codecId);if(d="candidate-pair"===(null==g?void 0:g.type)?g:p?u.find((e=>e.id===p))||u[u.length-1]||null:u[u.length-1]||null,o){const e=this._getOutboundAudioLevel(t,o);if(null!==e&&this.intervalAudioLevels.outbound.push(e),void 0!==this.previousStats.outboundBytes&&void 0!==this.previousStats.timestamp){const e=(o.bytesSent||0)-this.previousStats.outboundBytes,t=(o.timestamp||s.getTime())-this.previousStats.timestamp;if(t>0){const i=8*e*1e3/t;this.intervalBitrates.outbound.push(i)}}this.previousStats.outboundBytes=o.bytesSent}if(r){const e=this._getInboundAudioLevel(t,r);if(null!==e&&this.intervalAudioLevels.inbound.push(e),void 0!==r.jitter&&this.intervalJitters.push(1e3*r.jitter),void 0!==this.previousStats.inboundBytes&&void 0!==this.previousStats.timestamp){const e=(r.bytesReceived||0)-this.previousStats.inboundBytes,t=(r.timestamp||s.getTime())-this.previousStats.timestamp;if(t>0){const i=8*e*1e3/t;this.intervalBitrates.inbound.push(i)}}this.previousStats.inboundBytes=r.bytesReceived}let f,_,y,b,S;d&&void 0!==d.currentRoundTripTime&&this.intervalRTTs.push(d.currentRoundTripTime),d&&(f=this._resolveCandidate(t,d.localCandidateId),_=this._resolveCandidate(t,d.remoteCandidateId)),d&&(y=Object.assign(Object.assign({id:d.id,localCandidateId:d.localCandidateId,remoteCandidateId:d.remoteCandidateId,state:d.state,nominated:d.nominated,writable:d.writable,currentRoundTripTime:d.currentRoundTripTime,requestsSent:d.requestsSent,responsesReceived:d.responsesReceived},f?{local:f}:{}),_?{remote:_}:{}),null!==this.previousCandidatePairSnapshot&&d.id!==this.previousCandidatePairSnapshot.id&&(Te.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:y}),this._emitWarning(z)),this.previousCandidatePairSnapshot=y),o&&(b=this._getLocalAudioTrackSnapshot(),S=this._getOutboundAudioSourceStats(t,o)),this._logLocalAudioTrackSnapshot(b,S),this.previousStats.timestamp=s.getTime();const I=s.getTime()-this.intervalStartTime.getTime(),C=this._collectionIntervalFor();if(e||I>=C){const e=this._createStatsEntry(this.intervalStartTime,s,o,r,d,f,_,h,b,S,a,c,l,v,m);this.statsBuffer.push(e),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),Te.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(e,r),this._requestIntermediateFlushIfNeeded(s),this.intervalStartTime=s,this._resetIntervalAccumulators()}}catch(e){Te.error("CallReportCollector: Error collecting stats",{error:e})}}))}_getIntermediateReportInterval(){var e;return null!==(e=this.options.intermediateReportInterval)&&void 0!==e?e:Ti.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS}_requestIntermediateFlushIfNeeded(e){var t,i;const n=this.statsBuffer.length,s=null!==(i=null===(t=this.logCollector)||void 0===t?void 0:t.getLogCount())&&void 0!==i?i:0;if(!this.onFlushNeeded||this._flushing)return;if(0===n&&0===s)return void Te.debug("CallReportCollector: Skipping intermediate flush request — no stats or logs buffered");const o=this._getIntermediateReportInterval(),r=e.getTime()-this._lastIntermediateFlushTime.getTime();let a=null;if(n>=Ti.STATS_FLUSH_THRESHOLD||s>=Ti.LOGS_FLUSH_THRESHOLD?a="buffer-limit":o>0&&r>=o&&(a="safety-interval"),a){Te.info("CallReportCollector: Requesting intermediate report flush",{reason:a,statsIntervals:n,logEntries:s,msSinceLastFlush:r}),this._lastIntermediateFlushTime=e;try{this.onFlushNeeded()}catch(e){Te.error("CallReportCollector: onFlushNeeded callback error",{error:e})}}}_checkQualityWarnings(e,t){var i,n,s,o,r,a,c,l,d,u,h,p,g,v,m;if(!this.onWarning)return;const f=null===(i=e.connection)||void 0===i?void 0:i.roundTripTimeAvg,_=null===(s=null===(n=e.audio)||void 0===n?void 0:n.inbound)||void 0===s?void 0:s.jitterAvg;let y;if(t){const e=null!==(o=t.packetsReceived)&&void 0!==o?o:0,i=null!==(r=t.packetsLost)&&void 0!==r?r:0;if(null!==this._prevPacketsReceived&&null!==this._prevPacketsLost){const t=e-this._prevPacketsReceived,n=i-this._prevPacketsLost,s=t+n;s>0&&(y=n/s*100)}this._prevPacketsReceived=e,this._prevPacketsLost=i}if(this._trackBreach(M,void 0!==f&&f>Ti.THRESHOLD_RTT_MS),this._trackBreach(P,void 0!==_&&_>Ti.THRESHOLD_JITTER_MS),this._trackBreach(x,void 0!==y&&y>Ti.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),this._trackLowInboundAudio(e),void 0!==f&&void 0!==_&&void 0!==y){const e=93.2-.11*_-2.5*y-.01*(1e3*f),t=Math.max(1,Math.min(4.5,1+.035*e+e*(e-60)*(100-e)*7e-6));this._trackBreach(U,t<Ti.THRESHOLD_MOS)}else this._trackBreach(U,!1);if(void 0!==(null===(c=null===(a=e.audio)||void 0===a?void 0:a.inbound)||void 0===c?void 0:c.bytesReceived)){const t=null===(u=null===(d=null===(l=this._previousStatsEntryForWarnings)||void 0===l?void 0:l.audio)||void 0===d?void 0:d.inbound)||void 0===u?void 0:u.bytesReceived,i=e.audio.inbound.bytesReceived;this._trackBreach(j,void 0!==t&&i-t==0)}if(void 0!==(null===(p=null===(h=e.audio)||void 0===h?void 0:h.outbound)||void 0===p?void 0:p.bytesSent)){const t=null===(m=null===(v=null===(g=this._previousStatsEntryForWarnings)||void 0===g?void 0:g.audio)||void 0===v?void 0:v.outbound)||void 0===m?void 0:m.bytesSent,i=e.audio.outbound.bytesSent;this._trackBreach(B,void 0!==t&&i-t==0)}this._previousStatsEntryForWarnings=e}_trackLowLocalAudio(e){var t;const i=null===(t=e.audio)||void 0===t?void 0:t.outbound,n=null==i?void 0:i.audioLevelAvg,s=null==i?void 0:i.localTrack;if(void 0===n||!1===(null==s?void 0:s.enabled)||!0===(null==s?void 0:s.muted))return void this._resetLowLocalAudioWarning();if(!(n<=Ti.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(F,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=Ti.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(F)):this._trackBreach(F,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(F,!1)}_getStatsIntervalDurationMs(e){const t=new Date(e.intervalStartUtc).getTime(),i=new Date(e.intervalEndUtc).getTime()-t;return Number.isFinite(i)&&i>0?i:this.options.interval}_trackLowInboundAudio(e){var t;const i=null===(t=e.audio)||void 0===t?void 0:t.inbound,n=null==i?void 0:i.audioLevelAvg;if(void 0===n)return void this._trackBreach($,!1);const s=n<=Ti.THRESHOLD_INBOUND_AUDIO_LEVEL;this._trackBreach($,s)}_trackBreach(e,t){var i,n;if(t){if(this._breachCounters[e]=(null!==(i=this._breachCounters[e])&&void 0!==i?i:0)+1,this._breachCounters[e]>=Ti.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const t=Date.now();t-(null!==(n=this._lastWarningEmitted[e])&&void 0!==n?n:0)>=Ti.WARNING_THROTTLE_MS&&(this._lastWarningEmitted[e]=t,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 t;try{const i=ge(e);Te.warn(`CallReportCollector: warning ${i.code}: ${i.message}`),null===(t=this.onWarning)||void 0===t||t.call(this,i)}catch(t){Te.error(`CallReportCollector: Failed to emit warning ${e}`,{error:t})}}_createStatsEntry(e,t,i,n,s,o,r,a,c,l,d,u,h,p,g){const v={intervalStartUtc:e.toISOString(),intervalEndUtc:t.toISOString(),audio:{}};if(i&&(v.audio.outbound=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({packetsSent:i.packetsSent,bytesSent:i.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)},c?{localTrack:c}:{}),l?{mediaSource:l}:{}),void 0!==i.retransmittedPacketsSent?{retransmittedPacketsSent:i.retransmittedPacketsSent}:{}),void 0!==i.retransmittedBytesSent?{retransmittedBytesSent:i.retransmittedBytesSent}:{}),void 0!==i.headerBytesSent?{headerBytesSent:i.headerBytesSent}:{}),void 0!==i.nackCount?{nackCount:i.nackCount}:{}),void 0!==i.targetBitrate?{targetBitrate:i.targetBitrate}:{}),void 0!==i.totalPacketSendDelay?{totalPacketSendDelay:i.totalPacketSendDelay}:{}),void 0!==i.active?{active:i.active}:{}),p?{codec:this._buildCodecSnapshot(p,i.codecId)}:{})),n&&(v.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:n.packetsReceived,bytesReceived:n.bytesReceived,packetsLost:n.packetsLost,packetsDiscarded:n.packetsDiscarded,jitterBufferDelay:n.jitterBufferDelay,jitterBufferEmittedCount:n.jitterBufferEmittedCount,totalSamplesReceived:n.totalSamplesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,audioLevelAvg:this._average(this.intervalAudioLevels.inbound),jitterAvg:this._average(this.intervalJitters),bitrateAvg:this._average(this.intervalBitrates.inbound)},void 0!==n.nackCount?{nackCount:n.nackCount}:{}),void 0!==n.headerBytesReceived?{headerBytesReceived:n.headerBytesReceived}:{}),void 0!==n.fecPacketsReceived?{fecPacketsReceived:n.fecPacketsReceived}:{}),void 0!==n.fecPacketsDiscarded?{fecPacketsDiscarded:n.fecPacketsDiscarded}:{}),void 0!==n.jitterBufferTargetDelay?{jitterBufferTargetDelay:n.jitterBufferTargetDelay}:{}),void 0!==n.jitterBufferMinimumDelay?{jitterBufferMinimumDelay:n.jitterBufferMinimumDelay}:{}),void 0!==n.totalSamplesDecoded?{totalSamplesDecoded:n.totalSamplesDecoded}:{}),void 0!==n.samplesDecodedWithSilence?{samplesDecodedWithSilence:n.samplesDecodedWithSilence}:{}),void 0!==n.samplesDecodedWithConcealment?{samplesDecodedWithConcealment:n.samplesDecodedWithConcealment}:{}),void 0!==n.totalAudioEnergy?{totalAudioEnergy:n.totalAudioEnergy}:{}),void 0!==n.totalSamplesDuration?{totalSamplesDuration:n.totalSamplesDuration}:{}),g?{codec:this._buildCodecSnapshot(g,n.codecId)}:{})),s&&(v.connection=Object.assign(Object.assign({roundTripTimeAvg:this._average(this.intervalRTTs),currentRoundTripTime:s.currentRoundTripTime},void 0!==s.currentRoundTripTime?{roundTripTimeSource:"candidate-pair.currentRoundTripTime"}:{}),{packetsSent:s.packetsSent,packetsReceived:s.packetsReceived,bytesSent:s.bytesSent,bytesReceived:s.bytesReceived}),v.ice=Object.assign(Object.assign({id:s.id,localCandidateId:s.localCandidateId,remoteCandidateId:s.remoteCandidateId,state:s.state,nominated:s.nominated,writable:s.writable,currentRoundTripTime:s.currentRoundTripTime,requestsSent:s.requestsSent,responsesReceived:s.responsesReceived},o?{local:o}:{}),r?{remote:r}:{})),a&&(v.transport=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},void 0!==a.iceState?{iceState:a.iceState}:{}),void 0!==a.dtlsState?{dtlsState:a.dtlsState}:{}),void 0!==a.srtpCipher?{srtpCipher:a.srtpCipher}:{}),void 0!==a.tlsVersion?{tlsVersion:a.tlsVersion}:{}),void 0!==a.selectedCandidatePairChanges?{selectedCandidatePairChanges:a.selectedCandidatePairChanges}:{}),void 0!==a.selectedCandidatePairId?{selectedCandidatePairId:a.selectedCandidatePairId}:{})),d&&(v.mediaPlayout=this._withoutUndefined({synthesizedSamples:d.synthesizedSamples,synthesizedDuration:d.synthesizedDuration,totalPlayoutDelay:d.totalPlayoutDelay,totalSampleCount:d.totalSampleCount})),u||h){const e={};if(u){const t=void 0!==u.jitter?1e3*u.jitter:void 0;let i;"number"==typeof u.totalRoundTripTime&&"number"==typeof u.roundTripTimeMeasurements&&u.roundTripTimeMeasurements>0&&(i=u.totalRoundTripTime/u.roundTripTimeMeasurements),e.inbound=this._withoutUndefined({packetsReceived:u.packetsReceived,packetsLost:u.packetsLost,fractionLost:u.fractionLost,jitter:t,roundTripTime:u.roundTripTime,totalRoundTripTime:u.totalRoundTripTime,roundTripTimeMeasurements:u.roundTripTimeMeasurements,roundTripTimeAvg:i,nackCount:u.nackCount,reportsReceived:u.reportsReceived,packetsDiscarded:u.packetsDiscarded})}h&&(e.outbound=this._withoutUndefined({packetsSent:h.packetsSent,bytesSent:h.bytesSent,reportsCount:h.reportsCount,roundTripTime:h.roundTripTime,totalPacketSendDelay:h.totalPacketSendDelay})),v.remoteRtcp=e}return v}_resolveCandidate(e,t){if(!t)return void Te.debug("CallReportCollector: candidateId is empty, skipping resolve");const i=e.get(t);if(!i)return void Te.debug("CallReportCollector: candidate not found in stats report",{candidateId:t});const n={};if(void 0!==i.id&&(n.id=i.id),void 0!==i.address?n.address=i.address:void 0!==i.ip&&(n.address=i.ip),void 0!==i.port&&(n.port=i.port),void 0!==i.candidateType&&(n.candidateType=i.candidateType),void 0!==i.protocol&&(n.protocol=i.protocol),void 0!==i.networkType&&(n.networkType=i.networkType),void 0!==i.url&&(n.url=i.url),void 0!==i.relayProtocol&&(n.relayProtocol=i.relayProtocol),0!==Object.keys(n).length)return n;Te.debug("CallReportCollector: candidate report has no usable fields",{candidateId:t})}_getCodec(e,t){if(!t)return;const i=e.get(t);return i&&"codec"===i.type?i:void 0}_buildCodecSnapshot(e,t){const i=this._withoutUndefined(Object.assign({mimeType:e.mimeType,clockRate:e.clockRate,channels:e.channels,payloadType:e.payloadType,sdpFmtpLine:e.sdpFmtpLine},void 0!==t?{codecId:t}:{}));return Object.keys(i).length>0?i:void 0}_getOutboundMediaSource(e,t){let i;return t.mediaSourceId&&(i=e.get(t.mediaSourceId)),i||e.forEach((e=>{i||"media-source"!==e.type||"audio"!==e.kind||(i=e)})),i}_getLocalAudioTrackSnapshot(){var e,t;try{const i=null===(e=this.peerConnection)||void 0===e?void 0:e.getSenders().find((e=>{var t;return"audio"===(null===(t=e.track)||void 0===t?void 0:t.kind)})),n=null==i?void 0:i.track;if(!n)return;const s=null===(t=n.getSettings)||void 0===t?void 0:t.call(n),o=this._withoutUndefined({deviceId:null==s?void 0:s.deviceId,groupId:null==s?void 0:s.groupId,channelCount:null==s?void 0:s.channelCount,sampleRate:null==s?void 0:s.sampleRate,sampleSize:null==s?void 0:s.sampleSize,latency:null==s?void 0:s.latency,echoCancellation:null==s?void 0:s.echoCancellation,noiseSuppression:null==s?void 0:s.noiseSuppression,autoGainControl:null==s?void 0:s.autoGainControl}),r=this._withoutUndefined(Object.assign({id:n.id,label:n.label,enabled:n.enabled,muted:n.muted,readyState:n.readyState,contentHint:n.contentHint},Object.keys(o).length>0?{settings:o}:{}));return Object.keys(r).length>0?r:void 0}catch(e){return void Te.debug("CallReportCollector: unable to snapshot local audio track",{error:e})}}_getOutboundAudioSourceStats(e,t){const i=this._getOutboundMediaSource(e,t);if(!i)return;const n=this._withoutUndefined({id:i.id,trackIdentifier:i.trackIdentifier,audioLevel:i.audioLevel,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration,echoReturnLoss:i.echoReturnLoss,echoReturnLossEnhancement:i.echoReturnLossEnhancement});return Object.keys(n).length>0?n:void 0}_logLocalAudioTrackSnapshot(e,t){if(!e||0===Object.keys(e).length)return;const i=this._stableStringify(e);i!==this._lastLocalAudioTrackSnapshotJson&&(this._lastLocalAudioTrackSnapshotJson=i,Te.debug("CallReportCollector: local audio track snapshot",{localTrack:e,mediaSource:t}))}_withoutUndefined(e){return Object.keys(e).reduce(((t,i)=>{const n=e[i];return void 0!==n&&(t[i]=n),t}),{})}_stableStringify(e){return JSON.stringify(this._sortObjectKeys(e))}_sortObjectKeys(e){return Array.isArray(e)?e.map((e=>this._sortObjectKeys(e))):e&&"object"==typeof e?Object.keys(e).sort().reduce(((t,i)=>(t[i]=this._sortObjectKeys(e[i]),t)),{}):e}_getOutboundAudioLevel(e,t){const i=this._getOutboundMediaSource(e,t);if(void 0!==(null==i?void 0:i.audioLevel))return i.audioLevel;if(i){const e=this._computeAudioLevelFromEnergy(i.totalAudioEnergy,i.totalSamplesDuration,"outbound");if(null!==e)return e}return this._getTrackAudioLevel(e,t.trackId)}_getInboundAudioLevel(e,t){if(void 0!==t.audioLevel)return t.audioLevel;const i=this._computeAudioLevelFromEnergy(t.totalAudioEnergy,t.totalSamplesDuration,"inbound");return null!==i?i:this._getTrackAudioLevel(e,t.trackId)}_computeAudioLevelFromEnergy(e,t,i){if(void 0===e||void 0===t)return null;const n="inbound"===i?"inboundAudioEnergy":"outboundAudioEnergy",s="inbound"===i?"inboundSamplesDuration":"outboundSamplesDuration",o=this.previousStats[n],r=this.previousStats[s];if(this.previousStats[n]=e,this.previousStats[s]=t,void 0===o||void 0===r)return null;const a=e-o,c=t-r;if(c<=0)return null;const l=Math.sqrt(a/c);return Math.min(1,Math.max(0,l))}_getTrackAudioLevel(e,t){var i;if(!t)return null;const n=e.get(t);return n&&null!==(i=n.audioLevel)&&void 0!==i?i:null}_average(e){if(0===e.length)return;const t=e.reduce(((e,t)=>e+t),0);return parseFloat((t/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}Ti.INITIAL_COLLECTION_INTERVAL_MS=1e3,Ti.STATS_FLUSH_THRESHOLD=300,Ti.LOGS_FLUSH_THRESHOLD=800,Ti.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,Ti.CONSECUTIVE_BREACHES_REQUIRED=3,Ti.THRESHOLD_RTT_MS=.4,Ti.THRESHOLD_JITTER_MS=30,Ti.THRESHOLD_PACKET_LOSS_PCT=1,Ti.THRESHOLD_MOS=3.5,Ti.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,Ti.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,Ti.THRESHOLD_INBOUND_AUDIO_LEVEL=.001,Ti.WARNING_THROTTLE_MS=15e3,Ti.RETRY_DELAYS_MS=[500,1e3,2e3],Ti.KEEPALIVE_BODY_LIMIT_BYTES=61440;class Ri{constructor(e,t){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=!1,this.onWarning=null,this._host=null,this._callReportId=null,this.options=e,this.callContext=t,this.recordingId=t.recordingId||`${t.callId}-${Date.now().toString(36)}`}start(e,t){if(!this.options.enabled||this._started)return;if("function"!=typeof MediaStreamTrackProcessor)return Te.warn("CallRecorder: MediaStreamTrackProcessor unavailable — recording disabled for this call"),this._emitWarning(W),void(this._started=!0);const i=this.options.tracks||["local","remote"];let n=0;if(i.includes("local")&&e&&(this._attach(e,"local"),n++),i.includes("remote")&&t&&(this._attach(t,"remote"),n++),0===n)return Te.info("CallRecorder: no audio tracks available to record — recording idle for this call",{callId:this.callContext.callId}),void(this._started=!0);this._startedAt=new Date,this._started=!0,this._scheduleFlush(),Te.info("CallRecorder: started",{callId:this.callContext.callId,tracksAttached:n,flushIntervalMs:this._flushIntervalMs(),maxBufferBytes:this._maxBufferBytes()})}stop(){this._stopped||(this._stopped=!0,this._clearFlushTimer(),this._cancelReaders(),this._endedAt=new Date,Te.info("CallRecorder: stopped",{callId:this.callContext.callId,packetsBuffered:this._buffers.local.length+this._buffers.remote.length}))}postFinalReport(){return t(this,void 0,void 0,(function*(){if(!this.options.enabled)return;if(this.stop(),!this._startedAt)return void Te.debug("CallRecorder: postFinalReport skipped — never started");const e=this._resolveEndpointFromContext();if(!e)return void Te.debug("CallRecorder: postFinalReport skipped — no host available");const t=this.options.tracks||["local","remote"];for(const i of t){const t=this._drain(i);if(0===t.length)continue;const n=this._buildEnvelope(t,i,"final",this._startedAt,this._endedAt||new Date);yield this._postRecording(e,n,!0)}}))}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);(()=>t(this,void 0,void 0,(function*(){try{for(;!o&&!this._stopped;){const{done:e,value:t}=yield s.read();if(e)break;this._onFrame(i,t)}}catch(e){this._stopped||Te.warn("CallRecorder: reader loop error",{track:i,error:e})}})))()}catch(e){Te.warn("CallRecorder: failed to attach track",{track:i,error:e}),this._trackStates[i]=null}}_onFrame(e,t){var i;const n=this._trackStates[e];if(!n||this._stopped)return;const s=t.numberOfFrames,o=new Float32Array(s);t.copyTo(o,{planeIndex:0}),null===(i=t.close)||void 0===i||i.call(t);const r=new Uint8Array(o.buffer,o.byteOffset,o.byteLength);n.seq=n.seq+1&65535;const a=n.ts;n.ts+=s;const c={rtpSeq:n.seq,rtpTs:a,rtpSsrc:n.ssrc,capturedAt:(new Date).toISOString(),payloadBytes:r};this._pushPacket(c,e)}_pushPacket(e,t){const i=e.payloadBytes.length+Ri.PACKET_OVERHEAD_BYTES,n=this._maxBufferBytes(),s=this._buffers[t];if(s.push(e),this._bufferBytes[t]+=i,this._bufferBytes[t]>n){for(;s.length>1&&this._bufferBytes[t]>n;){const e=s.shift();e&&(this._bufferBytes[t]-=e.payloadBytes.length+Ri.PACKET_OVERHEAD_BYTES)}this._overflowWarnedThisWindow||(this._overflowWarnedThisWindow=!0,Te.warn("CallRecorder: buffer overflow — oldest packets dropped",{track:t}),this._emitWarning(H))}}_flushIntervalMs(){var e;return null!==(e=this.options.flushIntervalMs)&&void 0!==e?e:rt}_maxBufferBytes(){var e;return null!==(e=this.options.maxBufferBytes)&&void 0!==e?e:at}_sampleRate(){var e;return null!==(e=this.options.sampleRate)&&void 0!==e?e:48e3}_scheduleFlush(){if(this._stopped||this._flushTimerId)return;const e=this._flushIntervalMs();e<=0||(this._flushTimerId=setInterval((()=>{this._periodicFlush().catch((e=>{Te.error("CallRecorder: periodic flush error",{error:e})}))}),e))}_clearFlushTimer(){this._flushTimerId&&(clearInterval(this._flushTimerId),this._flushTimerId=null)}_cancelReaders(){for(const e of this._readerCancellers)try{e()}catch(e){}this._readerCancellers=[],this._processors=[]}_periodicFlush(){return t(this,void 0,void 0,(function*(){if(!this._flushing&&!this._stopped){this._flushing=!0;try{const e=this._resolveEndpointFromContext();if(!e)return void Te.debug("CallRecorder: periodic flush skipped — no host available");const t=this.options.tracks||["local","remote"],i=this._startedAt||new Date,n=new Date;for(const s of t){const t=this._drain(s);if(0===t.length)continue;const o=this._buildEnvelope(t,s,"intermediate",i,n);yield this._postRecording(e,o,!1)}this._overflowWarnedThisWindow=!1}finally{this._flushing=!1}}}))}_drain(e){const t=this._buffers[e];return this._buffers[e]=[],this._bufferBytes[e]=0,t}_resolveEndpointFromContext(){const e=this.callContext.host;return e?this._resolveEndpoint(e):this._host?this._resolveEndpoint(this._host):null}_setHost(e){this._host=e}_setCallReportId(e){e&&(this._callReportId=e)}_resolveCallReportId(){return this._callReportId||this.callContext.callReportId}_resolveEndpoint(e){const t=this.options.endpoint||"/call_recording";try{const i=new URL(e);return`${`${i.protocol.replace(/^ws/,"http")}//${i.host}`}${t}`}catch(i){return/^https?:\/\//.test(e)?`${e}${t}`:`https://${e}${t}`}}_buildEnvelope(e,t,i,n,s){let o=0;const r=e.map((e=>(o+=e.payloadBytes.length,{rtp_seq:e.rtpSeq,rtp_ts:e.rtpTs,rtp_ssrc:e.rtpSsrc,captured_at:e.capturedAt,payload_b64:this._toBase64(e.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:i,track:t,codec:"pcm-f32-le",sample_rate:this._sampleRate(),channels:1,started_at:n.toISOString(),ended_at:s.toISOString(),packet_count:e.length,byte_count:o,packets:r})}_postRecording(e,i,n){return t(this,void 0,void 0,(function*(){const t={"Content-Type":"application/json","x-call-report-id":i.call_report_id,"x-call-id":i.call_id};i.voice_sdk_id&&(t["x-voice-sdk-id"]=i.voice_sdk_id);const s=JSON.stringify(i),o=n&&s.length<=Ri.KEEPALIVE_BODY_LIMIT_BYTES,r=this.options.fetchImpl||fetch;let a;for(let n=0;n<=Ri.RETRY_DELAYS_MS.length;n++){try{const c=yield r(e,Object.assign({method:"POST",headers:t,body:s},o?{keepalive:!0}:{}));if(c.ok)return void Te.info("CallRecorder: posted",{track:i.track,segment:i.segment,attempt:n+1,status:c.status,packets:i.packet_count});{const e=yield c.text().catch((()=>""));a=new Error(`Call recording POST failed with status ${c.status}`),Te.error("CallRecorder: failed to post",{track:i.track,segment:i.segment,attempt:n+1,status:c.status,error:e})}}catch(e){a=e,Te.warn("CallRecorder: network error posting",{track:i.track,segment:i.segment,attempt:n+1,error:e})}const c=Ri.RETRY_DELAYS_MS[n];if(void 0===c)break;Te.info("CallRecorder: retrying",{track:i.track,segment:i.segment,inMs:c,attempt:n+2}),yield new Promise((e=>setTimeout(e,c)))}throw Te.error("CallRecorder: exhausted retries",{track:i.track,segment:i.segment,error:a}),a instanceof Error?a:new Error("Call recording POST failed after retries")}))}_emitWarning(e){var t;try{const i=ge(e);null===(t=this.onWarning)||void 0===t||t.call(this,i)}catch(t){Te.warn("CallRecorder: failed to emit warning",{code:e,error:t})}}_toBase64(e){let t="";for(let i=0;i<e.length;i+=32768){const n=e.subarray(i,i+32768);t+=String.fromCharCode.apply(null,Array.from(n))}return btoa(t)}}Ri.RETRY_DELAYS_MS=[500,1e3,2e3],Ri.KEEPALIVE_BODY_LIMIT_BYTES=61440,Ri.PACKET_OVERHEAD_BYTES=160;class Ai{constructor(){this._rawDeviceCache=[],this._deviceChangeHandler=null,this._stopped=!1}logDevicesAtStart(){return t(this,void 0,void 0,(function*(){try{const e=yield this._enumerateAudioDevices();this._rawDeviceCache=e,Te.debug("MediaDeviceCollector: devices at call start",{devices:e}),this._startDeviceChangeListener()}catch(e){Te.debug("MediaDeviceCollector: failed to log devices at start",{error:e})}}))}stop(){this._stopped=!0,this._removeDeviceChangeListener()}_enumerateAudioDevices(){return t(this,void 0,void 0,(function*(){try{if("undefined"!=typeof navigator&&navigator.mediaDevices&&"function"==typeof navigator.mediaDevices.enumerateDevices){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind||"audiooutput"===e.kind))}}catch(e){Te.debug("MediaDeviceCollector: enumerateDevices failed",{error:e})}return[]}))}_startDeviceChangeListener(){"undefined"!=typeof navigator&&navigator.mediaDevices&&"function"==typeof navigator.mediaDevices.addEventListener&&(this._deviceChangeHandler=()=>{this._onDeviceChange()},navigator.mediaDevices.addEventListener("devicechange",this._deviceChangeHandler))}_removeDeviceChangeListener(){this._deviceChangeHandler&&"undefined"!=typeof navigator&&navigator.mediaDevices&&"function"==typeof navigator.mediaDevices.removeEventListener&&navigator.mediaDevices.removeEventListener("devicechange",this._deviceChangeHandler),this._deviceChangeHandler=null}_onDeviceChange(){return t(this,void 0,void 0,(function*(){if(!this._stopped)try{const e=yield this._enumerateAudioDevices(),t=new Set(this._rawDeviceCache.map((e=>e.deviceId))),i=new Set(e.map((e=>e.deviceId))),n=e.filter((e=>!t.has(e.deviceId))),s=this._rawDeviceCache.filter((e=>!i.has(e.deviceId)));(n.length>0||s.length>0)&&Te.debug("MediaDeviceCollector: devices changed during call",{connected:n,disconnected:s}),this._rawDeviceCache=e}catch(e){Te.debug("MediaDeviceCollector: error handling devicechange",{error:e})}}))}}var Oi,Di=Ie((function(e,t){var i;function n(){}function s(){s.init.call(this)}function o(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function r(e,t,i,s){var r,a,c;if("function"!=typeof i)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),a=e._events),c=a[t]):(a=e._events=new n,e._eventsCount=0),c){if("function"==typeof c?c=a[t]=s?[i,c]:[c,i]:s?c.unshift(i):c.push(i),!c.warned&&((r=o(e))&&0<r&&c.length>r)){c.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=c.length,function(e){"function"==typeof console.warn?console.warn(e):console.log(e)}(l)}}else c=a[t]=i,++e._eventsCount;return e}function a(e,t,i){function n(){e.removeListener(t,n),s||(s=!0,i.apply(e,arguments))}var s=!1;return n.listener=i,n}function c(e){var t=this._events;if(t){var i=t[e];if("function"==typeof i)return 1;if(i)return i.length}return 0}function l(e,t){for(var i=Array(t);t--;)i[t]=e[t];return i}Object.defineProperty(t,"__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(e){if("number"!=typeof e||0>e||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(e){var t,i,n,s,o,r,a,c="error"===e;if(r=this._events)c=c&&null==r.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var d=new Error('Uncaught, unspecified "error" event. ('+t+")");throw d.context=t,d}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(i=r[e]))return!1;var u="function"==typeof i;switch(n=arguments.length){case 1:!function(e,t,i){if(t)e.call(i);else for(var n=e.length,s=l(e,n),o=0;o<n;++o)s[o].call(i)}(i,u,this);break;case 2:!function(e,t,i,n){if(t)e.call(i,n);else for(var s=e.length,o=l(e,s),r=0;r<s;++r)o[r].call(i,n)}(i,u,this,arguments[1]);break;case 3:!function(e,t,i,n,s){if(t)e.call(i,n,s);else for(var o=e.length,r=l(e,o),a=0;a<o;++a)r[a].call(i,n,s)}(i,u,this,arguments[1],arguments[2]);break;case 4:!function(e,t,i,n,s,o){if(t)e.call(i,n,s,o);else for(var r=e.length,a=l(e,r),c=0;c<r;++c)a[c].call(i,n,s,o)}(i,u,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=Array(n-1),o=1;o<n;o++)s[o-1]=arguments[o];!function(e,t,i,n){if(t)e.apply(i,n);else for(var s=e.length,o=l(e,s),r=0;r<s;++r)o[r].apply(i,n)}(i,u,this,s)}return!0},s.prototype.addListener=function(e,t){return r(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return r(this,e,t,!0)},s.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,a(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,a(this,e,t)),this},s.prototype.removeListener=function(e,t){var i,s,o,r,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(s=this._events))return this;if(!(i=s[e]))return this;if(i===t||i.listener&&i.listener===t)0==--this._eventsCount?this._events=new n:(delete s[e],s.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(o=-1,r=i.length;0<r--;)if(i[r]===t||i[r].listener&&i[r].listener===t){a=i[r].listener,o=r;break}if(0>o)return this;if(1===i.length){if(i[0]=void 0,0==--this._eventsCount)return this._events=new n,this;delete s[e]}else!function(e,t){for(var i=t,n=i+1,s=e.length;n<s;i+=1,n+=1)e[i]=e[n];e.pop()}(i,o);s.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.removeAllListeners=function(e){var t,i;if(!(i=this._events))return this;if(!i.removeListener)return 0===arguments.length?(this._events=new n,this._eventsCount=0):i[e]&&(0==--this._eventsCount?this._events=new n:delete i[e]),this;if(0===arguments.length){for(var s,o=Object.keys(i),r=0;r<o.length;++r)"removeListener"!==(s=o[r])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=new n,this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},s.prototype.listeners=function(e){var t,i,n=this._events;return n?i=(t=n[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(t):[]:i=[],i},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):c.call(e,t)},s.prototype.listenerCount=c,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var d,u=new Uint8Array(16);function h(){if(!d&&!(d="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return d(u)}var p=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;for(var g=[],v=0;256>v;++v)g.push((v+256).toString(16).substr(1));function m(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:0,i=(g[e[t+0]]+g[e[t+1]]+g[e[t+2]]+g[e[t+3]]+"-"+g[e[t+4]]+g[e[t+5]]+"-"+g[e[t+6]]+g[e[t+7]]+"-"+g[e[t+8]]+g[e[t+9]]+"-"+g[e[t+10]]+g[e[t+11]]+g[e[t+12]]+g[e[t+13]]+g[e[t+14]]+g[e[t+15]]).toLowerCase();if(!function(e){return"string"==typeof e&&p.test(e)}(i))throw TypeError("Stringified UUID is invalid");return i}function f(e,t,i){var n=(e=e||{}).random||(e.rng||h)();if(n[6]=64|15&n[6],n[8]=128|63&n[8],t){i=i||0;for(var s=0;16>s;++s)t[i+s]=n[s];return t}return m(n)}function _(e,t){if(!e||!t)return{};const i={...e};if(i.localCandidateId){const e=t.get(i.localCandidateId);i.local={...e}}if(i.remoteCandidateId){const e=t.get(i.remoteCandidateId);i.remote={...e}}return i}function y(e,t,i){return 8*function(e,t,i){const n=e[i],s=t?t[i]:null;return null===n||null===s?null:(n-s)/(e.timestamp-t.timestamp)*1e3}(e,t,i)}function b(e){if(!e.entries)return e;const t={};return e.forEach((function(e,i){t[i]=e})),t}function S(e,t,i={}){if(!e)return null;let n={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};i.remote&&(n.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const t of e.values())switch(t.type){case"outbound-rtp":{const i=t.mediaType||t.kind,s={};let o={};if(!["audio","video"].includes(i))continue;if(t.codecId){const i=e.get(t.codecId);i&&(s.clockRate=i.clockRate,s.mimeType=i.mimeType,s.payloadType=i.payloadType)}o=e.get(t.mediaSourceId)||e.get(t.trackId)||{},n[i].outbound.push({...t,...s,track:{...o}});break}case"inbound-rtp":{let i=t.mediaType||t.kind,s={};const o={};if(!["audio","video"].includes(i))if(t.id.includes("Video"))i="video";else{if(!t.id.includes("Audio"))continue;i="audio"}if(t.codecId){const i=e.get(t.codecId);i&&(o.clockRate=i.clockRate,o.mimeType=i.mimeType,o.payloadType=i.payloadType)}if(!n.connection.id&&t.transportId){const i=e.get(t.transportId);if(i&&i.selectedCandidatePairId){const t=e.get(i.selectedCandidatePairId);n.connection=_(t,e)}}s=e.get(t.mediaSourceId)||e.get(t.trackId)||{},n[i].inbound.push({...t,...o,track:{...s}});break}case"peer-connection":n.connection.dataChannelsClosed=t.dataChannelsClosed,n.connection.dataChannelsOpened=t.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!i.remote)break;let s=t.mediaType||t.kind;const o={};if(!["audio","video"].includes(s))if(t.id.includes("Video"))s="video";else{if(!t.id.includes("Audio"))continue;s="audio"}if(t.codecId){const i=e.get(t.codecId);i&&(o.clockRate=i.clockRate,o.mimeType=i.mimeType,o.payloadType=i.payloadType)}if(!n.connection.id&&t.transportId){const i=e.get(t.transportId);if(i&&i.selectedCandidatePairId){const t=e.get(i.selectedCandidatePairId);n.connection=_(t,e)}}n.remote[s].inbound.push({...t,...o});break}case"remote-outbound-rtp":{if(!i.remote)break;const s=t.mediaType||t.kind,o={};if(!["audio","video"].includes(s))continue;if(t.codecId){const i=e.get(t.codecId);i&&(o.clockRate=i.clockRate,o.mimeType=i.mimeType,o.payloadType=i.payloadType)}n.remote[s].outbound.push({...t,...o});break}}if(!n.connection.id)for(const t of e.values())"candidate-pair"===t.type&&t.nominated&&"succeeded"===t.state&&(n.connection=_(t,e));return n=function(e,t){return t?(e.audio.inbound.map((e=>{let i=t.audio.inbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesReceived"),e.packetRate=y(e,i,"packetsReceived")})),e.audio.outbound.map((e=>{let i=t.audio.outbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesSent"),e.packetRate=y(e,i,"packetsSent")})),e.video.inbound.map((e=>{let i=t.video.inbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesReceived"),e.packetRate=y(e,i,"packetsReceived")})),e.video.outbound.map((e=>{let i=t.video.outbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesSent"),e.packetRate=y(e,i,"packetsSent")})),e):e}(n,t),n}let I,C={},E=[];t.WebRTCStats=class extends s{constructor(e){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"],"undefined"==typeof window)throw new Error("WebRTCStats only works in browser");const t={...e};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=t.getStatsInterval||1e3,this.rawStats=!!t.rawStats,this.statsObject=!!t.statsObject,this.filteredStats=!!t.filteredStats,this.shouldWrapGetUserMedia=!!t.wrapGetUserMedia,"boolean"==typeof t.remote&&(this.remote=t.remote),this.debug=!!t.debug,this.logLevel=t.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(e,t){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:e,pc:t})}async addConnection(e){const{pc:t,peerId:i}=e;let{connectionId:n,remote:s}=e;if(s="boolean"==typeof s?s:this.remote,!(t&&t instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!i)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[i]){if(n&&n in this.peersToMonitor[i])throw new Error(`We are already monitoring connection with id ${n}.`);for(let e in this.peersToMonitor[i]){const n=this.peersToMonitor[i][e];if(n.pc===t)throw new Error(`We are already monitoring peer with id ${i}.`);"closed"===n.pc.connectionState&&this.removeConnection({pc:n.pc})}}const o=t.getConfiguration();return o.iceServers&&o.iceServers.forEach((function(e){delete e.credential})),n||(n=f()),this.emitEvent({event:"addConnection",tag:"peer",peerId:i,connectionId:n,data:{options:e,peerConfiguration:o}}),this.monitorPeer({peerId:i,connectionId:n,pc:t,remote:s}),{connectionId:n}}getTimeline(e){return this.timeline=this.timeline.sort(((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())),e?this.timeline.filter((t=>t.tag===e)):this.timeline}get logger(){const e=e=>{const t=["none","error","warn","info","debug"];return t.slice(0,t.indexOf(this.logLevel)+1).indexOf(e)>-1};return{error(...t){this.debug&&e("error")&&console.error("[webrtc-stats][error] ",...t)},warn(...t){this.debug&&e("warn")&&console.warn("[webrtc-stats][warn] ",...t)},info(...t){this.debug&&e("info")&&console.log("[webrtc-stats][info] ",...t)},debug(...t){this.debug&&e("debug")&&console.debug("[webrtc-stats][debug] ",...t)}}}removeConnection(e){let t,{connectionId:i,pc:n}=e;if(!n&&!i)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(i){if("string"!=typeof i)throw new Error("connectionId must be a string.");for(let e in this.peersToMonitor)i in this.peersToMonitor[e]&&(n=this.peersToMonitor[e][i].pc,t=e)}else if(n){if(!(n instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let e in this.peersToMonitor)for(let s in this.peersToMonitor[e])this.peersToMonitor[e][s].pc===n&&(i=s,t=e)}if(!n||!i)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(i,n),delete this.peersToMonitor[t][i],0===Object.values(this.peersToMonitor[t]).length&&delete this.peersToMonitor[t],{connectionId:i}}removeAllPeers(){for(let e in this.peersToMonitor)this.removePeer(e)}removePeer(e){if(this.logger.info(`Removing PeerConnection with id ${e}.`),this.peersToMonitor[e]){for(let t in this.peersToMonitor[e]){let i=this.peersToMonitor[e][t].pc;this.removePeerConnectionEventListeners(t,i)}delete this.peersToMonitor[e]}}destroy(){this.removeAllPeers(),E.forEach((e=>{this.removeTrackEventListeners(e)})),E=[],this.shouldWrapGetUserMedia&&I&&(navigator.mediaDevices.getUserMedia=I)}monitorPeer(e){let{peerId:t,connectionId:i,pc:n,remote:s}=e;if(!n)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const o={pc:n,connectionId:i,stream:null,stats:{parsed:null,raw:null},options:{remote:s}};if(this.peersToMonitor[t]){if(i in this.peersToMonitor[t])return void this.logger.warn(`Already watching connection with ID ${i}`);this.peersToMonitor[t][i]=o}else this.peersToMonitor[t]={[i]:o};this.addPeerConnectionEventListeners(t,i,n),1===this.numberOfMonitoredPeers&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then((e=>{e.forEach((e=>{this.emitEvent(e)}))}))}),this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(e=null){this.logger.info(e?`Getting stats from peer ${e}`:"Getting stats from all peers");let t={};if(e){if(!this.peersToMonitor[e])throw new Error(`Cannot get stats. Peer with id ${e} does not exist`);t[e]=this.peersToMonitor[e]}else t=this.peersToMonitor;let i=[];for(const e in t)for(const n in t[e]){const s=t[e][n],o=s.pc;if(o&&!this.checkIfConnectionIsClosed(e,n,o))try{const t=this.getTimestamp(),r=o.getStats(null);if(r){const o=await r,a=this.getTimestamp(),c=b(o),l={remote:s.options.remote},d=S(o,s.stats.parsed,l),u={event:"stats",tag:"stats",peerId:e,connectionId:n,timeTaken:a-t,data:d};!0===this.rawStats&&(u.rawStats=o),!0===this.statsObject&&(u.statsObject=c),!0===this.filteredStats&&(u.filteredStats=this.filteroutStats(c)),i.push(u),s.stats.parsed=d}else this.logger.error(`PeerConnection from peer ${e} did not return any stats data`)}catch(e){this.logger.error(e)}}return i}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const e in this.peersToMonitor)for(const t in this.peersToMonitor[e]){const i=this.peersToMonitor[e][t].pc;this.checkIfConnectionIsClosed(e,t,i)}}),this.connectionMonitoringInterval)}checkIfConnectionIsClosed(e,t,i){const n=this.isConnectionClosed(i);if(n){this.removeConnection({pc:i});let n="closed"===i.connectionState?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:n,peerId:e,connectionId:t,tag:"connection",data:"closed"})}return n}isConnectionClosed(e){return"closed"===e.connectionState||"closed"===e.iceConnectionState}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."),I=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const e=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=function(){return e({constraints:arguments[0]}),I.apply(navigator.mediaDevices,arguments).then((t=>(e({stream:t}),t)),(t=>(e({error:t}),Promise.reject(t))))}.bind(navigator.mediaDevices)}filteroutStats(e={}){const t={...e};for(const e in t){var i=t[e];this.statsToMonitor.includes(i.type)||delete t[e]}return t}get peerConnectionListeners(){return{icecandidate:(e,t,i,n)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",n),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:e,connectionId:t,data:n.candidate})},track:(e,t,i,n)=>{this.logger.debug(`[pc-event] track | peerId: ${e}`,n);const s=n.track,o=n.streams[0];e in this.peersToMonitor&&t in this.peersToMonitor[e]&&(this.peersToMonitor[e][t].stream=o),this.addTrackEventListeners(s,t),this.emitEvent({event:"ontrack",tag:"track",peerId:e,connectionId:t,data:{stream:o?this.getStreamDetails(o):null,track:s?this.getMediaTrackDetails(s):null,title:n.track.kind+":"+n.track.id+" "+n.streams.map((function(e){return"stream:"+e.id}))}})},signalingstatechange:(e,t,i)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${e}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:e,connectionId:t,data:{signalingState:i.signalingState,localDescription:i.localDescription,remoteDescription:i.remoteDescription}})},iceconnectionstatechange:(e,t,i)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${e}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:i.iceConnectionState})},icegatheringstatechange:(e,t,i)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${e}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:e,connectionId:t,data:i.iceGatheringState})},icecandidateerror:(e,t,i,n)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${e}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:e,connectionId:t,error:{errorCode:n.errorCode}})},connectionstatechange:(e,t,i)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${e}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:i.connectionState})},negotiationneeded:(e,t,i)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${e}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:e,connectionId:t})},datachannel:(e,t,i,n)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${e}`,n),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:e,connectionId:t,data:n.channel})}}}addPeerConnectionEventListeners(e,t,i){this.logger.debug(`Adding event listeners for peer ${e} and connection ${t}.`),C[t]={},Object.keys(this.peerConnectionListeners).forEach((n=>{C[t][n]=this.peerConnectionListeners[n].bind(this,e,t,i),i.addEventListener(n,C[t][n],!1)}))}parseGetUserMedia(e){try{const t={event:"getUserMedia",tag:"getUserMedia",data:{...e}};e.stream&&(t.data.details=this.parseStream(e.stream),e.stream.getTracks().map((e=>{this.addTrackEventListeners(e),E.push(e)}))),this.emitEvent(t)}catch(e){}}parseStream(e){const t={audio:[],video:[]};return e.getTracks().forEach((e=>{t[e.kind].push(this.getMediaTrackDetails(e))})),t}getMediaTrackDetails(e){return{enabled:e.enabled,id:e.id,contentHint:e.contentHint,kind:e.kind,label:e.label,muted:e.muted,readyState:e.readyState,constructorName:e.constructor.name,capabilities:e.getCapabilities?e.getCapabilities():{},constraints:e.getConstraints?e.getConstraints():{},settings:e.getSettings?e.getSettings():{},_track:e}}getStreamDetails(e){return{active:e.active,id:e.id,_stream:e}}getTrackEventObject(e){return{mute:t=>{this.emitEvent({event:"mute",tag:"track",connectionId:e,data:{event:t}})},unmute:t=>{this.emitEvent({event:"unmute",tag:"track",connectionId:e,data:{event:t}})},overconstrained:t=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:e,data:{event:t}})},ended:t=>{this.emitEvent({event:"ended",tag:"track",connectionId:e,data:{event:t}}),this.removeTrackEventListeners(t.target)}}}addTrackEventListeners(e,t){C[e.id]={};const i=this.getTrackEventObject(t);Object.keys(i).forEach((t=>{C[e.id][t]=i[t].bind(this),e.addEventListener(t,C[e.id][t])})),C[e.id].readyState=setInterval((()=>{if("ended"===e.readyState){let t=new CustomEvent("ended",{detail:{check:"readyState"}});e.dispatchEvent(t)}}),1e3)}removeTrackEventListeners(e){if(e.id in C){const t=this.getTrackEventObject();Object.keys(t).forEach((t=>{e.removeEventListener(t,C[e.id][t])})),clearInterval(C[e.id].readyState),delete C[e.id]}}addToTimeline(e){this.timeline.push(e),this.emit("timeline",e)}emitEvent(e){const t={...e,timestamp:new Date};this.addToTimeline(t),t.tag&&this.emit(t.tag,t)}set getStatsInterval(e){if(!Number.isInteger(e))throw new Error(`getStatsInterval should be an integer, got: ${e}`);this._getStatsInterval=e,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(e,t){e in C&&(Object.keys(this.peerConnectionListeners).forEach((i=>{t.removeEventListener(i,C[e][i],!1)})),delete C[e]),t.getSenders().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)})),t.getReceivers().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)}))}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const e=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const t=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),i=function(){return e.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),t.apply(navigator.mediaDevices,arguments).then((function(e){return e}),(function(t){return e.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,t.name),Promise.reject(t)}))};navigator.mediaDevices.getDisplayMedia=i.bind(navigator.mediaDevices)}}}}));(Oi=Di)&&Oi.__esModule&&Object.prototype.hasOwnProperty.call(Oi,"default")&&Oi.default;var Ni=Di.WebRTCStats;function Li(e){const{packetsLost:t,packetsReceived:i,jitter:n,rtt:s}=e,o=function(e){const{jitter:t,rtt:i}=e,n=t+i/2;return.024*n+.11*(n-177.3)*(n>177.3?1:0)}({rtt:s,jitter:n}),r=function(e){const{packetsLost:t,packetsReceived:i}=e,n=t/(i+t)*100;return 20*Math.log(1+n)}({packetsLost:t,packetsReceived:i}),a=93.2-o-r+0,c=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(c,1),5)}function Mi(e){return isNaN(e)?null:e>4.2?"excellent":e>=4.1&&e<=4.2?"good":e>=3.7&&e<=4?"fair":e>=3.1&&e<=3.6?"poor":"bad"}class Pi extends Ot{constructor(e,t){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:t})}}class xi extends Ot{constructor(e,t){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:t})}}class Ui extends Ot{constructor(e,t,i){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,call_id:t,debug_report_data:i})}}function Fi(e,i){const n=a();let s=!1;const o=new Ni({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),r=s=>t(this,void 0,void 0,(function*(){"stats"===s.event&&It(ue.StatsFrame,function({data:e}){var t,i,n,s,o,r,a,c;const{audio:l,remote:d}=e,{audio:u}=d,h=null!==(i=null===(t=u.inbound[0])||void 0===t?void 0:t.jitter)&&void 0!==i?i:1/0,p=null!==(s=null===(n=u.inbound[0])||void 0===n?void 0:n.roundTripTime)&&void 0!==s?s:1/0,g=null!==(r=null===(o=l.inbound[0])||void 0===o?void 0:o.packetsReceived)&&void 0!==r?r:-1,v=null!==(c=null===(a=l.inbound[0])||void 0===a?void 0:a.packetsLost)&&void 0!==c?c:-1,m=Li({jitter:1e3*h,rtt:1e3*p,packetsLost:v,packetsReceived:g});return{jitter:h,rtt:p,mos:m,quality:Mi(m),inboundAudio:l.inbound[0],outboundAudio:l.outbound[0],remoteInboundAudio:u.inbound[0],remoteOutboundAudio:u.outbound[0]}}(s),e.uuid),yield e.execute(new Ui(n,i,s))}));return{get isRunning(){return s},start:(a,c,l)=>t(this,void 0,void 0,(function*(){if(s)Te.debug(`[${i}] Stats reporter already running, skipping start`);else{yield e.execute(new Pi(n,i)),o.on("timeline",r);try{yield o.addConnection({pc:a,peerId:c,connectionId:l}),s=!0}catch(e){Te.error(`[${i}] Failed to start stats reporter:`,e),o.removeAllPeers(),o.destroy()}}})),stop:r=>t(this,void 0,void 0,(function*(){const t=o.getTimeline();if(It(ue.StatsReport,t,e.uuid),"file"===r){!function(e,t){const i=new Blob([JSON.stringify(e)],{type:"application/json"}),n=URL.createObjectURL(i),s=document.createElement("a");s.href=n,s.download=`${t}.json`,s.click(),URL.revokeObjectURL(n)}(t,`webrtc-stats-${n}-${Date.now()}`)}yield e.execute(new xi(n,i)),o.removeAllPeers(),o.destroy(),s=!1})),reportConnectionStateChange:e=>{const t={event:"connectionstatechange-detailed",tag:"connection",timestamp:(new Date).toISOString(),data:e};r(t)},reportIceCandidateError:e=>{const t={event:"icecandidateerror-detailed",tag:"connection",timestamp:(new Date).toISOString(),data:e};r(t)}}}const $i=(e,t)=>{const{contentType:i,canvasType:n,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&"mcu-personal-canvas"!==n&&delete o.memberID;const a={type:st.conferenceUpdate,call:e.calls[s],canvasInfo:ji(o),currentLayerIdx:r};switch(i){case"layer-info":{const t=Object.assign({action:ut.LayerInfo},a);It(ue.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:ut.LayoutInfo},a);It(ue.Notification,t,e.uuid);break}}},ji=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Le(t)},Bi=["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"],Wi={"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 Hi(e,t){return`telnyx:call:${e}:${t}`}function Gi(e){try{const t=performance.getEntriesByName(e,"mark");return t.length>0?t[0].startTime:void 0}catch(e){return}}function Vi(e){for(const t of Bi)try{performance.clearMarks(Hi(e,t))}catch(e){Te.warn("Clearing performance marks is failed")}}class qi{constructor(e,i,n,s,o){this.type=e,this.options=i,this.onSdpReadyTwice=null,this.statsReporter=null,this.isIceRestarting=!1,this.iceDone=!1,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this._iceGatheringSafetyTimeout=null,this._gatheredCandidatesCount=0,this._firstMediaTrackMarked=!1,this._timingsCollected=!1,this._iceRestartTimeoutId=null,this.handleConnectionStateChange=()=>t(this,void 0,void 0,(function*(){var e,i;if(!this.instance)return void Te.debug("Connection state change ignored: instance is null");const{connectionState:n}=this.instance;if(Te.info(`[${(new Date).toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${n}`),"failed"!==n&&"disconnected"!==n||(this.isDebugEnabled&&this.statsReporter&&function(e,i){return t(this,void 0,void 0,(function*(){const t={connectionState:e.connectionState,previousConnectionState:i,iceConnectionState:e.iceConnectionState,iceGatheringState:e.iceGatheringState,signalingState:e.signalingState},n=e.getTransceivers();if(n.length>0){const e=n[0].sender,i=null==e?void 0:e.transport;i&&(t.dtlsState=i.state)}e.sctp&&(t.sctpState=e.sctp.state);try{const i=yield e.getStats();i.forEach((e=>{"candidate-pair"===e.type&&"succeeded"===e.state&&(t.candidatePairState=e.state,i.forEach((i=>{"local-candidate"===i.type&&i.id===e.localCandidateId&&(t.localCandidateType=i.candidateType,t.selectedCandidatePair=t.selectedCandidatePair||{local:{},remote:{}},t.selectedCandidatePair.local={address:i.address,port:i.port,protocol:i.protocol,candidateType:i.candidateType}),"remote-candidate"===i.type&&i.id===e.remoteCandidateId&&(t.remoteCandidateType=i.candidateType,t.selectedCandidatePair=t.selectedCandidatePair||{local:{},remote:{}},t.selectedCandidatePair.remote={address:i.address,port:i.port,protocol:i.protocol,candidateType:i.candidateType})}))),"transport"===e.type&&(t.dtlsCipher=e.dtlsCipher,t.srtpCipher=e.srtpCipher,t.tlsVersion=e.tlsVersion,e.dtlsState&&(t.dtlsState=e.dtlsState))}))}catch(e){Te.error("Error gathering connection state details:",e)}return t}))}(this.instance,this._prevConnectionState).then((e=>{this.statsReporter.reportConnectionStateChange(e)})),null===(i=(e=this._session).reportPeerFailure)||void 0===i||i.call(e,this.options.id,"connection_failed")),"disconnected"===n){const e=ge(G);It(ue.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if("failed"===n){const e=ge(K);It(ue.PeerConnectionFailureError,{warning:e,error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${n}`),sessionId:this._session.sessionid},this.options.id)}this._prevConnectionState=n,"connected"===n&&(performance.mark(Hi(this.options.id,"dtls-connected")),this.tryCollectTimings(),this._restartedIceOnConnectionStateFailed=!1),this._isTrickleIce()&&("connecting"===n&&performance.mark(Hi(this.options.id,"peer-connection-connecting")),"connected"===n&&(this._clearIceGatheringSafetyTimeout(),performance.mark(Hi(this.options.id,"peer-connection-connected"))))})),this._handleIceConnectionStateChange=()=>{var e,t;if(!this.instance)return void Te.debug("ICE connection state change ignored: instance is null");const i=this.instance.iceConnectionState;Te.debug(`[${(new Date).toISOString()}] ICE Connection State`,i),"connected"===i&&performance.mark(Hi(this.options.id,"ice-connected")),"failed"===i&&(null===(t=(e=this._session).reportPeerFailure)||void 0===t||t.call(e,this.options.id,"ice_failed"))},this._handleIceGatheringStateChange=()=>{const e=this.instance.iceGatheringState;Te.debug(`[${(new Date).toISOString()}] ICE Gathering State`,e),"gathering"===e?(this._gatheredCandidatesCount=0,this._startIceGatheringSafetyTimeout()):"complete"===e&&this._clearIceGatheringSafetyTimeout()},this._setCodecs=(e,t)=>{if(e.setCodecPreferences)return e.setCodecPreferences(t)},Te.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!i.video},this._sdpReady=this._sdpReady.bind(this),this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this._session=n,this._trickleIceSdpFn=s,this._registerPeerEvents=o}finishIceRestart(){this.isIceRestarting&&(this.isIceRestarting=!1,this._iceRestartTimeoutId&&(clearTimeout(this._iceRestartTimeoutId),this._iceRestartTimeoutId=null))}restartIce(){return this.instance?this.isIceRestarting?(Te.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&&(Te.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null}),qi.ICE_RESTART_TIMEOUT_MS),Te.info("ICE restart: initiated by signaling health monitor"),{started:!0}):(Te.debug("ICE restart: session not connected, skipping"),{started:!1,reason:"session not connected"}):(Te.warn("ICE restart: no RTCPeerConnection instance"),{started:!1,reason:"no RTCPeerConnection instance"})}get isOffer(){return this.type===tt.Offer}get isAnswer(){return this.type===tt.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get restartedIceOnConnectionStateFailed(){return this._restartedIceOnConnectionStateFailed}isConnectionHealthy(){return"connected"===this.instance.connectionState&&"connected"===this.instance.iceConnectionState&&"closed"!==this.instance.signalingState}startNegotiation(){performance.mark(Hi(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 t(this,void 0,void 0,(function*(){performance.mark(Hi(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 ve&&It(ue.Error,{error:e,sessionId:this._session.sessionid},this.options.id)}_logTransceivers(){this.instance?(Te.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach(((e,t)=>{Te.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),Te.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))):Te.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(Te.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":It(ue.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(Te.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){Te.info("Negotiation needed event"),"stable"!==this.instance.signalingState||this._negotiating?Te.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(Hi(this.options.id,"first-remote-media-track")),this._firstMediaTrackMarked=!0);const{streams:[t]}=e,{remoteElement:i,screenShare:n}=this.options;this.options.remoteStream=t,!1===n&&ii(i,this.options.remoteStream)}tryCollectTimings(){if(this._timingsCollected)return;if(!(performance.getEntriesByName(Hi(this.options.id,"call-active"),"mark").length>0)||"connected"!==this.instance.connectionState)return;this._timingsCollected=!0;const e=this._isTrickleIce()?"trickle":"non-trickle",t=this.isOffer?"outbound":"inbound",i=function(e,t,i){const n=Gi(Hi(e,"new-call-start"));if(void 0===n)return{mode:t,direction:i,steps:[]};const s=[];for(const t of Bi){if("new-call-start"===t)continue;const i=Gi(Hi(e,t));void 0!==i&&s.push({label:Wi[t]||t,fromStart:i-n})}s.sort(((e,t)=>e.fromStart-t.fromStart));const o=[];let r=0;for(const e of s)o.push({label:e.label,fromStart:e.fromStart,delta:e.fromStart-r}),r=e.fromStart;return{mode:t,direction:i,steps:o}}(this.options.id,e,t);!function(e){const{mode:t,direction:i,steps:n}=e,s=`[CallTimings][${i}][${t}]`;if(0===n.length)return void Te.info(`${s} No timing data collected`);const o=Math.max(...n.map((e=>e.label.length)),4)+2,r=(e,t)=>{for(;e.length<t;)e+=" ";return e},a=(e,t)=>{for(;e.length<t;)e=" "+e;return e},c=r("Step",o)+a("Delta",14)+a("From Start",14);let l="";for(let e=0;e<c.length;e++)l+="-";Te.info(`${s} Call establishment timing breakdown:`),Te.info(`${s} ${c}`),Te.info(`${s} ${l}`),Te.info(`${s} ${r("Call Start",o)}${a("-",14)}${a("0.00ms",14)}`);for(const e of n){const t=e.delta.toFixed(2)+"ms",i=e.fromStart.toFixed(2)+"ms";Te.info(`${s} ${r(e.label,o)}${a(t,14)}${a(i,14)}`)}Te.info(`${s} ${l}`)}(i),Vi(this.options.id)}createPeerConnection(){return t(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",(e=>{this.options.remoteStream=e.stream})),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:tt.Offer}),performance.mark(Hi(this.options.id,"set-remote-description")),!this.instance))throw _e(I);const i=Boolean(this.options.receiveOnlyAudio)&&!this.options.audio;let n=null;if(this.options.localStream=yield this._retrieveLocalStream().catch((e=>t(this,void 0,void 0,(function*(){const i=this._session.options.mediaPermissionsRecovery;if((null==i?void 0:i.enabled)&&this._isAnswer()){let s=null,o=null;return yield new Promise(((t,n)=>{o=setTimeout((()=>n(new Error("Media recovery flow timed out!"))),i.timeout),It(ue.Error,{error:_e(fe(e),e,void 0,!1),callId:this.options.id,sessionId:this._session.sessionid,recoverable:!0,retryDeadline:Date.now()+i.timeout,resume:()=>{t()},reject:()=>{n(new Error("Call was rejected during media recovery flow!"))}},this._session.uuid)})).then((()=>t(this,void 0,void 0,(function*(){var e;o&&(clearTimeout(o),o=null),s=yield this._retrieveLocalStream(),null===(e=i.onSuccess)||void 0===e||e.call(i)})))).catch((e=>{var t;o&&(clearTimeout(o),o=null),n=e,null===(t=i.onError)||void 0===t||t.call(i,e)})),s}return n=e,null})))),!this.instance)throw _e(I);if(!this.options.localStream&&!i){throw _e(n?fe(n):f,null!=n?n:void 0)}performance.mark(Hi(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&ti(this.options.localStream)&&(Te.info("Muting local audio tracks on start"),_i(this.options.localStream)),this.options.applyDesiredAudioMuteState&&this.options.applyDesiredAudioMuteState(),performance.mark(Hi(this.options.id,"peer-creation-end"))}))}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout((()=>{if(this.instance)if(0===this._gatheredCandidatesCount){const e=ge(q);It(ue.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if("complete"!==this.instance.iceGatheringState){const e=ge(V);It(ue.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}),qi.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){null!==this._iceGatheringSafetyTimeout&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return t(this,void 0,void 0,(function*(){if(yield this.createPeerConnection(),!this.instance)throw _e(I);this.isDebugEnabled&&(this.statsReporter=Fi(this._session,this.options.id),yield null===(e=this.statsReporter)||void 0===e?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid));const{localElement:t,localStream:i=null,screenShare:n=!1}=this.options;if(ti(i)){const e=i.getAudioTracks();let s=[...e];if(Te.info("Local audio tracks: ",e),"object"==typeof this.options.audio&&e.forEach((e=>{Te.info("Local audio tracks constraints: ",e.getConstraints())})),this.options.video){const t=i.getVideoTracks();s=[...e,...t],Te.info("Local video tracks: ",t),"object"==typeof this.options.video&&t.forEach((e=>{Te.info("Local video tracks constraints: ",e.getConstraints())}))}const{audioCodecs:o,videoCodecs:r}=Ei(this.options.preferred_codecs);if(this.isOffer&&"function"==typeof this.instance.addTransceiver){const e={direction:"sendrecv",streams:[i]};s.forEach((t=>{"audio"===t.kind&&(this.options.userVariables.microphoneLabel=t.label),"video"===t.kind&&(this.options.userVariables.cameraLabel=t.label);const i=this.instance.addTransceiver(t,e);"audio"===t.kind&&o.length>0&&this._setCodecs(i,o),"video"===t.kind&&r.length>0&&this._setCodecs(i,r)}))}else"function"==typeof this.instance.addTrack?(s.forEach((e=>{"audio"===e.kind&&(this.options.userVariables.microphoneLabel=e.label),"video"===e.kind&&(this.options.userVariables.cameraLabel=e.label),this.instance.addTrack(e,i)})),this.instance.getTransceivers().forEach((e=>{"audio"===e.receiver.track.kind&&o.length>0&&this._setCodecs(e,o),"video"===e.receiver.track.kind&&r.length>0&&this._setCodecs(e,r)}))):this.instance.addStream(i);!1===n&&ii(t,i)}else if(this.options.receiveOnlyAudio&&"function"==typeof this.instance.addTransceiver){const e=this.instance.addTransceiver("audio",{direction:"recvonly"});Te.info("Added recvonly audio transceiver for receive-only mode",e);const{audioCodecs:t}=Ei(this.options.preferred_codecs);t.length>0&&this._setCodecs(e,t)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation().catch((e=>this._emitNegotiationError(e))),this._logTransceivers()}))}_getSenderByKind(e){return this.instance.getSenders().find((({track:t})=>t&&t.kind===e))}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const t=this.instance.addTransceiver(e);Te.info("Add transceiver",e,t)}}_createOffer(){return t(this,void 0,void 0,(function*(){if(this._isOffer()||this.isIceRestarting){this._constraints.offerToReceiveAudio=!1!==this.options.audio||Boolean(this.options.receiveOnlyAudio),this._constraints.offerToReceiveVideo=Boolean(this.options.video),Te.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark(Hi(this.options.id,"create-offer")),yield this._setLocalDescription(e),performance.mark(Hi(this.options.id,"set-local-description")),performance.mark(Hi(this.options.id,"ice-gathering-started")),this._isTrickleIce()||this._sdpReady(),e}catch(e){if(Te.error("Peer _createOffer error:",e),e instanceof ve)throw e;throw _e(d,e)}}}))}_setRemoteDescription(e){return t(this,void 0,void 0,(function*(){Te.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(e){Te.error("Peer _setRemoteDescription error:",e);throw _e(p,e)}}))}_createAnswer(){return t(this,void 0,void 0,(function*(){if(this._isAnswer()){if("stable"!==this.instance.signalingState&&"have-remote-offer"!==this.instance.signalingState)return Te.debug("Skipping negotiation, state:",this.instance.signalingState),Te.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:tt.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark(Hi(this.options.id,"create-answer")),yield this._setLocalDescription(e),performance.mark(Hi(this.options.id,"set-local-description")),performance.mark(Hi(this.options.id,"ice-gathering-started")),e}catch(e){if(Te.error("Peer _createAnswer error:",e),e instanceof ve)throw e;throw _e(u,e)}}}))}_setLocalDescription(e){return t(this,void 0,void 0,(function*(){try{yield this.instance.setLocalDescription(e)}catch(e){Te.error("Peer _setLocalDescription error:",e);throw _e(h,e)}}))}_sdpReady(){Me(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return t(this,void 0,void 0,(function*(){if(ti(this.options.localStream))return this.options.localStream;const e=yield(i=this.options,t(void 0,void 0,void 0,(function*(){let{audio:e=!0,micId:t,video:n=!1,camId:s}=i;const{micLabel:o="",camLabel:r=""}=i;return t&&(t=yield di(t,o,ht.AudioIn).catch((()=>null)),t&&("boolean"==typeof e&&(e={}),e.deviceId={exact:t})),s&&(s=yield di(s,r,ht.Video).catch((()=>null)),s&&("boolean"==typeof n&&(n={}),n.deviceId={exact:s})),{audio:e,video:n}})));var i;return ai(e)}))}_isOffer(){return this.type===tt.Offer}_isAnswer(){return this.type===tt.Answer}_isTrickleIce(){return!0===this.options.trickleIce}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:t,iceServers:i}=this.options,n={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:i,iceTransportPolicy:t?"relay":"all"};return Te.info("RTC config",n),n}restartStatsReporter(){return t(this,void 0,void 0,(function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?Te.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(Te.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):Te.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))}))}close(){return t(this,void 0,void 0,(function*(){Vi(this.options.id),this.finishIceRestart(),this._clearIceGatheringSafetyTimeout(),null!==this._sleepWakeupIntervalId&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)}))}}qi.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,qi.ICE_RESTART_TIMEOUT_MS=15e3;const Ki=Ft;class Yi{constructor(e,t){this.session=e,this._callReportCollector=null,this._callRecorder=null,this._mediaDeviceCollector=null,this.id="",this.recoveredCallId="",this.state=lt[lt.New],this.prevState="",this.channels=[],this.role=dt.Participant,this.extension=null,this._state=lt.New,this._prevState=lt.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._checkConferenceSerno=e=>{const t=e<0||!this._lastSerno||this._lastSerno&&e===this._lastSerno+1;return t&&e>=0&&(this._lastSerno=e),t},this._doStats=()=>{this.peer&&this.peer.instance&&0!==this._statsBindings.length&&this.peer.instance.getStats().then((e=>{e.forEach((e=>{this._statsBindings.forEach((t=>{if(t.callback){if(t.constraints)for(const i in t.constraints)if(t.constraints.hasOwnProperty(i)&&t.constraints[i]!==e[i])return;t.callback(e)}}))}))}))};const{iceServers:i,speaker:n,micId:s,micLabel:o,camId:r,camLabel:a,localElement:c,remoteElement:l,options:d,mediaConstraints:{audio:u,video:h},ringtoneFile:p,ringbackFile:g}=e;this.options=Object.assign({},ct,{audio:u,video:h,iceServers:(null==t?void 0:t.iceServers)&&Array.isArray(t.iceServers)?t.iceServers:i,localElement:c,remoteElement:l,micId:s,micLabel:o,camId:r,camLabel:a,speakerId:n,ringtoneFile:p,ringbackFile:g,debug:d.debug,debugOutput:d.debugOutput,trickleIce:d.trickleIce,prefetchIceCandidates:d.prefetchIceCandidates,forceRelayCandidate:d.forceRelayCandidate,keepConnectionAliveOnSocketClose:d.keepConnectionAliveOnSocketClose,mutedMicOnStart:d.mutedMicOnStart},t),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=Boolean(this.options.mutedMicOnStart),this.options.applyDesiredAudioMuteState=this._applyDesiredAudioMuteState.bind(this),this._init(),this.options&&(this._ringtone=Si(this.options.ringtoneFile,"_ringtone"),this._ringback=Si(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}_captureHangupCallerStack(){const e=new Error("Call.hangup caller").stack;return e?e.split("\n").map((e=>e.trim())).filter(Boolean).slice(1,11):[]}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}get isVideoCall(){return!!this.options.video}get telnyxIDs(){return{telnyxCallControlId:this.options.telnyxCallControlId,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId}}get localStream(){return this.options.localStream}get remoteStream(){return this.options.remoteStream}get memberChannel(){return`conference-member.${this.id}`}get isAudioMuted(){return this._desiredAudioMuted}_getLocalAudioTrackId(){var e,t;return null===(t=null===(e=this.options.localStream)||void 0===e?void 0:e.getAudioTracks()[0])||void 0===t?void 0:t.id}_hasActiveUnmutedLocalAudioTrack(){const e=this.options.localStream;return!!(null==e?void 0:e.getAudioTracks)&&e.getAudioTracks().some((e=>!0===e.enabled&&!0!==e.muted&&"live"===e.readyState))}shouldForceRelayCandidateForRecovery(){var e,t;return!this.options.forceRelayCandidate&&(!!this.recoveredCallId&&(null!==(t=null===(e=this._callReportCollector)||void 0===e?void 0:e.shouldForceRelayCandidateForRecovery())&&void 0!==t&&t))}invite(){return t(this,void 0,void 0,(function*(){this._creatingPeer=!0,this.direction=it.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(Hi(this.id,"new-peer")),this.peer=new qi(tt.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){Te.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const t=e instanceof ve?e:_e(L,e instanceof Error?e:void 0);return It(ue.Error,{error:t,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void this.hangup({initiator:"sdk:peer-init-failed"},!1)}this._creatingPeer=!1}))}answer(e={}){var i,n,s,o,r,a,c,l;return t(this,void 0,void 0,(function*(){const t=(null!==(s=null===(n=(i=this.session).getActiveCalls)||void 0===n?void 0:n.call(i))&&void 0!==s?s:[]).filter((e=>e.id!==this.id));if(t.length>0&&Te.debug(`[${this.id}] answer(): answering inbound call while ${t.length} other active call(s) exist in session ${this.session.sessionid}`),this._creatingPeer||(null===(o=this.peer)||void 0===o?void 0:o.instance)&&"closed"!==this.peer.instance.signalingState){const e=ge(J);return It(ue.Warning,{warning:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void Te.warn(`[${this.id}] answer() ignored: peer connection already exists or is being created (signalingState: ${null!==(c=null===(a=null===(r=this.peer)||void 0===r?void 0:r.instance)||void 0===a?void 0:a.signalingState)&&void 0!==c?c:"creating"})`)}if(this._registerInboundAnswerAttempt()){performance.mark(Hi(this.id,"answer-called")),this._creatingPeer=!0,this.stopRingtone(),this.direction=it.Inbound,(null===(l=null==e?void 0:e.customHeaders)||void 0===l?void 0:l.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(Hi(this.id,"new-peer")),this.peer=new qi(tt.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){Te.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const t=e instanceof ve?e:_e(L,e instanceof Error?e:void 0);return It(ue.Error,{error:t,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void(yield this.hangup({initiator:"sdk:peer-init-failed"},!0))}this._creatingPeer=!1}}))}playRingtone(){Ii(this._ringtone)}stopRingtone(){Ci(this._ringtone)}playRingback(){Ii(this._ringback)}stopRingback(){Ci(this._ringback)}hangup(e,i){var n,s,o,r,a,c;return t(this,void 0,void 0,(function*(){const t=e||{},l=!1!==i,d=this.state,u=this.prevState,h=this._captureHangupCallerStack(),p=t.initiator||"app:call.hangup",g=this._state<lt.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=t.cause||g.cause,this.causeCode=t.causeCode||g.causeCode,this.sipCode=t.sipCode||null,this.sipReason=t.sipReason||null,this.sipCallId=t.sip_call_id||null,this.options.customHeaders=[...null!==(n=this.options.customHeaders)&&void 0!==n?n:[],...null!==(o=null===(s=null==t?void 0:t.dialogParams)||void 0===s?void 0:s.customHeaders)&&void 0!==o?o:[]],Te.debug(`[${this.id}] hangup() invoked`,{callId:this.id,execute:l,state:d,prevState:u,cause:this.cause,causeCode:this.causeCode,initiator:p,sipCode:this.sipCode,sipReason:this.sipReason,sipCallId:this.sipCallId,isRecovering:Boolean(t.isRecovering),hasDialogCustomHeaders:Boolean(null===(a=null===(r=t.dialogParams)||void 0===r?void 0:r.customHeaders)||void 0===a?void 0:a.length),callerStack:h}),t.isRecovering)return this._isRecovering=!0,this.setState(lt.Recovering),void this._finalize();if(this.setState(lt.Hangup),this.stopRingtone(),this.stopRingback(),l){const e=new Gt({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});let t;try{yield Promise.race([this._execute(e),new Promise((e=>{t=setTimeout((()=>{Te.warn(`[${this.id}] BYE execution timed out after 5000ms — proceeding to destroy.`),e()}),5e3)}))])}catch(e){Te.error("telnyx_rtc.bye failed!",e);const t=_e(b,e);It(ue.Error,{error:t,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}finally{t&&clearTimeout(t)}}Te.debug(`[${this.id}] Closing peer from hangup`),null===(c=this.peer)||void 0===c||c.close(),this.setState(lt.Destroy)}))}hold(){const e=new Kt({sessid:this.session.sessionid,action:gt.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new Kt({sessid:this.session.sessionid,action:gt.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new Kt({sessid:this.session.sessionid,action:gt.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const t=new Yt({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(t)}message(e,t){const i={from:this.session.options.login,to:e,body:t},n=new Yt({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(n)}muteAudio(){Te.debug("muteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!0,_i(this.options.localStream)}unmuteAudio(){Te.debug("unmuteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!1,fi(this.options.localStream)}_applyDesiredAudioMuteState(){Te.debug("applyDesiredAudioMuteState called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted?_i(this.options.localStream):fi(this.options.localStream)}toggleAudioMute(){Te.debug("toggleAudioMute called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!this._desiredAudioMuted,this._applyDesiredAudioMuteState()}setAudioInDevice(e,i=this._desiredAudioMuted){var n,s,o;return t(this,void 0,void 0,(function*(){const t=Boolean(i),{instance:r}=this.peer,a=r.getSenders().find((({track:{kind:e}})=>"audio"===e));if(!a)return Te.warn("Skipping audio input device change: no audio sender found",{callId:this.id,deviceId:e,audioMuted:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),void It(ue.Warning,{warning:ge(Q),callId:this.id,deviceId:e,sessionId:this.session.sessionid},(null===(n=this.options)||void 0===n?void 0:n.id)||this.id);let c;Te.debug("Starting audio input device change",{callId:this.id,state:this.state,deviceId:e,previousDesiredAudioMuted:this._desiredAudioMuted,newDesiredMuted:t,currentSenderTrack:hi(a.track),localTracks:pi(this.options.localStream)});try{c=yield ei({audio:{deviceId:{exact:e}}})}catch(e){const t=_e(fe(e),e);return void It(ue.MediaError,t,(null===(s=this.options)||void 0===s?void 0:s.id)||this.id)}const l=c.getAudioTracks()[0];l.enabled=!t;try{yield a.replaceTrack(l)}catch(e){const t=_e(fe(e),e);return It(ue.MediaError,t,(null===(o=this.options)||void 0===o?void 0:o.id)||this.id),void c.getTracks().forEach((e=>e.stop()))}this._desiredAudioMuted=t,this.options.micId=e;const{localStream:d}=this.options;d.getAudioTracks().forEach((e=>e.stop())),d.getVideoTracks().forEach((e=>c.addTrack(e))),this.options.localStream=c,Te.debug("Finished audio input device change",{callId:this.id,state:this.state,deviceId:e,desiredAudioMuted:this._desiredAudioMuted,senderTrack:hi(a.track),localTracks:pi(this.options.localStream)})}))}muteVideo(){var e;e=this.options.localStream,mi(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,mi(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,mi(e,"video",null)}setVideoDevice(e){return t(this,void 0,void 0,(function*(){const{instance:t}=this.peer,i=t.getSenders().find((({track:{kind:e}})=>"video"===e));if(i){const t=yield ei({video:{deviceId:{exact:e}}}),n=t.getVideoTracks()[0];i.replaceTrack(n);const{localElement:s,localStream:o}=this.options;ii(s,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t,this._applyDesiredAudioMuteState()}}))}deaf(){_i(this.options.remoteStream)}undeaf(){fi(this.options.remoteStream)}toggleDeaf(){var e;e=this.options.remoteStream,mi(e,"audio",null)}setBandwidthEncodingsMaxBps(e,i){return t(this,void 0,void 0,(function*(){if(!this||!this.peer)return void Te.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:t}=this.peer,n=t.getSenders();if(!n)return void Te.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:e}})=>e===i));if(s){const t=s.getParameters();t.encodings||(t.encodings=[{rid:"h"}]),Te.info("Parameters: ",t),Te.info("Setting max ","audio"===i?"audio":"video"," bandwidth to: ",e," [bps]"),t.encodings[0].maxBitrate=e,yield s.setParameters(t).then((()=>{Te.info("audio"===i?"New audio":"New video"," bandwidth settings in use: ",s.getParameters())})).catch((e=>Te.error(e)))}else Te.error("Could not set bandwidth (reason: no "+i+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")}))}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}_isTerminatingOrTerminated(){return[lt.Hangup,lt.Destroy,lt.Purge].includes(this._state)}getStats(e,t){if(!e)return;const i={callback:e,constraints:t};if(this._statsBindings.push(i),!this._statsIntervalId){const e=2e3;this._startStats(e)}}setState(e){var t,i,n,s,o;switch(this._prevState=this._state,this._state=e,this.state=lt[this._state].toLowerCase(),this.prevState=lt[this._prevState].toLowerCase(),Te.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:st.callUpdate,call:this}),e){case lt.Purge:Te.info(`[${this.id}] Entering Purge state.`);break;case lt.Active:if(performance.mark(Hi(this.id,"call-active")),null===(t=this.peer)||void 0===t||t.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,Te.debug(`[${this.id}] Recovery complete, call is active`)),this.session.startSignalingHealthMonitor(),setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&si(e,t)}),0),this._callReportCollector&&(null===(i=this.peer)||void 0===i?void 0:i.instance)&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance),this._callRecorder){const e=null===(n=this.session.connection)||void 0===n?void 0:n.host;e&&this._callRecorder._setHost(e),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const t=null===(s=this.options.localStream)||void 0===s?void 0:s.getAudioTracks()[0],i=null===(o=this.options.remoteStream)||void 0===o?void 0:o.getAudioTracks()[0];this._callRecorder.start(t,i)}this._mediaDeviceCollector=new Ai,this._mediaDeviceCollector.logDevicesAtStart();break;case lt.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:i}=e;switch(t){case nt.Answer:if(performance.mark(Hi(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),this._state>=lt.Active)return;this._state>=lt.Early&&this.setState(lt.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case nt.Media:if(performance.mark(Hi(this.id,"telnyx-rtc-media")),this._state>=lt.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case nt.Display:{const{display_name:e,display_number:n,display_direction:s}=i;this.extension=n;const o=s===it.Inbound?it.Outbound:it.Inbound,r={type:st[t],call:this,displayName:e,displayNumber:n,displayDirection:o};It(ue.Notification,r,this.id)||It(ue.Notification,r,this.session.uuid);break}case nt.Candidate:this._addIceCandidate(i);break;case nt.Info:case nt.Event:{const e=Object.assign(Object.assign({},i),{type:st.generic,call:this});It(ue.Notification,e,this.id)||It(ue.Notification,e,this.session.uuid);break}case nt.Ringing:performance.mark(Hi(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 nt.Bye:const e=i.client_state||i.clientState;e&&(this.options.clientState=e),this.stopRingback(),this.stopRingtone(),this.hangup(Object.assign(Object.assign({},i),{initiator:"remote:telnyx_rtc.bye"}),!1)}}handleConferenceUpdate(e,i){return t(this,void 0,void 0,(function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==i.laName)return Te.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:t,data:n,hashKey:s=String(this._lastSerno),arrIndex:o}=e;switch(t){case"bootObj":{this._lastSerno=0;const{chatChannel:e,infoChannel:t,modChannel:s,laName:o,conferenceMemberID:r,role:a}=i;this._dispatchConferenceUpdate({action:ut.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),t&&(yield this._subscribeConferenceInfo(t));const c=[];for(const e in n)c.push(Object.assign({callId:n[e][0],index:Number(e)},Ne(n[e][1])));this._dispatchConferenceUpdate({action:ut.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:ut.Add,callId:s,index:o},Ne(n)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:ut.Modify,callId:s,index:o},Ne(n)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:ut.Delete,callId:s,index:o},Ne(n)));break;case"clear":this._dispatchConferenceUpdate({action:ut.Clear});break;default:this._dispatchConferenceUpdate({action:t,data:n,callId:s,index:o})}}))}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const t=this.session.relayProtocol;this.session._existsSubscription(t,e)&&(this.session.subscriptions[t][e]=Object.assign(Object.assign({},this.session.subscriptions[t][e]),{callId:this.id}))}_subscribeConferenceChat(e){return t(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{direction:t,from:i,fromDisplay:n,message:s,type:o}=e.data;this._dispatchConferenceUpdate({action:ut.ChatMessage,direction:t,participantNumber:i,participantName:n,messageText:s,messageType:o,messageId:e.eventSerno})}},i=yield this.session.vertoSubscribe(t).catch((e=>{Te.error("ConfChat subscription error:",e)}));gi(i,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(t,i)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:t,type:i}})}}}))}))}_subscribeConferenceInfo(e){return t(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{eventData:t}=e;if("layout-info"===t.contentType)t.callID=this.id,$i(this.session,t);else Te.error("Conference-Info unknown contentType",e)}},i=yield this.session.vertoSubscribe(t).catch((e=>{Te.error("ConfInfo subscription error:",e)}));gi(i,e)&&this._addChannel(e)}))}_confControl(e,t={}){const i=Object.assign({application:"conf-control",callID:this.id,value:null},t);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:i})}_handleChangeHoldStateSuccess(e){return"active"===e.holdState?this.setState(lt.Active):this.setState(lt.Held),!0}_handleChangeHoldStateError(e){Te.error(`Failed to ${e.action} on call ${this.id}`);const t=_e(_,e);return It(ue.Error,{error:t,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e,i={}){const n=new Kt(Object.assign(Object.assign({sessid:this.session.sessionid,action:gt.UpdateMedia,callID:this.options.id,sdp:e},i.trickle?{trickle:!0}:{}),{dialogParams:this.options}));Te.info(`ICE restart: sending ${i.trickle?"trickle ":""}Modify with new offer SDP`),this._execute(n).then((e=>t(this,void 0,void 0,(function*(){var t;(null==e?void 0:e.sdp)?(Te.info("ICE restart Modify response received"),null===(t=this.peer)||void 0===t||t.finishIceRestart(),yield this._onRemoteSdp(e.sdp)):this._onIceRestartFailed("ICE restart Modify response missing SDP")})))).catch((e=>{this._onIceRestartFailed("ICE restart Modify failed",e)}))}_onIceRestartFailed(e,t){var i,n,s;Te.error(e,t),null===(i=this.peer)||void 0===i||i.finishIceRestart();const o=_e(O,t);It(ue.Error,{error:o,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),null===(s=(n=this.session).reportIceRestartFailed)||void 0===s||s.call(n,this.id)}_onRemoteSdp(e){return t(this,void 0,void 0,(function*(){const i=new RTCSessionDescription({sdp:e,type:tt.Answer});yield this.peer.instance.setRemoteDescription(i).then((()=>{performance.mark(Hi(this.id,"set-remote-description")),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(lt.Early),this.gotAnswer&&this.setState(lt.Active)})).catch((e=>t(this,void 0,void 0,(function*(){Te.error("Call setRemoteDescription Error: ",e);const t=_e(p,e);It(ue.Error,{error:t,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(e){Te.error("Error during hangup after setRemoteDescription failure:",e)}}))))}))}_requestAnotherLocalDescription(){if(Me(this.peer.onSdpReadyTwice)){const e=_e(g,new Error("SDP without candidates for the second time!"));It(ue.Error,{error:e,sessionId:this.session.sessionid},this.session.uuid)}else Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this.peer.iceDone=!1,this.peer.startNegotiation()}_onIceSdp(e){var i,n,s;if(this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this.peer&&(this.peer.iceDone=!0),!e)return void Te.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:o,type:r}=e;if(-1===o.indexOf("candidate"))return Te.info("No candidate - retry \n"),void this._requestAnotherLocalDescription();if(null===(n=null===(i=this.peer)||void 0===i?void 0:i.instance)||void 0===n||n.removeEventListener("icecandidate",this._onIce),!oe.test(o)){const e=ge(Y);Te.warn(`[${this.id}] Warning ${e.code}: ${e.message}`),It(ue.Warning,{warning:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}performance.mark(Hi(this.id,"ice-gathering-end"));let a=null;const c={sessid:this.session.sessionid,sdp:o,dialogParams:this.options,"User-Agent":`Web-${Ki}`};if(null===(s=this.peer)||void 0===s?void 0:s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case tt.Offer:this.setState(lt.Requesting),a=new Bt(c);break;case tt.Answer:this._isRecovering||this.setState(lt.Answering),a=!0===this.options.attach?new Ht(c):new Wt(c);break;default:return Te.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(Hi(this.id,"send-sdp")),this._execute(a).then((e=>{if(this._isTerminatingOrTerminated())return void Te.debug(`[${this.id}] Ignoring ${r} response because call is ${this.state}`);const{node_id:t=null}=e;this._targetNodeId=t,r===tt.Offer?this.setState(lt.Trying):this.setState(lt.Active)})).catch((e=>t(this,void 0,void 0,(function*(){Te.error(`${this.id} - Sending ${r} error:`,e);const t=_e(g,e);It(ue.Error,{error:t,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(e){Te.error("Error during hangup after SDP send failure:",e)}}))))}}_onTrickleIceSdp(e){var i;if(!e)return Te.error("No SDP data provided"),void this.hangup({initiator:"sdk:missing-local-sdp"},!1);const{sdp:n,type:s}=e;let o=null;const r={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${Ki}`};if(null===(i=this.peer)||void 0===i?void 0:i.isIceRestarting)this._sendIceRestartModify(n,{trickle:!0});else{switch(s){case tt.Offer:this.setState(lt.Requesting),o=new Bt(r);break;case tt.Answer:this._isRecovering||this.setState(lt.Answering),o=!0===this.options.attach?new Ht(r):new Wt(r);break;default:return Te.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(Hi(this.id,"send-sdp")),this._execute(o).then((e=>{if(this._isTerminatingOrTerminated())return void Te.debug(`[${this.id}] Ignoring ${s} response because call is ${this.state}`);const{node_id:t=null}=e;this._targetNodeId=t,s===tt.Offer?this.setState(lt.Trying):this.setState(lt.Active)})).catch((e=>t(this,void 0,void 0,(function*(){Te.error(`${this.id} - Sending ${s} error:`,e);const t=_e(g,e);It(ue.Error,{error:t,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(e){Te.error("Error during hangup after SDP send failure:",e)}}))))}}_onIce(e){var t;const{instance:i}=this.peer;if(null===this._iceTimeout){const e=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout((()=>this._onIceSdp(i.localDescription)),e)}e.candidate?(Te.debug("RTCPeer Candidate:",e.candidate),null===(t=this.peer)||void 0===t||t.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate)):this._onIceSdp(i.localDescription)}_onTrickleIce(e){var t;e.candidate&&e.candidate.candidate?(Te.debug("RTCPeer Candidate:",e.candidate),null===(t=this.peer)||void 0===t||t.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const t=new Vt({sessid:this.session.sessionid,candidate:e.candidate,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,dialogParams:this.options});this._execute(t)}_addIceCandidate(e){if(!this._isRemoteDescriptionSet)return Te.debug("Remote description not set. Queued ICE candidate.",e),void this._pendingIceCandidates.push(e);this._addIceCandidateToPeer(e)}_addIceCandidateToPeer(e){const t=this.peer.instance.addIceCandidate(e);Promise.resolve(t).then((()=>{Te.debug("Successfully added ICE candidate:",e)})).catch((t=>{Te.error("Failed to add ICE candidate:",t,e)}))}_sendEndOfCandidates(){const e=new qt({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var t;if(this._firstCandidateSent||(performance.mark(Hi(this.id,"first-candidate")),this._firstCandidateSent=!0),!this._firstNonHostCandidateSent){const i=null===(t=e.candidate.match(/typ (\w+)/))||void 0===t?void 0:t[1];i&&"host"!==i&&(performance.mark(Hi(this.id,"first-non-host-candidate")),this._firstNonHostCandidateSent=!0)}}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach((e=>{this._addIceCandidateToPeer(e)}))}_registerPeerEvents(e){e.onicecandidate=e=>{var t;this.options.trickleIce?this._onTrickleIce(e):(null===(t=this.peer)||void 0===t?void 0:t.iceDone)||this._onIce(e)},e.onicegatheringstatechange=t=>{Te.debug("ICE gathering state changed:",e.iceGatheringState,t),"complete"===e.iceGatheringState&&(Te.debug("Finished gathering candidates"),performance.mark(Hi(this.id,"ice-gathering-completed")))},e.onicecandidateerror=t=>{var i;if(Te.debug("ICE candidate error:",t),null===(i=this.peer)||void 0===i?void 0:i.statsReporter){const i=function(e,t){var i,n;return{errorCode:e.errorCode,errorText:e.errorText,url:e.url,address:e.address,port:e.port,connectionState:t.connectionState,iceConnectionState:t.iceConnectionState,iceGatheringState:t.iceGatheringState,signalingState:t.signalingState,localDescriptionType:null===(i=t.localDescription)||void 0===i?void 0:i.type,remoteDescriptionType:null===(n=t.remoteDescription)||void 0===n?void 0:n.type}}(t,e);this.peer.statsReporter.reportIceCandidateError(i)}},e.addEventListener("addstream",(e=>{this.options.remoteStream=e.stream})),e.addEventListener("track",(e=>{this.options.remoteStream=e.streams[0];const{remoteElement:t,remoteStream:i,screenShare:n}=this.options;!1===n&&ii(t,i)}))}_onMediaError(e){const t=(null==e?void 0:e.name)||"UnknownError",i=(null==e?void 0:e.message)||"Unknown media error",n=(null==e?void 0:e.originalError)||e;this._dispatchNotification({type:st.userMediaError,error:n,call:this,errorName:t,errorMessage:i}),Te.error(`Media error (${t}): ${i}`,e),It(ue.Error,{error:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),this.hangup({initiator:"sdk:media-error"},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:st.peerConnectionFailureError,error:e.error}),Te.error("Peer connection failure error"),e.warning&&It(ue.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:st.signalingStateClosed},e)),Te.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:st.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(It(ue.Notification,e,this.id,!1)||It(ue.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_registerInboundAnswerAttempt(){var e;if(this.options.attach||this._isRecovering)return!0;const t=null===(e=this.session.calls)||void 0===e?void 0:e[this.id];if(t&&t!==this){const e=ge(Z);return It(ue.Warning,{warning:e,callId:this.id,activeCallId:t.id,sessionId:this.session.sessionid},this.session.uuid),Te.warn(`[${this.id}] answer() ignored: callID ${this.id} already has an active call (${t.id})`),!1}return!0}_init(){var e,t,i,n,s,o,r,c,l,d;const{id:u,userVariables:h,remoteCallerNumber:p,onNotification:g,recoveredCallId:v}=this.options;var m;this.options.id=u?u.toString():a(),this.id=this.options.id,v&&(this.recoveredCallId=v,this._isRecovering=!0),h&&(m=h,0!==Object.keys(m).length)||(this.options.userVariables=this.session.options.userVariables||{}),p||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,yt(ue.MediaError,this._onMediaError,this.id),yt(ue.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),yt(ue.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Me(g)&&yt(ue.Notification,g.bind(this),this.id);const f=!1!==this.session.options.enableCallReports,_=this.session.options.callReportInterval||5e3,y=null!==(e=this.session.options.callReportFlushInterval)&&void 0!==e?e:18e4,b=this.session.options.debugLogLevel||"debug",S=this.session.options.debugLogMaxEntries||1e3;f&&(this._callReportCollector=new Ti({enabled:!0,interval:_,intermediateReportInterval:y},{enabled:!0,level:b,maxEntries:S}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=e=>{var t,i,n,s;It(ue.Warning,{warning:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),e.code===j?null===(i=(t=this.session).reportNoRtp)||void 0===i||i.call(t,this.id,"inbound"):e.code===B&&this._hasActiveUnmutedLocalAudioTrack()&&(null===(s=(n=this.session).reportNoRtp)||void 0===s||s.call(n,this.id,"outbound"))});if(!0===this.session.options.enableCallRecording){const e={enabled:!0,flushIntervalMs:null!==(t=this.session.options.callRecordingFlushIntervalMs)&&void 0!==t?t:rt,maxBufferBytes:null!==(i=this.session.options.callRecordingMaxBufferBytes)&&void 0!==i?i:at,sampleRate:null!==(n=this.session.options.callRecordingSampleRate)&&void 0!==n?n:48e3,tracks:null!==(s=this.session.options.callRecordingTracks)&&void 0!==s?s:["local","remote"],endpoint:null!==(o=this.session.options.callRecordingEndpoint)&&void 0!==o?o:"/call_recording"},a={callId:this.id,callReportId:null!==(r=this.session.callReportId)&&void 0!==r?r:"",voiceSdkId:this._getCallReportVoiceSdkId()};this._callRecorder=new Ri(e,a);const l=null===(c=this.session.connection)||void 0===c?void 0:c.host;l&&this._callRecorder._setHost(l),this._callRecorder.onWarning=e=>{It(ue.Warning,{warning:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}this._isRecovering?this.setState(lt.Recovering):this.setState(lt.New),Te.info(`New Call — region: ${null!==(l=this.session.region)&&void 0!==l?l:"unknown"}, dc: ${null!==(d=this.session.dc)&&void 0!==d?d:"unknown"}`,this.options)}_finalize(){var e,t,i;this._stopStats(),null===(e=this._mediaDeviceCollector)||void 0===e||e.stop(),this._mediaDeviceCollector=null,null===(t=this._callRecorder)||void 0===t||t.stop(),Vi(this.id),Te.debug(`[${this.id}] Closing peer from _finalize`),null===(i=this.peer)||void 0===i||i.close();const{remoteStream:n,localStream:s,remoteElement:o,localElement:r}=this.options;ri(n),ri(s),ni(o,n),ni(r,s),St(ue.MediaError,null,this.id),St(ue.PeerConnectionFailureError,null,this.id),St(ue.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id];const a=this._postCallReport().catch((e=>{Te.error("Unexpected error in _postCallReport",{error:e})}));this.session.trackCallReportUpload(a)}_getCallReportVoiceSdkId(){return this.session.callReportVoiceSdkId||void 0}_getClientSummary(){var e,t,i,n,s,o,r,a,c,l,d,u;const h=this.session.options,p=h.anonymous_login;return{authentication:Object.assign({type:this._getAuthenticationType()},p?{anonymousLogin:{targetType:p.target_type,targetId:p.target_id,targetVersionId:p.target_version_id,targetParams:this._sanitizeClientOption(p.target_params)}}:{}),connection:{env:h.env,host:h.host,project:h.project,region:null!==(e=this.session.region)&&void 0!==e?e:h.region,dc:this.session.dc,rtcIp:h.rtcIp,rtcPort:h.rtcPort,autoReconnect:null===(t=h.autoReconnect)||void 0===t||t,maxReconnectAttempts:null!==(i=h.maxReconnectAttempts)&&void 0!==i?i:10,keepConnectionAliveOnSocketClose:null!==(n=h.keepConnectionAliveOnSocketClose)&&void 0!==n&&n,hangupOnBeforeUnload:!1!==h.hangupOnBeforeUnload,useCanaryRtcServer:null!==(s=h.useCanaryRtcServer)&&void 0!==s&&s,skipLastVoiceSdkId:null!==(o=h.skipLastVoiceSdkId)&&void 0!==o&&o,skipTrailing:null!==(r=h.skipTrailing)&&void 0!==r&&r},media:{audio:this._sanitizeClientOption(this.options.audio),video:this._sanitizeClientOption(this.options.video),mutedMicOnStart:null!==(a=this.options.mutedMicOnStart)&&void 0!==a&&a,prefetchIceCandidates:null===(c=this.options.prefetchIceCandidates)||void 0===c||c,forceRelayCandidate:null!==(l=this.options.forceRelayCandidate)&&void 0!==l&&l,trickleIce:null!==(d=this.options.trickleIce)&&void 0!==d&&d,iceServers:this._sanitizeIceServers(this.options.iceServers)},callReports:{enabled:!1!==h.enableCallReports,intervalMs:h.callReportInterval||5e3,flushIntervalMs:null!==(u=h.callReportFlushInterval)&&void 0!==u?u:18e4,debugLogLevel:h.debugLogLevel||"debug",debugLogMaxEntries:h.debugLogMaxEntries||1e3}}}_getAuthenticationType(){const e=this.session.options;return e.anonymous_login?"anonymous_login":e.login_token?"login_token":e.login&&(e.password||e.passwd)?"login_password":e.token?"token":"unknown"}_sanitizeIceServers(e){if(e&&0!==e.length)return e.map((({urls:e,username:t,credential:i})=>({urls:e,hasUsername:Boolean(t),hasCredential:Boolean(i)})))}_sanitizeClientOption(e,t=0){if(void 0!==e){if(null===e)return null;if("string"==typeof e)return e;if("number"==typeof e)return Number.isFinite(e)?e:void 0;if("boolean"==typeof e)return e;if("function"!=typeof e){if(t>=4)return"[truncated]";if(Array.isArray(e))return e.map((e=>this._sanitizeClientOption(e,t+1))).filter((e=>void 0!==e));if("object"==typeof e){const i=Object.entries(e).filter((([e])=>!this._isSensitiveClientOptionKey(e))).map((([e,i])=>[e,this._sanitizeClientOption(i,t+1)])).filter((e=>void 0!==e[1]));return Object.fromEntries(i)}}}}_isSensitiveClientOptionKey(e){return/(password|passwd|credential|secret|token|authorization|auth|api[_-]?key)/i.test(e)}flushIntermediateCallReport(e={type:"manual"}){this._flushIntermediateReport(e)}_flushIntermediateReport(e={type:"buffer-limit"}){var t;if(!this._callReportCollector)return;const i=this.session.callReportId;if(!i)return void Te.debug("Cannot flush intermediate report: call_report_id not available");const n=null===(t=this.session.connection)||void 0===t?void 0:t.host;if(!n)return void Te.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===it.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Ki,clientSummary:this._getClientSummary()},o=this._callReportCollector.flush(s,e);if(!o)return;Te.info("Flushing intermediate call report",{callId:this.id,flushReason:e,segment:o.segment});const r=this._getCallReportVoiceSdkId(),a="page-unload"===e.type,c=this._callReportCollector.sendPayload(o,i,n,r,a).catch((e=>{Te.error("Failed to post intermediate call report segment",{error:e})}));this.session.trackCallReportUpload(c)}_postCallReport(){var e,i,n,s;return t(this,void 0,void 0,(function*(){if(!this._callReportCollector)return void Te.warn("Call report collector not initialized");if(yield this._callReportCollector.stop(),this._callRecorder){this._callRecorder.stop();const t=null===(e=this.session.connection)||void 0===e?void 0:e.host;t&&this._callRecorder._setHost(t),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const i=this._callRecorder.postFinalReport().catch((e=>{Te.error("Failed to post final call recording",{error:e})})).finally((()=>{var e;null===(e=this._callRecorder)||void 0===e||e.cleanup()}));this.session.trackCallReportUpload(i)}const t=this.session.callReportId;if(!t)return Te.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===it.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Ki,clientSummary:this._getClientSummary()},r=null===(i=this.session.connection)||void 0===i?void 0:i.host;if(!r)return void Te.error("Cannot post call report: connection host not available");const a=this._getCallReportVoiceSdkId();try{yield this._callReportCollector.postReport(o,t,r,a)}catch(e){throw Te.error("Failed to post call report",{error:e}),e}finally{null===(n=this._callReportCollector)||void 0===n||n.cleanup(),null===(s=this._callRecorder)||void 0===s||s.cleanup()}}))}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),Te.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),Te.debug("Stats stopped")}}Yi.setStateTelnyx=e=>{if(e){switch(e._state){case lt.Recovering:e.state="recovering";break;case lt.Requesting:case lt.Trying:case lt.Early:e.state="connecting";break;case lt.Active:e.state="active";break;case lt.Held:e.state="held";break;case lt.Hangup:case lt.Destroy:e.state="done";break;case lt.Answering:e.state="ringing";break;case lt.New:e.state="new"}return e}};class Ji extends Yi{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,t)=>this.session.execute(new ki(e,t)),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 t=new wi(e);this.session.connection.sendRawText(JSON.stringify(t.request))}}hangup(e={},i=!0){const n=Object.create(null,{hangup:{get:()=>super.hangup}});return t(this,void 0,void 0,(function*(){this.screenShare instanceof Ji&&(yield this.screenShare.hangup(e,i)),yield n.hangup.call(this,e,i)}))}startScreenShare(e){return t(this,void 0,void 0,(function*(){const i=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;i.getTracks().forEach((e=>{e.addEventListener("ended",(()=>t(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,c=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 Ji(this.session,c),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){return t(this,void 0,void 0,(function*(){this.screenShare instanceof Ji&&(yield this.screenShare.hangup({initiator:"app:stopScreenShare"}))}))}setAudioOutDevice(e){return t(this,void 0,void 0,(function*(){this.options.speakerId=e;const{remoteElement:t,speakerId:i}=this.options;return!(!t||!i)&&si(t,i)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval((()=>t(this,void 0,void 0,(function*(){const e=yield this.peer.instance.getStats(null);let t="";const i=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],n=["id","type","timestamp"];e.forEach((e=>{i.includes(e.type)||(t+=`\n${e.type}\n`,Object.keys(e).forEach((i=>{n.includes(i)||(t+=`\t${i}: ${e[i]}\n`)})))})),Te.info(t)}))),2e3)}}class zi extends Zt{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=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=>zi.ACTIVE_CALL_STATE_NAMES.has(e.state)))}_extractSafeCallIdentifiers(e){var t,i;const n={callId:e.id,state:e.state,direction:e.direction};(null===(t=e.options)||void 0===t?void 0:t.telnyxSessionId)&&(n.telnyxSessionId=e.options.telnyxSessionId),(null===(i=e.options)||void 0===i?void 0:i.telnyxLegId)&&(n.telnyxLegId=e.options.telnyxLegId);const s=e.sipCallId;return"string"==typeof s&&s&&(n.sipCallId=s),n}emitMultipleActiveCallsWarning(e){const t=this.getActiveCalls().filter((t=>t.id!==e));if(0===t.length)return;const i=ge(X),n=this.calls[e],s=n?this._extractSafeCallIdentifiers(n):{callId:e};It(ue.Warning,{warning:i,callId:e,sessionId:this.sessionid,newCall:s,activeCalls:t.map((e=>this._extractSafeCallIdentifiers(e)))},this.uuid),Te.warn(`MULTIPLE_ACTIVE_CALLS_DETECTED: new call ${e} created while ${t.length} other call(s) are active in session ${this.sessionid}`)}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return t(this,void 0,void 0,(function*(){return e.getIsRegistered.call(this)}))}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return t(this,void 0,void 0,(function*(){Te.debug("BrowserSession.connect() called"),e.connect.call(this)}))}checkPermissions(e=!0,i=!0){return t(this,void 0,void 0,(function*(){try{const t=yield ai({audio:e,video:i});return ri(t),!0}catch(e){return!1}}))}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return t(this,void 0,void 0,(function*(){Te.info("[disconnect] Client-initiated disconnect — setting Purge with BYE on all active calls.");for(const e in this.calls){const t=this.calls[e];t.setState(lt.Purge),Te.info("Start hangup for ",t),yield t.hangup({initiator:"app:client.disconnect"},!0)}this.calls={},yield e.disconnect.call(this)}))}serverDisconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return t(this,void 0,void 0,(function*(){Te.info("[serverDisconnect] Server-initiated disconnect — setting Purge without BYE on all active calls.");for(const e in this.calls){const t=this.calls[e];t.setState(lt.Purge),t.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(((t,i)=>{if(bt(ue.SpeedTest,(i=>{const{upDur:n,downDur:s}=i,o=s?8*e/(s/1e3)/1024:0;t({upDur:n,downDur:s,upKps:(n?8*e/(n/1e3)/1024:0).toFixed(0),downKps:o.toFixed(0)})}),this.uuid),!(e=Number(e)))return i(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let n=e/1024;e%1024&&n++;const s=".".repeat(1024);for(let e=0;e<n;e++)this.executeRaw(`#SPB ${s}`);this.executeRaw("#SPE")}))}getDevices(){return ci().catch((e=>{const t=_e(fe(e),e);return It(ue.MediaError,t,this.uuid),[]}))}getVideoDevices(){return ci(ht.Video).catch((e=>(It(ue.MediaError,e,this.uuid),[])))}getAudioInDevices(){return ci(ht.AudioIn).catch((e=>{const t=_e(fe(e),e);return It(ue.MediaError,t,this.uuid),[]}))}getAudioOutDevices(){return ci(ht.AudioOut).catch((e=>(Te.error("getAudioOutDevices",e),It(ue.MediaError,e,this.uuid),[])))}validateDeviceId(e,t,i){return di(e,t,i)}getDeviceResolutions(e){return t(this,void 0,void 0,(function*(){try{return yield(e=>t(void 0,void 0,void 0,(function*(){const t=[],i=yield ai({video:{deviceId:{exact:e}}}),n=i.getVideoTracks()[0];for(let e=0;e<li.length;e++){const[i,s]=li[e];(yield n.applyConstraints({width:{exact:i},height:{exact:s}}).then((()=>!0)).catch((()=>!1)))&&t.push({resolution:`${i}x${s}`,width:i,height:s})}return ri(i),t})))(e)}catch(e){throw e}}))}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(i){return t(this,void 0,void 0,(function*(){if(!i)throw new Error("You need to provide the settings object");const{micId:n,micLabel:s}=i,o=e(i,["micId","micLabel"]);return ui(o),this._audioConstraints=yield((e,i,n,s)=>t(void 0,void 0,void 0,(function*(){const{deviceId:t}=s;if(void 0===t&&(e||i)){const t=yield di(e,i,n).catch((()=>null));t&&(s.deviceId={exact:t})}return s})))(n,s,"audioinput",o),this.micId=n,this.micLabel=s,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 e="development"===this.options.env;this._iceServers=e?de:le}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=Pe(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=Pe(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:t="",data:i}){if(!t)throw new Error(`Invalid channel for broadcast: ${t}`);const n=new Jt({sessid:this.sessionid,eventChannel:t,data:i});e&&(n.targetNodeId=e),this.execute(n).catch((e=>e))}vertoSubscribe({nodeId:e,channels:i=[],handler:n}){return t(this,void 0,void 0,(function*(){if(!(i=i.filter((e=>e&&!this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new zt({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const s=yield this.execute(t),{unauthorized:o=[],subscribed:r=[]}=vi(s);return o.length&&o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),r.forEach((e=>this._addSubscription(this.relayProtocol,n,e))),s}))}vertoUnsubscribe({nodeId:e,channels:i=[]}){return t(this,void 0,void 0,(function*(){if(!(i=i.filter((e=>e&&this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new Qt({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const n=yield this.execute(t),{unsubscribed:s=[],notSubscribed:o=[]}=vi(n);return s.forEach((e=>this._removeSubscription(this.relayProtocol,e))),o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),n}))}static telnyxStateCall(e){return Ji.setStateTelnyx(e)}}zi.ACTIVE_CALL_STATE_NAMES=new Set(["new","requesting","trying","recovering","ringing","answering","early","active","held"]);class Qi{constructor(e,t){this.code=t,this.message=e}}class Xi{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,t){const i=new jt(e,t);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*(e=2,t=6,Math.floor(Math.random()*(t-e+1)+e));var e,t}handleMessage(e){var t,i,n,s,o,r,a,c,l,d,u;const{session:h}=this;h.setPingReceived();const{id:p,method:g,params:v={},voice_sdk_id:m}=e,f=null==v?void 0:v.callID,_=null==v?void 0:v.eventChannel,y=null==v?void 0:v.eventType,b=h.calls[f],S=null===(t=null==b?void 0:b.peer)||void 0===t?void 0:t.isConnectionHealthy(),I=new Set(Object.keys(h.calls));if(Array.isArray(null==v?void 0:v.reattached_sessions)&&I.size){Te.debug(`Reattach: active call IDs before cleanup check: [${Array.from(I).join(", ")}].`);const e=0===v.reattached_sessions.length,t=v.reattached_sessions.some((e=>I.has(e)));if(e||!t)for(const e of Object.keys(h.calls)){const t=h.calls[e];Te.debug(`Session not reattached — terminating active call ${e} `);const i=_e(N);It(ue.Error,{error:i,callId:e,sessionId:h.sessionid},h.uuid),t.hangup({},!1)}}if(Array.isArray(null==v?void 0:v.reattached_sessions)&&h.sessionid){const e=Ze();if(e&&e.calls.length>0)if(e.sessionId!==h.sessionid)Te.debug(`Recovery markers were saved for a different sessid (saved=${e.sessionId}, current=${h.sessionid}) — ignoring all.`);else{const t=new Set(v.reattached_sessions);for(const i of e.calls)try{if(t.has(i.id)){Te.debug(`Recovery marker for call ${i.id} was reattached — no notification.`);continue}Te.info(`Recovery marker for call ${i.id} (sessid=${h.sessionid}) was not reattached — emitting SESSION_NOT_REATTACHED.`);const e=_e(N);It(ue.Error,{error:e,callId:i.id,sessionId:h.sessionid,customHeaders:i.customHeaders},h.uuid)}catch(e){Te.debug(`Recovery marker for a saved call failed to process (callId=${null==i?void 0:i.id}) — skipping: ${e instanceof Error?e.message:String(e)}`)}}}if("channelPvtData"===y)return this._handlePvtEvent(v.pvtData);const C=({recoveredCallId:e,forceRelayCandidateForRecovery:t,mutedMicOnStart:i}={})=>{var n,s,o,r,a;const c={audio:!0,video:h.options.video,remoteSdp:v.sdp,destinationNumber:v.callee_id_number,remoteCallerName:v.caller_id_name,remoteCallerNumber:v.caller_id_number,callerName:v.callee_id_name,callerNumber:v.callee_id_number,attach:g===nt.Attach,mediaSettings:v.mediaSettings,debug:null!==(n=h.options.debug)&&void 0!==n&&n,debugOutput:null!==(s=h.options.debugOutput)&&void 0!==s?s:"socket",trickleIce:null!==(o=h.options.trickleIce)&&void 0!==o&&o,prefetchIceCandidates:null===(r=h.options.prefetchIceCandidates)||void 0===r||r,forceRelayCandidate:t||h.options.forceRelayCandidate||!1,keepConnectionAliveOnSocketClose:null!==(a=h.options.keepConnectionAliveOnSocketClose)&&void 0!==a&&a,mutedMicOnStart:null!=i?i:h.options.mutedMicOnStart};f&&(c.id=f),v.telnyx_call_control_id&&(c.telnyxCallControlId=v.telnyx_call_control_id),v.telnyx_session_id&&(c.telnyxSessionId=v.telnyx_session_id),v.telnyx_leg_id&&(c.telnyxLegId=v.telnyx_leg_id),v.client_state&&(c.clientState=v.client_state),v.dialogParams&&v.dialogParams.custom_headers&&v.dialogParams.custom_headers.length&&(c.customHeaders=v.dialogParams.custom_headers),e&&(c.recoveredCallId=e),performance.mark(Hi(c.id,"new-call-start"));const l=new Ji(h,c);return l.nodeId=this.nodeId,l},E=new Lt(m),R=new Pt(m);switch(g){case nt.Answer:case nt.Display:case nt.Candidate:case nt.Ringing:case nt.Bye:case nt.Media:if(!f||!b)return void Te.error(`Received ${g} for non existing call:`,v);b.handleMessage(e),this._ack(p,g);break;case nt.Ping:this.session.setPingReceived(),this.session.execute(R);break;case nt.Punt:h.options.keepConnectionAliveOnSocketClose&&S?(Te.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),h.socketDisconnect(),this._ack(p,g)):(Te.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),h.serverDisconnect());break;case nt.Invite:{const e=C();e.direction=it.Inbound,e.playRingtone(),e.setState(lt.Ringing),this.session.emitMultipleActiveCallsWarning(e.id),this._ack(p,g);break}case nt.Attach:{const e=b||null;if(0===Object.keys(h.calls).length){Te.warn(`[${(new Date).toISOString()}][${f}] Attach: SDK doens't have any active call therefore we recover first arrived attach session ${f}`);const e=C({recoveredCallId:f});e.answer(),this.session.emitMultipleActiveCallsWarning(e.id),this._ack(p,g);break}if(e){const t=e.id,s=null!==(n=null===(i=e.shouldForceRelayCandidateForRecovery)||void 0===i?void 0:i.call(e))&&void 0!==n&&n;s&&Te.warn(`[${(new Date).toISOString()}][${f}] Attach: forcing relay candidate because recovered VPN media path is still stalled`),Te.info(`[${(new Date).toISOString()}][${f}] Attach: recovering active call ${t}.`),e.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1);const o=C({recoveredCallId:t,forceRelayCandidateForRecovery:s,mutedMicOnStart:e.isAudioMuted});o.answer(),this.session.emitMultipleActiveCallsWarning(o.id),this._ack(p,g);break}Te.warn(`Attach: callID ${f} does not match any active calls. `),It(ue.Warning,{warning:ge(te),callId:f,params:v,sessionId:h.sessionid},h.uuid),this._ack(p,g);break}case nt.Event:case"webrtc.event":if(!_)return void Te.error("Verto received an unknown event:",v);const t=h.relayProtocol,y=_.split(".")[0];h._existsSubscription(t,_)?It(t,v,_):_===h.sessionid?this._handleSessionEvent(v.eventData):h._existsSubscription(t,y)?It(t,v,y):h.calls.hasOwnProperty(_)?h.calls[_].handleMessage(e):It(ue.Notification,v,h.uuid);break;case nt.Info:v.type=st.generic,It(ue.Notification,v,h.uuid);break;case nt.ClientReady:this.session.execute(E);break;case"ai_conversation":It(ue.AIConversationMessage,{method:"ai_conversation",params:v,voice_sdk_id:m},h.uuid);break;default:{const t=je(e);if(t){switch(t){case pt.REGISTER:case pt.REGED:if(!this.isDuplicateGatewayState(t,[pt.REGED,pt.REGISTER])){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0,t===pt.REGED&&this.session.resetReconnectAttempts();const i=null===(o=null===(s=null==e?void 0:e.result)||void 0===s?void 0:s.params)||void 0===o?void 0:o.call_report_id;i&&(h.callReportId=i,Te.debug("Captured call_report_id from REGED:",i));const n=null===(a=null===(r=null==e?void 0:e.result)||void 0===r?void 0:r.params)||void 0===a?void 0:a.dc;n&&(h.dc=n);const p=null===(l=null===(c=null==e?void 0:e.result)||void 0===c?void 0:c.params)||void 0===l?void 0:l.region;p&&(h.region=p),Te.info(`Connected to Telnyx — region: ${null!==(d=h.region)&&void 0!==d?d:"unknown"}, dc: ${null!==(u=h.dc)&&void 0!==u?u:"unknown"}`),v.type=st.vertoClientReady,It(ue.Ready,v,h.uuid)}break;case pt.UNREGED:case pt.NOREG:if(this.retriedRegister+=1,5===this.retriedRegister){this.retriedRegister=0;const e=new Qi("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),t=_e(T,e);It(ue.Error,{error:t,sessionId:h.sessionid},h.uuid);break}setTimeout((()=>{this.session.execute(E)}),this.reconnectDelay());break;case pt.FAILED:case pt.FAIL_WAIT:case pt.TIMEOUT:if(!this.isDuplicateGatewayState(t,[pt.FAILED,pt.FAIL_WAIT,pt.TIMEOUT])){const e=_e(w,new Error(`Gateway state: ${t}`));if(It(ue.Error,{error:e,sessionId:h.sessionid},h.uuid),h.options.skipLastVoiceSdkId=!0,Te.debug(`Set skipLastVoiceSdkId=true on session options to avoid sticky reconnect to same b2bua-rtc instance (sessionId=${h.sessionid})`),!this.session.hasAutoReconnect()){this.retriedConnect=0;const e=new Qi("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT|TIMEOUT");this.session._terminateActiveCallsLocally();const t=_e(k,e);It(ue.Error,{error:t,sessionId:h.sessionid},h.uuid);break}if(this.retriedConnect+=1,5===this.retriedConnect){this.retriedConnect=0,this.session._terminateActiveCallsLocally();const e=_e(k,new Error("Connection Retry Failed"));It(ue.Error,{error:e,sessionId:h.sessionid},h.uuid);break}setTimeout((()=>{if(Te.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){const e=Object.values(h.calls).some((e=>{var t;return(null===(t=e.peer)||void 0===t?void 0:t.instance)&&!e.signalingStateClosed}));if(e)return Te.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();Te.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:Te.warn("GatewayState message unknown method:",e)}break}Te.debug("Verto message unknown method:",e);break}}}isDuplicateGatewayState(e,t){const{previousGatewayState:i}=this.session.connection,n=t.includes(i);return n&&Te.debug(`Gateway state '${e}' received but previous state was '${i}' — guard condition met, skipping re-emission (sessionId=${this.session.sessionid})`),n}_retrieveCallId(e,t){const i=Object.keys(this.session.calls);if("bootObj"!==e.action)return i.find((e=>this.session.calls[e].channels.includes(t)));{const t=e.data.find((e=>i.includes(e[0])));if(t instanceof Array)return t[0]}}_handlePvtEvent(e){return t(this,void 0,void 0,(function*(){const{session:t}=this,i=t.relayProtocol,{action:n,laChannel:s,laName:o,chatChannel:r,infoChannel:a,modChannel:c,conferenceMemberID:l,role:d,callID:u}=e;switch(n){case"conference-liveArray-join":{const i=()=>{t.vertoBroadcast({nodeId:this.nodeId,channel:s,data:{liveArray:{command:"bootstrap",context:s,name:o}}})},n={nodeId:this.nodeId,channels:[s],handler:({data:n})=>{const r=u||this._retrieveCallId(n,s);if(r&&t.calls.hasOwnProperty(r)){const a=t.calls[r];a._addChannel(s),a.extension=o,a.handleConferenceUpdate(n,e).then((e=>{"INVALID_PACKET"===e&&i()}))}}},r=yield t.vertoSubscribe(n).catch((e=>{Te.error("liveArray subscription error:",e);const i=_e(S,e);It(ue.Error,{error:i,sessionId:t.sessionid},t.uuid)}));gi(r,s)&&i();break}case"conference-liveArray-part":{let e=null;if(s&&t._existsSubscription(i,s)){const{callId:n=null}=t.subscriptions[i][s];if(e=t.calls[n]||null,null!==n){const i={type:st.conferenceUpdate,action:ut.Leave,conferenceName:o,participantId:Number(l),role:d};It(ue.Notification,i,n,!1)||It(ue.Notification,i,t.uuid),null===e&&St(ue.Notification,null,n)}}const n=[s,r,a,c];t.vertoUnsubscribe({nodeId:this.nodeId,channels:n}).then((({unsubscribedChannels:t=[]})=>{e&&(e.channels=e.channels.filter((e=>!t.includes(e))))})).catch((e=>{Te.error("liveArray unsubscribe error:",e)}));break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":$i(this.session,e);break;case"logo-info":{const t={type:st.conferenceUpdate,action:ut.LogoInfo,logo:e.logoURL};It(ue.Notification,t,this.session.uuid);break}}}}class Zi extends zi{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>t(this,void 0,void 0,(function*(){this._idle=!1;const{autoReconnect:e=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=e}})})),this.handleAnonymousLoginOnSocketOpen=()=>t(this,void 0,void 0,(function*(){this._idle=!1,yield this.login()})),this._vertoHandler=new Xi(this),window.addEventListener("beforeunload",(t=>{if(Te.debug("Window beforeunload triggered."),!1!==e.hangupOnBeforeUnload)return Qe(),void(this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&(Te.info(`Hanging up call due to window unload: ${e}`),this.calls[e].hangup({initiator:"sdk:beforeunload"},!0))})));this.calls&&Object.keys(this.calls).forEach((e=>{const t=this.calls[e];(null==t?void 0:t.flushIntermediateCallReport)&&(Te.debug(`beforeunload: flushing call report for ${e}.`),t.flushIntermediateCallReport({type:"page-unload"}))}));try{const e=(this.calls?Object.keys(this.calls):[]).filter((e=>!!this.calls[e])).map((e=>this.calls[e])).map((e=>({id:e.id,customHeaders:e.options.customHeaders})));if(!this.sessionid||0===e.length)return Te.debug(`No sessionID ${this.sessionid} or activeCalls ${e.length} during saving calls recover marker!`),void Xe();Te.info(`Saving recovery marker for ${e.length} active call(s) before unload (sessid=${this.sessionid}): [${e.map((e=>e.id)).join(", ")}].`),et(e,this.sessionid)}catch(e){const t=this.calls?Object.keys(this.calls):[];Te.debug(`Failed to save active-calls recovery marker before unload (active call ids: [${t.join(", ")}]): ${e instanceof Error?e.message:String(e)}`)}})),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&!1===e.hangupOnBeforeUnload&&this.sessionid&&this.hasActiveCall()&&(Te.debug("visibilitychange → hidden: re-stamping reconnect session-id freshness."),ze(this.sessionid))}))}validateOptions(){return Fe(this.options)||$e(this.options)}newCall(e){if(!this.validateCallOptions(e)){throw _e(y,void 0,"Error: destinationNumber is required")}const t=new Ji(this,e);return e.id||Te.debug(`newCall: callId was not provided in options, SDK-generated ID: ${t.id}`),this.emitMultipleActiveCallsWarning(t.id),performance.mark(Hi(t.id,"new-call-start")),t.invite(),t}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!$e(this.options)||Boolean(e.destinationNumber)}_onSocketOpen(){const e=Object.create(null,{_onSocketOpen:{get:()=>super._onSocketOpen}});return t(this,void 0,void 0,(function*(){return e._onSocketOpen.call(this),Fe(this.options)?this.handleLoginOnSocketOpen():$e(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0}))}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class en extends Zi{constructor(e){super(e),Te.info(`SDK version: ${Ut}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return yi()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:bi.full},{browserName:"Firefox",features:["audio"],supported:bi.partial},{browserName:"Safari",supported:bi.not_supported},{browserName:"Edge",supported:bi.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:bi.not_supported},{browserName:"Firefox",supported:bi.not_supported},{browserName:"Safari",features:["video","audio"],supported:bi.full},{browserName:"Edge",supported:bi.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:bi.full},{browserName:"Firefox",features:["audio"],supported:bi.partial},{browserName:"Safari",supported:bi.not_supported},{browserName:"Edge",supported:bi.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:bi.full},{browserName:"Firefox",features:["audio"],supported:bi.partial},{browserName:"Safari",features:["video","audio"],supported:bi.full},{browserName:"Edge",features:["audio"],supported:bi.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:bi.full},{browserName:"Firefox",features:["audio"],supported:bi.partial},{browserName:"Safari",supported:bi.not_supported},{browserName:"Edge",features:["audio"],supported:bi.partial}]}]}}class tn{static run(e){return t(this,void 0,void 0,(function*(){const t=Be({}),i=Be({}),n=new en(e.credentials);yield n.connect(),n.on(ue.Ready,t.resolve),n.on(ue.Error,t.reject),n.on(ue.MediaError,t.reject),n.on(ue.MediaError,t.reject),n.on(ue.Notification,(e=>{e.call&&e.call.sipCode>=400&&i.reject(new Error(e.call.sipReason))})),yt(ue.StatsReport,(e=>{i.resolve(tn.mapReport(e))})),yield t.promise,yield n.newCall({destinationNumber:e.texMLApplicationNumber,debug:!0});const s=yield i.promise;return yield n.disconnect(),s}))}static mapReport(e){var t,i,n,s,o,r,a,c,l,d,u,h,p;const g=[],v=[];for(const t of e)switch(t.event){case"onicecandidate":t.data&&g.push(t.data);break;case"stats":v.push(t.data)}let m=0,f=1/0,_=-1/0,y=0,b=1/0,S=-1/0,I=0;v.forEach((e=>{var t,i,n;if(!(null===(t=e.remote.audio.inbound)||void 0===t?void 0:t[0]))return;m+=1;const s=null!==(i=e.remote.audio.inbound[0].jitter)&&void 0!==i?i:0,o=null!==(n=e.remote.audio.inbound[0].roundTripTime)&&void 0!==n?n:0;y+=s,I+=o,_=Math.max(_,s),f=Math.min(f,s),S=Math.max(S,o),b=Math.min(b,o)}));const C=I/m,E=y/m,k=v[v.length-1],w=Li({jitter:1e3*E,rtt:1e3*C,packetsReceived:null!==(n=null===(i=null===(t=k.audio.inbound)||void 0===t?void 0:t[0])||void 0===i?void 0:i.packetsReceived)&&void 0!==n?n:0,packetsLost:null!==(r=null===(o=null===(s=k.audio.inbound)||void 0===s?void 0:s[0])||void 0===o?void 0:o.packetsLost)&&void 0!==r?r:0});return{iceCandidatePairStats:v[v.length-1].connection,summaryStats:{mos:w,jitter:{average:E,max:_,min:f},rtt:{average:C,max:S,min:b},quality:Mi(w)},sessionStats:{packetsSent:null!==(a=k.connection.packetsSent)&&void 0!==a?a:0,bytesSent:null!==(c=k.connection.bytesSent)&&void 0!==c?c:0,bytesReceived:null!==(l=k.connection.bytesReceived)&&void 0!==l?l:0,packetsLost:null!==(h=null===(u=null===(d=k.remote.audio.inbound)||void 0===d?void 0:d[0])||void 0===u?void 0:u.packetsLost)&&void 0!==h?h:0,packetsReceived:null!==(p=k.connection.packetsReceived)&&void 0!==p?p:0},iceCandidateStats:g}}getTelnyxIds(){return{telnyxCallControlId:"",telnyxSessionId:"",telnyxLegId:""}}}function nn(e){if(!e||"object"!=typeof e)return!1;if("conversation.item.created"!==e.type)return!1;const t=e.item;if("object"!=typeof t||null===t)return!1;const i=t;return"function_call"===i.type&&"string"==typeof i.call_id&&"string"==typeof i.name&&"string"==typeof i.arguments}function sn(e){if(!e||"object"!=typeof e)return!1;if("conversation.item.create"!==e.type)return!1;const t=e.item;if("object"!=typeof t||null===t)return!1;const i=t;return"function_call_output"===i.type&&"string"==typeof i.call_id&&"string"==typeof i.output}export{Ji as Call,ot as ERROR_TYPE,st as NOTIFICATION_TYPE,tn as PreCallDiagnosis,he as SDK_ERRORS,pe as SDK_WARNINGS,ue as SwEvent,c as TELNYX_ERROR_CODES,l as TELNYX_WARNING_CODES,ve as TelnyxError,en as TelnyxRTC,sn as isFunctionCallOutputParams,nn as isFunctionCallParams,me as isMediaRecoveryErrorEvent};