@telnyx/webrtc 2.27.0-beta.2 → 2.27.0-beta.3

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,UNEXPECTED_ERROR:49001},d={HIGH_RTT:31001,HIGH_JITTER:31002,HIGH_PACKET_LOSS:31003,LOW_MOS:31004,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,DUPLICATE_INBOUND_ANSWER:33007,TOKEN_EXPIRING_SOON:34001,SESSION_NOT_REATTACHED:35001},{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:f,MEDIA_GET_USER_MEDIA_FAILED:m,HOLD_FAILED:_,INVALID_CALL_PARAMETERS:y,BYE_SEND_FAILED:b,SUBSCRIBE_FAILED:S,PEER_CLOSED_DURING_INIT:C,WEBSOCKET_CONNECTION_FAILED:I,WEBSOCKET_ERROR:E,RECONNECTION_EXHAUSTED:w,GATEWAY_FAILED:k,LOGIN_FAILED:T,INVALID_CREDENTIALS:R,AUTHENTICATION_REQUIRED:O,ICE_RESTART_FAILED:A,NETWORK_OFFLINE:N,UNEXPECTED_ERROR:D}=c,{HIGH_RTT:L,HIGH_JITTER:P,HIGH_PACKET_LOSS:x,LOW_MOS:M,LOW_BYTES_RECEIVED:U,LOW_BYTES_SENT:F,ICE_CONNECTIVITY_LOST:j,ICE_GATHERING_TIMEOUT:H,ICE_GATHERING_EMPTY:B,PEER_CONNECTION_FAILED:$,ONLY_HOST_ICE_CANDIDATES:W,ANSWER_WHILE_PEER_ACTIVE:G,DUPLICATE_INBOUND_ANSWER:V,TOKEN_EXPIRING_SOON:q,SESSION_NOT_REATTACHED:K}=d,Y=/^a=candidate:.+typ (srflx|prflx|relay)/m,J="wss://rtc.telnyx.com",X=1006,Q={urls:"stun:stun.l.google.com:19302"},z=[{urls:"stun:stun.telnyx.com:3478"},Q,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],Z=[{urls:"stun:stundev.telnyx.com:3478"},Q,{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 ee;!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.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"}(ee||(ee={}));const te={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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},45004:{name:"GATEWAY_FAILED",message:"Gateway connection failed",description:"The upstream gateway reported a FAILED or FAIL_WAIT 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"]},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"]},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)"]},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"]},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"]},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"]},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"]}},ie={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"]},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"]},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"]},35001:{name:"SESSION_NOT_REATTACHED",message:"Active call lost after reconnect",description:"The WebSocket reconnected successfully but the server returned an empty reattached_sessions list while the SDK still has an active call. The server no longer knows about the call, so any subsequent call-control operation (hangup, hold, etc.) will fail with CALL_DOES_NOT_EXIST.",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"]}};function ne(e,t){const i=ie[e];return{code:e,name:i.name,message:t||i.message,description:i.description,causes:[...i.causes],solutions:[...i.solutions]}}class se 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,Object.setPrototypeOf(this,se.prototype)}toJSON(){return{code:this.code,name:this.name,description:this.description,message:this.message,causes:this.causes,solutions:this.solutions,originalError:this.originalError}}}function oe(e){return!0===e.recoverable}function re(e){if(e instanceof DOMException){if("NotAllowedError"===e.name)return v;if("NotFoundError"===e.name||"OverconstrainedError"===e.name)return f}return m}function ae(e,t,i){const n=te[e],s=t instanceof Error?t:void 0!==t?new Error(String(t)):void 0;return new se({code:e,name:n.name,description:n.description,message:i||n.message,causes:[...n.causes],solutions:[...n.solutions],originalError:s})}var ce="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function de(e,t){return e(t={exports:{}},t.exports),t.exports}var le=de((function(e){var t,i;t=ce,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 ue={debug:0,info:1,warn:2,error:3};class he{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(ue[e]<ue[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 pe=null;const ge=le.getLogger("telnyx"),ve={trace:0,debug:1,info:2,warn:3,error:4};let fe=ve.info;function me(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 _e=ge.methodFactory;ge.methodFactory=(e,t,i)=>{const n=_e(e,t,i);return function(...t){if(ve[e]>=fe){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(const i of t)e.push(i);n(...e)}const i=pe;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]?me(s[0]):{args:s.map(me)}),i.addEntry(e,o,r)}}},ge.setLevel("debug",!1);const ye=e=>{const[t,i,n,s,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){ge.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},be=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},Se=e=>e instanceof Function||"function"==typeof e,Ce=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,Ie=/^(ws|wss):\/\//,Ee=(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?Ee(a,r):{result:s}},we=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),ke=({login:e,passwd:t,password:i,login_token:n})=>Boolean(e&&(t||i)||n),Te=({anonymous_login:e})=>Boolean(e)&&Boolean(e.target_id)&&Boolean(e.target_type),Re=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 Oe({debounceTime:e}){let t,i;return{promise:new Promise(((n,s)=>{t=e?Ae(n,e):n,i=s})),resolve:t,reject:i}}const Ae=(e,t)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout((()=>{e(...n)}),t)}},Ne="telnyx-voice-sdk-id";function De(){return sessionStorage.getItem(Ne)}function Le(){sessionStorage.removeItem(Ne)}var Pe,xe,Me;"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{Le()})),function(e){e.Offer="offer",e.Answer="answer"}(Pe||(Pe={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(xe||(xe={})),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"}(Me||(Me={}));const Ue={generic:"event",[Me.Display]:"participantData",[Me.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},Fe={invalidCredentialsOptions:"InvalidCredentialsOptions"},je={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 He,Be,$e,We,Ge,Ve;!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"}(He||(He={})),function(e){e.Participant="participant",e.Moderator="moderator"}(Be||(Be={})),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"}($e||($e={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(We||(We={})),function(e){e.REGED="REGED",e.UNREGED="UNREGED",e.NOREG="NOREG",e.FAILED="FAILED",e.FAIL_WAIT="FAIL_WAIT",e.REGISTER="REGISTER",e.TRYING="TRYING",e.EXPIRED="EXPIRED",e.UNREGISTER="UNREGISTER"}(Ge||(Ge={})),function(e){e.Hold="hold",e.Unhold="unhold",e.ToggleHold="toggleHold",e.UpdateMedia="updateMedia"}(Ve||(Ve={}));const qe="GLOBAL",Ke={},Ye=(e,t)=>`${e}|${t}`,Je=(e,t=qe)=>Ye(e,t)in Ke,Xe=(e,t,i=qe)=>{const n=Ye(e,i);n in Ke||(Ke[n]=[]),Ke[n].push(t)},Qe=(e,t,i=qe)=>{const n=function(s){ze(e,n,i),t(s)};return n.prototype.targetRef=t,Xe(e,n,i)},ze=(e,t,i=qe)=>{if(!Je(e,i))return!1;const n=Ye(e,i);if(Se(t)){for(let e=Ke[n].length-1;e>=0;e--){const i=Ke[n][e];(t===i||i.prototype&&t===i.prototype.targetRef)&&Ke[n].splice(e,1)}}else Ke[n]=[];return 0===Ke[n].length&&delete Ke[n],!0},Ze=(e,t,i=qe,n=!0)=>{const s=n&&i!==qe;if(!Je(e,i))return s&&Ze(e,t),!1;const o=Ye(e,i),r=Ke[o].length;if(!r)return s&&Ze(e,t),!1;for(let e=r-1;e>=0;e--)Ke[o][e](t);return s&&Ze(e,t),!0},et=e=>{const t=Ye(e,"");Object.keys(Ke).filter((e=>0===e.indexOf(t))).forEach((e=>delete Ke[e]))};let tt="undefined"!=typeof WebSocket?WebSocket:null;const it=0,nt=1,st=2,ot=3;class rt{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=J,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this._safetyTimeoutId=null,this.upDur=null,this.downDur=null;const{host:t,env:i,region:n,useCanaryRtcServer:s}=e.options;i&&(this._host="development"===i?"wss://rtcdev.telnyx.com":J),t&&(this._host=(e=>`${Ie.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===nt}get connecting(){return!!this._wsClient&&this._wsClient.readyState===it}get closing(){return!!this._wsClient&&this._wsClient.readyState===st}get closed(){return!!this._wsClient&&this._wsClient.readyState===ot}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){const e=new URL(this._host);let t=De();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"),ge.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this.session.options.skipLastVoiceSdkId&&e.searchParams.has("voice_sdk_id")&&e.searchParams.set("skip_last_voice_sdk_id","true");try{this._wsClient=new tt(e.toString()),this._registerSocketEvents(this._wsClient)}catch(e){ge.error("WebSocket connection failed:",e);const t=ae(I,e);Ze(ee.Error,{error:t,sessionId:this.session.sessionid},this.session.uuid)}}sendRawText(e){var t;null===(t=this._wsClient)||void 0===t||t.send(e)}send(e){var t;const{request:i}=e,n=new Promise(((e,t)=>{if(i.hasOwnProperty("result"))return e();Qe(i.id,(i=>{const{result:n,error:s}=Ee(i);return s?t(s):e(n)}))}));return ge.debug("SEND: \n",JSON.stringify(i,null,2),"\n"),null===(t=this._wsClient)||void 0===t||t.send(JSON.stringify(i)),n}close(){if(!this._wsClient||this.closing)return;const e=this._wsClient;Se(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout((()=>this._handleCloseTimeout(e)),5e3))}_registerSocketEvents(e){e.onopen=e=>Ze(ee.SocketOpen,e,this.session.uuid),e.onclose=t=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),Ze(ee.SocketClose,t,this.session.uuid)),e.onerror=t=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error");const i=ae(E);return Ze(ee.Error,{error:i,sessionId:this.session.sessionid},this.session.uuid),Ze(ee.SocketError,{error:t,sessionId:this.session.sessionid},this.session.uuid)},e.onmessage=e=>{var t,i;const n=be(e.data);var s;if("string"!=typeof n){if(n.voice_sdk_id&&(s=n.voice_sdk_id,sessionStorage.setItem(Ne,s)),this._unsetTimer(n.id),ge.debug("RECV: \n",JSON.stringify(n,null,2),"\n"),Ge[`${null===(i=null===(t=null==n?void 0:n.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state}`]||!Ze(n.id,n)){const e=Re(n);Ze(ee.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!==ot?(ge.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e||Ze(ee.SocketClose,{code:X,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1},this.session.uuid)):ge.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(ge.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,t){this._wsClient===e?(ge.debug(`Nulling socket reference (reason: ${t})`),this._wsClient=null):ge.debug(`Skipping socket cleanup - old socket already replaced (reason: ${t})`)}_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)),Ze(ee.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else ge.warn("Unknown message from socket",e)}}class at{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:a()},e)}}const ct={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 dt extends at{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 ct)e&&i.hasOwnProperty(e)&&(i[ct[e]]=i[e],delete i[e]);t.dialogParams=i}this.buildRequest({method:this.toString(),params:t})}}class lt extends dt{constructor(e){super(),this.method=Me.GatewayState;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class ut{constructor(e){this.pendingRequestId=null,this.onSocketMessage=e=>t(this,void 0,void 0,(function*(){e.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Re(e))})),this.getIsRegistered=()=>t(this,void 0,void 0,(function*(){const e=new lt(De());this.pendingRequestId=e.request.id,this.gatewayStateTask=Oe({}),this.session.execute(e);const t=yield this.gatewayStateTask.promise;return!!t&&[Ge.REGISTER,Ge.REGED].includes(t)})),this.session=e,this.gatewayStateTask=Oe({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class ht extends dt{constructor(e){super(),this.method=Me.Ping;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}var pt="2.27.0-beta.2",gt=pt;class vt extends dt{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:gt,data:navigator.userAgent}};n&&(r.sessid=n),this.buildRequest({method:this.method,params:r})}}class ft extends dt{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class mt extends dt{toString(){return Me.Invite}}class _t extends dt{toString(){return Me.Answer}}class yt extends dt{toString(){return Me.Attach}}class bt extends dt{toString(){return Me.Bye}}class St extends dt{toString(){return Me.Candidate}}class Ct extends dt{toString(){return Me.EndOfCandidates}}class It extends dt{toString(){return Me.Modify}}class Et extends dt{toString(){return Me.Info}}class wt extends dt{toString(){return Me.Broadcast}}class kt extends dt{toString(){return Me.Subscribe}}class Tt extends dt{toString(){return Me.Unsubscribe}}class Rt extends dt{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:gt,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 Ot{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.dc=null,this.region=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._tokenExpiryTimeout=null,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var t,i;t=e.debug?"debug":"info",fe=null!==(i=ve[t])&&void 0!==i?i:ve.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._attachListeners(),this.connection=new rt(this),this.registerAgent=new ut(this)}get __logger(){return ge}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return t(this,void 0,void 0,(function*(){return this.registerAgent.getIsRegistered()}))}get reconnectDelay(){return 1e3*we(2,6)}execute(e){return this._idle?new Promise((t=>this._executeQueue.push({resolve:t,msg:e}))):this.connected?this.connection.send(e).catch((e=>t(this,void 0,void 0,(function*(){if((null==e?void 0:e.code)===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const t=ae(O,e);Ze(ee.Error,{error:t,sessionId:this.sessionid},this.uuid)}yield this.login()}throw e})))):new Promise((t=>{this._executeQueue.push({resolve:t,msg:e}),ge.debug("Calling connect from execute since not currently connected."),this.connect()}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return ke(this.options)||Te(this.options)}broadcast(e){}disconnect(){return t(this,void 0,void 0,(function*(){clearTimeout(this._reconnectTimeout),this._clearTokenExpiryTimeout(),this.subscriptions={},this._autoReconnect=!1,this.relayProtocol=null,this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),ge.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")}))}on(e,t){return Xe(e,t,this.uuid),this}off(e,t){return ze(e,t,this.uuid),this}connect(){return t(this,void 0,void 0,(function*(){this.connection||(ge.debug("No existing connection found, creating a new one."),this.connection=new rt(this)),this._attachListeners(),this._autoReconnect=!0,this.connection.isAlive||(ge.debug("Initiating connection to the server..."),this.connection.connect()),ge.debug("Connect method called. Connection initiated.")}))}_handleLoginError(e){const t=ae(T,e);Ze(ee.Error,{error:t,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){Le()}_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<=Ot.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const e=1e3*(n-Ot.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout((()=>{this._emitTokenExpiryWarning()}),e)}}catch(e){ge.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=ne(q);Ze(ee.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)),ke(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(Te(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const e="Invalid login options provided for authentication.";ge.error(e);const t=ae(R,void 0,e);return void Ze(ee.Error,{error:t,type:Fe.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}}))}_login({type:e,onSuccess:i,onError:n}){return t(this,void 0,void 0,(function*(){let t;t="login"===e?new vt(this.options.login,this.options.password||this.options.passwd,this.options.login_token,this.sessionid,this.options.userVariables,!!De()):new Rt({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:this.sessionid,userVariables:this.options.userVariables,reconnection:!!De()});const s=yield this.execute(t).catch((e=>{this._handleLoginError(e),n&&n(e)}));s&&(this.sessionid=s.sessid,this._checkTokenExpiry(),i&&i())}))}_onSocketOpen(){return t(this,void 0,void 0,(function*(){}))}onNetworkClose(){this.relayProtocol&&et(this.relayProtocol);for(const e in this.subscriptions)et(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect&&(this._reconnectTimeout=setTimeout((()=>{ge.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()}),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,t){this._existsSubscription(e,t)&&(t?(delete this.subscriptions[e][t],ze(e,null,t)):(delete this.subscriptions[e],et(e)))}_addSubscription(e,t=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},Se(t)&&Xe(e,t,i))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(ee.SocketOpen,this._onSocketOpen),this.on(ee.SocketClose,this.onNetworkClose),this.on(ee.SocketError,this.onNetworkClose),this.on(ee.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(ee.SocketOpen,this._onSocketOpen),this.off(ee.SocketClose,this.onNetworkClose),this.off(ee.SocketError,this.onNetworkClose),this.off(ee.SocketMessage,this._onSocketMessage)}_emptyExecuteQueues(){this._executeQueue.forEach((({resolve:e,msg:t})=>{"string"==typeof t?this.executeRaw(t):e(this.execute(t))}))}_closeConnection(){this._idle=!0,clearTimeout(this._keepAliveTimeout),this.connection&&this.connection.close()}_resetKeepAlive(){!1===this._pong&&(ge.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new ht(De()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout((()=>this._resetKeepAlive()),35e3)}setPingReceived(){ge.debug("Ping received"),this._pong=!0}static on(e,t){Xe(e,t)}static off(e){ze(e)}static uuid(){return a()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}Ot.TOKEN_EXPIRY_WARNING_SECONDS=120;const At=e=>navigator.mediaDevices.getUserMedia(e),Nt=e=>e&&e instanceof MediaStream,Dt=(e,t)=>{const i=Ce(e);null!==i&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=t)},Lt=(e,i)=>t(void 0,void 0,void 0,(function*(){const t=Ce(e);if(null===t)return ge.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof i)return ge.info(`Invalid speaker deviceId: '${i}'`),!1;try{return yield t.setSinkId(i),!0}catch(e){return!1}})),Pt=e=>{e&&"live"===e.readyState&&e.stop()},xt=e=>{Nt(e)&&e.getTracks().forEach(Pt),e=null},Mt=i=>t(void 0,void 0,void 0,(function*(){ge.info("RTCService.getUserMedia",i);const{audio:t,video:n}=i;if(!t&&!n)return null;try{return yield At(i)}catch(t){if(ge.error("getUserMedia error: ",t),(e=>"NotReadableError"===e.name||"NotFoundError"===e.name||"OverconstrainedError"===e.name)(t)){const n=(t=>{const{audio:i,video:n}=t;let s=!1,o=i,r=n;if("object"==typeof i&&null!==i&&"deviceId"in i){s=!0;const t=e(i,["deviceId"]);o=0===Object.keys(t).length||t}if("object"==typeof n&&null!==n&&"deviceId"in n){s=!0;const t=e(n,["deviceId"]);r=0===Object.keys(t).length||t}return s?{audio:o,video:r}:null})(i);if(n){ge.warn("Device not found or not readable, falling back to default device");try{return yield At(n)}catch(e){throw ge.error("Fallback getUserMedia also failed: ",e),t}}}throw t}})),Ut=(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===We.AudioIn||e===We.AudioOut,video:!e||e===We.Video}))(e)).catch((e=>(ge.error(e),null)));if(n){if(xt(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})),Ft=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],jt=(e,i,n)=>t(void 0,void 0,void 0,(function*(){const t=yield Ut(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})),Ht=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((i=>{t.hasOwnProperty(i)&&null!==e[i]&&void 0!==e[i]||delete e[i]}))},Bt=(e,t)=>{if(!e)return!1;const{subscribed:i,alreadySubscribed:n}=$t(e);return i.includes(t)||n.includes(t)},$t=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((i=>{t[i]=e[`${i}Channels`]||[]})),t},Wt=(e,t=null,i=null)=>{if(!Nt(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}}))},Gt=e=>{Wt(e,"audio",!0)},Vt=e=>{Wt(e,"audio",!1)},qt=e=>{Wt(e,"audio",null)},Kt=e=>((e,t=null)=>{if(!Nt(e))return null;let i=[];switch(t){case"audio":i=e.getAudioTracks();break;case"video":i=e.getVideoTracks();break;default:i=e.getTracks()}return i.some((e=>e.enabled))})(e,"audio");function Yt(){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:!!Mt}}catch(e){return e.message}}var Jt;function Xt(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 Qt(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then((()=>{e._playFulfilled=!0})).catch((t=>{ge.error("playAudio",t),e._playFulfilled=!0})))}function zt(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"}(Jt||(Jt={}));const Zt=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 ei extends at{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 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.previousCandidatePairId=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._lastLocalAudioTrackSnapshotJson=null,this._segmentIndex=0,this._flushing=!1,this.options=e,this.logCollectorOptions=t||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this.logCollectorOptions.enabled&&(this.logCollector=function(e){return new he(e)}(this.logCollectorOptions),this.logCollector.start(),i=this.logCollector,pe=i)}start(e){var t,i;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,ge.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,logCollectorActive:null!==(i=null===(t=this.logCollector)||void 0===t?void 0:t.isActive())&&void 0!==i&&i}),this.intervalId=setInterval((()=>{this._collectStats()}),this.options.interval))}stop(){var e,i;return t(this,void 0,void 0,(function*(){this.intervalId&&(clearInterval(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(),ge.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:t,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})}))}flush(e){var t,i;if(this._flushing||0===this.statsBuffer.length)return null;this._flushing=!0;try{const n=this._segmentIndex++,s=this.statsBuffer;this.statsBuffer=[];const o=null!==(i=null===(t=this.logCollector)||void 0===t?void 0:t.drain())&&void 0!==i?i:[],r=new Date,a=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(r.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:r.toISOString()}),stats:s},o.length>0?{logs:o}:{}),{segment:n});return ge.info("CallReportCollector: Flushed intermediate segment",{segment:n,intervals:s.length,logEntries:o.length,callId:e.callId}),a}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 ge.info("CallReportCollector: Skipping report — call reports disabled");if(0===this.statsBuffer.length&&!a)return void ge.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)}))}sendPayload(e,i,n,s){return t(this,void 0,void 0,(function*(){yield this._sendPayload(e,i,n,s)}))}_sendPayload(e,i,n,s){var o,r;return t(this,void 0,void 0,(function*(){try{const t=new URL(n),a=`${t.protocol.replace(/^ws/,"http")}//${t.host}/call_report`,c=void 0!==e.segment&&!e.summary.endTimestamp?`intermediate segment ${e.segment}`:"final report";ge.info(`CallReportCollector: Posting ${c}`,{endpoint:a,intervals:e.stats.length,logEntries:null!==(r=null===(o=e.logs)||void 0===o?void 0:o.length)&&void 0!==r?r:0,callId:e.summary.callId,segment:e.segment});const d={"Content-Type":"application/json","x-call-report-id":i,"x-call-id":e.summary.callId};s&&(d["x-voice-sdk-id"]=s);const l=JSON.stringify(e),u=()=>fetch(a,{method:"POST",headers:d,body:l}),h=yield u();if(h.ok)ge.info(`CallReportCollector: Successfully posted ${c}`);else{const e=yield h.text();ge.error(`CallReportCollector: Failed to post ${c}`,{status:h.status,error:e})}}catch(t){ge.warn(`CallReportCollector: Network error posting call report, retrying in ${ti.RETRY_DELAY_MS}ms`,{error:t}),yield new Promise((e=>setTimeout(e,ti.RETRY_DELAY_MS)));try{const t=new URL(n),o=`${t.protocol.replace(/^ws/,"http")}//${t.host}/call_report`,r={"Content-Type":"application/json","x-call-report-id":i,"x-call-id":e.summary.callId};s&&(r["x-voice-sdk-id"]=s);const a=yield fetch(o,{method:"POST",headers:r,body:JSON.stringify(e)});if(a.ok)ge.info("CallReportCollector: Successfully posted call report on retry");else{const e=yield a.text();ge.error("CallReportCollector: Failed to post call report on retry",{status:a.status,error:e})}}catch(e){ge.error("CallReportCollector: Retry also failed, giving up",{error:e})}}}))}getStatsBuffer(){return this.statsBuffer}getLogs(){var e,t;return null!==(t=null===(e=this.logCollector)||void 0===e?void 0:e.getLogs())&&void 0!==t?t:[]}cleanup(){this._lastLocalAudioTrackSnapshotJson=null,this.logCollector&&(this.logCollector.clear(),this.logCollector=null)}_collectStats(e=!1){var i,n,s;return t(this,void 0,void 0,(function*(){if(this.peerConnection&&this.intervalStartTime)try{const t=yield this.peerConnection.getStats(),o=new Date;let r,a,c,d,l=null,u=null,h=null,p=null;if(t.forEach((e=>{switch(e.type){case"outbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(l=e);break;case"inbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(u=e);break;case"candidate-pair":(e.nominated||"succeeded"===e.state)&&(h=e);break;case"transport":p=e}})),l){const e=this._getOutboundAudioLevel(t,l);if(null!==e&&this.intervalAudioLevels.outbound.push(e),void 0!==this.previousStats.outboundBytes&&void 0!==this.previousStats.timestamp){const e=(l.bytesSent||0)-this.previousStats.outboundBytes,t=(l.timestamp||o.getTime())-this.previousStats.timestamp;if(t>0){const i=8*e*1e3/t;this.intervalBitrates.outbound.push(i)}}this.previousStats.outboundBytes=l.bytesSent}if(u){const e=this._getInboundAudioLevel(t,u);if(null!==e&&this.intervalAudioLevels.inbound.push(e),void 0!==u.jitter&&this.intervalJitters.push(1e3*u.jitter),void 0!==this.previousStats.inboundBytes&&void 0!==this.previousStats.timestamp){const e=(u.bytesReceived||0)-this.previousStats.inboundBytes,t=(u.timestamp||o.getTime())-this.previousStats.timestamp;if(t>0){const i=8*e*1e3/t;this.intervalBitrates.inbound.push(i)}}this.previousStats.inboundBytes=u.bytesReceived}h&&(void 0!==h.currentRoundTripTime&&this.intervalRTTs.push(h.currentRoundTripTime),null!==this.previousCandidatePairId&&h.id!==this.previousCandidatePairId&&ge.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairId,current:h.id}),this.previousCandidatePairId=null!==(i=h.id)&&void 0!==i?i:null),h&&(r=this._resolveCandidate(t,h.localCandidateId),a=this._resolveCandidate(t,h.remoteCandidateId)),l&&(c=this._getLocalAudioTrackSnapshot(),d=this._getOutboundAudioSourceStats(t,l)),this._logLocalAudioTrackSnapshot(c,d),this.previousStats.timestamp=o.getTime();const g=o.getTime()-this.intervalStartTime.getTime();if(e||g>=this.options.interval){const e=this._createStatsEntry(this.intervalStartTime,o,l,u,h,r,a,p,c,d);if(this.statsBuffer.push(e),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),ge.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this.onFlushNeeded&&!this._flushing){const e=this.statsBuffer.length,t=null!==(s=null===(n=this.logCollector)||void 0===n?void 0:n.getLogCount())&&void 0!==s?s:0;if(e>=ti.STATS_FLUSH_THRESHOLD||t>=ti.LOGS_FLUSH_THRESHOLD){ge.info("CallReportCollector: Approaching buffer limits, requesting flush",{statsIntervals:e,logEntries:t});try{this.onFlushNeeded()}catch(e){ge.error("CallReportCollector: onFlushNeeded callback error",{error:e})}}}this._checkQualityWarnings(e,u),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(e){ge.error("CallReportCollector: Error collecting stats",{error:e})}}))}_checkQualityWarnings(e,t){var i,n,s,o,r,a,c,d,l,u,h,p,g,v,f,m,_;if(!this.onWarning)return;const y=null===(i=e.connection)||void 0===i?void 0:i.roundTripTimeAvg,b=null===(s=null===(n=e.audio)||void 0===n?void 0:n.inbound)||void 0===s?void 0:s.jitterAvg;let S;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&&(S=n/s*100)}this._prevPacketsReceived=e,this._prevPacketsLost=i}if(this._trackBreach(L,void 0!==y&&y>ti.THRESHOLD_RTT_MS),this._trackBreach(P,void 0!==b&&b>ti.THRESHOLD_JITTER_MS),this._trackBreach(x,void 0!==S&&S>ti.THRESHOLD_PACKET_LOSS_PCT),void 0!==y&&void 0!==b&&void 0!==S){const e=93.2-.11*b-2.5*S-.01*(1e3*y),t=Math.max(1,Math.min(4.5,1+.035*e+e*(e-60)*(100-e)*7e-6));this._trackBreach(M,t<ti.THRESHOLD_MOS)}else this._trackBreach(M,!1);if(void 0!==(null===(c=null===(a=e.audio)||void 0===a?void 0:a.inbound)||void 0===c?void 0:c.bytesReceived)&&this.statsBuffer.length>1){const t=this.statsBuffer[this.statsBuffer.length-2],i=null!==(u=null===(l=null===(d=null==t?void 0:t.audio)||void 0===d?void 0:d.inbound)||void 0===l?void 0:l.bytesReceived)&&void 0!==u?u:0,n=null!==(h=e.audio.inbound.bytesReceived)&&void 0!==h?h:0;this._trackBreach(U,n-i==0)}if(void 0!==(null===(g=null===(p=e.audio)||void 0===p?void 0:p.outbound)||void 0===g?void 0:g.bytesSent)&&this.statsBuffer.length>1){const t=this.statsBuffer[this.statsBuffer.length-2],i=null!==(m=null===(f=null===(v=null==t?void 0:t.audio)||void 0===v?void 0:v.outbound)||void 0===f?void 0:f.bytesSent)&&void 0!==m?m:0,n=null!==(_=e.audio.outbound.bytesSent)&&void 0!==_?_:0;this._trackBreach(F,n-i==0)}}_trackBreach(e,t){var i,n,s;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();if(t-(null!==(n=this._lastWarningEmitted[e])&&void 0!==n?n:0)>=ti.WARNING_THROTTLE_MS){this._lastWarningEmitted[e]=t;try{const t=ne(e);ge.warn(`CallReportCollector: warning ${t.code}: ${t.message}`),null===(s=this.onWarning)||void 0===s||s.call(this,t)}catch(t){ge.error(`CallReportCollector: Failed to emit warning ${e}`,{error:t})}}}}else this._breachCounters[e]=0,this._activeWarnings.delete(e),delete this._lastWarningEmitted[e]}_createStatsEntry(e,t,i,n,s,o,r,a,c,d){const l={intervalStartUtc:e.toISOString(),intervalEndUtc:t.toISOString(),audio:{}};return i&&(l.audio.outbound=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}:{})),n&&(l.audio.inbound={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)}),s&&(l.connection={roundTripTimeAvg:this._average(this.intervalRTTs),packetsSent:s.packetsSent,packetsReceived:s.packetsReceived,bytesSent:s.bytesSent,bytesReceived:s.bytesReceived},l.ice=Object.assign(Object.assign({id:s.id,state:s.state,nominated:s.nominated,writable:s.writable,requestsSent:s.requestsSent,responsesReceived:s.responsesReceived},o?{local:o}:{}),r?{remote:r}:{})),a&&(l.transport=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}:{})),l}_resolveCandidate(e,t){if(!t)return void ge.debug("CallReportCollector: candidateId is empty, skipping resolve");const i=e.get(t);if(!i)return void ge.debug("CallReportCollector: candidate not found in stats report",{candidateId:t});const n={};if(void 0!==i.address&&(n.address=i.address),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),0!==Object.keys(n).length)return n;ge.debug("CallReportCollector: candidate report has no usable fields",{candidateId:t})}_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 ge.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,ge.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:[]}}}ti.STATS_FLUSH_THRESHOLD=300,ti.LOGS_FLUSH_THRESHOLD=800,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.WARNING_THROTTLE_MS=15e3,ti.RETRY_DELAY_MS=500;var ii,ni=de((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 f(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 m(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 f(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 C,I={},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=m()),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&&C&&(navigator.mediaDevices.getUserMedia=C)}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."),C=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const e=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=function(){return e({constraints:arguments[0]}),C.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}.`),I[t]={},Object.keys(this.peerConnectionListeners).forEach((n=>{I[t][n]=this.peerConnectionListeners[n].bind(this,e,t,i),i.addEventListener(n,I[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){I[e.id]={};const i=this.getTrackEventObject(t);Object.keys(i).forEach((t=>{I[e.id][t]=i[t].bind(this),e.addEventListener(t,I[e.id][t])})),I[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 I){const t=this.getTrackEventObject();Object.keys(t).forEach((t=>{e.removeEventListener(t,I[e.id][t])})),clearInterval(I[e.id].readyState),delete I[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 I&&(Object.keys(this.peerConnectionListeners).forEach((i=>{t.removeEventListener(i,I[e][i],!1)})),delete I[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)}}}}));(ii=ni)&&ii.__esModule&&Object.prototype.hasOwnProperty.call(ii,"default")&&ii.default;var si=ni.WebRTCStats;function oi(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 ri(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 ai extends at{constructor(e,t){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:t})}}class ci extends at{constructor(e,t){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:t})}}class di extends at{constructor(e,t){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:t})}}function li(e,i){const n=a();let s=!1;const o=new si({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),r=i=>t(this,void 0,void 0,(function*(){"stats"===i.event&&Ze(ee.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,f=oi({jitter:1e3*h,rtt:1e3*p,packetsLost:v,packetsReceived:g});return{jitter:h,rtt:p,mos:f,quality:ri(f),inboundAudio:d.inbound[0],outboundAudio:d.outbound[0],remoteInboundAudio:u.inbound[0],remoteOutboundAudio:u.outbound[0]}}(i),e.uuid),yield e.execute(new di(n,i))}));return{get isRunning(){return s},start:(a,c,d)=>t(this,void 0,void 0,(function*(){if(s)ge.debug(`[${i}] Stats reporter already running, skipping start`);else{yield e.execute(new ai(n,i)),o.on("timeline",r);try{yield o.addConnection({pc:a,peerId:c,connectionId:d}),s=!0}catch(e){ge.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(Ze(ee.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 ci(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 ui=(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:Ue.conferenceUpdate,call:e.calls[s],canvasInfo:hi(o),currentLayerIdx:r};switch(i){case"layer-info":{const t=Object.assign({action:$e.LayerInfo},a);Ze(ee.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:$e.LayoutInfo},a);Ze(ee.Notification,t,e.uuid);break}}},hi=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return be(t)},pi=["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"],gi={"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 vi(e){try{const t=performance.getEntriesByName(e,"mark");return t.length>0?t[0].startTime:void 0}catch(e){return}}class fi{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._hadOfflineEvent=!1,this._offlineHandler=null,this.handleConnectionStateChange=()=>t(this,void 0,void 0,(function*(){const{connectionState:e}=this.instance;if(ge.info(`[${(new Date).toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${e}`),"failed"===e||"disconnected"===e){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){ge.error("Error gathering connection state details:",e)}return t}))}(this.instance,this._prevConnectionState).then((e=>{this.statsReporter.reportConnectionStateChange(e)}));const i=!this._hadOfflineEvent&&this._session.connected;this._restartedIceOnConnectionStateFailed||"failed"!==e&&"disconnected"!==e||!i||(this.isIceRestarting=!0,this._restartedIceOnConnectionStateFailed=!0,this.instance.restartIce(),this.iceDone=!1,this._iceRestartTimeoutId=setTimeout((()=>{this.isIceRestarting&&(ge.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null}),fi.ICE_RESTART_TIMEOUT_MS),ge.info(`ICE restart: peer ${e}, canRestartIceWithoutAttach=${i}. Creating new offer via Modify.`))}if("disconnected"===e){const e=ne(j);Ze(ee.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if("failed"===e){const t=ne($);Ze(ee.PeerConnectionFailureError,{warning:t,error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${e}`),sessionId:this._session.sessionid},this.options.id)}this._prevConnectionState=e,"connected"===e&&(performance.mark("dtls-connected"),this.tryCollectTimings(),this._restartedIceOnConnectionStateFailed=!1,this._hadOfflineEvent=!1),this._isTrickleIce()&&("connecting"===e&&performance.mark("peer-connection-connecting"),"connected"===e&&(this._clearIceGatheringSafetyTimeout(),performance.mark("peer-connection-connected")))})),this._handleIceConnectionStateChange=()=>{const e=this.instance.iceConnectionState;ge.debug(`[${(new Date).toISOString()}] ICE Connection State`,e),"connected"===e&&performance.mark("ice-connected")},this._handleIceGatheringStateChange=()=>{const e=this.instance.iceGatheringState;ge.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)},ge.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,"undefined"!=typeof window&&(this._offlineHandler=()=>{this._hadOfflineEvent=!0},window.addEventListener("offline",this._offlineHandler))}finishIceRestart(){this.isIceRestarting&&(this.isIceRestarting=!1,this._iceRestartTimeoutId&&(clearTimeout(this._iceRestartTimeoutId),this._iceRestartTimeoutId=null))}get isOffer(){return this.type===Pe.Offer}get isAnswer(){return this.type===Pe.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("start-negotiation"),this._negotiating=!0,this._isOffer()||this.isIceRestarting?this._createOffer():this._createAnswer()}startTrickleIceNegotiation(){return t(this,void 0,void 0,(function*(){performance.mark("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))}))}_logTransceivers(){this.instance?(ge.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach(((e,t)=>{ge.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),ge.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))):ge.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(ge.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":Ze(ee.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(ge.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){ge.info("Negotiation needed event"),"stable"!==this.instance.signalingState||this._negotiating?ge.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()&&!this.isIceRestarting?this.startTrickleIceNegotiation():this.startNegotiation()}handleTrackEvent(e){this._firstMediaTrackMarked||(performance.mark("first-remote-media-track"),this._firstMediaTrackMarked=!0);const{streams:[t]}=e,{remoteElement:i,screenShare:n}=this.options;this.options.remoteStream=t,!1===n&&Dt(i,this.options.remoteStream)}tryCollectTimings(){if(this._timingsCollected)return;if(!(performance.getEntriesByName("call-active","mark").length>0)||"connected"!==this.instance.connectionState)return;this._timingsCollected=!0;const e=function(e,t){const i=vi("new-call-start");if(void 0===i)return{mode:e,direction:t,steps:[]};const n=[];for(const e of pi){if("new-call-start"===e)continue;const t=vi(e);void 0!==t&&n.push({label:gi[e]||e,fromStart:t-i})}n.sort(((e,t)=>e.fromStart-t.fromStart));const s=[];let o=0;for(const e of n)s.push({label:e.label,fromStart:e.fromStart,delta:e.fromStart-o}),o=e.fromStart;return{mode:e,direction:t,steps:s}}(this._isTrickleIce()?"trickle":"non-trickle",this.isOffer?"outbound":"inbound");!function(e){const{mode:t,direction:i,steps:n}=e,s=`[CallTimings][${i}][${t}]`;if(0===n.length)return void ge.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+="-";ge.info(`${s} Call establishment timing breakdown:`),ge.info(`${s} ${c}`),ge.info(`${s} ${d}`),ge.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";ge.info(`${s} ${r(e.label,o)}${a(t,14)}${a(i,14)}`)}ge.info(`${s} ${d}`)}(e),function(){for(const e of pi)try{performance.clearMarks(e)}catch(e){ge.warn("Clearing performance marks is failed")}}()}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:Pe.Offer}),performance.mark("set-remote-description"),!this.instance))throw ae(C);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),Ze(ee.Error,{error:ae(re(e),e),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 ae(C);if(!this.options.localStream&&!i){throw ae(n?re(n):m,null!=n?n:void 0)}performance.mark("get-user-media"),this.options.mutedMicOnStart&&Nt(this.options.localStream)&&(ge.info("Muting local audio tracks on start"),Vt(this.options.localStream)),performance.mark("peer-creation-end")}))}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout((()=>{if(this.instance)if(0===this._gatheredCandidatesCount){const e=ne(B);Ze(ee.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if("complete"!==this.instance.iceGatheringState){const e=ne(H);Ze(ee.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}),fi.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 ae(C);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(Nt(i)){const e=i.getAudioTracks();let s=[...e];if(ge.info("Local audio tracks: ",e),"object"==typeof this.options.audio&&e.forEach((e=>{ge.info("Local audio tracks constraints: ",e.getConstraints())})),this.options.video){const t=i.getVideoTracks();s=[...e,...t],ge.info("Local video tracks: ",t),"object"==typeof this.options.video&&t.forEach((e=>{ge.info("Local video tracks constraints: ",e.getConstraints())}))}const{audioCodecs:o,videoCodecs:r}=Zt(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&&Dt(t,i)}else if(this.options.receiveOnlyAudio&&"function"==typeof this.instance.addTransceiver){const e=this.instance.addTransceiver("audio",{direction:"recvonly"});ge.info("Added recvonly audio transceiver for receive-only mode",e);const{audioCodecs:t}=Zt(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(),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);ge.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),ge.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark("create-offer"),yield this._setLocalDescription(e),performance.mark("set-local-description"),performance.mark("ice-gathering-started"),this._isTrickleIce()||this._sdpReady(),e}catch(e){ge.error("Peer _createOffer error:",e);const t=ae(l,e);Ze(ee.Error,{error:t,sessionId:this._session.sessionid},this.options.id)}}}))}_setRemoteDescription(e){return t(this,void 0,void 0,(function*(){ge.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(e){ge.error("Peer _setRemoteDescription error:",e);const t=ae(p,e);throw Ze(ee.Error,{error:t,sessionId:this._session.sessionid},this.options.id),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 ge.debug("Skipping negotiation, state:",this.instance.signalingState),ge.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:Pe.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark("create-answer"),yield this._setLocalDescription(e),performance.mark("set-local-description"),performance.mark("ice-gathering-started"),e}catch(e){ge.error("Peer _createAnswer error:",e);const t=ae(u,e);Ze(ee.Error,{error:t,sessionId:this._session.sessionid},this.options.id)}}}))}_setLocalDescription(e){return t(this,void 0,void 0,(function*(){try{yield this.instance.setLocalDescription(e)}catch(e){ge.error("Peer _setLocalDescription error:",e);const t=ae(h,e);throw Ze(ee.Error,{error:t,sessionId:this._session.sessionid},this.options.id),e}}))}_sdpReady(){Se(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return t(this,void 0,void 0,(function*(){if(Nt(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 jt(t,o,We.AudioIn).catch((e=>null)),t&&("boolean"==typeof e&&(e={}),e.deviceId={exact:t})),s&&(s=yield jt(s,r,We.Video).catch((e=>null)),s&&("boolean"==typeof n&&(n={}),n.deviceId={exact:s})),{audio:e,video:n}})));var i;return Mt(e)}))}_isOffer(){return this.type===Pe.Offer}_isAnswer(){return this.type===Pe.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 ge.info("RTC config",n),n}restartStatsReporter(){return t(this,void 0,void 0,(function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?ge.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(ge.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):ge.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))}))}close(){return t(this,void 0,void 0,(function*(){this.finishIceRestart(),this._clearIceGatheringSafetyTimeout(),this._offlineHandler&&"undefined"!=typeof window&&(window.removeEventListener("offline",this._offlineHandler),this._offlineHandler=null),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)}))}}fi.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,fi.ICE_RESTART_TIMEOUT_MS=15e3;const mi=gt;class _i{constructor(e,t){this.session=e,this._callReportCollector=null,this.id="",this.recoveredCallId="",this.state=He[He.New],this.prevState="",this.channels=[],this.role=Be.Participant,this.extension=null,this._state=He.New,this._prevState=He.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._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({},je,{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._init(),this.options&&(this._ringtone=Xt(this.options.ringtoneFile,"_ringtone"),this._ringback=Xt(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!Kt(this.options.localStream)}invite(){return t(this,void 0,void 0,(function*(){this._creatingPeer=!0,this.direction=xe.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("new-peer"),this.peer=new fi(Pe.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){ge.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const t=e instanceof se?e:ae(D,e instanceof Error?e:void 0);return Ze(ee.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;return t(this,void 0,void 0,(function*(){if(this._creatingPeer||(null===(i=this.peer)||void 0===i?void 0:i.instance)&&"closed"!==this.peer.instance.signalingState){const e=ne(G);return Ze(ee.Warning,{warning:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void ge.warn(`[${this.id}] answer() ignored: peer connection already exists or is being created (signalingState: ${null!==(o=null===(s=null===(n=this.peer)||void 0===n?void 0:n.instance)||void 0===s?void 0:s.signalingState)&&void 0!==o?o:"creating"})`)}if(this._registerInboundAnswerAttempt()){performance.mark("answer-called"),this._creatingPeer=!0,this.stopRingtone(),this.direction=xe.Inbound,(null===(r=null==e?void 0:e.customHeaders)||void 0===r?void 0:r.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("new-peer"),this.peer=new fi(Pe.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){ge.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const t=e instanceof se?e:ae(D,e instanceof Error?e:void 0);return Ze(ee.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(){Qt(this._ringtone)}stopRingtone(){zt(this._ringtone)}playRingback(){Qt(this._ringback)}stopRingback(){zt(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<He.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:[]],ge.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(He.Recovering),void this._finalize();if(this.setState(He.Hangup),this.stopRingtone(),this.stopRingback(),d){const e=new bt({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});try{yield this._execute(e)}catch(e){ge.error("telnyx_rtc.bye failed!",e);const t=ae(b,e);Ze(ee.Error,{error:t,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}ge.debug(`[${this.id}] Closing peer from hangup`),null===(c=this.peer)||void 0===c||c.close(),this.setState(He.Destroy)}))}hold(){const e=new It({sessid:this.session.sessionid,action:Ve.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new It({sessid:this.session.sessionid,action:Ve.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new It({sessid:this.session.sessionid,action:Ve.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const t=new Et({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 Et({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(n)}muteAudio(){Vt(this.options.localStream)}unmuteAudio(){Gt(this.options.localStream)}toggleAudioMute(){qt(this.options.localStream)}setAudioInDevice(e,i=this.options.mutedMicOnStart){var n;return t(this,void 0,void 0,(function*(){const{instance:t}=this.peer,s=t.getSenders().find((({track:{kind:e}})=>"audio"===e));if(s){let t;try{t=yield At({audio:{deviceId:{exact:e}}})}catch(e){const t=ae(re(e),e);return void Ze(ee.MediaError,t,(null===(n=this.options)||void 0===n?void 0:n.id)||this.id)}const o=t.getAudioTracks()[0];o.enabled=!i,s.replaceTrack(o),this.options.micId=e;const{localStream:r}=this.options;r.getAudioTracks().forEach((e=>e.stop())),r.getVideoTracks().forEach((e=>t.addTrack(e))),this.options.localStream=t}}))}muteVideo(){var e;e=this.options.localStream,Wt(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Wt(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Wt(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 At({video:{deviceId:{exact:e}}}),n=t.getVideoTracks()[0];i.replaceTrack(n);const{localElement:s,localStream:o}=this.options;Dt(s,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t}}))}deaf(){Vt(this.options.remoteStream)}undeaf(){Gt(this.options.remoteStream)}toggleDeaf(){qt(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,i){return t(this,void 0,void 0,(function*(){if(!this||!this.peer)return void ge.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 ge.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"}]),ge.info("Parameters: ",t),ge.info("Setting max ","audio"===i?"audio":"video"," bandwidth to: ",e," [bps]"),t.encodings[0].maxBitrate=e,yield s.setParameters(t).then((()=>{ge.info("audio"===i?"New audio":"New video"," bandwidth settings in use: ",s.getParameters())})).catch((e=>ge.error(e)))}else ge.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")}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=He[this._state].toLowerCase(),this.prevState=He[this._prevState].toLowerCase(),ge.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:Ue.callUpdate,call:this}),e){case He.Purge:ge.info(`[${this.id}] Entering Purge state.`);break;case He.Active:performance.mark("call-active"),null===(t=this.peer)||void 0===t||t.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,ge.debug(`[${this.id}] Recovery complete, call is active`)),setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&Lt(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);break;case He.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:i}=e;switch(t){case Me.Answer:if(performance.mark("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>=He.Active)return;this._state>=He.Early&&this.setState(He.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case Me.Media:if(performance.mark("telnyx-rtc-media"),this._state>=He.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case Me.Display:{const{display_name:e,display_number:n,display_direction:s}=i;this.extension=n;const o=s===xe.Inbound?xe.Outbound:xe.Inbound,r={type:Ue[t],call:this,displayName:e,displayNumber:n,displayDirection:o};Ze(ee.Notification,r,this.id)||Ze(ee.Notification,r,this.session.uuid);break}case Me.Candidate:this._addIceCandidate(i);break;case Me.Info:case Me.Event:{const e=Object.assign(Object.assign({},i),{type:Ue.generic,call:this});Ze(ee.Notification,e,this.id)||Ze(ee.Notification,e,this.session.uuid);break}case Me.Ringing:performance.mark("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 Me.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 ge.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:$e.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)},ye(n[e][1])));this._dispatchConferenceUpdate({action:$e.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:$e.Add,callId:s,index:o},ye(n)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:$e.Modify,callId:s,index:o},ye(n)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:$e.Delete,callId:s,index:o},ye(n)));break;case"clear":this._dispatchConferenceUpdate({action:$e.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:$e.ChatMessage,direction:t,participantNumber:i,participantName:n,messageText:s,messageType:o,messageId:e.eventSerno})}},i=yield this.session.vertoSubscribe(t).catch((e=>{ge.error("ConfChat subscription error:",e)}));Bt(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,ui(this.session,t);else ge.error("Conference-Info unknown contentType",e)}},i=yield this.session.vertoSubscribe(t).catch((e=>{ge.error("ConfInfo subscription error:",e)}));Bt(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(He.Active):this.setState(He.Held),!0}_handleChangeHoldStateError(e){ge.error(`Failed to ${e.action} on call ${this.id}`);const t=ae(_,e);return Ze(ee.Error,{error:t,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e){const i=new It({sessid:this.session.sessionid,action:Ve.UpdateMedia,callID:this.options.id,sdp:e,dialogParams:this.options});ge.info("ICE restart: sending Modify with new offer SDP"),this._execute(i).then((e=>t(this,void 0,void 0,(function*(){var t;(null==e?void 0:e.sdp)?(ge.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;ge.error(e,t),null===(i=this.peer)||void 0===i||i.finishIceRestart();const n=ae(A,t);Ze(ee.Error,{error:n,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onRemoteSdp(e){return t(this,void 0,void 0,(function*(){const i=new RTCSessionDescription({sdp:e,type:Pe.Answer});yield this.peer.instance.setRemoteDescription(i).then((()=>{performance.mark("set-remote-description"),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(He.Early),this.gotAnswer&&this.setState(He.Active)})).catch((e=>t(this,void 0,void 0,(function*(){ge.error("Call setRemoteDescription Error: ",e);const t=ae(p,e);Ze(ee.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){ge.error("Error during hangup after setRemoteDescription failure:",e)}}))))}))}_requestAnotherLocalDescription(){Se(this.peer.onSdpReadyTwice)?Ze(ee.Error,{error:new Error("SDP without candidates for the second time!"),sessionId:this.session.sessionid},this.session.uuid):(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 ge.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:o,type:r}=e;if(-1===o.indexOf("candidate"))return ge.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),!Y.test(o)){const e=ne(W);ge.warn(`[${this.id}] Warning ${e.code}: ${e.message}`),Ze(ee.Warning,{warning:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}performance.mark("ice-gathering-end");let a=null;const c={sessid:this.session.sessionid,sdp:o,dialogParams:this.options,"User-Agent":`Web-${mi}`};if(null===(s=this.peer)||void 0===s?void 0:s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case Pe.Offer:this.setState(He.Requesting),a=new mt(c);break;case Pe.Answer:this._isRecovering||this.setState(He.Answering),a=!0===this.options.attach?new yt(c):new _t(c);break;default:return ge.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark("send-sdp"),this._execute(a).then((e=>{const{node_id:t=null}=e;this._targetNodeId=t,r===Pe.Offer?this.setState(He.Trying):this.setState(He.Active)})).catch((e=>t(this,void 0,void 0,(function*(){ge.error(`${this.id} - Sending ${r} error:`,e);const t=ae(g,e);Ze(ee.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){ge.error("Error during hangup after SDP send failure:",e)}}))))}}_onTrickleIceSdp(e){var i;if(!e)return ge.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-${mi}`};if(null===(i=this.peer)||void 0===i?void 0:i.isIceRestarting)this._sendIceRestartModify(n);else{switch(s){case Pe.Offer:this.setState(He.Requesting),o=new mt(r);break;case Pe.Answer:this._isRecovering||this.setState(He.Answering),o=!0===this.options.attach?new yt(r):new _t(r);break;default:return ge.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark("send-sdp"),this._execute(o).then((e=>{const{node_id:t=null}=e;this._targetNodeId=t,s===Pe.Offer?this.setState(He.Trying):this.setState(He.Active)})).catch((e=>t(this,void 0,void 0,(function*(){ge.error(`${this.id} - Sending ${s} error:`,e);const t=ae(g,e);Ze(ee.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){ge.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?(ge.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?(ge.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 St({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 ge.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((()=>{ge.debug("Successfully added ICE candidate:",e)})).catch((t=>{ge.error("Failed to add ICE candidate:",t,e)}))}_sendEndOfCandidates(){const e=new Ct({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var t;if(this._firstCandidateSent||(performance.mark("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("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,i;if(this.options.trickleIce&&!(null===(t=this.peer)||void 0===t?void 0:t.isIceRestarting))this._onTrickleIce(e);else{if(null===(i=this.peer)||void 0===i?void 0:i.iceDone)return;this._onIce(e)}},e.onicegatheringstatechange=t=>{ge.debug("ICE gathering state changed:",e.iceGatheringState,t),"complete"===e.iceGatheringState&&(ge.debug("Finished gathering candidates"),performance.mark("ice-gathering-completed"))},e.onicecandidateerror=t=>{var i;if(ge.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&&Dt(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:Ue.userMediaError,error:n,call:this,errorName:t,errorMessage:i}),ge.error(`Media error (${t}): ${i}`,e),Ze(ee.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:Ue.peerConnectionFailureError,error:e.error}),ge.error("Peer connection failure error"),e.warning&&Ze(ee.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:Ue.signalingStateClosed},e)),ge.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:Ue.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(Ze(ee.Notification,e,this.id,!1)||Ze(ee.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=ne(V);return Ze(ee.Warning,{warning:t,callId:this.id,activeCallId:e.id,sessionId:this.session.sessionid,activeSessionId:e.session.sessionid},this.session.uuid),ge.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===xe.Inbound))}_isBlockingInboundAnswer(){var e;if([He.Hangup,He.Destroy,He.Purge].includes(this._state))return!1;const t=[He.Answering,He.Early,He.Active,He.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;const{id:i,userVariables:n,remoteCallerNumber:s,onNotification:o,recoveredCallId:r}=this.options;var c;this.options.id=i?i.toString():a(),this.id=this.options.id,r&&(this.recoveredCallId=r,this._isRecovering=!0),n&&(c=n,0!==Object.keys(c).length)||(this.options.userVariables=this.session.options.userVariables||{}),s||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Xe(ee.MediaError,this._onMediaError,this.id),Xe(ee.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Xe(ee.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Se(o)&&Xe(ee.Notification,o.bind(this),this.id);const d=!1!==this.session.options.enableCallReports,l=this.session.options.callReportInterval||5e3,u=this.session.options.debugLogLevel||"debug",h=this.session.options.debugLogMaxEntries||1e3;d&&(this._callReportCollector=new ti({enabled:!0,interval:l},{enabled:!0,level:u,maxEntries:h}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=e=>{Ze(ee.Warning,{warning:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}),this._isRecovering?this.setState(He.Recovering):this.setState(He.New),ge.info(`New Call — region: ${null!==(e=this.session.region)&&void 0!==e?e:"unknown"}, dc: ${null!==(t=this.session.dc)&&void 0!==t?t:"unknown"}`,this.options)}_finalize(){var e;this._stopStats(),ge.debug(`[${this.id}] Closing peer from _finalize`),null===(e=this.peer)||void 0===e||e.close();const{remoteStream:t,localStream:i}=this.options;xt(t),xt(i),ze(ee.MediaError,null,this.id),ze(ee.PeerConnectionFailureError,null,this.id),ze(ee.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id],this._postCallReport().catch((e=>{ge.error("Unexpected error in _postCallReport",{error:e})}))}_flushIntermediateReport(){var e;if(!this._callReportCollector)return;const t=this.session.callReportId;if(!t)return void ge.debug("Cannot flush intermediate report: call_report_id not available");const i=null===(e=this.session.connection)||void 0===e?void 0:e.host;if(!i)return void ge.debug("Cannot flush intermediate report: connection host not available");const n={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===xe.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:mi},s=this._callReportCollector.flush(n);if(!s)return;const o=De()||void 0;this._callReportCollector.sendPayload(s,t,i,o).catch((e=>{ge.error("Failed to post intermediate call report segment",{error:e})}))}_postCallReport(){var e;return t(this,void 0,void 0,(function*(){if(!this._callReportCollector)return void ge.warn("Call report collector not initialized");yield this._callReportCollector.stop();const t=this.session.callReportId;if(!t)return ge.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const i={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===xe.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:mi},n=null===(e=this.session.connection)||void 0===e?void 0:e.host;if(!n)return void ge.error("Cannot post call report: connection host not available");const s=De()||void 0;this._callReportCollector.postReport(i,t,n,s).catch((e=>{ge.error("Failed to post call report",{error:e})})).finally((()=>{var e;null===(e=this._callReportCollector)||void 0===e||e.cleanup()}))}))}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),ge.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),ge.debug("Stats stopped")}}_i.setStateTelnyx=e=>{if(e){switch(e._state){case He.Recovering:e.state="recovering";break;case He.Requesting:case He.Trying:case He.Early:e.state="connecting";break;case He.Active:e.state="active";break;case He.Held:e.state="held";break;case He.Hangup:case He.Destroy:e.state="done";break;case He.Answering:e.state="ringing";break;case He.New:e.state="new"}return e}};class yi extends _i{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,t)=>this.session.execute(new ei(e,t))}hangup(e={},i=!0){const n=Object.create(null,{hangup:{get:()=>super.hangup}});return t(this,void 0,void 0,(function*(){this.screenShare instanceof yi&&(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 yi(this.session,c),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){return t(this,void 0,void 0,(function*(){this.screenShare instanceof yi&&(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)&&Lt(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`)})))})),ge.info(t)}))),2e3)}}class bi extends Ot{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()}get reconnectDelay(){return 1e3}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*(){e.connect.call(this)}))}checkPermissions(e=!0,i=!0){return t(this,void 0,void 0,(function*(){try{const t=yield Mt({audio:e,video:i});return xt(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*(){ge.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(He.Purge),ge.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*(){ge.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(He.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(Qe(ee.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 Ut().catch((e=>{const t=ae(re(e),e);return Ze(ee.MediaError,t,this.uuid),[]}))}getVideoDevices(){return Ut(We.Video).catch((e=>(Ze(ee.MediaError,e,this.uuid),[])))}getAudioInDevices(){return Ut(We.AudioIn).catch((e=>{const t=ae(re(e),e);return Ze(ee.MediaError,t,this.uuid),[]}))}getAudioOutDevices(){return Ut(We.AudioOut).catch((e=>(ge.error("getAudioOutDevices",e),Ze(ee.MediaError,e,this.uuid),[])))}validateDeviceId(e,t,i){return jt(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 Mt({video:{deviceId:{exact:e}}}),n=i.getVideoTracks()[0];for(let e=0;e<Ft.length;e++){const[i,s]=Ft[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 xt(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 Ht(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 jt(e,i,n).catch((e=>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?Z:z}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=Ce(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=Ce(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 wt({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 kt({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const s=yield this.execute(t),{unauthorized:o=[],subscribed:r=[]}=$t(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 Tt({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const n=yield this.execute(t),{unsubscribed:s=[],notSubscribed:o=[]}=$t(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&&(ge.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,ge.debug(`Network connectivity lost for session ${this.sessionid}`);const e=ae(N);Ze(ee.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 yi.setStateTelnyx(e)}}class Si{constructor(e,t){this.code=t,this.message=e}}class Ci{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,t){const i=new ft(e,t);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*we(2,6)}handleMessage(e){var t,i,n,s,o,r,a,c,d;const{session:l}=this;l.setPingReceived();const{id:u,method:h,params:p={},voice_sdk_id:g}=e,v=null==p?void 0:p.callID,f=null==p?void 0:p.eventChannel,m=null==p?void 0:p.eventType,_=l.calls[v],y=null===(t=null==_?void 0:_.peer)||void 0===t?void 0:t.isConnectionHealthy();if(Array.isArray(null==p?void 0:p.reattached_sessions)&&0===p.reattached_sessions.length&&Object.keys(l.calls).length>0){const e=ne(K);Ze(ee.Warning,{warning:e,sessionId:l.sessionid},l.uuid)}if("channelPvtData"===m)return this._handlePvtEvent(p.pvtData);const b=e=>{var t,i,n,s,o,r;const a={audio:!0,video:l.options.video,remoteSdp:p.sdp,destinationNumber:p.callee_id_number,remoteCallerName:p.caller_id_name,remoteCallerNumber:p.caller_id_number,callerName:p.callee_id_name,callerNumber:p.callee_id_number,attach:h===Me.Attach,mediaSettings:p.mediaSettings,debug:null!==(t=l.options.debug)&&void 0!==t&&t,debugOutput:null!==(i=l.options.debugOutput)&&void 0!==i?i:"socket",trickleIce:null!==(n=l.options.trickleIce)&&void 0!==n&&n,prefetchIceCandidates:null===(s=l.options.prefetchIceCandidates)||void 0===s||s,forceRelayCandidate:null!==(o=l.options.forceRelayCandidate)&&void 0!==o&&o,keepConnectionAliveOnSocketClose:null!==(r=l.options.keepConnectionAliveOnSocketClose)&&void 0!==r&&r};v&&(a.id=v),p.telnyx_call_control_id&&(a.telnyxCallControlId=p.telnyx_call_control_id),p.telnyx_session_id&&(a.telnyxSessionId=p.telnyx_session_id),p.telnyx_leg_id&&(a.telnyxLegId=p.telnyx_leg_id),p.client_state&&(a.clientState=p.client_state),p.dialogParams&&p.dialogParams.custom_headers&&p.dialogParams.custom_headers.length&&(a.customHeaders=p.dialogParams.custom_headers),e&&(a.recoveredCallId=e),performance.mark("new-call-start");const c=new yi(l,a);return c.nodeId=this.nodeId,c},S=new lt(g),C=new ht(g);switch(h){case Me.Answer:case Me.Display:case Me.Candidate:case Me.Ringing:case Me.Bye:case Me.Media:if(!v||!_)return void ge.error(`Received ${h} for non existing call:`,p);_.handleMessage(e),this._ack(u,h);break;case Me.Ping:this.session.setPingReceived(),this.session.execute(C);break;case Me.Punt:l.options.keepConnectionAliveOnSocketClose&&y?(ge.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),l.socketDisconnect(),this._ack(u,h)):(ge.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),l.serverDisconnect());break;case Me.Invite:{const e=b();e.direction=xe.Inbound,e.playRingtone(),e.setState(He.Ringing),this._ack(u,h);break}case Me.Attach:{if(!_){return b().answer(),void this._ack(u,h)}const e=_.id;ge.info(`[${(new Date).toISOString()}][${v}] closing existing call on ATTACH.`),_.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1),ge.info(`[${(new Date).toISOString()}][${v}] Attach: Creating new call for recovery (recoveredCallId: ${e})`);b(e).answer(),this._ack(u,h);break}case Me.Event:case"webrtc.event":if(!f)return void ge.error("Verto received an unknown event:",p);const t=l.relayProtocol,g=f.split(".")[0];l._existsSubscription(t,f)?Ze(t,p,f):f===l.sessionid?this._handleSessionEvent(p.eventData):l._existsSubscription(t,g)?Ze(t,p,g):l.calls.hasOwnProperty(f)?l.calls[f].handleMessage(e):Ze(ee.Notification,p,l.uuid);break;case Me.Info:p.type=Ue.generic,Ze(ee.Notification,p,l.uuid);break;case Me.ClientReady:this.session.execute(S);break;default:{const t=Re(e);if(t){switch(t){case Ge.REGISTER:case Ge.REGED:if(l.connection.previousGatewayState!==Ge.REGED&&l.connection.previousGatewayState!==Ge.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0;const t=null===(n=null===(i=null==e?void 0:e.result)||void 0===i?void 0:i.params)||void 0===n?void 0:n.call_report_id;t&&(l.callReportId=t,ge.debug("Captured call_report_id from REGED:",t));const u=null===(o=null===(s=null==e?void 0:e.result)||void 0===s?void 0:s.params)||void 0===o?void 0:o.dc;u&&(l.dc=u);const h=null===(a=null===(r=null==e?void 0:e.result)||void 0===r?void 0:r.params)||void 0===a?void 0:a.region;h&&(l.region=h),ge.info(`Connected to Telnyx — region: ${null!==(c=l.region)&&void 0!==c?c:"unknown"}, dc: ${null!==(d=l.dc)&&void 0!==d?d:"unknown"}`),p.type=Ue.vertoClientReady,Ze(ee.Ready,p,l.uuid)}break;case Ge.UNREGED:case Ge.NOREG:if(this.retriedRegister+=1,5===this.retriedRegister){this.retriedRegister=0;const e=new Si("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),t=ae(T,e);Ze(ee.Error,{error:t,sessionId:l.sessionid},l.uuid);break}setTimeout((()=>{this.session.execute(S)}),this.reconnectDelay());break;case Ge.FAILED:case Ge.FAIL_WAIT:if(l.connection.previousGatewayState!==Ge.FAILED&&l.connection.previousGatewayState!==Ge.FAIL_WAIT){const e=ae(k,new Error(`Gateway state: ${t}`));if(Ze(ee.Error,{error:e,sessionId:l.sessionid},l.uuid),!this.session.hasAutoReconnect()){this.retriedConnect=0;const e=new Si("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),t=ae(w,e);Ze(ee.Error,{error:t,sessionId:l.sessionid},l.uuid);break}if(this.retriedConnect+=1,5===this.retriedConnect){this.retriedConnect=0;const e=ae(45003,new Error("Connection Retry Failed"));Ze(ee.Error,{error:e,sessionId:l.sessionid},l.uuid);break}setTimeout((()=>{if(ge.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){const e=Object.values(l.calls).some((e=>{var t;return(null===(t=e.peer)||void 0===t?void 0:t.instance)&&!e.signalingStateClosed}));if(e)return ge.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();ge.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:ge.warn("GatewayState message unknown method:",e)}break}ge.debug("Verto message unknown method:",e);break}}}_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=>{ge.error("liveArray subscription error:",e);const i=ae(S,e);Ze(ee.Error,{error:i,sessionId:t.sessionid},t.uuid)}));Bt(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:Ue.conferenceUpdate,action:$e.Leave,conferenceName:o,participantId:Number(d),role:l};Ze(ee.Notification,i,n,!1)||Ze(ee.Notification,i,t.uuid),null===e&&ze(ee.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=>{ge.error("liveArray unsubscribe error:",e)}));break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":ui(this.session,e);break;case"logo-info":{const t={type:Ue.conferenceUpdate,action:$e.LogoInfo,logo:e.logoURL};Ze(ee.Notification,t,this.session.uuid);break}}}}class Ii extends bi{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 Ci(this),window.addEventListener("beforeunload",(e=>{this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&(ge.info(`Hanging up call due to window unload: ${e}`),this.calls[e].hangup({initiator:"sdk:beforeunload"},!0))}))}))}validateOptions(){return ke(this.options)||Te(this.options)}newCall(e){if(!this.validateCallOptions(e)){throw ae(y,void 0,"Error: destinationNumber is required")}const t=new yi(this,e);return performance.mark("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!!Te(this.options)||Boolean(e.destinationNumber)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){return ke(this.options)?this.handleLoginOnSocketOpen():Te(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0}))}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class Ei extends Ii{constructor(e){super(e),ge.info(`SDK version: ${pt}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Yt()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Jt.full},{browserName:"Firefox",features:["audio"],supported:Jt.partial},{browserName:"Safari",supported:Jt.not_supported},{browserName:"Edge",supported:Jt.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Jt.not_supported},{browserName:"Firefox",supported:Jt.not_supported},{browserName:"Safari",features:["video","audio"],supported:Jt.full},{browserName:"Edge",supported:Jt.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Jt.full},{browserName:"Firefox",features:["audio"],supported:Jt.partial},{browserName:"Safari",supported:Jt.not_supported},{browserName:"Edge",supported:Jt.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Jt.full},{browserName:"Firefox",features:["audio"],supported:Jt.partial},{browserName:"Safari",features:["video","audio"],supported:Jt.full},{browserName:"Edge",features:["audio"],supported:Jt.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Jt.full},{browserName:"Firefox",features:["audio"],supported:Jt.partial},{browserName:"Safari",supported:Jt.not_supported},{browserName:"Edge",features:["audio"],supported:Jt.partial}]}]}}class wi{static run(e){return t(this,void 0,void 0,(function*(){const t=Oe({}),i=Oe({}),n=new Ei(e.credentials);yield n.connect(),n.on(ee.Ready,t.resolve),n.on(ee.Error,t.reject),n.on(ee.MediaError,t.reject),n.on(ee.MediaError,t.reject),n.on(ee.Notification,(e=>{e.call&&e.call.sipCode>=400&&i.reject(new Error(e.call.sipReason))})),Xe(ee.StatsReport,(e=>{i.resolve(wi.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 f=0,m=1/0,_=-1/0,y=0,b=1/0,S=-1/0,C=0;v.forEach((e=>{var t,i,n;if(!(null===(t=e.remote.audio.inbound)||void 0===t?void 0:t[0]))return;f+=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,C+=o,_=Math.max(_,s),m=Math.min(m,s),S=Math.max(S,o),b=Math.min(b,o)}));const I=C/f,E=y/f,w=v[v.length-1],k=oi({jitter:1e3*E,rtt:1e3*I,packetsReceived:null!==(n=null===(i=null===(t=w.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=w.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:k,jitter:{average:E,max:_,min:m},rtt:{average:I,max:S,min:b},quality:ri(k)},sessionStats:{packetsSent:null!==(a=w.connection.packetsSent)&&void 0!==a?a:0,bytesSent:null!==(c=w.connection.bytesSent)&&void 0!==c?c:0,bytesReceived:null!==(d=w.connection.bytesReceived)&&void 0!==d?d:0,packetsLost:null!==(h=null===(u=null===(l=w.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=w.connection.packetsReceived)&&void 0!==p?p:0},iceCandidateStats:g}}getTelnyxIds(){return{telnyxCallControlId:"",telnyxSessionId:"",telnyxLegId:""}}}export{yi as Call,Fe as ERROR_TYPE,Ue as NOTIFICATION_TYPE,wi as PreCallDiagnosis,te as SDK_ERRORS,ie as SDK_WARNINGS,ee as SwEvent,c as TELNYX_ERROR_CODES,d as TELNYX_WARNING_CODES,se as TelnyxError,Ei as TelnyxRTC,oe 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,UNEXPECTED_ERROR:49001},d={HIGH_RTT:31001,HIGH_JITTER:31002,HIGH_PACKET_LOSS:31003,LOW_MOS:31004,LOW_LOCAL_AUDIO:31005,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,DUPLICATE_INBOUND_ANSWER:33007,TOKEN_EXPIRING_SOON:34001,SESSION_NOT_REATTACHED:35001},{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:C,WEBSOCKET_CONNECTION_FAILED:I,WEBSOCKET_ERROR:E,RECONNECTION_EXHAUSTED:w,GATEWAY_FAILED:k,LOGIN_FAILED:T,INVALID_CREDENTIALS:R,AUTHENTICATION_REQUIRED:A,ICE_RESTART_FAILED:O,NETWORK_OFFLINE:N,UNEXPECTED_ERROR:L}=c,{HIGH_RTT:D,HIGH_JITTER:P,HIGH_PACKET_LOSS:x,LOW_MOS:M,LOW_LOCAL_AUDIO:U,LOW_BYTES_RECEIVED:F,LOW_BYTES_SENT:j,ICE_CONNECTIVITY_LOST:H,ICE_GATHERING_TIMEOUT:B,ICE_GATHERING_EMPTY:W,PEER_CONNECTION_FAILED:$,ONLY_HOST_ICE_CANDIDATES:G,ANSWER_WHILE_PEER_ACTIVE:V,DUPLICATE_INBOUND_ANSWER:q,TOKEN_EXPIRING_SOON:K,SESSION_NOT_REATTACHED:Y}=d,J=/^a=candidate:.+typ (srflx|prflx|relay)/m,X="wss://rtc.telnyx.com",Q=1006,z={urls:"stun:stun.l.google.com:19302"},Z=[{urls:"stun:stun.telnyx.com:3478"},z,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],ee=[{urls:"stun:stundev.telnyx.com:3478"},z,{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 te;!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.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"}(te||(te={}));const ie={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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},45004:{name:"GATEWAY_FAILED",message:"Gateway connection failed",description:"The upstream gateway reported a FAILED or FAIL_WAIT 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"]},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"]},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)"]},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"]},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"]},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"]},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"]}},ne={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"]},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"]},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"]},35001:{name:"SESSION_NOT_REATTACHED",message:"Active call lost after reconnect",description:"The WebSocket reconnected successfully but the server returned an empty reattached_sessions list while the SDK still has an active call. The server no longer knows about the call, so any subsequent call-control operation (hangup, hold, etc.) will fail with CALL_DOES_NOT_EXIST.",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"]}};function se(e,t){const i=ne[e];return{code:e,name:i.name,message:t||i.message,description:i.description,causes:[...i.causes],solutions:[...i.solutions]}}class oe 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,Object.setPrototypeOf(this,oe.prototype)}toJSON(){return{code:this.code,name:this.name,description:this.description,message:this.message,causes:this.causes,solutions:this.solutions,originalError:this.originalError}}}function re(e){return!0===e.recoverable}function ae(e){if(e instanceof DOMException){if("NotAllowedError"===e.name)return v;if("NotFoundError"===e.name||"OverconstrainedError"===e.name)return m}return f}function ce(e,t,i){const n=ie[e],s=t instanceof Error?t:void 0!==t?new Error(String(t)):void 0;return new oe({code:e,name:n.name,description:n.description,message:i||n.message,causes:[...n.causes],solutions:[...n.solutions],originalError:s})}var de="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function le(e,t){return e(t={exports:{}},t.exports),t.exports}var ue=le((function(e){var t,i;t=de,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 he={debug:0,info:1,warn:2,error:3};class pe{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(he[e]<he[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 ge=null;const ve=ue.getLogger("telnyx"),me={trace:0,debug:1,info:2,warn:3,error:4};let fe=me.info;function _e(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 ye=ve.methodFactory;ve.methodFactory=(e,t,i)=>{const n=ye(e,t,i);return function(...t){if(me[e]>=fe){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(const i of t)e.push(i);n(...e)}const i=ge;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]?_e(s[0]):{args:s.map(_e)}),i.addEntry(e,o,r)}}},ve.setLevel("debug",!1);const be=e=>{const[t,i,n,s,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){ve.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},Se=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},Ce=e=>e instanceof Function||"function"==typeof e,Ie=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,Ee=/^(ws|wss):\/\//,we=(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?we(a,r):{result:s}},ke=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),Te=({login:e,passwd:t,password:i,login_token:n})=>Boolean(e&&(t||i)||n),Re=({anonymous_login:e})=>Boolean(e)&&Boolean(e.target_id)&&Boolean(e.target_type),Ae=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 Oe({debounceTime:e}){let t,i;return{promise:new Promise(((n,s)=>{t=e?Ne(n,e):n,i=s})),resolve:t,reject:i}}const Ne=(e,t)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout((()=>{e(...n)}),t)}},Le="telnyx-voice-sdk-id";function De(){return sessionStorage.getItem(Le)}function Pe(){sessionStorage.removeItem(Le)}var xe,Me,Ue;"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{Pe()})),function(e){e.Offer="offer",e.Answer="answer"}(xe||(xe={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(Me||(Me={})),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"}(Ue||(Ue={}));const Fe={generic:"event",[Ue.Display]:"participantData",[Ue.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},je={invalidCredentialsOptions:"InvalidCredentialsOptions"},He={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 Be,We,$e,Ge,Ve,qe;!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"}(Be||(Be={})),function(e){e.Participant="participant",e.Moderator="moderator"}(We||(We={})),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"}($e||($e={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(Ge||(Ge={})),function(e){e.REGED="REGED",e.UNREGED="UNREGED",e.NOREG="NOREG",e.FAILED="FAILED",e.FAIL_WAIT="FAIL_WAIT",e.REGISTER="REGISTER",e.TRYING="TRYING",e.EXPIRED="EXPIRED",e.UNREGISTER="UNREGISTER"}(Ve||(Ve={})),function(e){e.Hold="hold",e.Unhold="unhold",e.ToggleHold="toggleHold",e.UpdateMedia="updateMedia"}(qe||(qe={}));const Ke="GLOBAL",Ye={},Je=(e,t)=>`${e}|${t}`,Xe=(e,t=Ke)=>Je(e,t)in Ye,Qe=(e,t,i=Ke)=>{const n=Je(e,i);n in Ye||(Ye[n]=[]),Ye[n].push(t)},ze=(e,t,i=Ke)=>{const n=function(s){Ze(e,n,i),t(s)};return n.prototype.targetRef=t,Qe(e,n,i)},Ze=(e,t,i=Ke)=>{if(!Xe(e,i))return!1;const n=Je(e,i);if(Ce(t)){for(let e=Ye[n].length-1;e>=0;e--){const i=Ye[n][e];(t===i||i.prototype&&t===i.prototype.targetRef)&&Ye[n].splice(e,1)}}else Ye[n]=[];return 0===Ye[n].length&&delete Ye[n],!0},et=(e,t,i=Ke,n=!0)=>{const s=n&&i!==Ke;if(!Xe(e,i))return s&&et(e,t),!1;const o=Je(e,i),r=Ye[o].length;if(!r)return s&&et(e,t),!1;for(let e=r-1;e>=0;e--)Ye[o][e](t);return s&&et(e,t),!0},tt=e=>{const t=Je(e,"");Object.keys(Ye).filter((e=>0===e.indexOf(t))).forEach((e=>delete Ye[e]))};let it="undefined"!=typeof WebSocket?WebSocket:null;const nt=0,st=1,ot=2,rt=3;class at{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=X,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this._safetyTimeoutId=null,this.upDur=null,this.downDur=null;const{host:t,env:i,region:n,useCanaryRtcServer:s}=e.options;i&&(this._host="development"===i?"wss://rtcdev.telnyx.com":X),t&&(this._host=(e=>`${Ee.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===st}get connecting(){return!!this._wsClient&&this._wsClient.readyState===nt}get closing(){return!!this._wsClient&&this._wsClient.readyState===ot}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(){const e=new URL(this._host);let t=De();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"),ve.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this.session.options.skipLastVoiceSdkId&&e.searchParams.has("voice_sdk_id")&&e.searchParams.set("skip_last_voice_sdk_id","true");try{this._wsClient=new it(e.toString()),this._registerSocketEvents(this._wsClient)}catch(e){ve.error("WebSocket connection failed:",e);const t=ce(I,e);et(te.Error,{error:t,sessionId:this.session.sessionid},this.session.uuid)}}sendRawText(e){var t;null===(t=this._wsClient)||void 0===t||t.send(e)}send(e){var t;const{request:i}=e,n=new Promise(((e,t)=>{if(i.hasOwnProperty("result"))return e();ze(i.id,(i=>{const{result:n,error:s}=we(i);return s?t(s):e(n)}))}));return ve.debug("SEND: \n",JSON.stringify(i,null,2),"\n"),null===(t=this._wsClient)||void 0===t||t.send(JSON.stringify(i)),n}close(){if(!this._wsClient||this.closing)return;const e=this._wsClient;Ce(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout((()=>this._handleCloseTimeout(e)),5e3))}_registerSocketEvents(e){e.onopen=e=>et(te.SocketOpen,e,this.session.uuid),e.onclose=t=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),et(te.SocketClose,t,this.session.uuid)),e.onerror=t=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error");const i=ce(E);return et(te.Error,{error:i,sessionId:this.session.sessionid},this.session.uuid),et(te.SocketError,{error:t,sessionId:this.session.sessionid},this.session.uuid)},e.onmessage=e=>{var t,i;const n=Se(e.data);var s;if("string"!=typeof n){if(n.voice_sdk_id&&(s=n.voice_sdk_id,sessionStorage.setItem(Le,s)),this._unsetTimer(n.id),ve.debug("RECV: \n",JSON.stringify(n,null,2),"\n"),Ve[`${null===(i=null===(t=null==n?void 0:n.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state}`]||!et(n.id,n)){const e=Ae(n);et(te.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?(ve.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e||et(te.SocketClose,{code:Q,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1},this.session.uuid)):ve.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(ve.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,t){this._wsClient===e?(ve.debug(`Nulling socket reference (reason: ${t})`),this._wsClient=null):ve.debug(`Skipping socket cleanup - old socket already replaced (reason: ${t})`)}_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)),et(te.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else ve.warn("Unknown message from socket",e)}}class ct{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:a()},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 lt extends ct{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 ut extends lt{constructor(e){super(),this.method=Ue.GatewayState;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class ht{constructor(e){this.pendingRequestId=null,this.onSocketMessage=e=>t(this,void 0,void 0,(function*(){e.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Ae(e))})),this.getIsRegistered=()=>t(this,void 0,void 0,(function*(){const e=new ut(De());this.pendingRequestId=e.request.id,this.gatewayStateTask=Oe({}),this.session.execute(e);const t=yield this.gatewayStateTask.promise;return!!t&&[Ve.REGISTER,Ve.REGED].includes(t)})),this.session=e,this.gatewayStateTask=Oe({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class pt extends lt{constructor(e){super(),this.method=Ue.Ping;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}var gt="2.27.0-beta.3",vt=gt;class mt extends lt{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:vt,data:navigator.userAgent}};n&&(r.sessid=n),this.buildRequest({method:this.method,params:r})}}class ft extends lt{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class _t extends lt{toString(){return Ue.Invite}}class yt extends lt{toString(){return Ue.Answer}}class bt extends lt{toString(){return Ue.Attach}}class St extends lt{toString(){return Ue.Bye}}class Ct extends lt{toString(){return Ue.Candidate}}class It extends lt{toString(){return Ue.EndOfCandidates}}class Et extends lt{toString(){return Ue.Modify}}class wt extends lt{toString(){return Ue.Info}}class kt extends lt{toString(){return Ue.Broadcast}}class Tt extends lt{toString(){return Ue.Subscribe}}class Rt extends lt{toString(){return Ue.Unsubscribe}}class At extends lt{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:vt,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 Ot{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.dc=null,this.region=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._reconnectAttempts=0,this._tokenExpiryTimeout=null,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var t,i;t=e.debug?"debug":"info",fe=null!==(i=me[t])&&void 0!==i?i:me.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._attachListeners(),this.connection=new at(this),this.registerAgent=new ht(this)}get __logger(){return ve}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return t(this,void 0,void 0,(function*(){return this.registerAgent.getIsRegistered()}))}get reconnectDelay(){return 1e3*ke(2,6)}execute(e){return this._idle?new Promise((t=>this._executeQueue.push({resolve:t,msg:e}))):this.connected?this.connection.send(e).catch((e=>t(this,void 0,void 0,(function*(){if((null==e?void 0:e.code)===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const t=ce(A,e);et(te.Error,{error:t,sessionId:this.sessionid},this.uuid)}yield this.login()}throw e})))):new Promise((t=>{this._executeQueue.push({resolve:t,msg:e}),ve.debug("Calling connect from execute since not currently connected."),this.connect()}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return Te(this.options)||Re(this.options)}broadcast(e){}disconnect(){return t(this,void 0,void 0,(function*(){clearTimeout(this._reconnectTimeout),this._clearTokenExpiryTimeout(),this.subscriptions={},this._autoReconnect=!1,this._reconnectAttempts=0,this.relayProtocol=null,this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),ve.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")}))}on(e,t){return Qe(e,t,this.uuid),this}off(e,t){return Ze(e,t,this.uuid),this}connect(){return t(this,void 0,void 0,(function*(){this.connection||(ve.debug("No existing connection found, creating a new one."),this.connection=new at(this)),this._attachListeners(),this._autoReconnect||(this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(ve.debug("Initiating connection to the server..."),this.connection.connect()),ve.debug("Connect method called. Connection initiated.")}))}resetReconnectAttempts(){this._reconnectAttempts=0}_handleLoginError(e){const t=ce(T,e);et(te.Error,{error:t,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){Pe()}_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<=Ot.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const e=1e3*(n-Ot.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout((()=>{this._emitTokenExpiryWarning()}),e)}}catch(e){ve.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=se(K);et(te.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)),Te(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(Re(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const e="Invalid login options provided for authentication.";ve.error(e);const t=ce(R,void 0,e);return void et(te.Error,{error:t,type:je.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}}))}_login({type:e,onSuccess:i,onError:n}){return t(this,void 0,void 0,(function*(){let t;t="login"===e?new mt(this.options.login,this.options.password||this.options.passwd,this.options.login_token,this.sessionid,this.options.userVariables,!!De()):new At({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:this.sessionid,userVariables:this.options.userVariables,reconnection:!!De()});const s=yield this.execute(t).catch((e=>{this._handleLoginError(e),n&&n(e)}));s&&(this.sessionid=s.sessid,this._checkTokenExpiry(),i&&i())}))}_onSocketOpen(){return t(this,void 0,void 0,(function*(){}))}onNetworkClose(){var e;this.relayProtocol&&tt(this.relayProtocol);for(const e in this.subscriptions)tt(e);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect){const t=null!==(e=this.options.maxReconnectAttempts)&&void 0!==e?e:10;if(this._reconnectAttempts+=1,t>0&&this._reconnectAttempts>t){ve.info(`Reconnection exhausted after ${t} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1;const e=ce(w);return void et(te.Error,{error:e,sessionId:this.sessionid},this.uuid)}ve.debug(`Reconnect attempt ${this._reconnectAttempts}${t>0?` of ${t}`:""}`),this._reconnectTimeout=setTimeout((()=>{ve.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()}),this.reconnectDelay)}}_onSocketMessage(e){}_removeSubscription(e,t){this._existsSubscription(e,t)&&(t?(delete this.subscriptions[e][t],Ze(e,null,t)):(delete this.subscriptions[e],tt(e)))}_addSubscription(e,t=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},Ce(t)&&Qe(e,t,i))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(te.SocketOpen,this._onSocketOpen),this.on(te.SocketClose,this.onNetworkClose),this.on(te.SocketError,this.onNetworkClose),this.on(te.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(te.SocketOpen,this._onSocketOpen),this.off(te.SocketClose,this.onNetworkClose),this.off(te.SocketError,this.onNetworkClose),this.off(te.SocketMessage,this._onSocketMessage)}_emptyExecuteQueues(){this._executeQueue.forEach((({resolve:e,msg:t})=>{"string"==typeof t?this.executeRaw(t):e(this.execute(t))}))}_closeConnection(){this._idle=!0,clearTimeout(this._keepAliveTimeout),this.connection&&this.connection.close()}_resetKeepAlive(){!1===this._pong&&(ve.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new pt(De()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout((()=>this._resetKeepAlive()),35e3)}setPingReceived(){ve.debug("Ping received"),this._pong=!0}static on(e,t){Qe(e,t)}static off(e){Ze(e)}static uuid(){return a()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}Ot.TOKEN_EXPIRY_WARNING_SECONDS=120;const Nt=e=>navigator.mediaDevices.getUserMedia(e),Lt=e=>e&&e instanceof MediaStream,Dt=(e,t)=>{const i=Ie(e);null!==i&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=t)},Pt=(e,t)=>{const i=Ie(e);if(i){if(t&&i.srcObject!==t)return;i.srcObject=null}},xt=(e,i)=>t(void 0,void 0,void 0,(function*(){const t=Ie(e);if(null===t)return ve.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof i)return ve.info(`Invalid speaker deviceId: '${i}'`),!1;try{return yield t.setSinkId(i),!0}catch(e){return!1}})),Mt=e=>{e&&"live"===e.readyState&&e.stop()},Ut=e=>{Lt(e)&&e.getTracks().forEach(Mt),e=null},Ft=i=>t(void 0,void 0,void 0,(function*(){ve.info("RTCService.getUserMedia",i);const{audio:t,video:n}=i;if(!t&&!n)return null;try{return yield Nt(i)}catch(t){if(ve.error("getUserMedia error: ",t),(e=>"NotReadableError"===e.name||"NotFoundError"===e.name||"OverconstrainedError"===e.name)(t)){const n=(t=>{const{audio:i,video:n}=t;let s=!1,o=i,r=n;if("object"==typeof i&&null!==i&&"deviceId"in i){s=!0;const t=e(i,["deviceId"]);o=0===Object.keys(t).length||t}if("object"==typeof n&&null!==n&&"deviceId"in n){s=!0;const t=e(n,["deviceId"]);r=0===Object.keys(t).length||t}return s?{audio:o,video:r}:null})(i);if(n){ve.warn("Device not found or not readable, falling back to default device");try{return yield Nt(n)}catch(e){throw ve.error("Fallback getUserMedia also failed: ",e),t}}}throw t}})),jt=(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===Ge.AudioIn||e===Ge.AudioOut,video:!e||e===Ge.Video}))(e)).catch((e=>(ve.error(e),null)));if(n){if(Ut(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})),Ht=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Bt=(e,i,n)=>t(void 0,void 0,void 0,(function*(){const t=yield jt(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})),Wt=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((i=>{t.hasOwnProperty(i)&&null!==e[i]&&void 0!==e[i]||delete e[i]}))},$t=(e,t)=>{if(!e)return!1;const{subscribed:i,alreadySubscribed:n}=Gt(e);return i.includes(t)||n.includes(t)},Gt=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((i=>{t[i]=e[`${i}Channels`]||[]})),t},Vt=(e,t=null,i=null)=>{if(!Lt(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}}))},qt=e=>{Vt(e,"audio",!0)},Kt=e=>{Vt(e,"audio",!1)},Yt=e=>{Vt(e,"audio",null)},Jt=e=>((e,t=null)=>{if(!Lt(e))return null;let i=[];switch(t){case"audio":i=e.getAudioTracks();break;case"video":i=e.getVideoTracks();break;default:i=e.getTracks()}return i.some((e=>e.enabled))})(e,"audio");function Xt(){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:!!Ft}}catch(e){return e.message}}var Qt;function zt(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 Zt(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then((()=>{e._playFulfilled=!0})).catch((t=>{ve.error("playAudio",t),e._playFulfilled=!0})))}function ei(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"}(Qt||(Qt={}));const ti=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 ii extends ct{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 ni{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.previousCandidatePairId=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._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.logCollectorOptions.enabled&&(this.logCollector=function(e){return new pe(e)}(this.logCollectorOptions),this.logCollector.start(),i=this.logCollector,ge=i)}start(e){var t,i;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._stopped=!1,ve.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:ni.INITIAL_COLLECTION_INTERVAL_MS,initialDuration:ni.INITIAL_COLLECTION_DURATION_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(),ve.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:t,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})}))}flush(e){var t,i;if(this._flushing||0===this.statsBuffer.length)return null;this._flushing=!0;try{const n=this._segmentIndex++,s=this.statsBuffer;this.statsBuffer=[];const o=null!==(i=null===(t=this.logCollector)||void 0===t?void 0:t.drain())&&void 0!==i?i:[],r=new Date,a=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(r.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:r.toISOString()}),stats:s},o.length>0?{logs:o}:{}),{segment:n});return ve.info("CallReportCollector: Flushed intermediate segment",{segment:n,intervals:s.length,logEntries:o.length,callId:e.callId}),a}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 ve.info("CallReportCollector: Skipping report — call reports disabled");if(0===this.statsBuffer.length&&!a)return void ve.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)}))}sendPayload(e,i,n,s){return t(this,void 0,void 0,(function*(){yield this._sendPayload(e,i,n,s)}))}_sendPayload(e,i,n,s){var o,r;return t(this,void 0,void 0,(function*(){try{const t=new URL(n),a=`${t.protocol.replace(/^ws/,"http")}//${t.host}/call_report`,c=void 0!==e.segment&&!e.summary.endTimestamp?`intermediate segment ${e.segment}`:"final report";ve.info(`CallReportCollector: Posting ${c}`,{endpoint:a,intervals:e.stats.length,logEntries:null!==(r=null===(o=e.logs)||void 0===o?void 0:o.length)&&void 0!==r?r:0,callId:e.summary.callId,segment:e.segment});const d={"Content-Type":"application/json","x-call-report-id":i,"x-call-id":e.summary.callId};s&&(d["x-voice-sdk-id"]=s);const l=JSON.stringify(e),u=()=>fetch(a,{method:"POST",headers:d,body:l}),h=yield u();if(h.ok)ve.info(`CallReportCollector: Successfully posted ${c}`);else{const e=yield h.text();ve.error(`CallReportCollector: Failed to post ${c}`,{status:h.status,error:e})}}catch(t){ve.warn(`CallReportCollector: Network error posting call report, retrying in ${ni.RETRY_DELAY_MS}ms`,{error:t}),yield new Promise((e=>setTimeout(e,ni.RETRY_DELAY_MS)));try{const t=new URL(n),o=`${t.protocol.replace(/^ws/,"http")}//${t.host}/call_report`,r={"Content-Type":"application/json","x-call-report-id":i,"x-call-id":e.summary.callId};s&&(r["x-voice-sdk-id"]=s);const a=yield fetch(o,{method:"POST",headers:r,body:JSON.stringify(e)});if(a.ok)ve.info("CallReportCollector: Successfully posted call report on retry");else{const e=yield a.text();ve.error("CallReportCollector: Failed to post call report on retry",{status:a.status,error:e})}}catch(e){ve.error("CallReportCollector: Retry also failed, giving up",{error:e})}}}))}getStatsBuffer(){return this.statsBuffer}getLogs(){var e,t;return null!==(t=null===(e=this.logCollector)||void 0===e?void 0:e.getLogs())&&void 0!==t?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.intervalStartTime);this.intervalId=setTimeout((()=>{this.intervalId=null,this._collectStats().finally((()=>{!this._stopped&&this.peerConnection&&this._scheduleNextCollection()}))}),e)}_collectionIntervalFor(e){const t=this._positiveInterval(this.options.interval,5e3);return e.getTime()-this.callStartTime.getTime()<ni.INITIAL_COLLECTION_DURATION_MS?Math.min(ni.INITIAL_COLLECTION_INTERVAL_MS,t):t}_positiveInterval(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}_collectStats(e=!1){var i,n,s;return t(this,void 0,void 0,(function*(){if(this.peerConnection&&this.intervalStartTime)try{const t=yield this.peerConnection.getStats(),o=new Date;let r,a,c,d,l=null,u=null,h=null,p=null;if(t.forEach((e=>{switch(e.type){case"outbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(l=e);break;case"inbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(u=e);break;case"candidate-pair":(e.nominated||"succeeded"===e.state)&&(h=e);break;case"transport":p=e}})),l){const e=this._getOutboundAudioLevel(t,l);if(null!==e&&this.intervalAudioLevels.outbound.push(e),void 0!==this.previousStats.outboundBytes&&void 0!==this.previousStats.timestamp){const e=(l.bytesSent||0)-this.previousStats.outboundBytes,t=(l.timestamp||o.getTime())-this.previousStats.timestamp;if(t>0){const i=8*e*1e3/t;this.intervalBitrates.outbound.push(i)}}this.previousStats.outboundBytes=l.bytesSent}if(u){const e=this._getInboundAudioLevel(t,u);if(null!==e&&this.intervalAudioLevels.inbound.push(e),void 0!==u.jitter&&this.intervalJitters.push(1e3*u.jitter),void 0!==this.previousStats.inboundBytes&&void 0!==this.previousStats.timestamp){const e=(u.bytesReceived||0)-this.previousStats.inboundBytes,t=(u.timestamp||o.getTime())-this.previousStats.timestamp;if(t>0){const i=8*e*1e3/t;this.intervalBitrates.inbound.push(i)}}this.previousStats.inboundBytes=u.bytesReceived}h&&(void 0!==h.currentRoundTripTime&&this.intervalRTTs.push(h.currentRoundTripTime),null!==this.previousCandidatePairId&&h.id!==this.previousCandidatePairId&&ve.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairId,current:h.id}),this.previousCandidatePairId=null!==(i=h.id)&&void 0!==i?i:null),h&&(r=this._resolveCandidate(t,h.localCandidateId),a=this._resolveCandidate(t,h.remoteCandidateId)),l&&(c=this._getLocalAudioTrackSnapshot(),d=this._getOutboundAudioSourceStats(t,l)),this._logLocalAudioTrackSnapshot(c,d),this.previousStats.timestamp=o.getTime();const g=o.getTime()-this.intervalStartTime.getTime(),v=this._collectionIntervalFor(this.intervalStartTime);if(e||g>=v){const e=this._createStatsEntry(this.intervalStartTime,o,l,u,h,r,a,p,c,d);if(this.statsBuffer.push(e),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),ve.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this.onFlushNeeded&&!this._flushing){const e=this.statsBuffer.length,t=null!==(s=null===(n=this.logCollector)||void 0===n?void 0:n.getLogCount())&&void 0!==s?s:0;if(e>=ni.STATS_FLUSH_THRESHOLD||t>=ni.LOGS_FLUSH_THRESHOLD){ve.info("CallReportCollector: Approaching buffer limits, requesting flush",{statsIntervals:e,logEntries:t});try{this.onFlushNeeded()}catch(e){ve.error("CallReportCollector: onFlushNeeded callback error",{error:e})}}}this._checkQualityWarnings(e,u),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(e){ve.error("CallReportCollector: Error collecting stats",{error:e})}}))}_checkQualityWarnings(e,t){var i,n,s,o,r,a,c,d,l,u,h,p,g,v,m,f,_;if(!this.onWarning)return;const y=null===(i=e.connection)||void 0===i?void 0:i.roundTripTimeAvg,b=null===(s=null===(n=e.audio)||void 0===n?void 0:n.inbound)||void 0===s?void 0:s.jitterAvg;let S;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&&(S=n/s*100)}this._prevPacketsReceived=e,this._prevPacketsLost=i}if(this._trackBreach(D,void 0!==y&&y>ni.THRESHOLD_RTT_MS),this._trackBreach(P,void 0!==b&&b>ni.THRESHOLD_JITTER_MS),this._trackBreach(x,void 0!==S&&S>ni.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),void 0!==y&&void 0!==b&&void 0!==S){const e=93.2-.11*b-2.5*S-.01*(1e3*y),t=Math.max(1,Math.min(4.5,1+.035*e+e*(e-60)*(100-e)*7e-6));this._trackBreach(M,t<ni.THRESHOLD_MOS)}else this._trackBreach(M,!1);if(void 0!==(null===(c=null===(a=e.audio)||void 0===a?void 0:a.inbound)||void 0===c?void 0:c.bytesReceived)&&this.statsBuffer.length>1){const t=this.statsBuffer[this.statsBuffer.length-2],i=null!==(u=null===(l=null===(d=null==t?void 0:t.audio)||void 0===d?void 0:d.inbound)||void 0===l?void 0:l.bytesReceived)&&void 0!==u?u:0,n=null!==(h=e.audio.inbound.bytesReceived)&&void 0!==h?h:0;this._trackBreach(F,n-i==0)}if(void 0!==(null===(g=null===(p=e.audio)||void 0===p?void 0:p.outbound)||void 0===g?void 0:g.bytesSent)&&this.statsBuffer.length>1){const t=this.statsBuffer[this.statsBuffer.length-2],i=null!==(f=null===(m=null===(v=null==t?void 0:t.audio)||void 0===v?void 0:v.outbound)||void 0===m?void 0:m.bytesSent)&&void 0!==f?f:0,n=null!==(_=e.audio.outbound.bytesSent)&&void 0!==_?_:0;this._trackBreach(j,n-i==0)}}_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<=ni.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(U,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=ni.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(U)):this._trackBreach(U,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(U,!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}_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]>=ni.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const t=Date.now();t-(null!==(n=this._lastWarningEmitted[e])&&void 0!==n?n:0)>=ni.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=se(e);ve.warn(`CallReportCollector: warning ${i.code}: ${i.message}`),null===(t=this.onWarning)||void 0===t||t.call(this,i)}catch(t){ve.error(`CallReportCollector: Failed to emit warning ${e}`,{error:t})}}_createStatsEntry(e,t,i,n,s,o,r,a,c,d){const l={intervalStartUtc:e.toISOString(),intervalEndUtc:t.toISOString(),audio:{}};return i&&(l.audio.outbound=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}:{})),n&&(l.audio.inbound={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)}),s&&(l.connection={roundTripTimeAvg:this._average(this.intervalRTTs),packetsSent:s.packetsSent,packetsReceived:s.packetsReceived,bytesSent:s.bytesSent,bytesReceived:s.bytesReceived},l.ice=Object.assign(Object.assign({id:s.id,state:s.state,nominated:s.nominated,writable:s.writable,requestsSent:s.requestsSent,responsesReceived:s.responsesReceived},o?{local:o}:{}),r?{remote:r}:{})),a&&(l.transport=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}:{})),l}_resolveCandidate(e,t){if(!t)return void ve.debug("CallReportCollector: candidateId is empty, skipping resolve");const i=e.get(t);if(!i)return void ve.debug("CallReportCollector: candidate not found in stats report",{candidateId:t});const n={};if(void 0!==i.address&&(n.address=i.address),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),0!==Object.keys(n).length)return n;ve.debug("CallReportCollector: candidate report has no usable fields",{candidateId:t})}_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 ve.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,ve.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:[]}}}ni.INITIAL_COLLECTION_INTERVAL_MS=1e3,ni.INITIAL_COLLECTION_DURATION_MS=1e4,ni.STATS_FLUSH_THRESHOLD=300,ni.LOGS_FLUSH_THRESHOLD=800,ni.CONSECUTIVE_BREACHES_REQUIRED=3,ni.THRESHOLD_RTT_MS=.4,ni.THRESHOLD_JITTER_MS=30,ni.THRESHOLD_PACKET_LOSS_PCT=1,ni.THRESHOLD_MOS=3.5,ni.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,ni.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,ni.WARNING_THROTTLE_MS=15e3,ni.RETRY_DELAY_MS=500;var si,oi=le((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 C,I={},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&&C&&(navigator.mediaDevices.getUserMedia=C)}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."),C=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const e=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=function(){return e({constraints:arguments[0]}),C.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}.`),I[t]={},Object.keys(this.peerConnectionListeners).forEach((n=>{I[t][n]=this.peerConnectionListeners[n].bind(this,e,t,i),i.addEventListener(n,I[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){I[e.id]={};const i=this.getTrackEventObject(t);Object.keys(i).forEach((t=>{I[e.id][t]=i[t].bind(this),e.addEventListener(t,I[e.id][t])})),I[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 I){const t=this.getTrackEventObject();Object.keys(t).forEach((t=>{e.removeEventListener(t,I[e.id][t])})),clearInterval(I[e.id].readyState),delete I[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 I&&(Object.keys(this.peerConnectionListeners).forEach((i=>{t.removeEventListener(i,I[e][i],!1)})),delete I[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)}}}}));(si=oi)&&si.__esModule&&Object.prototype.hasOwnProperty.call(si,"default")&&si.default;var ri=oi.WebRTCStats;function ai(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 ci(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 di extends ct{constructor(e,t){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:t})}}class li extends ct{constructor(e,t){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:t})}}class ui extends ct{constructor(e,t){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:t})}}function hi(e,i){const n=a();let s=!1;const o=new ri({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),r=i=>t(this,void 0,void 0,(function*(){"stats"===i.event&&et(te.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=ai({jitter:1e3*h,rtt:1e3*p,packetsLost:v,packetsReceived:g});return{jitter:h,rtt:p,mos:m,quality:ci(m),inboundAudio:d.inbound[0],outboundAudio:d.outbound[0],remoteInboundAudio:u.inbound[0],remoteOutboundAudio:u.outbound[0]}}(i),e.uuid),yield e.execute(new ui(n,i))}));return{get isRunning(){return s},start:(a,c,d)=>t(this,void 0,void 0,(function*(){if(s)ve.debug(`[${i}] Stats reporter already running, skipping start`);else{yield e.execute(new di(n,i)),o.on("timeline",r);try{yield o.addConnection({pc:a,peerId:c,connectionId:d}),s=!0}catch(e){ve.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(et(te.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 li(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:Fe.conferenceUpdate,call:e.calls[s],canvasInfo:gi(o),currentLayerIdx:r};switch(i){case"layer-info":{const t=Object.assign({action:$e.LayerInfo},a);et(te.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:$e.LayoutInfo},a);et(te.Notification,t,e.uuid);break}}},gi=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Se(t)},vi=["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"],mi={"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 _i(e){try{const t=performance.getEntriesByName(e,"mark");return t.length>0?t[0].startTime:void 0}catch(e){return}}function yi(e){for(const t of vi)try{performance.clearMarks(fi(e,t))}catch(e){ve.warn("Clearing performance marks is failed")}}class bi{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._hadOfflineEvent=!1,this._offlineHandler=null,this.handleConnectionStateChange=()=>t(this,void 0,void 0,(function*(){const{connectionState:e}=this.instance;if(ve.info(`[${(new Date).toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${e}`),"failed"===e||"disconnected"===e){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){ve.error("Error gathering connection state details:",e)}return t}))}(this.instance,this._prevConnectionState).then((e=>{this.statsReporter.reportConnectionStateChange(e)}));const i=!this._hadOfflineEvent&&this._session.connected;this._restartedIceOnConnectionStateFailed||"failed"!==e&&"disconnected"!==e||!i||(this.isIceRestarting=!0,this._restartedIceOnConnectionStateFailed=!0,this.instance.restartIce(),this.iceDone=!1,this._iceRestartTimeoutId=setTimeout((()=>{this.isIceRestarting&&(ve.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null}),bi.ICE_RESTART_TIMEOUT_MS),ve.info(`ICE restart: peer ${e}, canRestartIceWithoutAttach=${i}. Creating new offer via Modify.`))}if("disconnected"===e){const e=se(H);et(te.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if("failed"===e){const t=se($);et(te.PeerConnectionFailureError,{warning:t,error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${e}`),sessionId:this._session.sessionid},this.options.id)}this._prevConnectionState=e,"connected"===e&&(performance.mark(fi(this.options.id,"dtls-connected")),this.tryCollectTimings(),this._restartedIceOnConnectionStateFailed=!1,this._hadOfflineEvent=!1),this._isTrickleIce()&&("connecting"===e&&performance.mark(fi(this.options.id,"peer-connection-connecting")),"connected"===e&&(this._clearIceGatheringSafetyTimeout(),performance.mark(fi(this.options.id,"peer-connection-connected"))))})),this._handleIceConnectionStateChange=()=>{const e=this.instance.iceConnectionState;ve.debug(`[${(new Date).toISOString()}] ICE Connection State`,e),"connected"===e&&performance.mark(fi(this.options.id,"ice-connected"))},this._handleIceGatheringStateChange=()=>{const e=this.instance.iceGatheringState;ve.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)},ve.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,"undefined"!=typeof window&&(this._offlineHandler=()=>{this._hadOfflineEvent=!0},window.addEventListener("offline",this._offlineHandler))}finishIceRestart(){this.isIceRestarting&&(this.isIceRestarting=!1,this._iceRestartTimeoutId&&(clearTimeout(this._iceRestartTimeoutId),this._iceRestartTimeoutId=null))}get isOffer(){return this.type===xe.Offer}get isAnswer(){return this.type===xe.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():this._createAnswer()}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))}))}_logTransceivers(){this.instance?(ve.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach(((e,t)=>{ve.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),ve.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))):ve.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(ve.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":et(te.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(ve.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){ve.info("Negotiation needed event"),"stable"!==this.instance.signalingState||this._negotiating?ve.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()&&!this.isIceRestarting?this.startTrickleIceNegotiation():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&&Dt(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=_i(fi(e,"new-call-start"));if(void 0===n)return{mode:t,direction:i,steps:[]};const s=[];for(const t of vi){if("new-call-start"===t)continue;const i=_i(fi(e,t));void 0!==i&&s.push({label:mi[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 ve.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+="-";ve.info(`${s} Call establishment timing breakdown:`),ve.info(`${s} ${c}`),ve.info(`${s} ${d}`),ve.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";ve.info(`${s} ${r(e.label,o)}${a(t,14)}${a(i,14)}`)}ve.info(`${s} ${d}`)}(i),yi(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:xe.Offer}),performance.mark(fi(this.options.id,"set-remote-description")),!this.instance))throw ce(C);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),et(te.Error,{error:ce(ae(e),e),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 ce(C);if(!this.options.localStream&&!i){throw ce(n?ae(n):f,null!=n?n:void 0)}performance.mark(fi(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&Lt(this.options.localStream)&&(ve.info("Muting local audio tracks on start"),Kt(this.options.localStream)),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=se(W);et(te.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if("complete"!==this.instance.iceGatheringState){const e=se(B);et(te.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}),bi.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 ce(C);this.isDebugEnabled&&(this.statsReporter=hi(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(Lt(i)){const e=i.getAudioTracks();let s=[...e];if(ve.info("Local audio tracks: ",e),"object"==typeof this.options.audio&&e.forEach((e=>{ve.info("Local audio tracks constraints: ",e.getConstraints())})),this.options.video){const t=i.getVideoTracks();s=[...e,...t],ve.info("Local video tracks: ",t),"object"==typeof this.options.video&&t.forEach((e=>{ve.info("Local video tracks constraints: ",e.getConstraints())}))}const{audioCodecs:o,videoCodecs:r}=ti(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&&Dt(t,i)}else if(this.options.receiveOnlyAudio&&"function"==typeof this.instance.addTransceiver){const e=this.instance.addTransceiver("audio",{direction:"recvonly"});ve.info("Added recvonly audio transceiver for receive-only mode",e);const{audioCodecs:t}=ti(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(),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);ve.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),ve.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){ve.error("Peer _createOffer error:",e);const t=ce(l,e);et(te.Error,{error:t,sessionId:this._session.sessionid},this.options.id)}}}))}_setRemoteDescription(e){return t(this,void 0,void 0,(function*(){ve.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(e){ve.error("Peer _setRemoteDescription error:",e);const t=ce(p,e);throw et(te.Error,{error:t,sessionId:this._session.sessionid},this.options.id),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 ve.debug("Skipping negotiation, state:",this.instance.signalingState),ve.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:xe.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){ve.error("Peer _createAnswer error:",e);const t=ce(u,e);et(te.Error,{error:t,sessionId:this._session.sessionid},this.options.id)}}}))}_setLocalDescription(e){return t(this,void 0,void 0,(function*(){try{yield this.instance.setLocalDescription(e)}catch(e){ve.error("Peer _setLocalDescription error:",e);const t=ce(h,e);throw et(te.Error,{error:t,sessionId:this._session.sessionid},this.options.id),e}}))}_sdpReady(){Ce(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return t(this,void 0,void 0,(function*(){if(Lt(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 Bt(t,o,Ge.AudioIn).catch((e=>null)),t&&("boolean"==typeof e&&(e={}),e.deviceId={exact:t})),s&&(s=yield Bt(s,r,Ge.Video).catch((e=>null)),s&&("boolean"==typeof n&&(n={}),n.deviceId={exact:s})),{audio:e,video:n}})));var i;return Ft(e)}))}_isOffer(){return this.type===xe.Offer}_isAnswer(){return this.type===xe.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 ve.info("RTC config",n),n}restartStatsReporter(){return t(this,void 0,void 0,(function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?ve.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(ve.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):ve.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))}))}close(){return t(this,void 0,void 0,(function*(){yi(this.options.id),this.finishIceRestart(),this._clearIceGatheringSafetyTimeout(),this._offlineHandler&&"undefined"!=typeof window&&(window.removeEventListener("offline",this._offlineHandler),this._offlineHandler=null),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)}))}}bi.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,bi.ICE_RESTART_TIMEOUT_MS=15e3;const Si=vt;class Ci{constructor(e,t){this.session=e,this._callReportCollector=null,this.id="",this.recoveredCallId="",this.state=Be[Be.New],this.prevState="",this.channels=[],this.role=We.Participant,this.extension=null,this._state=Be.New,this._prevState=Be.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._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({},He,{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._init(),this.options&&(this._ringtone=zt(this.options.ringtoneFile,"_ringtone"),this._ringback=zt(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!Jt(this.options.localStream)}invite(){return t(this,void 0,void 0,(function*(){this._creatingPeer=!0,this.direction=Me.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(fi(this.id,"new-peer")),this.peer=new bi(xe.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){ve.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const t=e instanceof oe?e:ce(L,e instanceof Error?e:void 0);return et(te.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;return t(this,void 0,void 0,(function*(){if(this._creatingPeer||(null===(i=this.peer)||void 0===i?void 0:i.instance)&&"closed"!==this.peer.instance.signalingState){const e=se(V);return et(te.Warning,{warning:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void ve.warn(`[${this.id}] answer() ignored: peer connection already exists or is being created (signalingState: ${null!==(o=null===(s=null===(n=this.peer)||void 0===n?void 0:n.instance)||void 0===s?void 0:s.signalingState)&&void 0!==o?o:"creating"})`)}if(this._registerInboundAnswerAttempt()){performance.mark(fi(this.id,"answer-called")),this._creatingPeer=!0,this.stopRingtone(),this.direction=Me.Inbound,(null===(r=null==e?void 0:e.customHeaders)||void 0===r?void 0:r.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 bi(xe.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){ve.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const t=e instanceof oe?e:ce(L,e instanceof Error?e:void 0);return et(te.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(){Zt(this._ringtone)}stopRingtone(){ei(this._ringtone)}playRingback(){Zt(this._ringback)}stopRingback(){ei(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<Be.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:[]],ve.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(Be.Recovering),void this._finalize();if(this.setState(Be.Hangup),this.stopRingtone(),this.stopRingback(),d){const e=new St({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});try{yield this._execute(e)}catch(e){ve.error("telnyx_rtc.bye failed!",e);const t=ce(b,e);et(te.Error,{error:t,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}ve.debug(`[${this.id}] Closing peer from hangup`),null===(c=this.peer)||void 0===c||c.close(),this.setState(Be.Destroy)}))}hold(){const e=new Et({sessid:this.session.sessionid,action:qe.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new Et({sessid:this.session.sessionid,action:qe.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new Et({sessid:this.session.sessionid,action:qe.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const t=new wt({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 wt({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(n)}muteAudio(){Kt(this.options.localStream)}unmuteAudio(){qt(this.options.localStream)}toggleAudioMute(){Yt(this.options.localStream)}setAudioInDevice(e,i=this.options.mutedMicOnStart){var n;return t(this,void 0,void 0,(function*(){const{instance:t}=this.peer,s=t.getSenders().find((({track:{kind:e}})=>"audio"===e));if(s){let t;try{t=yield Nt({audio:{deviceId:{exact:e}}})}catch(e){const t=ce(ae(e),e);return void et(te.MediaError,t,(null===(n=this.options)||void 0===n?void 0:n.id)||this.id)}const o=t.getAudioTracks()[0];o.enabled=!i,s.replaceTrack(o),this.options.micId=e;const{localStream:r}=this.options;r.getAudioTracks().forEach((e=>e.stop())),r.getVideoTracks().forEach((e=>t.addTrack(e))),this.options.localStream=t}}))}muteVideo(){var e;e=this.options.localStream,Vt(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Vt(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Vt(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 Nt({video:{deviceId:{exact:e}}}),n=t.getVideoTracks()[0];i.replaceTrack(n);const{localElement:s,localStream:o}=this.options;Dt(s,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t}}))}deaf(){Kt(this.options.remoteStream)}undeaf(){qt(this.options.remoteStream)}toggleDeaf(){Yt(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,i){return t(this,void 0,void 0,(function*(){if(!this||!this.peer)return void ve.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 ve.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"}]),ve.info("Parameters: ",t),ve.info("Setting max ","audio"===i?"audio":"video"," bandwidth to: ",e," [bps]"),t.encodings[0].maxBitrate=e,yield s.setParameters(t).then((()=>{ve.info("audio"===i?"New audio":"New video"," bandwidth settings in use: ",s.getParameters())})).catch((e=>ve.error(e)))}else ve.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")}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=Be[this._state].toLowerCase(),this.prevState=Be[this._prevState].toLowerCase(),ve.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:Fe.callUpdate,call:this}),e){case Be.Purge:ve.info(`[${this.id}] Entering Purge state.`);break;case Be.Active:performance.mark(fi(this.id,"call-active")),null===(t=this.peer)||void 0===t||t.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,ve.debug(`[${this.id}] Recovery complete, call is active`)),setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&xt(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);break;case Be.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:i}=e;switch(t){case Ue.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>=Be.Active)return;this._state>=Be.Early&&this.setState(Be.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case Ue.Media:if(performance.mark(fi(this.id,"telnyx-rtc-media")),this._state>=Be.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case Ue.Display:{const{display_name:e,display_number:n,display_direction:s}=i;this.extension=n;const o=s===Me.Inbound?Me.Outbound:Me.Inbound,r={type:Fe[t],call:this,displayName:e,displayNumber:n,displayDirection:o};et(te.Notification,r,this.id)||et(te.Notification,r,this.session.uuid);break}case Ue.Candidate:this._addIceCandidate(i);break;case Ue.Info:case Ue.Event:{const e=Object.assign(Object.assign({},i),{type:Fe.generic,call:this});et(te.Notification,e,this.id)||et(te.Notification,e,this.session.uuid);break}case Ue.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 Ue.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 ve.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:$e.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)},be(n[e][1])));this._dispatchConferenceUpdate({action:$e.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:$e.Add,callId:s,index:o},be(n)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:$e.Modify,callId:s,index:o},be(n)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:$e.Delete,callId:s,index:o},be(n)));break;case"clear":this._dispatchConferenceUpdate({action:$e.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:$e.ChatMessage,direction:t,participantNumber:i,participantName:n,messageText:s,messageType:o,messageId:e.eventSerno})}},i=yield this.session.vertoSubscribe(t).catch((e=>{ve.error("ConfChat subscription error:",e)}));$t(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 ve.error("Conference-Info unknown contentType",e)}},i=yield this.session.vertoSubscribe(t).catch((e=>{ve.error("ConfInfo subscription error:",e)}));$t(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(Be.Active):this.setState(Be.Held),!0}_handleChangeHoldStateError(e){ve.error(`Failed to ${e.action} on call ${this.id}`);const t=ce(_,e);return et(te.Error,{error:t,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e){const i=new Et({sessid:this.session.sessionid,action:qe.UpdateMedia,callID:this.options.id,sdp:e,dialogParams:this.options});ve.info("ICE restart: sending Modify with new offer SDP"),this._execute(i).then((e=>t(this,void 0,void 0,(function*(){var t;(null==e?void 0:e.sdp)?(ve.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;ve.error(e,t),null===(i=this.peer)||void 0===i||i.finishIceRestart();const n=ce(O,t);et(te.Error,{error:n,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onRemoteSdp(e){return t(this,void 0,void 0,(function*(){const i=new RTCSessionDescription({sdp:e,type:xe.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(Be.Early),this.gotAnswer&&this.setState(Be.Active)})).catch((e=>t(this,void 0,void 0,(function*(){ve.error("Call setRemoteDescription Error: ",e);const t=ce(p,e);et(te.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){ve.error("Error during hangup after setRemoteDescription failure:",e)}}))))}))}_requestAnotherLocalDescription(){Ce(this.peer.onSdpReadyTwice)?et(te.Error,{error:new Error("SDP without candidates for the second time!"),sessionId:this.session.sessionid},this.session.uuid):(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 ve.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:o,type:r}=e;if(-1===o.indexOf("candidate"))return ve.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),!J.test(o)){const e=se(G);ve.warn(`[${this.id}] Warning ${e.code}: ${e.message}`),et(te.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-${Si}`};if(null===(s=this.peer)||void 0===s?void 0:s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case xe.Offer:this.setState(Be.Requesting),a=new _t(c);break;case xe.Answer:this._isRecovering||this.setState(Be.Answering),a=!0===this.options.attach?new bt(c):new yt(c);break;default:return ve.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=>{const{node_id:t=null}=e;this._targetNodeId=t,r===xe.Offer?this.setState(Be.Trying):this.setState(Be.Active)})).catch((e=>t(this,void 0,void 0,(function*(){ve.error(`${this.id} - Sending ${r} error:`,e);const t=ce(g,e);et(te.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){ve.error("Error during hangup after SDP send failure:",e)}}))))}}_onTrickleIceSdp(e){var i;if(!e)return ve.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-${Si}`};if(null===(i=this.peer)||void 0===i?void 0:i.isIceRestarting)this._sendIceRestartModify(n);else{switch(s){case xe.Offer:this.setState(Be.Requesting),o=new _t(r);break;case xe.Answer:this._isRecovering||this.setState(Be.Answering),o=!0===this.options.attach?new bt(r):new yt(r);break;default:return ve.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=>{const{node_id:t=null}=e;this._targetNodeId=t,s===xe.Offer?this.setState(Be.Trying):this.setState(Be.Active)})).catch((e=>t(this,void 0,void 0,(function*(){ve.error(`${this.id} - Sending ${s} error:`,e);const t=ce(g,e);et(te.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){ve.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?(ve.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?(ve.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 Ct({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 ve.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((()=>{ve.debug("Successfully added ICE candidate:",e)})).catch((t=>{ve.error("Failed to add ICE candidate:",t,e)}))}_sendEndOfCandidates(){const e=new It({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,i;if(this.options.trickleIce&&!(null===(t=this.peer)||void 0===t?void 0:t.isIceRestarting))this._onTrickleIce(e);else{if(null===(i=this.peer)||void 0===i?void 0:i.iceDone)return;this._onIce(e)}},e.onicegatheringstatechange=t=>{ve.debug("ICE gathering state changed:",e.iceGatheringState,t),"complete"===e.iceGatheringState&&(ve.debug("Finished gathering candidates"),performance.mark(fi(this.id,"ice-gathering-completed")))},e.onicecandidateerror=t=>{var i;if(ve.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&&Dt(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:Fe.userMediaError,error:n,call:this,errorName:t,errorMessage:i}),ve.error(`Media error (${t}): ${i}`,e),et(te.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:Fe.peerConnectionFailureError,error:e.error}),ve.error("Peer connection failure error"),e.warning&&et(te.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:Fe.signalingStateClosed},e)),ve.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:Fe.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(et(te.Notification,e,this.id,!1)||et(te.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=se(q);return et(te.Warning,{warning:t,callId:this.id,activeCallId:e.id,sessionId:this.session.sessionid,activeSessionId:e.session.sessionid},this.session.uuid),ve.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===Me.Inbound))}_isBlockingInboundAnswer(){var e;if([Be.Hangup,Be.Destroy,Be.Purge].includes(this._state))return!1;const t=[Be.Answering,Be.Early,Be.Active,Be.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;const{id:i,userVariables:n,remoteCallerNumber:s,onNotification:o,recoveredCallId:r}=this.options;var c;this.options.id=i?i.toString():a(),this.id=this.options.id,r&&(this.recoveredCallId=r,this._isRecovering=!0),n&&(c=n,0!==Object.keys(c).length)||(this.options.userVariables=this.session.options.userVariables||{}),s||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Qe(te.MediaError,this._onMediaError,this.id),Qe(te.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Qe(te.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Ce(o)&&Qe(te.Notification,o.bind(this),this.id);const d=!1!==this.session.options.enableCallReports,l=this.session.options.callReportInterval||5e3,u=this.session.options.debugLogLevel||"debug",h=this.session.options.debugLogMaxEntries||1e3;d&&(this._callReportCollector=new ni({enabled:!0,interval:l},{enabled:!0,level:u,maxEntries:h}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=e=>{et(te.Warning,{warning:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}),this._isRecovering?this.setState(Be.Recovering):this.setState(Be.New),ve.info(`New Call — region: ${null!==(e=this.session.region)&&void 0!==e?e:"unknown"}, dc: ${null!==(t=this.session.dc)&&void 0!==t?t:"unknown"}`,this.options)}_finalize(){var e;this._stopStats(),yi(this.id),ve.debug(`[${this.id}] Closing peer from _finalize`),null===(e=this.peer)||void 0===e||e.close();const{remoteStream:t,localStream:i,remoteElement:n,localElement:s}=this.options;Ut(t),Ut(i),Pt(n,t),Pt(s,i),Ze(te.MediaError,null,this.id),Ze(te.PeerConnectionFailureError,null,this.id),Ze(te.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id],this._postCallReport().catch((e=>{ve.error("Unexpected error in _postCallReport",{error:e})}))}_flushIntermediateReport(){var e;if(!this._callReportCollector)return;const t=this.session.callReportId;if(!t)return void ve.debug("Cannot flush intermediate report: call_report_id not available");const i=null===(e=this.session.connection)||void 0===e?void 0:e.host;if(!i)return void ve.debug("Cannot flush intermediate report: connection host not available");const n={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===Me.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Si},s=this._callReportCollector.flush(n);if(!s)return;const o=De()||void 0;this._callReportCollector.sendPayload(s,t,i,o).catch((e=>{ve.error("Failed to post intermediate call report segment",{error:e})}))}_postCallReport(){var e;return t(this,void 0,void 0,(function*(){if(!this._callReportCollector)return void ve.warn("Call report collector not initialized");yield this._callReportCollector.stop();const t=this.session.callReportId;if(!t)return ve.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const i={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===Me.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Si},n=null===(e=this.session.connection)||void 0===e?void 0:e.host;if(!n)return void ve.error("Cannot post call report: connection host not available");const s=De()||void 0;this._callReportCollector.postReport(i,t,n,s).catch((e=>{ve.error("Failed to post call report",{error:e})})).finally((()=>{var e;null===(e=this._callReportCollector)||void 0===e||e.cleanup()}))}))}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),ve.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),ve.debug("Stats stopped")}}Ci.setStateTelnyx=e=>{if(e){switch(e._state){case Be.Recovering:e.state="recovering";break;case Be.Requesting:case Be.Trying:case Be.Early:e.state="connecting";break;case Be.Active:e.state="active";break;case Be.Held:e.state="held";break;case Be.Hangup:case Be.Destroy:e.state="done";break;case Be.Answering:e.state="ringing";break;case Be.New:e.state="new"}return e}};class Ii extends Ci{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,t)=>this.session.execute(new ii(e,t))}hangup(e={},i=!0){const n=Object.create(null,{hangup:{get:()=>super.hangup}});return t(this,void 0,void 0,(function*(){this.screenShare instanceof Ii&&(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 Ii(this.session,c),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){return t(this,void 0,void 0,(function*(){this.screenShare instanceof Ii&&(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)&&xt(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`)})))})),ve.info(t)}))),2e3)}}class Ei extends Ot{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()}get reconnectDelay(){return 1e3}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*(){e.connect.call(this)}))}checkPermissions(e=!0,i=!0){return t(this,void 0,void 0,(function*(){try{const t=yield Ft({audio:e,video:i});return Ut(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*(){ve.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(Be.Purge),ve.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*(){ve.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(Be.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(ze(te.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 jt().catch((e=>{const t=ce(ae(e),e);return et(te.MediaError,t,this.uuid),[]}))}getVideoDevices(){return jt(Ge.Video).catch((e=>(et(te.MediaError,e,this.uuid),[])))}getAudioInDevices(){return jt(Ge.AudioIn).catch((e=>{const t=ce(ae(e),e);return et(te.MediaError,t,this.uuid),[]}))}getAudioOutDevices(){return jt(Ge.AudioOut).catch((e=>(ve.error("getAudioOutDevices",e),et(te.MediaError,e,this.uuid),[])))}validateDeviceId(e,t,i){return Bt(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 Ft({video:{deviceId:{exact:e}}}),n=i.getVideoTracks()[0];for(let e=0;e<Ht.length;e++){const[i,s]=Ht[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 Ut(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 Wt(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 Bt(e,i,n).catch((e=>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?ee:Z}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=Ie(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=Ie(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 kt({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 Tt({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const s=yield this.execute(t),{unauthorized:o=[],subscribed:r=[]}=Gt(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 Rt({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const n=yield this.execute(t),{unsubscribed:s=[],notSubscribed:o=[]}=Gt(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&&(ve.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,ve.debug(`Network connectivity lost for session ${this.sessionid}`);const e=ce(N);et(te.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 Ii.setStateTelnyx(e)}}class wi{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 ft(e,t);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*ke(2,6)}handleMessage(e){var t,i,n,s,o,r,a,c,d;const{session:l}=this;l.setPingReceived();const{id:u,method:h,params:p={},voice_sdk_id:g}=e,v=null==p?void 0:p.callID,m=null==p?void 0:p.eventChannel,f=null==p?void 0:p.eventType,_=l.calls[v],y=null===(t=null==_?void 0:_.peer)||void 0===t?void 0:t.isConnectionHealthy();if(Array.isArray(null==p?void 0:p.reattached_sessions)&&0===p.reattached_sessions.length&&Object.keys(l.calls).length>0){const e=se(Y);et(te.Warning,{warning:e,sessionId:l.sessionid},l.uuid)}if("channelPvtData"===f)return this._handlePvtEvent(p.pvtData);const b=e=>{var t,i,n,s,o,r;const a={audio:!0,video:l.options.video,remoteSdp:p.sdp,destinationNumber:p.callee_id_number,remoteCallerName:p.caller_id_name,remoteCallerNumber:p.caller_id_number,callerName:p.callee_id_name,callerNumber:p.callee_id_number,attach:h===Ue.Attach,mediaSettings:p.mediaSettings,debug:null!==(t=l.options.debug)&&void 0!==t&&t,debugOutput:null!==(i=l.options.debugOutput)&&void 0!==i?i:"socket",trickleIce:null!==(n=l.options.trickleIce)&&void 0!==n&&n,prefetchIceCandidates:null===(s=l.options.prefetchIceCandidates)||void 0===s||s,forceRelayCandidate:null!==(o=l.options.forceRelayCandidate)&&void 0!==o&&o,keepConnectionAliveOnSocketClose:null!==(r=l.options.keepConnectionAliveOnSocketClose)&&void 0!==r&&r};v&&(a.id=v),p.telnyx_call_control_id&&(a.telnyxCallControlId=p.telnyx_call_control_id),p.telnyx_session_id&&(a.telnyxSessionId=p.telnyx_session_id),p.telnyx_leg_id&&(a.telnyxLegId=p.telnyx_leg_id),p.client_state&&(a.clientState=p.client_state),p.dialogParams&&p.dialogParams.custom_headers&&p.dialogParams.custom_headers.length&&(a.customHeaders=p.dialogParams.custom_headers),e&&(a.recoveredCallId=e),performance.mark(fi(a.id,"new-call-start"));const c=new Ii(l,a);return c.nodeId=this.nodeId,c},S=new ut(g),C=new pt(g);switch(h){case Ue.Answer:case Ue.Display:case Ue.Candidate:case Ue.Ringing:case Ue.Bye:case Ue.Media:if(!v||!_)return void ve.error(`Received ${h} for non existing call:`,p);_.handleMessage(e),this._ack(u,h);break;case Ue.Ping:this.session.setPingReceived(),this.session.execute(C);break;case Ue.Punt:l.options.keepConnectionAliveOnSocketClose&&y?(ve.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),l.socketDisconnect(),this._ack(u,h)):(ve.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),l.serverDisconnect());break;case Ue.Invite:{const e=b();e.direction=Me.Inbound,e.playRingtone(),e.setState(Be.Ringing),this._ack(u,h);break}case Ue.Attach:{if(!_){return b().answer(),void this._ack(u,h)}const e=_.id;ve.info(`[${(new Date).toISOString()}][${v}] closing existing call on ATTACH.`),_.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1),ve.info(`[${(new Date).toISOString()}][${v}] Attach: Creating new call for recovery (recoveredCallId: ${e})`);b(e).answer(),this._ack(u,h);break}case Ue.Event:case"webrtc.event":if(!m)return void ve.error("Verto received an unknown event:",p);const t=l.relayProtocol,g=m.split(".")[0];l._existsSubscription(t,m)?et(t,p,m):m===l.sessionid?this._handleSessionEvent(p.eventData):l._existsSubscription(t,g)?et(t,p,g):l.calls.hasOwnProperty(m)?l.calls[m].handleMessage(e):et(te.Notification,p,l.uuid);break;case Ue.Info:p.type=Fe.generic,et(te.Notification,p,l.uuid);break;case Ue.ClientReady:this.session.execute(S);break;default:{const t=Ae(e);if(t){switch(t){case Ve.REGISTER:case Ve.REGED:if(l.connection.previousGatewayState!==Ve.REGED&&l.connection.previousGatewayState!==Ve.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0,t===Ve.REGED&&this.session.resetReconnectAttempts();const u=null===(n=null===(i=null==e?void 0:e.result)||void 0===i?void 0:i.params)||void 0===n?void 0:n.call_report_id;u&&(l.callReportId=u,ve.debug("Captured call_report_id from REGED:",u));const h=null===(o=null===(s=null==e?void 0:e.result)||void 0===s?void 0:s.params)||void 0===o?void 0:o.dc;h&&(l.dc=h);const g=null===(a=null===(r=null==e?void 0:e.result)||void 0===r?void 0:r.params)||void 0===a?void 0:a.region;g&&(l.region=g),ve.info(`Connected to Telnyx — region: ${null!==(c=l.region)&&void 0!==c?c:"unknown"}, dc: ${null!==(d=l.dc)&&void 0!==d?d:"unknown"}`),p.type=Fe.vertoClientReady,et(te.Ready,p,l.uuid)}break;case Ve.UNREGED:case Ve.NOREG:if(this.retriedRegister+=1,5===this.retriedRegister){this.retriedRegister=0;const e=new wi("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),t=ce(T,e);et(te.Error,{error:t,sessionId:l.sessionid},l.uuid);break}setTimeout((()=>{this.session.execute(S)}),this.reconnectDelay());break;case Ve.FAILED:case Ve.FAIL_WAIT:if(l.connection.previousGatewayState!==Ve.FAILED&&l.connection.previousGatewayState!==Ve.FAIL_WAIT){const e=ce(k,new Error(`Gateway state: ${t}`));if(et(te.Error,{error:e,sessionId:l.sessionid},l.uuid),!this.session.hasAutoReconnect()){this.retriedConnect=0;const e=new wi("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),t=ce(w,e);et(te.Error,{error:t,sessionId:l.sessionid},l.uuid);break}if(this.retriedConnect+=1,5===this.retriedConnect){this.retriedConnect=0;const e=ce(45003,new Error("Connection Retry Failed"));et(te.Error,{error:e,sessionId:l.sessionid},l.uuid);break}setTimeout((()=>{if(ve.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){const e=Object.values(l.calls).some((e=>{var t;return(null===(t=e.peer)||void 0===t?void 0:t.instance)&&!e.signalingStateClosed}));if(e)return ve.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();ve.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:ve.warn("GatewayState message unknown method:",e)}break}ve.debug("Verto message unknown method:",e);break}}}_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=>{ve.error("liveArray subscription error:",e);const i=ce(S,e);et(te.Error,{error:i,sessionId:t.sessionid},t.uuid)}));$t(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:Fe.conferenceUpdate,action:$e.Leave,conferenceName:o,participantId:Number(d),role:l};et(te.Notification,i,n,!1)||et(te.Notification,i,t.uuid),null===e&&Ze(te.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=>{ve.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:Fe.conferenceUpdate,action:$e.LogoInfo,logo:e.logoURL};et(te.Notification,t,this.session.uuid);break}}}}class Ti extends Ei{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",(e=>{this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&(ve.info(`Hanging up call due to window unload: ${e}`),this.calls[e].hangup({initiator:"sdk:beforeunload"},!0))}))}))}validateOptions(){return Te(this.options)||Re(this.options)}newCall(e){if(!this.validateCallOptions(e)){throw ce(y,void 0,"Error: destinationNumber is required")}const t=new Ii(this,e);return 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!!Re(this.options)||Boolean(e.destinationNumber)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){return Te(this.options)?this.handleLoginOnSocketOpen():Re(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0}))}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class Ri extends Ti{constructor(e){super(e),ve.info(`SDK version: ${gt}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Xt()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Qt.full},{browserName:"Firefox",features:["audio"],supported:Qt.partial},{browserName:"Safari",supported:Qt.not_supported},{browserName:"Edge",supported:Qt.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Qt.not_supported},{browserName:"Firefox",supported:Qt.not_supported},{browserName:"Safari",features:["video","audio"],supported:Qt.full},{browserName:"Edge",supported:Qt.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Qt.full},{browserName:"Firefox",features:["audio"],supported:Qt.partial},{browserName:"Safari",supported:Qt.not_supported},{browserName:"Edge",supported:Qt.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Qt.full},{browserName:"Firefox",features:["audio"],supported:Qt.partial},{browserName:"Safari",features:["video","audio"],supported:Qt.full},{browserName:"Edge",features:["audio"],supported:Qt.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Qt.full},{browserName:"Firefox",features:["audio"],supported:Qt.partial},{browserName:"Safari",supported:Qt.not_supported},{browserName:"Edge",features:["audio"],supported:Qt.partial}]}]}}class Ai{static run(e){return t(this,void 0,void 0,(function*(){const t=Oe({}),i=Oe({}),n=new Ri(e.credentials);yield n.connect(),n.on(te.Ready,t.resolve),n.on(te.Error,t.reject),n.on(te.MediaError,t.reject),n.on(te.MediaError,t.reject),n.on(te.Notification,(e=>{e.call&&e.call.sipCode>=400&&i.reject(new Error(e.call.sipReason))})),Qe(te.StatsReport,(e=>{i.resolve(Ai.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,C=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,C+=o,_=Math.max(_,s),f=Math.min(f,s),S=Math.max(S,o),b=Math.min(b,o)}));const I=C/m,E=y/m,w=v[v.length-1],k=ai({jitter:1e3*E,rtt:1e3*I,packetsReceived:null!==(n=null===(i=null===(t=w.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=w.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:k,jitter:{average:E,max:_,min:f},rtt:{average:I,max:S,min:b},quality:ci(k)},sessionStats:{packetsSent:null!==(a=w.connection.packetsSent)&&void 0!==a?a:0,bytesSent:null!==(c=w.connection.bytesSent)&&void 0!==c?c:0,bytesReceived:null!==(d=w.connection.bytesReceived)&&void 0!==d?d:0,packetsLost:null!==(h=null===(u=null===(l=w.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=w.connection.packetsReceived)&&void 0!==p?p:0},iceCandidateStats:g}}getTelnyxIds(){return{telnyxCallControlId:"",telnyxSessionId:"",telnyxLegId:""}}}export{Ii as Call,je as ERROR_TYPE,Fe as NOTIFICATION_TYPE,Ai as PreCallDiagnosis,ie as SDK_ERRORS,ne as SDK_WARNINGS,te as SwEvent,c as TELNYX_ERROR_CODES,d as TELNYX_WARNING_CODES,oe as TelnyxError,Ri as TelnyxRTC,re as isMediaRecoveryErrorEvent};