@telnyx/webrtc 2.25.26-beta.4 → 2.26.1-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/bundle.js +1 -1
- package/lib/bundle.mjs +1 -1
- package/lib/{packages/js/src → src}/Modules/Verto/BaseSession.d.ts +9 -2
- package/lib/src/Modules/Verto/util/constants/errorCodes.d.ts +36 -0
- package/lib/src/Modules/Verto/util/constants/errors.d.ts +143 -0
- package/lib/{packages/js/src → src}/Modules/Verto/util/constants/index.d.ts +2 -0
- package/lib/src/Modules/Verto/util/constants/warnings.d.ts +103 -0
- package/lib/src/Modules/Verto/util/errors.d.ts +27 -0
- package/lib/{packages/js/src → src}/Modules/Verto/util/interfaces.d.ts +0 -1
- package/lib/{packages/js/src → src}/Modules/Verto/webrtc/BaseCall.d.ts +5 -4
- package/lib/{packages/js/src → src}/Modules/Verto/webrtc/Call.d.ts +2 -2
- package/lib/src/Modules/Verto/webrtc/CallEstablishmentTimings.d.ts +12 -0
- package/lib/{packages/js/src → src}/Modules/Verto/webrtc/CallReportCollector.d.ts +15 -0
- package/lib/{packages/js/src → src}/Modules/Verto/webrtc/Peer.d.ts +9 -1
- package/lib/{packages/js/src → src}/Modules/Verto/webrtc/VertoHandler.d.ts +0 -1
- package/lib/{packages/js/src → src}/Modules/Verto/webrtc/interfaces.d.ts +2 -3
- package/lib/{packages/js/src → src}/index.d.ts +2 -0
- package/package.json +3 -2
- package/lib/packages/js/src/Modules/Verto/webrtc/CandidateFilter.d.ts +0 -14
- /package/lib/{packages/js/src → src}/Modules/Verto/BrowserSession.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/index.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/messages/BaseMessage.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/messages/Verto.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/messages/WebRTCStats.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/messages/verto/AnonymousLogin.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/messages/verto/BaseRequest.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/messages/verto/ConverstationMessage.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/messages/verto/Gateway.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/messages/verto/Login.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/messages/verto/Ping.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/messages/verto/Result.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/services/Connection.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/services/Handler.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/services/RegisterAgent.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/util/LogCollector.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/util/debug.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/util/helpers.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/util/logger.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/util/reconnect.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/util/storage/index.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/util/storage/index.native.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/util/webrtc/index.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/util/webrtc/index.native.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/webrtc/Call.native.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/webrtc/ErrorResponse.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/webrtc/LayoutHandler.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/webrtc/constants.d.ts +0 -0
- /package/lib/{packages/js/src → src}/Modules/Verto/webrtc/helpers.d.ts +0 -0
- /package/lib/{packages/js/src → src}/PreCallDiagnosis.d.ts +0 -0
- /package/lib/{packages/js/src → src}/TelnyxRTC.d.ts +0 -0
- /package/lib/{packages/js/src → src}/utils/interfaces.d.ts +0 -0
- /package/lib/{packages/js/src → src}/utils/mos.d.ts +0 -0
- /package/lib/{packages/js/src → src}/utils/types.d.ts +0 -0
package/lib/bundle.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).TelnyxWebRTC={})}(this,(function(e){"use strict";function t(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 i(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 n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),s=new Uint8Array(16);function o(){if(!n)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return n(s)}for(var r=[],a=0;a<256;++a)r[a]=(a+256).toString(16).substr(1);function c(e,t,i){var n=t&&i||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var s=(e=e||{}).random||(e.rng||o)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var a=0;a<16;++a)t[n+a]=s[a];return t||function(e,t){var i=t||0,n=r;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("")}(s)}const d="wss://rtc.telnyx.com",l=1006,u={urls:"stun:stun.l.google.com:19302"},h=[{urls:"stun:stun.telnyx.com:3478"},u,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],p=[{urls:"stun:stundev.telnyx.com:3478"},u,{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 g;(g=e.SwEvent||(e.SwEvent={})).SocketOpen="telnyx.socket.open",g.SocketClose="telnyx.socket.close",g.SocketError="telnyx.socket.error",g.SocketMessage="telnyx.socket.message",g.SpeedTest="telnyx.internal.speedtest",g.Ready="telnyx.ready",g.Error="telnyx.error",g.Notification="telnyx.notification",g.StatsFrame="telnyx.stats.frame",g.StatsReport="telnyx.stats.report",g.Messages="telnyx.messages",g.Calls="telnyx.calls",g.MediaError="telnyx.rtc.mediaError",g.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError",g.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed";var v="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function f(e,t){return e(t={exports:{}},t.exports),t.exports}var m=f((function(e){var t,i;t=v,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 b={debug:0,info:1,warn:2,error:3};class _{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(b[e]<b[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 y=null;function S(){return y}function C(e){y=e}const w=m.getLogger("telnyx"),I={trace:0,debug:1,info:2,warn:3,error:4};let k=I.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 T=w.methodFactory;w.methodFactory=(e,t,i)=>{const n=T(e,t,i);return function(...t){if(I[e]>=k){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(const i of t)e.push(i);n(...e)}const i=S();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)}}},w.setLevel("debug",!1);const R=e=>{const[t,i,n,s,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){w.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},x=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},O=e=>e instanceof Function||"function"==typeof e,A=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,L=/^(ws|wss):\/\//,P=(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?P(a,r):{result:s}},N=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),D=({login:e,passwd:t,password:i,login_token:n})=>Boolean(e&&(t||i)||n),M=({anonymous_login:e})=>Boolean(e)&&Boolean(e.target_id)&&Boolean(e.target_type),j=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 U({debounceTime:e}){let t,i;return{promise:new Promise(((n,s)=>{t=e?$(n,e):n,i=s})),resolve:t,reject:i}}const $=(e,t)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout((()=>{e(...n)}),t)}},F="telnyx-voice-sdk-id";function B(){return sessionStorage.getItem(F)}var V,G,H;"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{sessionStorage.removeItem(F)})),function(e){e.Offer="offer",e.Answer="answer"}(V||(V={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(G||(G={})),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"}(H||(H={}));const q={generic:"event",[H.Display]:"participantData",[H.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},W={invalidCredentialsOptions:"InvalidCredentialsOptions"},J={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 K,Y,z,Q,X;!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"}(K||(K={})),function(e){e.Participant="participant",e.Moderator="moderator"}(Y||(Y={})),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"}(z||(z={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(Q||(Q={})),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"}(X||(X={}));const Z="GLOBAL",ee={},te=(e,t)=>`${e}|${t}`,ie=(e,t=Z)=>te(e,t)in ee,ne=(e,t,i=Z)=>{const n=te(e,i);n in ee||(ee[n]=[]),ee[n].push(t)},se=(e,t,i=Z)=>{const n=function(s){oe(e,n,i),t(s)};return n.prototype.targetRef=t,ne(e,n,i)},oe=(e,t,i=Z)=>{if(!ie(e,i))return!1;const n=te(e,i);if(O(t)){for(let e=ee[n].length-1;e>=0;e--){const i=ee[n][e];(t===i||i.prototype&&t===i.prototype.targetRef)&&ee[n].splice(e,1)}}else ee[n]=[];return 0===ee[n].length&&delete ee[n],!0},re=(e,t,i=Z,n=!0)=>{const s=n&&i!==Z;if(!ie(e,i))return s&&re(e,t),!1;const o=te(e,i),r=ee[o].length;if(!r)return s&&re(e,t),!1;for(let e=r-1;e>=0;e--)ee[o][e](t);return s&&re(e,t),!0},ae=e=>{const t=te(e,"");Object.keys(ee).filter((e=>0===e.indexOf(t))).forEach((e=>delete ee[e]))};let ce="undefined"!=typeof WebSocket?WebSocket:null;const de=0,le=1,ue=2,he=3;class pe{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=d,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":d),t&&(this._host=(e=>`${L.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===le}get connecting(){return!!this._wsClient&&this._wsClient.readyState===de}get closing(){return!!this._wsClient&&this._wsClient.readyState===ue}get closed(){return!!this._wsClient&&this._wsClient.readyState===he}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){const t=new URL(this._host);let i=B();this.session.options.rtcIp&&this.session.options.rtcPort&&(i=null,this._useCanaryRtcServer=!1,t.searchParams.set("rtc_ip",this.session.options.rtcIp),t.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),i&&t.searchParams.set("voice_sdk_id",i),this._useCanaryRtcServer&&(t.searchParams.set("canary","true"),i&&!this._hasCanaryBeenUsed&&(t.searchParams.delete("voice_sdk_id"),w.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0);try{this._wsClient=new ce(t.toString()),this._registerSocketEvents(this._wsClient)}catch(t){const i=t instanceof Error?t:new Error(`Failed to create WebSocket: ${String(t)}`);re(e.SwEvent.Error,{error:i},this.session.uuid),w.error("WebSocket connection failed:",i)}}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();se(i.id,(i=>{const{result:n,error:s}=P(i);return s?t(s):e(n)}))}));return w.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;O(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout((()=>this._handleCloseTimeout(e)),5e3))}_registerSocketEvents(t){t.onopen=t=>re(e.SwEvent.SocketOpen,t,this.session.uuid),t.onclose=i=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(t,"close"),re(e.SwEvent.SocketClose,i,this.session.uuid)),t.onerror=i=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(t,"error"),re(e.SwEvent.SocketError,{error:i,sessionId:this.session.sessionid},this.session.uuid)),t.onmessage=t=>{var i,n;const s=x(t.data);var o;if("string"!=typeof s){if(s.voice_sdk_id&&(o=s.voice_sdk_id,sessionStorage.setItem(F,o)),this._unsetTimer(s.id),w.debug("RECV: \n",JSON.stringify(s,null,2),"\n"),X[`${null===(n=null===(i=null==s?void 0:s.result)||void 0===i?void 0:i.params)||void 0===n?void 0:n.state}`]||!re(s.id,s)){const t=j(s);re(e.SwEvent.SocketMessage,s,this.session.uuid),Boolean(t)&&(this.previousGatewayState=t)}}else this._handleStringResponse(s)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(t){this._safetyTimeoutId=null,t&&t.readyState!==he?(w.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(t),this._safetyCleanupSocket(t,"timeout"),this._wsClient&&this._wsClient!==t||re(e.SwEvent.SocketClose,{code:l,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1},this.session.uuid)):w.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(w.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,t){this._wsClient===e?(w.debug(`Nulling socket reference (reason: ${t})`),this._wsClient=null):w.debug(`Skipping socket cleanup - old socket already replaced (reason: ${t})`)}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(t){if(/^#SP/.test(t))switch(t[3]){case"U":this.upDur=parseInt(t.substring(4));break;case"D":this.downDur=parseInt(t.substring(4)),re(e.SwEvent.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else w.warn("Unknown message from socket",t)}}class ge{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:c()},e)}}const ve={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 fe extends ge{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=t(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const e in ve)e&&i.hasOwnProperty(e)&&(i[ve[e]]=i[e],delete i[e]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class me extends fe{constructor(e){super(),this.method=H.GatewayState;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class be{constructor(e){this.pendingRequestId=null,this.onSocketMessage=e=>i(this,void 0,void 0,(function*(){e.id===this.pendingRequestId&&this.gatewayStateTask.resolve(j(e))})),this.getIsRegistered=()=>i(this,void 0,void 0,(function*(){const e=new me(B());this.pendingRequestId=e.request.id,this.gatewayStateTask=U({}),this.session.execute(e);const t=yield this.gatewayStateTask.promise;return!!t&&[X.REGISTER,X.REGED].includes(t)})),this.session=e,this.gatewayStateTask=U({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class _e extends fe{constructor(e){super(),this.method=H.Ping;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}var ye="2.25.26-beta.4",Se=ye;class Ce extends fe{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:Se,data:navigator.userAgent}};n&&(r.sessid=n),this.buildRequest({method:this.method,params:r})}}class we extends fe{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Ie extends fe{toString(){return H.Invite}}class ke extends fe{toString(){return H.Answer}}class Ee extends fe{toString(){return H.Attach}}class Te extends fe{toString(){return H.Bye}}class Re extends fe{toString(){return H.Candidate}}class xe extends fe{toString(){return H.EndOfCandidates}}class Oe extends fe{toString(){return H.Modify}}class Ae extends fe{toString(){return H.Info}}class Le extends fe{toString(){return H.Broadcast}}class Pe extends fe{toString(){return H.Subscribe}}class Ne extends fe{toString(){return H.Unsubscribe}}class De extends fe{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:Se,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 Me{constructor(e){if(this.options=e,this.uuid=c(),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.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var t,i;t=e.debug?"debug":"info",k=null!==(i=I[t])&&void 0!==i?i:I.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 pe(this),this.registerAgent=new be(this)}get __logger(){return w}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return i(this,void 0,void 0,(function*(){return this.registerAgent.getIsRegistered()}))}get reconnectDelay(){return 1e3*N(2,6)}execute(e){return this._idle?new Promise((t=>this._executeQueue.push({resolve:t,msg:e}))):this.connected?this.connection.send(e):new Promise((t=>{this._executeQueue.push({resolve:t,msg:e}),w.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 D(this.options)||M(this.options)}broadcast(e){}disconnect(){return i(this,void 0,void 0,(function*(){clearTimeout(this._reconnectTimeout),this.subscriptions={},this._autoReconnect=!1,this.relayProtocol=null,this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),w.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")}))}on(e,t){return ne(e,t,this.uuid),this}off(e,t){return oe(e,t,this.uuid),this}connect(){return i(this,void 0,void 0,(function*(){this.connection||(w.debug("No existing connection found, creating a new one."),this.connection=new pe(this)),this._attachListeners(),this._autoReconnect=!0,this.connection.isAlive||(w.debug("Initiating connection to the server..."),this.connection.connect()),w.debug("Connect method called. Connection initiated.")}))}_handleLoginError(t){re(e.SwEvent.Error,{error:t,sessionId:this.sessionid},this.uuid)}login({creds:t,onSuccess:n,onError:s}={}){return i(this,void 0,void 0,(function*(){if(this.connection&&this.connection.isAlive){if(t&&(void 0!==t.login&&(this.options.login=t.login),void 0!==t.password&&(this.options.password=t.password),void 0!==t.passwd&&(this.options.passwd=t.passwd),void 0!==t.login_token&&(this.options.login_token=t.login_token),void 0!==t.userVariables&&(this.options.userVariables=t.userVariables),void 0!==t.anonymous_login&&(this.options.anonymous_login=t.anonymous_login)),D(this.options))return this._login({type:"login",onSuccess:n,onError:s});if(M(this.options))return this._login({type:"anonymous_login",onSuccess:n,onError:s});{const t="Invalid login options provided for authentication.";return w.error(t),void re(e.SwEvent.Error,{error:new Error(t),type:W.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}}))}_login({type:e,onSuccess:t,onError:n}){return i(this,void 0,void 0,(function*(){let i;i="login"===e?new Ce(this.options.login,this.options.password||this.options.passwd,this.options.login_token,this.sessionid,this.options.userVariables,!!B()):new De({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:!!B()});const s=yield this.execute(i).catch((e=>{this._handleLoginError(e),n&&n(e)}));s&&(this.sessionid=s.sessid,t&&t())}))}_onSocketOpen(){return i(this,void 0,void 0,(function*(){}))}onNetworkClose(){this.relayProtocol&&ae(this.relayProtocol);for(const e in this.subscriptions)ae(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect&&(this._reconnectTimeout=setTimeout((()=>{w.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],oe(e,null,t)):(delete this.subscriptions[e],ae(e)))}_addSubscription(e,t=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},O(t)&&ne(e,t,i))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(e.SwEvent.SocketOpen,this._onSocketOpen),this.on(e.SwEvent.SocketClose,this.onNetworkClose),this.on(e.SwEvent.SocketError,this.onNetworkClose),this.on(e.SwEvent.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(e.SwEvent.SocketOpen,this._onSocketOpen),this.off(e.SwEvent.SocketClose,this.onNetworkClose),this.off(e.SwEvent.SocketError,this.onNetworkClose),this.off(e.SwEvent.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&&(w.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new _e(B()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout((()=>this._resetKeepAlive()),35e3)}setPingReceived(){w.debug("Ping received"),this._pong=!0}static on(e,t){ne(e,t)}static off(e){oe(e)}static uuid(){return c()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const je=e=>navigator.mediaDevices.getUserMedia(e),Ue=e=>e&&e instanceof MediaStream,$e=(e,t)=>{const i=A(e);null!==i&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=t)},Fe=(e,t)=>i(void 0,void 0,void 0,(function*(){const i=A(e);if(null===i)return w.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof t)return w.info(`Invalid speaker deviceId: '${t}'`),!1;try{return yield i.setSinkId(t),!0}catch(e){return!1}})),Be=e=>{e&&"live"===e.readyState&&e.stop()},Ve=e=>{Ue(e)&&e.getTracks().forEach(Be),e=null},Ge=e=>i(void 0,void 0,void 0,(function*(){w.info("RTCService.getUserMedia",e);const{audio:i,video:n}=e;if(!i&&!n)return null;try{return yield je(e)}catch(i){if(w.error("getUserMedia error: ",i),(e=>"NotReadableError"===e.name||"NotFoundError"===e.name||"OverconstrainedError"===e.name)(i)){const n=(e=>{const{audio:i,video:n}=e;let s=!1,o=i,r=n;if("object"==typeof i&&null!==i&&"deviceId"in i){s=!0;const e=t(i,["deviceId"]);o=0===Object.keys(e).length||e}if("object"==typeof n&&null!==n&&"deviceId"in n){s=!0;const e=t(n,["deviceId"]);r=0===Object.keys(e).length||e}return s?{audio:o,video:r}:null})(e);if(n){w.warn("Device not found or not readable, falling back to default device");try{return yield je(n)}catch(e){throw w.error("Fallback getUserMedia also failed: ",e),i}}}throw i}})),He=(e=null,t=!1)=>i(void 0,void 0,void 0,(function*(){let i=[];const n=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===Q.AudioIn||e===Q.AudioOut,video:!e||e===Q.Video}))(e)).catch((e=>(w.error(e),null)));if(n){if(Ve(n),i=yield navigator.mediaDevices.enumerateDevices(),e&&(i=i.filter((t=>t.kind===e))),!0===t)return i;const s=[];i=i.filter((e=>{if(!e.groupId)return!0;const t=`${e.kind}-${e.groupId}`;return!s.includes(t)&&(s.push(t),!0)}))}return i})),qe=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],We=(e,t,n)=>i(void 0,void 0,void 0,(function*(){const i=yield He(n,!0);for(let n=0;n<i.length;n++){const{deviceId:s,label:o}=i[n];if(e===s||t===o)return s}return null})),Je=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((i=>{t.hasOwnProperty(i)&&null!==e[i]&&void 0!==e[i]||delete e[i]}))},Ke=(e,t)=>{if(!e)return!1;const{subscribed:i,alreadySubscribed:n}=Ye(e);return i.includes(t)||n.includes(t)},Ye=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((i=>{t[i]=e[`${i}Channels`]||[]})),t},ze=(e,t=null,i=null)=>{if(!Ue(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}}))},Qe=e=>{ze(e,"audio",!0)},Xe=e=>{ze(e,"audio",!1)},Ze=e=>{ze(e,"audio",null)},et=e=>((e,t=null)=>{if(!Ue(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 tt(){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:!!Ge}}catch(e){return e.message}}var it;function nt(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 st(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then((()=>{e._playFulfilled=!0})).catch((t=>{w.error("playAudio",t),e._playFulfilled=!0})))}function ot(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"}(it||(it={}));const rt=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 at extends ge{constructor(e,t){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:c(),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 ct{constructor(e,t){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._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 _(e)}(this.logCollectorOptions),this.logCollector.start(),C(this.logCollector))}start(e){var t,i;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,w.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,t;return i(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 i=null!==(t=null===(e=this.logCollector)||void 0===e?void 0:e.getLogCount())&&void 0!==t?t:0;this.logCollector&&this.logCollector.stop(),w.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:i,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 w.info("CallReportCollector: Flushed intermediate segment",{segment:n,intervals:s.length,logEntries:o.length,callId:e.callId}),a}finally{this._flushing=!1}}postReport(e,t,n,s){var o,r;return i(this,void 0,void 0,(function*(){const i=null===(o=this.logCollector)||void 0===o?void 0:o.getLogs(),a=i&&i.length>0;if(!this.options.enabled)return void w.info("CallReportCollector: Skipping report — call reports disabled");if(0===this.statsBuffer.length&&!a)return void w.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},i&&i.length>0?{logs:i}:{}),c?{segment:d}:{});yield this._sendPayload(l,t,n,s)}))}sendPayload(e,t,n,s){return i(this,void 0,void 0,(function*(){yield this._sendPayload(e,t,n,s)}))}_sendPayload(e,t,n,s){var o,r;return i(this,void 0,void 0,(function*(){try{const i=new URL(n),a=`${i.protocol.replace(/^ws/,"http")}//${i.host}/call_report`,c=void 0!==e.segment&&!e.summary.endTimestamp?`intermediate segment ${e.segment}`:"final report";w.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":t,"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)w.info(`CallReportCollector: Successfully posted ${c}`);else{const e=yield h.text();w.error(`CallReportCollector: Failed to post ${c}`,{status:h.status,error:e})}}catch(i){w.warn(`CallReportCollector: Network error posting call report, retrying in ${ct.RETRY_DELAY_MS}ms`,{error:i}),yield new Promise((e=>setTimeout(e,ct.RETRY_DELAY_MS)));try{const i=new URL(n),o=`${i.protocol.replace(/^ws/,"http")}//${i.host}/call_report`,r={"Content-Type":"application/json","x-call-report-id":t,"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)w.info("CallReportCollector: Successfully posted call report on retry");else{const e=yield a.text();w.error("CallReportCollector: Failed to post call report on retry",{status:a.status,error:e})}}catch(e){w.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.logCollector&&(this.logCollector.clear(),S()===this.logCollector&&C(null),this.logCollector=null)}_collectStats(e=!1){var t,n,s;return i(this,void 0,void 0,(function*(){if(this.peerConnection&&this.intervalStartTime)try{const i=yield this.peerConnection.getStats(),o=new Date;let r,a,c=null,d=null,l=null,u=null;if(i.forEach((e=>{switch(e.type){case"outbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(c=e);break;case"inbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(d=e);break;case"candidate-pair":(e.nominated||"succeeded"===e.state)&&(l=e);break;case"transport":u=e}})),c){const e=this._getOutboundAudioLevel(i,c);if(null!==e&&this.intervalAudioLevels.outbound.push(e),void 0!==this.previousStats.outboundBytes&&void 0!==this.previousStats.timestamp){const e=(c.bytesSent||0)-this.previousStats.outboundBytes,t=(c.timestamp||o.getTime())-this.previousStats.timestamp;if(t>0){const i=8*e*1e3/t;this.intervalBitrates.outbound.push(i)}}this.previousStats.outboundBytes=c.bytesSent}if(d){const e=this._getInboundAudioLevel(i,d);if(null!==e&&this.intervalAudioLevels.inbound.push(e),void 0!==d.jitter&&this.intervalJitters.push(1e3*d.jitter),void 0!==this.previousStats.inboundBytes&&void 0!==this.previousStats.timestamp){const e=(d.bytesReceived||0)-this.previousStats.inboundBytes,t=(d.timestamp||o.getTime())-this.previousStats.timestamp;if(t>0){const i=8*e*1e3/t;this.intervalBitrates.inbound.push(i)}}this.previousStats.inboundBytes=d.bytesReceived}l&&(void 0!==l.currentRoundTripTime&&this.intervalRTTs.push(l.currentRoundTripTime),null!==this.previousCandidatePairId&&l.id!==this.previousCandidatePairId&&w.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairId,current:l.id}),this.previousCandidatePairId=null!==(t=l.id)&&void 0!==t?t:null),l&&(r=this._resolveCandidate(i,l.localCandidateId),a=this._resolveCandidate(i,l.remoteCandidateId)),this.previousStats.timestamp=o.getTime();const h=o.getTime()-this.intervalStartTime.getTime();if(e||h>=this.options.interval){const e=this._createStatsEntry(this.intervalStartTime,o,c,d,l,r,a,u);if(this.statsBuffer.push(e),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),w.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>=ct.STATS_FLUSH_THRESHOLD||t>=ct.LOGS_FLUSH_THRESHOLD){w.info("CallReportCollector: Approaching buffer limits, requesting flush",{statsIntervals:e,logEntries:t});try{this.onFlushNeeded()}catch(e){w.error("CallReportCollector: onFlushNeeded callback error",{error:e})}}}this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(e){w.error("CallReportCollector: Error collecting stats",{error:e})}}))}_createStatsEntry(e,t,i,n,s,o,r,a){const c={intervalStartUtc:e.toISOString(),intervalEndUtc:t.toISOString(),audio:{}};return i&&(c.audio.outbound={packetsSent:i.packetsSent,bytesSent:i.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)}),n&&(c.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&&(c.connection={roundTripTimeAvg:this._average(this.intervalRTTs),packetsSent:s.packetsSent,packetsReceived:s.packetsReceived,bytesSent:s.bytesSent,bytesReceived:s.bytesReceived},c.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&&(c.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}:{})),c}_resolveCandidate(e,t){if(!t)return void w.debug("CallReportCollector: candidateId is empty, skipping resolve");const i=e.get(t);if(!i)return void w.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;w.debug("CallReportCollector: candidate report has no usable fields",{candidateId:t})}_getOutboundAudioLevel(e,t){let i;if(t.mediaSourceId&&(i=e.get(t.mediaSourceId)),i||e.forEach((e=>{i||"media-source"!==e.type||"audio"!==e.kind||(i=e)})),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:[]}}}ct.STATS_FLUSH_THRESHOLD=300,ct.LOGS_FLUSH_THRESHOLD=800,ct.RETRY_DELAY_MS=500;var dt,lt=f((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 b(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 _(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 y(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=b(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=b(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=b(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=_(e,i,"bytesReceived"),e.packetRate=_(e,i,"packetsReceived")})),e.audio.outbound.map((e=>{let i=t.audio.outbound.find((t=>t.id===e.id));e.bitrate=_(e,i,"bytesSent"),e.packetRate=_(e,i,"packetsSent")})),e.video.inbound.map((e=>{let i=t.video.inbound.find((t=>t.id===e.id));e.bitrate=_(e,i,"bytesReceived"),e.packetRate=_(e,i,"packetsReceived")})),e.video.outbound.map((e=>{let i=t.video.outbound.find((t=>t.id===e.id));e.bitrate=_(e,i,"bytesSent"),e.packetRate=_(e,i,"packetsSent")})),e):e}(n,t),n}let C,w={},I=[];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(),I.forEach((e=>{this.removeTrackEventListeners(e)})),I=[],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=y(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}.`),w[t]={},Object.keys(this.peerConnectionListeners).forEach((n=>{w[t][n]=this.peerConnectionListeners[n].bind(this,e,t,i),i.addEventListener(n,w[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),I.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){w[e.id]={};const i=this.getTrackEventObject(t);Object.keys(i).forEach((t=>{w[e.id][t]=i[t].bind(this),e.addEventListener(t,w[e.id][t])})),w[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 w){const t=this.getTrackEventObject();Object.keys(t).forEach((t=>{e.removeEventListener(t,w[e.id][t])})),clearInterval(w[e.id].readyState),delete w[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 w&&(Object.keys(this.peerConnectionListeners).forEach((i=>{t.removeEventListener(i,w[e][i],!1)})),delete w[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)}}}}));(dt=lt)&&dt.__esModule&&Object.prototype.hasOwnProperty.call(dt,"default")&&dt.default;var ut=lt.WebRTCStats;function ht(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 pt(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 gt extends ge{constructor(e,t){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:t})}}class vt extends ge{constructor(e,t){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:t})}}class ft extends ge{constructor(e,t){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:t})}}function mt(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}}function bt(t,n){const s=c();let o=!1;const r=new ut({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),a=n=>i(this,void 0,void 0,(function*(){"stats"===n.event&&re(e.SwEvent.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=ht({jitter:1e3*h,rtt:1e3*p,packetsLost:v,packetsReceived:g});return{jitter:h,rtt:p,mos:f,quality:pt(f),inboundAudio:d.inbound[0],outboundAudio:d.outbound[0],remoteInboundAudio:u.inbound[0],remoteOutboundAudio:u.outbound[0]}}(n),t.uuid),yield t.execute(new ft(s,n))}));return{get isRunning(){return o},start:(e,c,d)=>i(this,void 0,void 0,(function*(){if(o)w.debug(`[${n}] Stats reporter already running, skipping start`);else{yield t.execute(new gt(s,n)),r.on("timeline",a);try{yield r.addConnection({pc:e,peerId:c,connectionId:d}),o=!0}catch(e){w.error(`[${n}] Failed to start stats reporter:`,e),r.removeAllPeers(),r.destroy()}}})),stop:a=>i(this,void 0,void 0,(function*(){const i=r.getTimeline();if(re(e.SwEvent.StatsReport,i,t.uuid),"file"===a){!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)}(i,`webrtc-stats-${s}-${Date.now()}`)}yield t.execute(new vt(s,n)),r.removeAllPeers(),r.destroy(),o=!1})),reportConnectionStateChange:e=>{const t={event:"connectionstatechange-detailed",tag:"connection",timestamp:(new Date).toISOString(),data:e};a(t)},reportIceCandidateError:e=>{const t={event:"icecandidateerror-detailed",tag:"connection",timestamp:(new Date).toISOString(),data:e};a(t)}}}const _t=(t,i)=>{const{contentType:n,canvasType:s,callID:o,canvasInfo:r=null,currentLayerIdx:a=-1}=i;r&&"mcu-personal-canvas"!==s&&delete r.memberID;const c={type:q.conferenceUpdate,call:t.calls[o],canvasInfo:yt(r),currentLayerIdx:a};switch(n){case"layer-info":{const i=Object.assign({action:z.LayerInfo},c);re(e.SwEvent.Notification,i,t.uuid);break}case"layout-info":{const i=Object.assign({action:z.LayoutInfo},c);re(e.SwEvent.Notification,i,t.uuid);break}}},yt=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return x(t)};class St{constructor(t,n,s,o,r){this.type=t,this.options=n,this.onSdpReadyTwice=null,this.statsReporter=null,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this.handleConnectionStateChange=()=>i(this,void 0,void 0,(function*(){const{connectionState:t}=this.instance;if(w.info(`[${(new Date).toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${t}`),"failed"===t||"disconnected"===t){const e=()=>i(this,void 0,void 0,(function*(){if(this.isDebugEnabled&&this.statsReporter){const e=yield function(e,t){return i(this,void 0,void 0,(function*(){const i={connectionState:e.connectionState,previousConnectionState:t,iceConnectionState:e.iceConnectionState,iceGatheringState:e.iceGatheringState,signalingState:e.signalingState},n=e.getTransceivers();if(n.length>0){const e=n[0].sender,t=null==e?void 0:e.transport;t&&(i.dtlsState=t.state)}e.sctp&&(i.sctpState=e.sctp.state);try{const t=yield e.getStats();t.forEach((e=>{"candidate-pair"===e.type&&"succeeded"===e.state&&(i.candidatePairState=e.state,t.forEach((t=>{"local-candidate"===t.type&&t.id===e.localCandidateId&&(i.localCandidateType=t.candidateType,i.selectedCandidatePair=i.selectedCandidatePair||{local:{},remote:{}},i.selectedCandidatePair.local={address:t.address,port:t.port,protocol:t.protocol,candidateType:t.candidateType}),"remote-candidate"===t.type&&t.id===e.remoteCandidateId&&(i.remoteCandidateType=t.candidateType,i.selectedCandidatePair=i.selectedCandidatePair||{local:{},remote:{}},i.selectedCandidatePair.remote={address:t.address,port:t.port,protocol:t.protocol,candidateType:t.candidateType})}))),"transport"===e.type&&(i.dtlsCipher=e.dtlsCipher,i.srtpCipher=e.srtpCipher,i.tlsVersion=e.tlsVersion,e.dtlsState&&(i.dtlsState=e.dtlsState))}))}catch(e){w.error("Error gathering connection state details:",e)}return i}))}(this.instance,this._prevConnectionState);this.statsReporter.reportConnectionStateChange(e)}window.removeEventListener("online",e)}));navigator.onLine?e():window.addEventListener("online",e)}"failed"===t&&re(e.SwEvent.PeerConnectionFailureError,{error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${t}`),sessionId:this._session.sessionid},this.options.id),this._prevConnectionState=t,this._isTrickleIce()&&("connecting"===t&&performance.mark("peer-connection-connecting"),"connected"===t&&(performance.mark("peer-connection-connected"),console.group("Performance Metrics"),console.table(this.trickleIcePerformanceMetrics),console.groupEnd(),performance.clearMarks()))})),this._handleIceConnectionStateChange=()=>{w.debug(`[${(new Date).toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=()=>{w.debug(`[${(new Date).toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setCodecs=(e,t)=>{if(e.setCodecPreferences)return e.setCodecPreferences(t)},w.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!n.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=s,this._trickleIceSdpFn=o,this._registerPeerEvents=r}get isOffer(){return this.type===V.Offer}get isAnswer(){return this.type===V.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("ice-gathering-start"),this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}startTrickleIceNegotiation(){return i(this,void 0,void 0,(function*(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))}))}_logTransceivers(){this.instance?(w.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach(((e,t)=>{w.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),w.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))):w.warn("Cannot log transceivers: peer connection is null")}get trickleIcePerformanceMetrics(){const e=performance.measure("new-call","new-call-start","new-call-end"),t=performance.measure("peer-creation","peer-creation-start","peer-creation-end"),i=performance.measure("ice-gathering","ice-gathering-start","ice-gathering-end"),n=performance.measure("sdp-send","sdp-send-start","sdp-send-end"),s=performance.measure("invite-send","new-call-start","sdp-send-start"),o=performance.measure("total-duration","peer-creation-start","sdp-send-end"),r=e=>`${e.toFixed(2)}ms`;return{"New Call":{duration:r(e.duration)},"Peer Creation":{duration:r(t.duration)},"ICE Gathering":{duration:r(i.duration)},[this._isOffer()?"Invite Send":"Answer Send"]:{duration:r(s.duration)},"SDP Send":{duration:r(n.duration)},"Total Duration":{duration:r(o.duration)}}}handleSignalingStateChangeEvent(){switch(w.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":re(e.SwEvent.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(w.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){w.info("Negotiation needed event"),"stable"!==this.instance.signalingState||this._negotiating?w.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation():this.startNegotiation()}handleTrackEvent(e){const{streams:[t]}=e,{remoteElement:i,screenShare:n}=this.options;this.options.remoteStream=t,!1===n&&$e(i,this.options.remoteStream)}createPeerConnection(){return i(this,void 0,void 0,(function*(){var t;this.instance=(t=this._config(),new window.RTCPeerConnection(t)),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:V.Offer})),this.options.localStream=yield this._retrieveLocalStream().catch((t=>(re(e.SwEvent.MediaError,t,this.options.id),null))),this.options.mutedMicOnStart&&Ue(this.options.localStream)&&(w.info("Muting local audio tracks on start"),Xe(this.options.localStream)),this.options.localStream||(w.warn("No local media stream available"),!this.options.audio)?performance.mark("peer-creation-end"):w.warn("Audio is required but no local stream — skipping negotiation")}))}init(){var e;return i(this,void 0,void 0,(function*(){yield this.createPeerConnection(),this.isDebugEnabled&&(this.statsReporter=bt(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(Ue(i)){const e=i.getAudioTracks();let s=[...e];if(w.info("Local audio tracks: ",e),"object"==typeof this.options.audio&&e.forEach((e=>{w.info("Local audio tracks constraints: ",e.getConstraints())})),this.options.video){const t=i.getVideoTracks();s=[...e,...t],w.info("Local video tracks: ",t),"object"==typeof this.options.video&&t.forEach((e=>{w.info("Local video tracks constraints: ",e.getConstraints())}))}const{audioCodecs:o,videoCodecs:r}=rt(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&&$e(t,i)}else if(this.options.receiveOnlyAudio&&"function"==typeof this.instance.addTransceiver){const e=this.instance.addTransceiver("audio",{direction:"recvonly"});w.info("Added recvonly audio transceiver for receive-only mode",e);const{audioCodecs:t}=rt(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);w.info("Add transceiver",e,t)}}_createOffer(){return i(this,void 0,void 0,(function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=!1!==this.options.audio||Boolean(this.options.receiveOnlyAudio),this._constraints.offerToReceiveVideo=Boolean(this.options.video),w.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return yield this._setLocalDescription(e),this._isTrickleIce()||this._sdpReady(),e}catch(e){w.error("Peer _createOffer error:",e)}}}))}_setRemoteDescription(e){return i(this,void 0,void 0,(function*(){w.debug("Setting remote description",e),yield this.instance.setRemoteDescription(e)}))}_createAnswer(){return i(this,void 0,void 0,(function*(){if(this._isAnswer()){if("stable"!==this.instance.signalingState&&"have-remote-offer"!==this.instance.signalingState)return w.debug("Skipping negotiation, state:",this.instance.signalingState),w.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:V.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return yield this._setLocalDescription(e),e}catch(e){w.error("Peer _createAnswer error:",e)}}}))}_setLocalDescription(e){return i(this,void 0,void 0,(function*(){yield this.instance.setLocalDescription(e)}))}_sdpReady(){O(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return i(this,void 0,void 0,(function*(){if(Ue(this.options.localStream))return this.options.localStream;const e=yield(t=this.options,i(void 0,void 0,void 0,(function*(){let{audio:e=!0,micId:i,video:n=!1,camId:s}=t;const{micLabel:o="",camLabel:r=""}=t;return i&&(i=yield We(i,o,Q.AudioIn).catch((e=>null)),i&&("boolean"==typeof e&&(e={}),e.deviceId={exact:i})),s&&(s=yield We(s,r,Q.Video).catch((e=>null)),s&&("boolean"==typeof n&&(n={}),n.deviceId={exact:s})),{audio:e,video:n}})));var t;return Ge(e)}))}_isOffer(){return this.type===V.Offer}_isAnswer(){return this.type===V.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 w.info("RTC config",n),n}restartStatsReporter(){return i(this,void 0,void 0,(function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?w.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(w.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):w.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))}))}close(){return i(this,void 0,void 0,(function*(){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)}))}}class Ct{constructor(e,t,i){this._lockedInterface=null,this._filteredCount=0,this._passedCount=0,this._enabled=e,this._onCandidate=t,this._onEndOfCandidates=i}add(e){if(!e.candidate||!e.candidate.candidate)return this._enabled&&this._filteredCount>0&&w.info(`[CandidateFilter] Gathering complete. Passed: ${this._passedCount}, Filtered: ${this._filteredCount}, Locked interface: ${this._lockedInterface}`),void this._onEndOfCandidates();if(!this._enabled)return void this._onCandidate(e.candidate);const t=e.candidate.candidate;if(t.includes("typ host"))return void this._onCandidate(e.candidate);if(this._isTcpCandidate(t))return;const i=this._extractRaddr(t),n=this._extractNetworkId(t),s=i&&"0.0.0.0"!==i?i:n;if(!s)return this._passedCount++,void this._onCandidate(e.candidate);this._lockedInterface||(this._lockedInterface=s,w.info(`[CandidateFilter] Locked to interface: ${s}`)),s===this._lockedInterface?(this._passedCount++,this._onCandidate(e.candidate)):(this._filteredCount++,w.debug(`[CandidateFilter] Dropped candidate from ${s} (locked: ${this._lockedInterface}): ${t}`))}reset(){this._lockedInterface=null,this._filteredCount=0,this._passedCount=0}_extractRaddr(e){const t=e.match(/raddr (\S+)/);return t?t[1]:null}_extractNetworkId(e){const t=e.match(/network-id (\d+)/);return t?`network-id:${t[1]}`:null}_isTcpCandidate(e){const t=e.split(" ");return t.length>2&&"tcp"===t[2].toLowerCase()}}const wt=Se;class It{constructor(e,t){this.session=e,this._callReportCollector=null,this.id="",this.recoveredCallId="",this.state=K[K.New],this.prevState="",this.channels=[],this.role=Y.Participant,this.extension=null,this._state=K.New,this._prevState=K.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._iceDone=!1,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!1,this._isRecovering=!1,this._candidateFilter=null,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({},J,{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,singleInterfaceIce:l.singleInterfaceIce,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._registerTrickleIcePeerEvents=this._registerTrickleIcePeerEvents.bind(this),this._init(),this.options&&(this._ringtone=nt(this.options.ringtoneFile,"_ringtone"),this._ringback=nt(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}get performanceMetrics(){const e=performance.measure("peer-creation","peer-creation-start","peer-creation-end"),t=performance.measure("ice-gathering","ice-gathering-start","ice-gathering-end"),i=performance.measure("sdp-send","sdp-send-start","sdp-send-end"),n=performance.measure("total-duration","peer-creation-start","sdp-send-end"),s=e=>`${e.toFixed(2)}ms`;return{"Peer Creation":{duration:s(e.duration)},"ICE Gathering":{duration:s(t.duration)},"SDP Send":{duration:s(i.duration)},"Total Duration":{duration:s(n.duration)}}}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!et(this.options.localStream)}invite(){return i(this,void 0,void 0,(function*(){this._creatingPeer=!0,this.direction=G.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new St(V.Offer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),this._creatingPeer=!1}))}answer(e={}){var t;return i(this,void 0,void 0,(function*(){this._creatingPeer=!0,performance.mark("new-call-start"),this.stopRingtone(),this.direction=G.Inbound,(null===(t=null==e?void 0:e.customHeaders)||void 0===t?void 0:t.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new St(V.Answer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),performance.mark("new-call-end"),this._creatingPeer=!1}))}playRingtone(){st(this._ringtone)}stopRingtone(){ot(this._ringtone)}playRingback(){st(this._ringback)}stopRingback(){ot(this._ringback)}hangup(t,i){var n,s,o;const r=t||{},a=!1!==i,c=this._state<K.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=r.cause||c.cause,this.causeCode=r.causeCode||c.causeCode,this.sipCode=r.sipCode||null,this.sipReason=r.sipReason||null,this.sipCallId=r.sip_call_id||null,this.options.customHeaders=[...null!==(n=this.options.customHeaders)&&void 0!==n?n:[],...null!==(o=null===(s=null==r?void 0:r.dialogParams)||void 0===s?void 0:s.customHeaders)&&void 0!==o?o:[]],r.isRecovering)return this._isRecovering=!0,this.setState(K.Recovering),void this._finalize();this.setState(K.Hangup);const d=()=>{var e;w.debug(`[${this.id}] Closing peer from hangup`),null===(e=this.peer)||void 0===e||e.close(),this.setState(K.Destroy)};if(this.stopRingtone(),this.stopRingback(),a){const t=new Te({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});this._execute(t).catch((t=>{w.error("telnyx_rtc.bye failed!",t),re(e.SwEvent.Error,{error:t,sessionId:this.session.sessionid},this.session.uuid)})).then(d.bind(this))}else d()}hold(){const e=new Oe({sessid:this.session.sessionid,action:"hold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new Oe({sessid:this.session.sessionid,action:"unhold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new Oe({sessid:this.session.sessionid,action:"toggleHold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const t=new Ae({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 Ae({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(n)}muteAudio(){Xe(this.options.localStream)}unmuteAudio(){Qe(this.options.localStream)}toggleAudioMute(){Ze(this.options.localStream)}setAudioInDevice(e,t=this.options.mutedMicOnStart){return i(this,void 0,void 0,(function*(){const{instance:i}=this.peer,n=i.getSenders().find((({track:{kind:e}})=>"audio"===e));if(n){const i=yield je({audio:{deviceId:{exact:e}}}),s=i.getAudioTracks()[0];s.enabled=!t,n.replaceTrack(s),this.options.micId=e;const{localStream:o}=this.options;o.getAudioTracks().forEach((e=>e.stop())),o.getVideoTracks().forEach((e=>i.addTrack(e))),this.options.localStream=i}}))}muteVideo(){var e;e=this.options.localStream,ze(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,ze(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,ze(e,"video",null)}setVideoDevice(e){return i(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 je({video:{deviceId:{exact:e}}}),n=t.getVideoTracks()[0];i.replaceTrack(n);const{localElement:s,localStream:o}=this.options;$e(s,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t}}))}deaf(){Xe(this.options.remoteStream)}undeaf(){Qe(this.options.remoteStream)}toggleDeaf(){Ze(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,t){return i(this,void 0,void 0,(function*(){if(!this||!this.peer)return void w.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:i}=this.peer,n=i.getSenders();if(!n)return void w.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===t));if(s){const i=s.getParameters();i.encodings||(i.encodings=[{rid:"h"}]),w.info("Parameters: ",i),w.info("Setting max ","audio"===t?"audio":"video"," bandwidth to: ",e," [bps]"),i.encodings[0].maxBitrate=e,yield s.setParameters(i).then((()=>{w.info("audio"===t?"New audio":"New video"," bandwidth settings in use: ",s.getParameters())})).catch((e=>w.error(e)))}else w.error("Could not set bandwidth (reason: no "+t+" 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;switch(this._prevState=this._state,this._state=e,this.state=K[this._state].toLowerCase(),this.prevState=K[this._prevState].toLowerCase(),w.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:q.callUpdate,call:this}),e){case K.Purge:w.debug(`Call ${this.id} hangup call due to purge state`),this.hangup({cause:"PURGE",causeCode:1},!1);break;case K.Active:this._isRecovering&&(this._isRecovering=!1,w.debug(`[${this.id}] Recovery complete, call is active`)),setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&Fe(e,t)}),0),this._callReportCollector&&(null===(t=this.peer)||void 0===t?void 0:t.instance)&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance);break;case K.Destroy:this._finalize()}}handleMessage(t){const{method:i,params:n}=t;switch(i){case H.Answer:if(this.gotAnswer=!0,n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id),this._state>=K.Active)return;this._state>=K.Early&&this.setState(K.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case H.Media:if(this._state>=K.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case H.Display:{const{display_name:t,display_number:s,display_direction:o}=n;this.extension=s;const r=o===G.Inbound?G.Outbound:G.Inbound,a={type:q[i],call:this,displayName:t,displayNumber:s,displayDirection:r};re(e.SwEvent.Notification,a,this.id)||re(e.SwEvent.Notification,a,this.session.uuid);break}case H.Candidate:this._addIceCandidate(n);break;case H.Info:case H.Event:{const t=Object.assign(Object.assign({},n),{type:q.generic,call:this});re(e.SwEvent.Notification,t,this.id)||re(e.SwEvent.Notification,t,this.session.uuid);break}case H.Ringing:this.playRingback(),n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id);break;case H.Bye:const t=n.client_state||n.clientState;t&&(this.options.clientState=t),this.stopRingback(),this.stopRingtone(),this.hangup(n,!1)}}handleConferenceUpdate(e,t){return i(this,void 0,void 0,(function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==t.laName)return w.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:i,data:n,hashKey:s=String(this._lastSerno),arrIndex:o}=e;switch(i){case"bootObj":{this._lastSerno=0;const{chatChannel:e,infoChannel:i,modChannel:s,laName:o,conferenceMemberID:r,role:a}=t;this._dispatchConferenceUpdate({action:z.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),i&&(yield this._subscribeConferenceInfo(i));const c=[];for(const e in n)c.push(Object.assign({callId:n[e][0],index:Number(e)},R(n[e][1])));this._dispatchConferenceUpdate({action:z.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:z.Add,callId:s,index:o},R(n)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:z.Modify,callId:s,index:o},R(n)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:z.Delete,callId:s,index:o},R(n)));break;case"clear":this._dispatchConferenceUpdate({action:z.Clear});break;default:this._dispatchConferenceUpdate({action:i,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 i(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:z.ChatMessage,direction:t,participantNumber:i,participantName:n,messageText:s,messageType:o,messageId:e.eventSerno})}},i=yield this.session.vertoSubscribe(t).catch((e=>{w.error("ConfChat subscription error:",e)}));Ke(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 i(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,_t(this.session,t);else w.error("Conference-Info unknown contentType",e)}},i=yield this.session.vertoSubscribe(t).catch((e=>{w.error("ConfInfo subscription error:",e)}));Ke(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(K.Active):this.setState(K.Held),!0}_handleChangeHoldStateError(e){return w.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){return i(this,void 0,void 0,(function*(){const t=new RTCSessionDescription({sdp:e,type:V.Answer});yield this.peer.instance.setRemoteDescription(t).then((()=>{this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(K.Early),this.gotAnswer&&this.setState(K.Active)})).catch((e=>{w.error("Call setRemoteDescription Error: ",e),this.hangup({cause:"USER_BUSY",causeCode:17},!0)}))}))}_requestAnotherLocalDescription(){O(this.peer.onSdpReadyTwice)?re(e.SwEvent.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._iceDone=!1,this.peer.startNegotiation())}_onIceSdp(e){var t,i;this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:n,type:s}=e;if(-1===n.indexOf("candidate"))return w.info("No candidate - retry \n"),void this._requestAnotherLocalDescription();null===(i=null===(t=this.peer)||void 0===t?void 0:t.instance)||void 0===i||i.removeEventListener("icecandidate",this._onIce),performance.mark("ice-gathering-end");let o=null;const r={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,"User-Agent":`Web-${wt}`};switch(s){case V.Offer:this.setState(K.Requesting),o=new Ie(r);break;case V.Answer:this._isRecovering||this.setState(K.Answering),o=!0===this.options.attach?new Ee(r):new ke(r);break;default:return w.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(o).then((e=>{const{node_id:t=null}=e;this._targetNodeId=t,s===V.Offer?this.setState(K.Trying):this.setState(K.Active)})).catch((e=>{w.error(`${this.id} - Sending ${s} error:`,e),this.hangup({cause:"USER_BUSY",causeCode:17},!0)})).finally((()=>{performance.mark("sdp-send-end"),console.group("Performance Metrics"),console.table(this.performanceMetrics),console.groupEnd(),performance.clearMarks()}))}_onTrickleIceSdp(e){if(!e)return w.error("No SDP data provided"),this.hangup({},!1);const{sdp:t,type:i}=e;let n=null;const s={sessid:this.session.sessionid,sdp:t,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${wt}`};switch(i){case V.Offer:this.setState(K.Requesting),n=new Ie(s);break;case V.Answer:this._isRecovering||this.setState(K.Answering),n=!0===this.options.attach?new Ee(s):new ke(s);break;default:return w.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(n).then((e=>{const{node_id:t=null}=e;this._targetNodeId=t,i===V.Offer?this.setState(K.Trying):this.setState(K.Active)})).catch((e=>{w.error(`${this.id} - Sending ${i} error:`,e),this.hangup({cause:"USER_BUSY",causeCode:17},!0)})).finally((()=>{performance.mark("sdp-send-end")}))}_onIce(e){const{instance:t}=this.peer;if(null===this._iceTimeout){const e=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout((()=>this._onIceSdp(t.localDescription)),e)}e.candidate?w.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(t.localDescription)}_onTrickleIce(e){e.candidate&&e.candidate.candidate?(w.debug("RTCPeer Candidate:",e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const t=new Re({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 w.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((()=>{w.debug("Successfully added ICE candidate:",e)})).catch((t=>{w.error("Failed to add ICE candidate:",t,e)}))}_sendEndOfCandidates(){const e=new xe({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e),performance.mark("ice-gathering-end")}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._candidateFilter&&this._candidateFilter.reset()}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach((e=>{this._addIceCandidateToPeer(e)}))}_registerPeerEvents(e){this._iceDone=!1,e.onicecandidate=e=>{this._iceDone||this._onIce(e)},e.onicecandidateerror=t=>{var i;if(w.debug("ICE candidate error:",t),null===(i=this.peer)||void 0===i?void 0:i.statsReporter){const i=mt(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&&$e(t,i)}))}_registerTrickleIcePeerEvents(e){this._candidateFilter=new Ct(!0===this.options.singleInterfaceIce,(e=>this._sendIceCandidate(e)),(()=>this._sendEndOfCandidates())),e.onicecandidate=e=>{this._candidateFilter.add(e)},e.onicegatheringstatechange=t=>{w.debug("ICE gathering state changed:",e.iceGatheringState),"complete"===e.iceGatheringState&&w.debug("Finished gathering candidates")},e.onicecandidateerror=t=>{var i;if(w.debug("ICE candidate error:",t),null===(i=this.peer)||void 0===i?void 0:i.statsReporter){const i=mt(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&&$e(t,i)}))}_onMediaError(e){const t=(null==e?void 0:e.name)||"UnknownError",i=(null==e?void 0:e.message)||"Unknown media error";this._dispatchNotification({type:q.userMediaError,error:e,call:this,errorName:t,errorMessage:i}),w.error(`Media error (${t}): ${i}`,e),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:q.peerConnectionFailureError,error:e}),w.error("Peer connection failure error")}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:q.signalingStateClosed},e)),w.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:q.conferenceUpdate,call:this},e))}_dispatchNotification(t){!0!==this.options.screenShare&&(re(e.SwEvent.Notification,t,this.id,!1)||re(e.SwEvent.Notification,t,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){const{id:t,userVariables:i,remoteCallerNumber:n,onNotification:s,recoveredCallId:o}=this.options;var r;this.options.id=t?t.toString():c(),this.id=this.options.id,o&&(this.recoveredCallId=o,this._isRecovering=!0),i&&(r=i,0!==Object.keys(r).length)||(this.options.userVariables=this.session.options.userVariables||{}),n||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,ne(e.SwEvent.MediaError,this._onMediaError,this.id),ne(e.SwEvent.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),ne(e.SwEvent.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),O(s)&&ne(e.SwEvent.Notification,s.bind(this),this.id);const a=!1!==this.session.options.enableCallReports,d=this.session.options.callReportInterval||5e3,l=this.session.options.debugLogLevel||"debug",u=this.session.options.debugLogMaxEntries||1e3;a&&(this._callReportCollector=new ct({enabled:!0,interval:d},{enabled:!0,level:l,maxEntries:u}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()}),this._isRecovering?this.setState(K.Recovering):this.setState(K.New),w.info("New Call with Options:",this.options)}_finalize(){var t;this._stopStats(),w.debug(`[${this.id}] Closing peer from _finalize`),null===(t=this.peer)||void 0===t||t.close();const{remoteStream:i,localStream:n}=this.options;Ve(i),Ve(n),oe(e.SwEvent.MediaError,null,this.id),oe(e.SwEvent.PeerConnectionFailureError,null,this.id),oe(e.SwEvent.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id],this._postCallReport().catch((e=>{w.error("Unexpected error in _postCallReport",{error:e})}))}_flushIntermediateReport(){var e;if(!this._callReportCollector)return;const t=this.session.callReportId;if(!t)return void w.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 w.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===G.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:wt},s=this._callReportCollector.flush(n);if(!s)return;const o=B()||void 0;this._callReportCollector.sendPayload(s,t,i,o).catch((e=>{w.error("Failed to post intermediate call report segment",{error:e})}))}_postCallReport(){var e;return i(this,void 0,void 0,(function*(){if(!this._callReportCollector)return void w.warn("Call report collector not initialized");yield this._callReportCollector.stop();const t=this.session.callReportId;if(!t)return w.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===G.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:wt},n=null===(e=this.session.connection)||void 0===e?void 0:e.host;if(!n)return void w.error("Cannot post call report: connection host not available");const s=B()||void 0;this._callReportCollector.postReport(i,t,n,s).catch((e=>{w.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),w.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),w.debug("Stats stopped")}}It.setStateTelnyx=e=>{if(e){switch(e._state){case K.Recovering:e.state="recovering";break;case K.Requesting:case K.Trying:case K.Early:e.state="connecting";break;case K.Active:e.state="active";break;case K.Held:e.state="held";break;case K.Hangup:case K.Destroy:e.state="done";break;case K.Answering:e.state="ringing";break;case K.New:e.state="new"}return e}};class kt extends It{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,t)=>this.session.execute(new at(e,t))}hangup(e={},t=!0){this.screenShare instanceof kt&&this.screenShare.hangup(e,t),super.hangup(e,t)}startScreenShare(e){return i(this,void 0,void 0,(function*(){const t=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;t.getTracks().forEach((e=>{e.addEventListener("ended",(()=>{this.screenShare&&this.screenShare.hangup()}))}));const{remoteCallerName:n,remoteCallerNumber:s,callerName:o,callerNumber:r}=this.options,a=Object.assign({screenShare:!0,localStream:t,destinationNumber:`${this.extension}-screen`,remoteCallerName:n,remoteCallerNumber:`${s}-screen`,callerName:`${o} (Screen)`,callerNumber:`${r} (Screen)`},e);return this.screenShare=new kt(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof kt&&this.screenShare.hangup()}setAudioOutDevice(e){return i(this,void 0,void 0,(function*(){this.options.speakerId=e;const{remoteElement:t,speakerId:i}=this.options;return!(!t||!i)&&Fe(t,i)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval((()=>i(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`)})))})),w.info(t)}))),2e3)}}class Et extends Me{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 i(this,void 0,void 0,(function*(){return e.getIsRegistered.call(this)}))}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return i(this,void 0,void 0,(function*(){e.connect.call(this)}))}checkPermissions(e=!0,t=!0){return i(this,void 0,void 0,(function*(){try{const i=yield Ge({audio:e,video:t});return Ve(i),!0}catch(e){return!1}}))}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return i(this,void 0,void 0,(function*(){Object.keys(this.calls).forEach((e=>this.calls[e].setState(K.Purge))),this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)}))}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(t){return new Promise(((i,n)=>{if(se(e.SwEvent.SpeedTest,(e=>{const{upDur:n,downDur:s}=e,o=s?8*t/(s/1e3)/1024:0;i({upDur:n,downDur:s,upKps:(n?8*t/(n/1e3)/1024:0).toFixed(0),downKps:o.toFixed(0)})}),this.uuid),!(t=Number(t)))return n(`Invalid parameter 'bytes': ${t}`);this.executeRaw(`#SPU ${t}`);let s=t/1024;t%1024&&s++;const o=".".repeat(1024);for(let e=0;e<s;e++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")}))}getDevices(){return He().catch((t=>(re(e.SwEvent.MediaError,t,this.uuid),[])))}getVideoDevices(){return He(Q.Video).catch((t=>(re(e.SwEvent.MediaError,t,this.uuid),[])))}getAudioInDevices(){return He(Q.AudioIn).catch((t=>(re(e.SwEvent.MediaError,t,this.uuid),[])))}getAudioOutDevices(){return He(Q.AudioOut).catch((t=>(w.error("getAudioOutDevices",t),re(e.SwEvent.MediaError,t,this.uuid),[])))}validateDeviceId(e,t,i){return We(e,t,i)}getDeviceResolutions(e){return i(this,void 0,void 0,(function*(){try{return yield(e=>i(void 0,void 0,void 0,(function*(){const t=[],i=yield Ge({video:{deviceId:{exact:e}}}),n=i.getVideoTracks()[0];for(let e=0;e<qe.length;e++){const[i,s]=qe[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 Ve(i),t})))(e)}catch(e){throw e}}))}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return i(this,void 0,void 0,(function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:s}=e,o=t(e,["micId","micLabel"]);return Je(o),this._audioConstraints=yield((e,t,n,s)=>i(void 0,void 0,void 0,(function*(){const{deviceId:i}=s;if(void 0===i&&(e||t)){const i=yield We(e,t,n).catch((e=>null));i&&(s.deviceId={exact:i})}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?p:h}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=A(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=A(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 Le({sessid:this.sessionid,eventChannel:t,data:i});e&&(n.targetNodeId=e),this.execute(n).catch((e=>e))}vertoSubscribe({nodeId:e,channels:t=[],handler:n}){return i(this,void 0,void 0,(function*(){if(!(t=t.filter((e=>e&&!this._existsSubscription(this.relayProtocol,e)))).length)return{};const i=new Pe({sessid:this.sessionid,eventChannel:t});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unauthorized:o=[],subscribed:r=[]}=Ye(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:t=[]}){return i(this,void 0,void 0,(function*(){if(!(t=t.filter((e=>e&&this._existsSubscription(this.relayProtocol,e)))).length)return{};const i=new Ne({sessid:this.sessionid,eventChannel:t});e&&(i.targetNodeId=e);const n=yield this.execute(i),{unsubscribed:s=[],notSubscribed:o=[]}=Ye(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&&(w.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,w.debug(`Network connectivity lost for session ${this.sessionid}`)},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 kt.setStateTelnyx(e)}}class Tt{constructor(e,t){this.code=t,this.message=e}}class Rt{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0,this.receivedAuthenticationRequired=0}_ack(e,t){const i=new we(e,t);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*N(2,6)}handleMessage(t){var n,s,o;const{session:r}=this,{id:a,method:c,params:d={},voice_sdk_id:l}=t,u=null==d?void 0:d.callID,h=null==d?void 0:d.eventChannel,p=null==d?void 0:d.eventType,g=r.calls[u],v=null===(n=null==g?void 0:g.peer)||void 0===n?void 0:n.isConnectionHealthy();if("channelPvtData"===p)return this._handlePvtEvent(d.pvtData);const f=e=>{var t,i,n,s,o,a;const l={audio:!0,video:r.options.video,remoteSdp:d.sdp,destinationNumber:d.callee_id_number,remoteCallerName:d.caller_id_name,remoteCallerNumber:d.caller_id_number,callerName:d.callee_id_name,callerNumber:d.callee_id_number,attach:c===H.Attach,mediaSettings:d.mediaSettings,debug:null!==(t=r.options.debug)&&void 0!==t&&t,debugOutput:null!==(i=r.options.debugOutput)&&void 0!==i?i:"socket",trickleIce:c!==H.Attach&&(null!==(n=r.options.trickleIce)&&void 0!==n&&n),prefetchIceCandidates:null===(s=r.options.prefetchIceCandidates)||void 0===s||s,forceRelayCandidate:null!==(o=r.options.forceRelayCandidate)&&void 0!==o&&o,keepConnectionAliveOnSocketClose:null!==(a=r.options.keepConnectionAliveOnSocketClose)&&void 0!==a&&a};u&&(l.id=u),d.telnyx_call_control_id&&(l.telnyxCallControlId=d.telnyx_call_control_id),d.telnyx_session_id&&(l.telnyxSessionId=d.telnyx_session_id),d.telnyx_leg_id&&(l.telnyxLegId=d.telnyx_leg_id),d.client_state&&(l.clientState=d.client_state),d.dialogParams&&d.dialogParams.custom_headers&&d.dialogParams.custom_headers.length&&(l.customHeaders=d.dialogParams.custom_headers),e&&(l.recoveredCallId=e);const h=new kt(r,l);return h.nodeId=this.nodeId,h},m=new me(l),b=new _e(l);switch(c){case H.Answer:case H.Display:case H.Candidate:case H.Ringing:case H.Bye:case H.Media:if(!u||!g)return void w.error(`Received ${c} for non existing call:`,d);g.handleMessage(t),this._ack(a,c);break;case H.Ping:this.session.setPingReceived(),this.session.execute(b).then((()=>{this.receivedAuthenticationRequired=0})).catch((e=>i(this,void 0,void 0,(function*(){e.code===this.session.authenticationRequiredErrorCode&&this.receivedAuthenticationRequired>=0&&(this.receivedAuthenticationRequired+=1,this.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(w.warn("Ping failed twice with Authentication Required. Re-logging in..."),this.session.login(),this.receivedAuthenticationRequired=-1))}))));break;case H.Punt:r.options.keepConnectionAliveOnSocketClose&&v?(w.info(`[${(new Date).toISOString()}][${u}] keeping session calls alive due to PUNT and keepConnectionAliveOnSocketClose. Disconnecting base session...`),r.socketDisconnect(),this._ack(a,c)):r.disconnect();break;case H.Invite:{const e=f();e.direction=G.Inbound,e.playRingtone(),e.setState(K.Ringing),this._ack(a,c);break}case H.Attach:{if(!g){return f().answer(),void this._ack(a,c)}const e=g.id;w.info(`[${(new Date).toISOString()}][${u}] closing existing call on ATTACH.`),g.hangup({isRecovering:!0},!1),w.info(`[${(new Date).toISOString()}][${u}] Attach: Creating new call for recovery (recoveredCallId: ${e})`);f(e).answer(),this._ack(a,c);break}case H.Event:case"webrtc.event":if(!h)return void w.error("Verto received an unknown event:",d);const n=r.relayProtocol,l=h.split(".")[0];r._existsSubscription(n,h)?re(n,d,h):h===r.sessionid?this._handleSessionEvent(d.eventData):r._existsSubscription(n,l)?re(n,d,l):r.calls.hasOwnProperty(h)?r.calls[h].handleMessage(t):re(e.SwEvent.Notification,d,r.uuid);break;case H.Info:d.type=q.generic,re(e.SwEvent.Notification,d,r.uuid);break;case H.ClientReady:this.session.execute(m);break;default:{const i=j(t);if(i){switch(i){case X.REGISTER:case X.REGED:if(r.connection.previousGatewayState!==X.REGED&&r.connection.previousGatewayState!==X.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0;const i=null===(o=null===(s=null==t?void 0:t.result)||void 0===s?void 0:s.params)||void 0===o?void 0:o.call_report_id;i&&(r.callReportId=i,w.debug("Captured call_report_id from REGED:",i)),d.type=q.vertoClientReady,re(e.SwEvent.Ready,d,r.uuid)}break;case X.UNREGED:case X.NOREG:if(this.retriedRegister+=1,5===this.retriedRegister){this.retriedRegister=0,re(e.SwEvent.Error,{error:new Tt("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:r.sessionid},r.uuid);break}setTimeout((()=>{this.session.execute(m)}),this.reconnectDelay());break;case X.FAILED:case X.FAIL_WAIT:if(r.connection.previousGatewayState!==X.FAILED&&r.connection.previousGatewayState!==X.FAIL_WAIT){if(!this.session.hasAutoReconnect()){this.retriedConnect=0,re(e.SwEvent.Error,{error:new Tt("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:r.sessionid},r.uuid);break}if(this.retriedConnect+=1,5===this.retriedConnect){this.retriedConnect=0,re(e.SwEvent.Error,{error:new Error("Connection Retry Failed"),sessionId:r.sessionid},r.uuid);break}setTimeout((()=>{if(w.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){const e=Object.values(r.calls).some((e=>{var t;return(null===(t=e.peer)||void 0===t?void 0:t.instance)&&!e.signalingStateClosed}));if(e)return w.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();w.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:w.warn("GatewayState message unknown method:",t)}break}w.debug("Verto message unknown method:",t);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(t){return i(this,void 0,void 0,(function*(){const{session:i}=this,n=i.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:c,modChannel:d,conferenceMemberID:l,role:u,callID:h}=t;switch(s){case"conference-liveArray-join":{const e=()=>{i.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},n={nodeId:this.nodeId,channels:[o],handler:({data:n})=>{const s=h||this._retrieveCallId(n,o);if(s&&i.calls.hasOwnProperty(s)){const a=i.calls[s];a._addChannel(o),a.extension=r,a.handleConferenceUpdate(n,t).then((t=>{"INVALID_PACKET"===t&&e()}))}}},s=yield i.vertoSubscribe(n).catch((e=>{w.error("liveArray subscription error:",e)}));Ke(s,o)&&e();break}case"conference-liveArray-part":{let t=null;if(o&&i._existsSubscription(n,o)){const{callId:s=null}=i.subscriptions[n][o];if(t=i.calls[s]||null,null!==s){const n={type:q.conferenceUpdate,action:z.Leave,conferenceName:r,participantId:Number(l),role:u};re(e.SwEvent.Notification,n,s,!1)||re(e.SwEvent.Notification,n,i.uuid),null===t&&oe(e.SwEvent.Notification,null,s)}}const s=[o,a,c,d];i.vertoUnsubscribe({nodeId:this.nodeId,channels:s}).then((({unsubscribedChannels:e=[]})=>{t&&(t.channels=t.channels.filter((t=>!e.includes(t))))})).catch((e=>{w.error("liveArray unsubscribe error:",e)}));break}}}))}_handleSessionEvent(t){switch(t.contentType){case"layout-info":case"layer-info":_t(this.session,t);break;case"logo-info":{const i={type:q.conferenceUpdate,action:z.LogoInfo,logo:t.logoURL};re(e.SwEvent.Notification,i,this.session.uuid);break}}}}class xt extends Et{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>i(this,void 0,void 0,(function*(){this._idle=!1;const{autoReconnect:e=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=e}})})),this.handleAnonymousLoginOnSocketOpen=()=>i(this,void 0,void 0,(function*(){this._idle=!1,yield this.login()})),this._vertoHandler=new Rt(this),window.addEventListener("beforeunload",(e=>{this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&(w.info(`Hanging up call due to window unload: ${e}`),this.calls[e].hangup({},!0))}))}))}validateOptions(){return D(this.options)||M(this.options)}newCall(e){if(!this.validateCallOptions(e))throw new Error("Verto.newCall() error: destinationNumber is required.");performance.mark("new-call-start");const t=new kt(this,e);return t.invite(),performance.mark("new-call-end"),t}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!M(this.options)||Boolean(e.destinationNumber)}_onSocketOpen(){return i(this,void 0,void 0,(function*(){return D(this.options)?this.handleLoginOnSocketOpen():M(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0}))}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class Ot extends xt{constructor(e){super(e),w.info(`SDK version: ${ye}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return tt()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:it.full},{browserName:"Firefox",features:["audio"],supported:it.partial},{browserName:"Safari",supported:it.not_supported},{browserName:"Edge",supported:it.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:it.not_supported},{browserName:"Firefox",supported:it.not_supported},{browserName:"Safari",features:["video","audio"],supported:it.full},{browserName:"Edge",supported:it.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:it.full},{browserName:"Firefox",features:["audio"],supported:it.partial},{browserName:"Safari",supported:it.not_supported},{browserName:"Edge",supported:it.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:it.full},{browserName:"Firefox",features:["audio"],supported:it.partial},{browserName:"Safari",features:["video","audio"],supported:it.full},{browserName:"Edge",features:["audio"],supported:it.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:it.full},{browserName:"Firefox",features:["audio"],supported:it.partial},{browserName:"Safari",supported:it.not_supported},{browserName:"Edge",features:["audio"],supported:it.partial}]}]}}class At{static run(t){return i(this,void 0,void 0,(function*(){const i=U({}),n=U({}),s=new Ot(t.credentials);yield s.connect(),s.on(e.SwEvent.Ready,i.resolve),s.on(e.SwEvent.Error,i.reject),s.on(e.SwEvent.MediaError,i.reject),s.on(e.SwEvent.MediaError,i.reject),s.on(e.SwEvent.Notification,(e=>{e.call&&e.call.sipCode>=400&&n.reject(new Error(e.call.sipReason))})),ne(e.SwEvent.StatsReport,(e=>{n.resolve(At.mapReport(e))})),yield i.promise,yield s.newCall({destinationNumber:t.texMLApplicationNumber,debug:!0});const o=yield n.promise;return yield s.disconnect(),o}))}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,b=-1/0,_=0,y=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;_+=s,C+=o,b=Math.max(b,s),m=Math.min(m,s),S=Math.max(S,o),y=Math.min(y,o)}));const w=C/f,I=_/f,k=v[v.length-1],E=ht({jitter:1e3*I,rtt:1e3*w,packetsReceived:null!==(n=null===(i=null===(t=k.audio.inbound)||void 0===t?void 0:t[0])||void 0===i?void 0:i.packetsReceived)&&void 0!==n?n:0,packetsLost:null!==(r=null===(o=null===(s=k.audio.inbound)||void 0===s?void 0:s[0])||void 0===o?void 0:o.packetsLost)&&void 0!==r?r:0});return{iceCandidatePairStats:v[v.length-1].connection,summaryStats:{mos:E,jitter:{average:I,max:b,min:m},rtt:{average:w,max:S,min:y},quality:pt(E)},sessionStats:{packetsSent:null!==(a=k.connection.packetsSent)&&void 0!==a?a:0,bytesSent:null!==(c=k.connection.bytesSent)&&void 0!==c?c:0,bytesReceived:null!==(d=k.connection.bytesReceived)&&void 0!==d?d:0,packetsLost:null!==(h=null===(u=null===(l=k.remote.audio.inbound)||void 0===l?void 0:l[0])||void 0===u?void 0:u.packetsLost)&&void 0!==h?h:0,packetsReceived:null!==(p=k.connection.packetsReceived)&&void 0!==p?p:0},iceCandidateStats:g}}getTelnyxIds(){return{telnyxCallControlId:"",telnyxSessionId:"",telnyxLegId:""}}}e.Call=kt,e.ERROR_TYPE=W,e.NOTIFICATION_TYPE=q,e.PreCallDiagnosis=At,e.TelnyxRTC=Ot,Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).TelnyxWebRTC={})}(this,(function(e){"use strict";function t(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 i(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 n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),s=new Uint8Array(16);function o(){if(!n)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return n(s)}for(var r=[],a=0;a<256;++a)r[a]=(a+256).toString(16).substr(1);function c(e,t,i){var n=t&&i||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var s=(e=e||{}).random||(e.rng||o)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var a=0;a<16;++a)t[n+a]=s[a];return t||function(e,t){var i=t||0,n=r;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("")}(s)}const d=/^a=candidate:.+typ (srflx|prflx|relay)/m,l="wss://rtc.telnyx.com",u=1006,h={urls:"stun:stun.l.google.com:19302"},p=[{urls:"stun:stun.telnyx.com:3478"},h,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],g=[{urls:"stun:stundev.telnyx.com:3478"},h,{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 v;(v=e.SwEvent||(e.SwEvent={})).SocketOpen="telnyx.socket.open",v.SocketClose="telnyx.socket.close",v.SocketError="telnyx.socket.error",v.SocketMessage="telnyx.socket.message",v.SpeedTest="telnyx.internal.speedtest",v.Ready="telnyx.ready",v.Error="telnyx.error",v.Warning="telnyx.warning",v.Notification="telnyx.notification",v.StatsFrame="telnyx.stats.frame",v.StatsReport="telnyx.stats.report",v.Messages="telnyx.messages",v.Calls="telnyx.calls",v.MediaError="telnyx.rtc.mediaError",v.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError",v.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed";const m={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"]},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"]},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"]}},f={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"]},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 y(e,t){const i=f[e];return{code:e,name:i.name,message:t||i.message,description:i.description,causes:[...i.causes],solutions:[...i.solutions]}}class b 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,b.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 _(e){if(e instanceof DOMException){if("NotAllowedError"===e.name)return 42001;if("NotFoundError"===e.name||"OverconstrainedError"===e.name)return 42002}return 42003}function S(e,t,i){const n=m[e],s=t instanceof Error?t:void 0!==t?new Error(String(t)):void 0;return new b({code:e,name:n.name,description:n.description,message:i||n.message,causes:[...n.causes],solutions:[...n.solutions],originalError:s})}var w="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function C(e,t){return e(t={exports:{}},t.exports),t.exports}var E=C((function(e){var t,i;t=w,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 k={debug:0,info:1,warn:2,error:3};class I{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(k[e]<k[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 T=null;const R=E.getLogger("telnyx"),O={trace:0,debug:1,info:2,warn:3,error:4};let N=O.info;function x(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 A=R.methodFactory;R.methodFactory=(e,t,i)=>{const n=A(e,t,i);return function(...t){if(O[e]>=N){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(const i of t)e.push(i);n(...e)}const i=T;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]?x(s[0]):{args:s.map(x)}),i.addEntry(e,o,r)}}},R.setLevel("debug",!1);const L=e=>{const[t,i,n,s,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){R.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},D=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},P=e=>e instanceof Function||"function"==typeof e,M=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,U=/^(ws|wss):\/\//,j=(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?j(a,r):{result:s}},F=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),$=({login:e,passwd:t,password:i,login_token:n})=>Boolean(e&&(t||i)||n),B=({anonymous_login:e})=>Boolean(e)&&Boolean(e.target_id)&&Boolean(e.target_type),G=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 H({debounceTime:e}){let t,i;return{promise:new Promise(((n,s)=>{t=e?W(n,e):n,i=s})),resolve:t,reject:i}}const W=(e,t)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout((()=>{e(...n)}),t)}},V="telnyx-voice-sdk-id";function q(){return sessionStorage.getItem(V)}var K,Y,J;"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{sessionStorage.removeItem(V)})),function(e){e.Offer="offer",e.Answer="answer"}(K||(K={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(Y||(Y={})),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"}(J||(J={}));const Q={generic:"event",[J.Display]:"participantData",[J.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},z={invalidCredentialsOptions:"InvalidCredentialsOptions"},X={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 Z,ee,te,ie,ne;!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"}(Z||(Z={})),function(e){e.Participant="participant",e.Moderator="moderator"}(ee||(ee={})),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"}(te||(te={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(ie||(ie={})),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"}(ne||(ne={}));const se="GLOBAL",oe={},re=(e,t)=>`${e}|${t}`,ae=(e,t=se)=>re(e,t)in oe,ce=(e,t,i=se)=>{const n=re(e,i);n in oe||(oe[n]=[]),oe[n].push(t)},de=(e,t,i=se)=>{const n=function(s){le(e,n,i),t(s)};return n.prototype.targetRef=t,ce(e,n,i)},le=(e,t,i=se)=>{if(!ae(e,i))return!1;const n=re(e,i);if(P(t)){for(let e=oe[n].length-1;e>=0;e--){const i=oe[n][e];(t===i||i.prototype&&t===i.prototype.targetRef)&&oe[n].splice(e,1)}}else oe[n]=[];return 0===oe[n].length&&delete oe[n],!0},ue=(e,t,i=se,n=!0)=>{const s=n&&i!==se;if(!ae(e,i))return s&&ue(e,t),!1;const o=re(e,i),r=oe[o].length;if(!r)return s&&ue(e,t),!1;for(let e=r-1;e>=0;e--)oe[o][e](t);return s&&ue(e,t),!0},he=e=>{const t=re(e,"");Object.keys(oe).filter((e=>0===e.indexOf(t))).forEach((e=>delete oe[e]))};let pe="undefined"!=typeof WebSocket?WebSocket:null;const ge=0,ve=1,me=2,fe=3;class ye{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=l,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":l),t&&(this._host=(e=>`${U.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===ve}get connecting(){return!!this._wsClient&&this._wsClient.readyState===ge}get closing(){return!!this._wsClient&&this._wsClient.readyState===me}get closed(){return!!this._wsClient&&this._wsClient.readyState===fe}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){const t=new URL(this._host);let i=q();this.session.options.rtcIp&&this.session.options.rtcPort&&(i=null,this._useCanaryRtcServer=!1,t.searchParams.set("rtc_ip",this.session.options.rtcIp),t.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),i&&t.searchParams.set("voice_sdk_id",i),this._useCanaryRtcServer&&(t.searchParams.set("canary","true"),i&&!this._hasCanaryBeenUsed&&(t.searchParams.delete("voice_sdk_id"),R.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0);try{this._wsClient=new pe(t.toString()),this._registerSocketEvents(this._wsClient)}catch(t){R.error("WebSocket connection failed:",t);const i=S(45001,t);ue(e.SwEvent.Error,{error:i,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();de(i.id,(i=>{const{result:n,error:s}=j(i);return s?t(s):e(n)}))}));return R.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;P(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout((()=>this._handleCloseTimeout(e)),5e3))}_registerSocketEvents(t){t.onopen=t=>ue(e.SwEvent.SocketOpen,t,this.session.uuid),t.onclose=i=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(t,"close"),ue(e.SwEvent.SocketClose,i,this.session.uuid)),t.onerror=i=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(t,"error");const n=S(45002);return ue(e.SwEvent.Error,{error:n,sessionId:this.session.sessionid},this.session.uuid),ue(e.SwEvent.SocketError,{error:i,sessionId:this.session.sessionid},this.session.uuid)},t.onmessage=t=>{var i,n;const s=D(t.data);var o;if("string"!=typeof s){if(s.voice_sdk_id&&(o=s.voice_sdk_id,sessionStorage.setItem(V,o)),this._unsetTimer(s.id),R.debug("RECV: \n",JSON.stringify(s,null,2),"\n"),ne[`${null===(n=null===(i=null==s?void 0:s.result)||void 0===i?void 0:i.params)||void 0===n?void 0:n.state}`]||!ue(s.id,s)){const t=G(s);ue(e.SwEvent.SocketMessage,s,this.session.uuid),Boolean(t)&&(this.previousGatewayState=t)}}else this._handleStringResponse(s)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(t){this._safetyTimeoutId=null,t&&t.readyState!==fe?(R.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(t),this._safetyCleanupSocket(t,"timeout"),this._wsClient&&this._wsClient!==t||ue(e.SwEvent.SocketClose,{code:u,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1},this.session.uuid)):R.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(R.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,t){this._wsClient===e?(R.debug(`Nulling socket reference (reason: ${t})`),this._wsClient=null):R.debug(`Skipping socket cleanup - old socket already replaced (reason: ${t})`)}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(t){if(/^#SP/.test(t))switch(t[3]){case"U":this.upDur=parseInt(t.substring(4));break;case"D":this.downDur=parseInt(t.substring(4)),ue(e.SwEvent.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else R.warn("Unknown message from socket",t)}}class be{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:c()},e)}}const _e={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 Se extends be{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=t(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const e in _e)e&&i.hasOwnProperty(e)&&(i[_e[e]]=i[e],delete i[e]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class we extends Se{constructor(e){super(),this.method=J.GatewayState;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Ce{constructor(e){this.pendingRequestId=null,this.onSocketMessage=e=>i(this,void 0,void 0,(function*(){e.id===this.pendingRequestId&&this.gatewayStateTask.resolve(G(e))})),this.getIsRegistered=()=>i(this,void 0,void 0,(function*(){const e=new we(q());this.pendingRequestId=e.request.id,this.gatewayStateTask=H({}),this.session.execute(e);const t=yield this.gatewayStateTask.promise;return!!t&&[ne.REGISTER,ne.REGED].includes(t)})),this.session=e,this.gatewayStateTask=H({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Ee extends Se{constructor(e){super(),this.method=J.Ping;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}var ke="2.26.1-beta.2",Ie=ke;class Te extends Se{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:Ie,data:navigator.userAgent}};n&&(r.sessid=n),this.buildRequest({method:this.method,params:r})}}class Re extends Se{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Oe extends Se{toString(){return J.Invite}}class Ne extends Se{toString(){return J.Answer}}class xe extends Se{toString(){return J.Attach}}class Ae extends Se{toString(){return J.Bye}}class Le extends Se{toString(){return J.Candidate}}class De extends Se{toString(){return J.EndOfCandidates}}class Pe extends Se{toString(){return J.Modify}}class Me extends Se{toString(){return J.Info}}class Ue extends Se{toString(){return J.Broadcast}}class je extends Se{toString(){return J.Subscribe}}class Fe extends Se{toString(){return J.Unsubscribe}}class $e extends Se{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:Ie,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 Be{constructor(e){if(this.options=e,this.uuid=c(),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",N=null!==(i=O[t])&&void 0!==i?i:O.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 ye(this),this.registerAgent=new Ce(this)}get __logger(){return R}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return i(this,void 0,void 0,(function*(){return this.registerAgent.getIsRegistered()}))}get reconnectDelay(){return 1e3*F(2,6)}execute(t){return this._idle?new Promise((e=>this._executeQueue.push({resolve:e,msg:t}))):this.connected?this.connection.send(t).catch((t=>i(this,void 0,void 0,(function*(){if((null==t?void 0:t.code)===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const i=S(46003,t);ue(e.SwEvent.Error,{error:i,sessionId:this.sessionid},this.uuid)}yield this.login()}throw t})))):new Promise((e=>{this._executeQueue.push({resolve:e,msg:t}),R.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 $(this.options)||B(this.options)}broadcast(e){}disconnect(){return i(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(),R.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")}))}on(e,t){return ce(e,t,this.uuid),this}off(e,t){return le(e,t,this.uuid),this}connect(){return i(this,void 0,void 0,(function*(){this.connection||(R.debug("No existing connection found, creating a new one."),this.connection=new ye(this)),this._attachListeners(),this._autoReconnect=!0,this.connection.isAlive||(R.debug("Initiating connection to the server..."),this.connection.connect()),R.debug("Connect method called. Connection initiated.")}))}_handleLoginError(t){const i=S(46001,t);ue(e.SwEvent.Error,{error:i,sessionId:this.sessionid},this.uuid)}_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<=Be.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const e=1e3*(n-Be.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout((()=>{this._emitTokenExpiryWarning()}),e)}}catch(e){R.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const t=y(34001);ue(e.SwEvent.Warning,{warning:t,sessionId:this.sessionid},this.uuid)}_clearTokenExpiryTimeout(){null!==this._tokenExpiryTimeout&&(clearTimeout(this._tokenExpiryTimeout),this._tokenExpiryTimeout=null)}login({creds:t,onSuccess:n,onError:s}={}){return i(this,void 0,void 0,(function*(){if(this.connection&&this.connection.isAlive){if(t&&(void 0!==t.login&&(this.options.login=t.login),void 0!==t.password&&(this.options.password=t.password),void 0!==t.passwd&&(this.options.passwd=t.passwd),void 0!==t.login_token&&(this.options.login_token=t.login_token),void 0!==t.userVariables&&(this.options.userVariables=t.userVariables),void 0!==t.anonymous_login&&(this.options.anonymous_login=t.anonymous_login)),$(this.options))return this._login({type:"login",onSuccess:n,onError:s});if(B(this.options))return this._login({type:"anonymous_login",onSuccess:n,onError:s});{const t="Invalid login options provided for authentication.";R.error(t);const i=S(46002,void 0,t);return void ue(e.SwEvent.Error,{error:i,type:z.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}}))}_login({type:e,onSuccess:t,onError:n}){return i(this,void 0,void 0,(function*(){let i;i="login"===e?new Te(this.options.login,this.options.password||this.options.passwd,this.options.login_token,this.sessionid,this.options.userVariables,!!q()):new $e({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:!!q()});const s=yield this.execute(i).catch((e=>{this._handleLoginError(e),n&&n(e)}));s&&(this.sessionid=s.sessid,this._checkTokenExpiry(),t&&t())}))}_onSocketOpen(){return i(this,void 0,void 0,(function*(){}))}onNetworkClose(){this.relayProtocol&&he(this.relayProtocol);for(const e in this.subscriptions)he(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect&&(this._reconnectTimeout=setTimeout((()=>{R.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],le(e,null,t)):(delete this.subscriptions[e],he(e)))}_addSubscription(e,t=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},P(t)&&ce(e,t,i))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(e.SwEvent.SocketOpen,this._onSocketOpen),this.on(e.SwEvent.SocketClose,this.onNetworkClose),this.on(e.SwEvent.SocketError,this.onNetworkClose),this.on(e.SwEvent.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(e.SwEvent.SocketOpen,this._onSocketOpen),this.off(e.SwEvent.SocketClose,this.onNetworkClose),this.off(e.SwEvent.SocketError,this.onNetworkClose),this.off(e.SwEvent.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&&(R.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Ee(q()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout((()=>this._resetKeepAlive()),35e3)}setPingReceived(){R.debug("Ping received"),this._pong=!0}static on(e,t){ce(e,t)}static off(e){le(e)}static uuid(){return c()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}Be.TOKEN_EXPIRY_WARNING_SECONDS=120;const Ge=e=>navigator.mediaDevices.getUserMedia(e),He=e=>e&&e instanceof MediaStream,We=(e,t)=>{const i=M(e);null!==i&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=t)},Ve=(e,t)=>i(void 0,void 0,void 0,(function*(){const i=M(e);if(null===i)return R.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof t)return R.info(`Invalid speaker deviceId: '${t}'`),!1;try{return yield i.setSinkId(t),!0}catch(e){return!1}})),qe=e=>{e&&"live"===e.readyState&&e.stop()},Ke=e=>{He(e)&&e.getTracks().forEach(qe),e=null},Ye=e=>i(void 0,void 0,void 0,(function*(){R.info("RTCService.getUserMedia",e);const{audio:i,video:n}=e;if(!i&&!n)return null;try{return yield Ge(e)}catch(i){if(R.error("getUserMedia error: ",i),(e=>"NotReadableError"===e.name||"NotFoundError"===e.name||"OverconstrainedError"===e.name)(i)){const n=(e=>{const{audio:i,video:n}=e;let s=!1,o=i,r=n;if("object"==typeof i&&null!==i&&"deviceId"in i){s=!0;const e=t(i,["deviceId"]);o=0===Object.keys(e).length||e}if("object"==typeof n&&null!==n&&"deviceId"in n){s=!0;const e=t(n,["deviceId"]);r=0===Object.keys(e).length||e}return s?{audio:o,video:r}:null})(e);if(n){R.warn("Device not found or not readable, falling back to default device");try{return yield Ge(n)}catch(e){throw R.error("Fallback getUserMedia also failed: ",e),i}}}throw i}})),Je=(e=null,t=!1)=>i(void 0,void 0,void 0,(function*(){let i=[];const n=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===ie.AudioIn||e===ie.AudioOut,video:!e||e===ie.Video}))(e)).catch((e=>(R.error(e),null)));if(n){if(Ke(n),i=yield navigator.mediaDevices.enumerateDevices(),e&&(i=i.filter((t=>t.kind===e))),!0===t)return i;const s=[];i=i.filter((e=>{if(!e.groupId)return!0;const t=`${e.kind}-${e.groupId}`;return!s.includes(t)&&(s.push(t),!0)}))}return i})),Qe=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],ze=(e,t,n)=>i(void 0,void 0,void 0,(function*(){const i=yield Je(n,!0);for(let n=0;n<i.length;n++){const{deviceId:s,label:o}=i[n];if(e===s||t===o)return s}return null})),Xe=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((i=>{t.hasOwnProperty(i)&&null!==e[i]&&void 0!==e[i]||delete e[i]}))},Ze=(e,t)=>{if(!e)return!1;const{subscribed:i,alreadySubscribed:n}=et(e);return i.includes(t)||n.includes(t)},et=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((i=>{t[i]=e[`${i}Channels`]||[]})),t},tt=(e,t=null,i=null)=>{if(!He(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}}))},it=e=>{tt(e,"audio",!0)},nt=e=>{tt(e,"audio",!1)},st=e=>{tt(e,"audio",null)},ot=e=>((e,t=null)=>{if(!He(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 rt(){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:!!Ye}}catch(e){return e.message}}var at;function ct(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 dt(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then((()=>{e._playFulfilled=!0})).catch((t=>{R.error("playAudio",t),e._playFulfilled=!0})))}function lt(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"}(at||(at={}));const ut=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 ht extends be{constructor(e,t){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:c(),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 pt{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._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 I(e)}(this.logCollectorOptions),this.logCollector.start(),i=this.logCollector,T=i)}start(e){var t,i;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,R.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,t;return i(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 i=null!==(t=null===(e=this.logCollector)||void 0===e?void 0:e.getLogCount())&&void 0!==t?t:0;this.logCollector&&this.logCollector.stop(),R.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:i,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 R.info("CallReportCollector: Flushed intermediate segment",{segment:n,intervals:s.length,logEntries:o.length,callId:e.callId}),a}finally{this._flushing=!1}}postReport(e,t,n,s){var o,r;return i(this,void 0,void 0,(function*(){const i=null===(o=this.logCollector)||void 0===o?void 0:o.getLogs(),a=i&&i.length>0;if(!this.options.enabled)return void R.info("CallReportCollector: Skipping report — call reports disabled");if(0===this.statsBuffer.length&&!a)return void R.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},i&&i.length>0?{logs:i}:{}),c?{segment:d}:{});yield this._sendPayload(l,t,n,s)}))}sendPayload(e,t,n,s){return i(this,void 0,void 0,(function*(){yield this._sendPayload(e,t,n,s)}))}_sendPayload(e,t,n,s){var o,r;return i(this,void 0,void 0,(function*(){try{const i=new URL(n),a=`${i.protocol.replace(/^ws/,"http")}//${i.host}/call_report`,c=void 0!==e.segment&&!e.summary.endTimestamp?`intermediate segment ${e.segment}`:"final report";R.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":t,"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)R.info(`CallReportCollector: Successfully posted ${c}`);else{const e=yield h.text();R.error(`CallReportCollector: Failed to post ${c}`,{status:h.status,error:e})}}catch(i){R.warn(`CallReportCollector: Network error posting call report, retrying in ${pt.RETRY_DELAY_MS}ms`,{error:i}),yield new Promise((e=>setTimeout(e,pt.RETRY_DELAY_MS)));try{const i=new URL(n),o=`${i.protocol.replace(/^ws/,"http")}//${i.host}/call_report`,r={"Content-Type":"application/json","x-call-report-id":t,"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)R.info("CallReportCollector: Successfully posted call report on retry");else{const e=yield a.text();R.error("CallReportCollector: Failed to post call report on retry",{status:a.status,error:e})}}catch(e){R.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.logCollector&&(this.logCollector.clear(),this.logCollector=null)}_collectStats(e=!1){var t,n,s;return i(this,void 0,void 0,(function*(){if(this.peerConnection&&this.intervalStartTime)try{const i=yield this.peerConnection.getStats(),o=new Date;let r,a,c=null,d=null,l=null,u=null;if(i.forEach((e=>{switch(e.type){case"outbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(c=e);break;case"inbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(d=e);break;case"candidate-pair":(e.nominated||"succeeded"===e.state)&&(l=e);break;case"transport":u=e}})),c){const e=this._getOutboundAudioLevel(i,c);if(null!==e&&this.intervalAudioLevels.outbound.push(e),void 0!==this.previousStats.outboundBytes&&void 0!==this.previousStats.timestamp){const e=(c.bytesSent||0)-this.previousStats.outboundBytes,t=(c.timestamp||o.getTime())-this.previousStats.timestamp;if(t>0){const i=8*e*1e3/t;this.intervalBitrates.outbound.push(i)}}this.previousStats.outboundBytes=c.bytesSent}if(d){const e=this._getInboundAudioLevel(i,d);if(null!==e&&this.intervalAudioLevels.inbound.push(e),void 0!==d.jitter&&this.intervalJitters.push(1e3*d.jitter),void 0!==this.previousStats.inboundBytes&&void 0!==this.previousStats.timestamp){const e=(d.bytesReceived||0)-this.previousStats.inboundBytes,t=(d.timestamp||o.getTime())-this.previousStats.timestamp;if(t>0){const i=8*e*1e3/t;this.intervalBitrates.inbound.push(i)}}this.previousStats.inboundBytes=d.bytesReceived}l&&(void 0!==l.currentRoundTripTime&&this.intervalRTTs.push(l.currentRoundTripTime),null!==this.previousCandidatePairId&&l.id!==this.previousCandidatePairId&&R.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairId,current:l.id}),this.previousCandidatePairId=null!==(t=l.id)&&void 0!==t?t:null),l&&(r=this._resolveCandidate(i,l.localCandidateId),a=this._resolveCandidate(i,l.remoteCandidateId)),this.previousStats.timestamp=o.getTime();const h=o.getTime()-this.intervalStartTime.getTime();if(e||h>=this.options.interval){const e=this._createStatsEntry(this.intervalStartTime,o,c,d,l,r,a,u);if(this.statsBuffer.push(e),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),R.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>=pt.STATS_FLUSH_THRESHOLD||t>=pt.LOGS_FLUSH_THRESHOLD){R.info("CallReportCollector: Approaching buffer limits, requesting flush",{statsIntervals:e,logEntries:t});try{this.onFlushNeeded()}catch(e){R.error("CallReportCollector: onFlushNeeded callback error",{error:e})}}}this._checkQualityWarnings(e,d),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(e){R.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,y;if(!this.onWarning)return;const b=null===(i=e.connection)||void 0===i?void 0:i.roundTripTimeAvg,_=null===(s=null===(n=e.audio)||void 0===n?void 0:n.inbound)||void 0===s?void 0:s.jitterAvg;let 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(31001,void 0!==b&&b>pt.THRESHOLD_RTT_MS),this._trackBreach(31002,void 0!==_&&_>pt.THRESHOLD_JITTER_MS),this._trackBreach(31003,void 0!==S&&S>pt.THRESHOLD_PACKET_LOSS_PCT),void 0!==b&&void 0!==_&&void 0!==S){const e=93.2-.11*_-2.5*S-.01*(1e3*b),t=Math.max(1,Math.min(4.5,1+.035*e+e*(e-60)*(100-e)*7e-6));this._trackBreach(31004,t<pt.THRESHOLD_MOS)}else this._trackBreach(31004,!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(32001,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!==(y=e.audio.outbound.bytesSent)&&void 0!==y?y:0;this._trackBreach(32002,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]>=pt.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const t=Date.now();if(t-(null!==(n=this._lastWarningEmitted[e])&&void 0!==n?n:0)>=pt.WARNING_THROTTLE_MS){this._lastWarningEmitted[e]=t;try{const t=y(e);R.warn(`CallReportCollector: warning ${t.code}: ${t.message}`),null===(s=this.onWarning)||void 0===s||s.call(this,t)}catch(t){R.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){const c={intervalStartUtc:e.toISOString(),intervalEndUtc:t.toISOString(),audio:{}};return i&&(c.audio.outbound={packetsSent:i.packetsSent,bytesSent:i.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)}),n&&(c.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&&(c.connection={roundTripTimeAvg:this._average(this.intervalRTTs),packetsSent:s.packetsSent,packetsReceived:s.packetsReceived,bytesSent:s.bytesSent,bytesReceived:s.bytesReceived},c.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&&(c.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}:{})),c}_resolveCandidate(e,t){if(!t)return void R.debug("CallReportCollector: candidateId is empty, skipping resolve");const i=e.get(t);if(!i)return void R.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;R.debug("CallReportCollector: candidate report has no usable fields",{candidateId:t})}_getOutboundAudioLevel(e,t){let i;if(t.mediaSourceId&&(i=e.get(t.mediaSourceId)),i||e.forEach((e=>{i||"media-source"!==e.type||"audio"!==e.kind||(i=e)})),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:[]}}}pt.STATS_FLUSH_THRESHOLD=300,pt.LOGS_FLUSH_THRESHOLD=800,pt.CONSECUTIVE_BREACHES_REQUIRED=3,pt.THRESHOLD_RTT_MS=.4,pt.THRESHOLD_JITTER_MS=30,pt.THRESHOLD_PACKET_LOSS_PCT=1,pt.THRESHOLD_MOS=3.5,pt.WARNING_THROTTLE_MS=15e3,pt.RETRY_DELAY_MS=500;var gt,vt=C((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 y(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 b(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 _(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=y(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=y(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=y(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=b(e,i,"bytesReceived"),e.packetRate=b(e,i,"packetsReceived")})),e.audio.outbound.map((e=>{let i=t.audio.outbound.find((t=>t.id===e.id));e.bitrate=b(e,i,"bytesSent"),e.packetRate=b(e,i,"packetsSent")})),e.video.inbound.map((e=>{let i=t.video.inbound.find((t=>t.id===e.id));e.bitrate=b(e,i,"bytesReceived"),e.packetRate=b(e,i,"packetsReceived")})),e.video.outbound.map((e=>{let i=t.video.outbound.find((t=>t.id===e.id));e.bitrate=b(e,i,"bytesSent"),e.packetRate=b(e,i,"packetsSent")})),e):e}(n,t),n}let w,C={},E=[];t.WebRTCStats=class extends s{constructor(e){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],"undefined"==typeof window)throw new Error("WebRTCStats only works in browser");const t={...e};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=t.getStatsInterval||1e3,this.rawStats=!!t.rawStats,this.statsObject=!!t.statsObject,this.filteredStats=!!t.filteredStats,this.shouldWrapGetUserMedia=!!t.wrapGetUserMedia,"boolean"==typeof t.remote&&(this.remote=t.remote),this.debug=!!t.debug,this.logLevel=t.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(e,t){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:e,pc:t})}async addConnection(e){const{pc:t,peerId:i}=e;let{connectionId:n,remote:s}=e;if(s="boolean"==typeof s?s:this.remote,!(t&&t instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!i)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[i]){if(n&&n in this.peersToMonitor[i])throw new Error(`We are already monitoring connection with id ${n}.`);for(let e in this.peersToMonitor[i]){const n=this.peersToMonitor[i][e];if(n.pc===t)throw new Error(`We are already monitoring peer with id ${i}.`);"closed"===n.pc.connectionState&&this.removeConnection({pc:n.pc})}}const o=t.getConfiguration();return o.iceServers&&o.iceServers.forEach((function(e){delete e.credential})),n||(n=f()),this.emitEvent({event:"addConnection",tag:"peer",peerId:i,connectionId:n,data:{options:e,peerConfiguration:o}}),this.monitorPeer({peerId:i,connectionId:n,pc:t,remote:s}),{connectionId:n}}getTimeline(e){return this.timeline=this.timeline.sort(((e,t)=>e.timestamp.getTime()-t.timestamp.getTime())),e?this.timeline.filter((t=>t.tag===e)):this.timeline}get logger(){const e=e=>{const t=["none","error","warn","info","debug"];return t.slice(0,t.indexOf(this.logLevel)+1).indexOf(e)>-1};return{error(...t){this.debug&&e("error")&&console.error("[webrtc-stats][error] ",...t)},warn(...t){this.debug&&e("warn")&&console.warn("[webrtc-stats][warn] ",...t)},info(...t){this.debug&&e("info")&&console.log("[webrtc-stats][info] ",...t)},debug(...t){this.debug&&e("debug")&&console.debug("[webrtc-stats][debug] ",...t)}}}removeConnection(e){let t,{connectionId:i,pc:n}=e;if(!n&&!i)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(i){if("string"!=typeof i)throw new Error("connectionId must be a string.");for(let e in this.peersToMonitor)i in this.peersToMonitor[e]&&(n=this.peersToMonitor[e][i].pc,t=e)}else if(n){if(!(n instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let e in this.peersToMonitor)for(let s in this.peersToMonitor[e])this.peersToMonitor[e][s].pc===n&&(i=s,t=e)}if(!n||!i)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(i,n),delete this.peersToMonitor[t][i],0===Object.values(this.peersToMonitor[t]).length&&delete this.peersToMonitor[t],{connectionId:i}}removeAllPeers(){for(let e in this.peersToMonitor)this.removePeer(e)}removePeer(e){if(this.logger.info(`Removing PeerConnection with id ${e}.`),this.peersToMonitor[e]){for(let t in this.peersToMonitor[e]){let i=this.peersToMonitor[e][t].pc;this.removePeerConnectionEventListeners(t,i)}delete this.peersToMonitor[e]}}destroy(){this.removeAllPeers(),E.forEach((e=>{this.removeTrackEventListeners(e)})),E=[],this.shouldWrapGetUserMedia&&w&&(navigator.mediaDevices.getUserMedia=w)}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=_(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."),w=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const e=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=function(){return e({constraints:arguments[0]}),w.apply(navigator.mediaDevices,arguments).then((t=>(e({stream:t}),t)),(t=>(e({error:t}),Promise.reject(t))))}.bind(navigator.mediaDevices)}filteroutStats(e={}){const t={...e};for(const e in t){var i=t[e];this.statsToMonitor.includes(i.type)||delete t[e]}return t}get peerConnectionListeners(){return{icecandidate:(e,t,i,n)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",n),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:e,connectionId:t,data:n.candidate})},track:(e,t,i,n)=>{this.logger.debug(`[pc-event] track | peerId: ${e}`,n);const s=n.track,o=n.streams[0];e in this.peersToMonitor&&t in this.peersToMonitor[e]&&(this.peersToMonitor[e][t].stream=o),this.addTrackEventListeners(s,t),this.emitEvent({event:"ontrack",tag:"track",peerId:e,connectionId:t,data:{stream:o?this.getStreamDetails(o):null,track:s?this.getMediaTrackDetails(s):null,title:n.track.kind+":"+n.track.id+" "+n.streams.map((function(e){return"stream:"+e.id}))}})},signalingstatechange:(e,t,i)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${e}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:e,connectionId:t,data:{signalingState:i.signalingState,localDescription:i.localDescription,remoteDescription:i.remoteDescription}})},iceconnectionstatechange:(e,t,i)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${e}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:i.iceConnectionState})},icegatheringstatechange:(e,t,i)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${e}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:e,connectionId:t,data:i.iceGatheringState})},icecandidateerror:(e,t,i,n)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${e}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:e,connectionId:t,error:{errorCode:n.errorCode}})},connectionstatechange:(e,t,i)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${e}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:i.connectionState})},negotiationneeded:(e,t,i)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${e}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:e,connectionId:t})},datachannel:(e,t,i,n)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${e}`,n),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:e,connectionId:t,data:n.channel})}}}addPeerConnectionEventListeners(e,t,i){this.logger.debug(`Adding event listeners for peer ${e} and connection ${t}.`),C[t]={},Object.keys(this.peerConnectionListeners).forEach((n=>{C[t][n]=this.peerConnectionListeners[n].bind(this,e,t,i),i.addEventListener(n,C[t][n],!1)}))}parseGetUserMedia(e){try{const t={event:"getUserMedia",tag:"getUserMedia",data:{...e}};e.stream&&(t.data.details=this.parseStream(e.stream),e.stream.getTracks().map((e=>{this.addTrackEventListeners(e),E.push(e)}))),this.emitEvent(t)}catch(e){}}parseStream(e){const t={audio:[],video:[]};return e.getTracks().forEach((e=>{t[e.kind].push(this.getMediaTrackDetails(e))})),t}getMediaTrackDetails(e){return{enabled:e.enabled,id:e.id,contentHint:e.contentHint,kind:e.kind,label:e.label,muted:e.muted,readyState:e.readyState,constructorName:e.constructor.name,capabilities:e.getCapabilities?e.getCapabilities():{},constraints:e.getConstraints?e.getConstraints():{},settings:e.getSettings?e.getSettings():{},_track:e}}getStreamDetails(e){return{active:e.active,id:e.id,_stream:e}}getTrackEventObject(e){return{mute:t=>{this.emitEvent({event:"mute",tag:"track",connectionId:e,data:{event:t}})},unmute:t=>{this.emitEvent({event:"unmute",tag:"track",connectionId:e,data:{event:t}})},overconstrained:t=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:e,data:{event:t}})},ended:t=>{this.emitEvent({event:"ended",tag:"track",connectionId:e,data:{event:t}}),this.removeTrackEventListeners(t.target)}}}addTrackEventListeners(e,t){C[e.id]={};const i=this.getTrackEventObject(t);Object.keys(i).forEach((t=>{C[e.id][t]=i[t].bind(this),e.addEventListener(t,C[e.id][t])})),C[e.id].readyState=setInterval((()=>{if("ended"===e.readyState){let t=new CustomEvent("ended",{detail:{check:"readyState"}});e.dispatchEvent(t)}}),1e3)}removeTrackEventListeners(e){if(e.id in C){const t=this.getTrackEventObject();Object.keys(t).forEach((t=>{e.removeEventListener(t,C[e.id][t])})),clearInterval(C[e.id].readyState),delete C[e.id]}}addToTimeline(e){this.timeline.push(e),this.emit("timeline",e)}emitEvent(e){const t={...e,timestamp:new Date};this.addToTimeline(t),t.tag&&this.emit(t.tag,t)}set getStatsInterval(e){if(!Number.isInteger(e))throw new Error(`getStatsInterval should be an integer, got: ${e}`);this._getStatsInterval=e,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(e,t){e in C&&(Object.keys(this.peerConnectionListeners).forEach((i=>{t.removeEventListener(i,C[e][i],!1)})),delete C[e]),t.getSenders().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)})),t.getReceivers().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)}))}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const e=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const t=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),i=function(){return e.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),t.apply(navigator.mediaDevices,arguments).then((function(e){return e}),(function(t){return e.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,t.name),Promise.reject(t)}))};navigator.mediaDevices.getDisplayMedia=i.bind(navigator.mediaDevices)}}}}));(gt=vt)&>.__esModule&&Object.prototype.hasOwnProperty.call(gt,"default")&>.default;var mt=vt.WebRTCStats;function ft(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 yt(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 bt extends be{constructor(e,t){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:t})}}class _t extends be{constructor(e,t){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:t})}}class St extends be{constructor(e,t){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:t})}}function wt(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}}function Ct(t,n){const s=c();let o=!1;const r=new mt({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),a=n=>i(this,void 0,void 0,(function*(){"stats"===n.event&&ue(e.SwEvent.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=ft({jitter:1e3*h,rtt:1e3*p,packetsLost:v,packetsReceived:g});return{jitter:h,rtt:p,mos:m,quality:yt(m),inboundAudio:d.inbound[0],outboundAudio:d.outbound[0],remoteInboundAudio:u.inbound[0],remoteOutboundAudio:u.outbound[0]}}(n),t.uuid),yield t.execute(new St(s,n))}));return{get isRunning(){return o},start:(e,c,d)=>i(this,void 0,void 0,(function*(){if(o)R.debug(`[${n}] Stats reporter already running, skipping start`);else{yield t.execute(new bt(s,n)),r.on("timeline",a);try{yield r.addConnection({pc:e,peerId:c,connectionId:d}),o=!0}catch(e){R.error(`[${n}] Failed to start stats reporter:`,e),r.removeAllPeers(),r.destroy()}}})),stop:a=>i(this,void 0,void 0,(function*(){const i=r.getTimeline();if(ue(e.SwEvent.StatsReport,i,t.uuid),"file"===a){!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)}(i,`webrtc-stats-${s}-${Date.now()}`)}yield t.execute(new _t(s,n)),r.removeAllPeers(),r.destroy(),o=!1})),reportConnectionStateChange:e=>{const t={event:"connectionstatechange-detailed",tag:"connection",timestamp:(new Date).toISOString(),data:e};a(t)},reportIceCandidateError:e=>{const t={event:"icecandidateerror-detailed",tag:"connection",timestamp:(new Date).toISOString(),data:e};a(t)}}}const Et=(t,i)=>{const{contentType:n,canvasType:s,callID:o,canvasInfo:r=null,currentLayerIdx:a=-1}=i;r&&"mcu-personal-canvas"!==s&&delete r.memberID;const c={type:Q.conferenceUpdate,call:t.calls[o],canvasInfo:kt(r),currentLayerIdx:a};switch(n){case"layer-info":{const i=Object.assign({action:te.LayerInfo},c);ue(e.SwEvent.Notification,i,t.uuid);break}case"layout-info":{const i=Object.assign({action:te.LayoutInfo},c);ue(e.SwEvent.Notification,i,t.uuid);break}}},kt=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return D(t)},It=["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"],Tt={"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 Rt(e){try{const t=performance.getEntriesByName(e,"mark");return t.length>0?t[0].startTime:void 0}catch(e){return}}class Ot{constructor(t,n,s,o,r){this.type=t,this.options=n,this.onSdpReadyTwice=null,this.statsReporter=null,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.handleConnectionStateChange=()=>i(this,void 0,void 0,(function*(){const{connectionState:t}=this.instance;if(R.info(`[${(new Date).toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${t}`),"failed"===t||"disconnected"===t){const e=()=>i(this,void 0,void 0,(function*(){if(this.isDebugEnabled&&this.statsReporter){const e=yield function(e,t){return i(this,void 0,void 0,(function*(){const i={connectionState:e.connectionState,previousConnectionState:t,iceConnectionState:e.iceConnectionState,iceGatheringState:e.iceGatheringState,signalingState:e.signalingState},n=e.getTransceivers();if(n.length>0){const e=n[0].sender,t=null==e?void 0:e.transport;t&&(i.dtlsState=t.state)}e.sctp&&(i.sctpState=e.sctp.state);try{const t=yield e.getStats();t.forEach((e=>{"candidate-pair"===e.type&&"succeeded"===e.state&&(i.candidatePairState=e.state,t.forEach((t=>{"local-candidate"===t.type&&t.id===e.localCandidateId&&(i.localCandidateType=t.candidateType,i.selectedCandidatePair=i.selectedCandidatePair||{local:{},remote:{}},i.selectedCandidatePair.local={address:t.address,port:t.port,protocol:t.protocol,candidateType:t.candidateType}),"remote-candidate"===t.type&&t.id===e.remoteCandidateId&&(i.remoteCandidateType=t.candidateType,i.selectedCandidatePair=i.selectedCandidatePair||{local:{},remote:{}},i.selectedCandidatePair.remote={address:t.address,port:t.port,protocol:t.protocol,candidateType:t.candidateType})}))),"transport"===e.type&&(i.dtlsCipher=e.dtlsCipher,i.srtpCipher=e.srtpCipher,i.tlsVersion=e.tlsVersion,e.dtlsState&&(i.dtlsState=e.dtlsState))}))}catch(e){R.error("Error gathering connection state details:",e)}return i}))}(this.instance,this._prevConnectionState);this.statsReporter.reportConnectionStateChange(e)}window.removeEventListener("online",e)}));navigator.onLine?e():window.addEventListener("online",e)}if("disconnected"===t){const t=y(33001);ue(e.SwEvent.Warning,{warning:t,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if("failed"===t){const i=y(33004);ue(e.SwEvent.PeerConnectionFailureError,{warning:i,error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${t}`),sessionId:this._session.sessionid},this.options.id)}this._prevConnectionState=t,"connected"===t&&(performance.mark("dtls-connected"),this.tryCollectTimings()),this._isTrickleIce()&&("connecting"===t&&performance.mark("peer-connection-connecting"),"connected"===t&&(this._clearIceGatheringSafetyTimeout(),performance.mark("peer-connection-connected")))})),this._handleIceConnectionStateChange=()=>{const e=this.instance.iceConnectionState;R.debug(`[${(new Date).toISOString()}] ICE Connection State`,e),"connected"===e&&performance.mark("ice-connected")},this._handleIceGatheringStateChange=()=>{const e=this.instance.iceGatheringState;R.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)},R.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!n.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=s,this._trickleIceSdpFn=o,this._registerPeerEvents=r}get isOffer(){return this.type===K.Offer}get isAnswer(){return this.type===K.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._createOffer():this._createAnswer()}startTrickleIceNegotiation(){return i(this,void 0,void 0,(function*(){performance.mark("start-negotiation"),this._negotiating=!0,this._isOffer()?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))}))}_logTransceivers(){this.instance?(R.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach(((e,t)=>{R.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),R.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))):R.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(R.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":ue(e.SwEvent.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(R.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){R.info("Negotiation needed event"),"stable"!==this.instance.signalingState||this._negotiating?R.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?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&&We(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=Rt("new-call-start");if(void 0===i)return{mode:e,direction:t,steps:[]};const n=[];for(const e of It){if("new-call-start"===e)continue;const t=Rt(e);void 0!==t&&n.push({label:Tt[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 R.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+="-";R.info(`${s} Call establishment timing breakdown:`),R.info(`${s} ${c}`),R.info(`${s} ${d}`),R.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";R.info(`${s} ${r(e.label,o)}${a(t,14)}${a(i,14)}`)}R.info(`${s} ${d}`)}(e),function(){for(const e of It)try{performance.clearMarks(e)}catch(e){R.warn("Clearing performance marks is failed")}}()}createPeerConnection(){return i(this,void 0,void 0,(function*(){var t;this.instance=(t=this._config(),new window.RTCPeerConnection(t)),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:K.Offer}),performance.mark("set-remote-description"));const i=Boolean(this.options.receiveOnlyAudio)&&!this.options.audio;if(this.options.localStream=yield this._retrieveLocalStream().catch((t=>{const i=S(_(t),t);return ue(e.SwEvent.MediaError,i,this.options.id),null})),performance.mark("get-user-media"),this.options.mutedMicOnStart&&He(this.options.localStream)&&(R.info("Muting local audio tracks on start"),nt(this.options.localStream)),!this.options.localStream&&!i){const t=S(42003);throw ue(e.SwEvent.MediaError,t,this.options.id),t}performance.mark("peer-creation-end")}))}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout((()=>{if(this.instance)if(0===this._gatheredCandidatesCount){const t=y(33003);ue(e.SwEvent.Warning,{warning:t,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if("complete"!==this.instance.iceGatheringState){const t=y(33002);ue(e.SwEvent.Warning,{warning:t,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}),Ot.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){null!==this._iceGatheringSafetyTimeout&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return i(this,void 0,void 0,(function*(){yield this.createPeerConnection(),this.isDebugEnabled&&(this.statsReporter=Ct(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(He(i)){const e=i.getAudioTracks();let s=[...e];if(R.info("Local audio tracks: ",e),"object"==typeof this.options.audio&&e.forEach((e=>{R.info("Local audio tracks constraints: ",e.getConstraints())})),this.options.video){const t=i.getVideoTracks();s=[...e,...t],R.info("Local video tracks: ",t),"object"==typeof this.options.video&&t.forEach((e=>{R.info("Local video tracks constraints: ",e.getConstraints())}))}const{audioCodecs:o,videoCodecs:r}=ut(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&&We(t,i)}else if(this.options.receiveOnlyAudio&&"function"==typeof this.instance.addTransceiver){const e=this.instance.addTransceiver("audio",{direction:"recvonly"});R.info("Added recvonly audio transceiver for receive-only mode",e);const{audioCodecs:t}=ut(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);R.info("Add transceiver",e,t)}}_createOffer(){return i(this,void 0,void 0,(function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=!1!==this.options.audio||Boolean(this.options.receiveOnlyAudio),this._constraints.offerToReceiveVideo=Boolean(this.options.video),R.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(t){R.error("Peer _createOffer error:",t);const i=S(40001,t);ue(e.SwEvent.Error,{error:i,sessionId:this._session.sessionid},this.options.id)}}}))}_setRemoteDescription(t){return i(this,void 0,void 0,(function*(){R.debug("Setting remote description",t);try{yield this.instance.setRemoteDescription(t)}catch(t){R.error("Peer _setRemoteDescription error:",t);const i=S(40004,t);throw ue(e.SwEvent.Error,{error:i,sessionId:this._session.sessionid},this.options.id),t}}))}_createAnswer(){return i(this,void 0,void 0,(function*(){if(this._isAnswer()){if("stable"!==this.instance.signalingState&&"have-remote-offer"!==this.instance.signalingState)return R.debug("Skipping negotiation, state:",this.instance.signalingState),R.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:K.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(t){R.error("Peer _createAnswer error:",t);const i=S(40002,t);ue(e.SwEvent.Error,{error:i,sessionId:this._session.sessionid},this.options.id)}}}))}_setLocalDescription(t){return i(this,void 0,void 0,(function*(){try{yield this.instance.setLocalDescription(t)}catch(t){R.error("Peer _setLocalDescription error:",t);const i=S(40003,t);throw ue(e.SwEvent.Error,{error:i,sessionId:this._session.sessionid},this.options.id),t}}))}_sdpReady(){P(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return i(this,void 0,void 0,(function*(){if(He(this.options.localStream))return this.options.localStream;const e=yield(t=this.options,i(void 0,void 0,void 0,(function*(){let{audio:e=!0,micId:i,video:n=!1,camId:s}=t;const{micLabel:o="",camLabel:r=""}=t;return i&&(i=yield ze(i,o,ie.AudioIn).catch((e=>null)),i&&("boolean"==typeof e&&(e={}),e.deviceId={exact:i})),s&&(s=yield ze(s,r,ie.Video).catch((e=>null)),s&&("boolean"==typeof n&&(n={}),n.deviceId={exact:s})),{audio:e,video:n}})));var t;return Ye(e)}))}_isOffer(){return this.type===K.Offer}_isAnswer(){return this.type===K.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 R.info("RTC config",n),n}restartStatsReporter(){return i(this,void 0,void 0,(function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?R.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(R.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):R.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))}))}close(){return i(this,void 0,void 0,(function*(){this._clearIceGatheringSafetyTimeout(),null!==this._sleepWakeupIntervalId&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)}))}}Ot.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3;const Nt=Ie;class xt{constructor(e,t){this.session=e,this._callReportCollector=null,this.id="",this.recoveredCallId="",this.state=Z[Z.New],this.prevState="",this.channels=[],this.role=ee.Participant,this.extension=null,this._state=Z.New,this._prevState=Z.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._iceDone=!1,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({},X,{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._registerTrickleIcePeerEvents=this._registerTrickleIcePeerEvents.bind(this),this._init(),this.options&&(this._ringtone=ct(this.options.ringtoneFile,"_ringtone"),this._ringback=ct(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}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!ot(this.options.localStream)}invite(){return i(this,void 0,void 0,(function*(){this._creatingPeer=!0,this.direction=Y.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("new-peer"),this.peer=new Ot(K.Offer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents);try{yield this.peer.init()}catch(e){return R.error("Peer init failed, aborting call",e),this._creatingPeer=!1,void this.hangup({},!1)}this._creatingPeer=!1}))}answer(e={}){var t;return i(this,void 0,void 0,(function*(){performance.mark("answer-called"),this._creatingPeer=!0,this.stopRingtone(),this.direction=Y.Inbound,(null===(t=null==e?void 0:e.customHeaders)||void 0===t?void 0:t.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 Ot(K.Answer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents);try{yield this.peer.init()}catch(e){return R.error("Peer init failed, aborting call",e),this._creatingPeer=!1,void(yield this.hangup())}this._creatingPeer=!1}))}playRingtone(){dt(this._ringtone)}stopRingtone(){lt(this._ringtone)}playRingback(){dt(this._ringback)}stopRingback(){lt(this._ringback)}hangup(t,n){var s,o,r,a;return i(this,void 0,void 0,(function*(){const i=t||{},c=!1!==n,d=this._state<Z.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=i.cause||d.cause,this.causeCode=i.causeCode||d.causeCode,this.sipCode=i.sipCode||null,this.sipReason=i.sipReason||null,this.sipCallId=i.sip_call_id||null,this.options.customHeaders=[...null!==(s=this.options.customHeaders)&&void 0!==s?s:[],...null!==(r=null===(o=null==i?void 0:i.dialogParams)||void 0===o?void 0:o.customHeaders)&&void 0!==r?r:[]],i.isRecovering)return this._isRecovering=!0,this.setState(Z.Recovering),void this._finalize();if(this.setState(Z.Hangup),this.stopRingtone(),this.stopRingback(),c){const t=new Ae({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(t)}catch(t){R.error("telnyx_rtc.bye failed!",t);const i=S(44003,t);ue(e.SwEvent.Error,{error:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}R.debug(`[${this.id}] Closing peer from hangup`),null===(a=this.peer)||void 0===a||a.close(),this.setState(Z.Destroy)}))}hold(){const e=new Pe({sessid:this.session.sessionid,action:"hold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new Pe({sessid:this.session.sessionid,action:"unhold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new Pe({sessid:this.session.sessionid,action:"toggleHold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const t=new Me({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 Me({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(n)}muteAudio(){nt(this.options.localStream)}unmuteAudio(){it(this.options.localStream)}toggleAudioMute(){st(this.options.localStream)}setAudioInDevice(t,n=this.options.mutedMicOnStart){var s;return i(this,void 0,void 0,(function*(){const{instance:i}=this.peer,o=i.getSenders().find((({track:{kind:e}})=>"audio"===e));if(o){let i;try{i=yield Ge({audio:{deviceId:{exact:t}}})}catch(t){const i=S(_(t),t);return void ue(e.SwEvent.MediaError,i,(null===(s=this.options)||void 0===s?void 0:s.id)||this.id)}const r=i.getAudioTracks()[0];r.enabled=!n,o.replaceTrack(r),this.options.micId=t;const{localStream:a}=this.options;a.getAudioTracks().forEach((e=>e.stop())),a.getVideoTracks().forEach((e=>i.addTrack(e))),this.options.localStream=i}}))}muteVideo(){var e;e=this.options.localStream,tt(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,tt(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,tt(e,"video",null)}setVideoDevice(e){return i(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 Ge({video:{deviceId:{exact:e}}}),n=t.getVideoTracks()[0];i.replaceTrack(n);const{localElement:s,localStream:o}=this.options;We(s,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t}}))}deaf(){nt(this.options.remoteStream)}undeaf(){it(this.options.remoteStream)}toggleDeaf(){st(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,t){return i(this,void 0,void 0,(function*(){if(!this||!this.peer)return void R.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:i}=this.peer,n=i.getSenders();if(!n)return void R.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===t));if(s){const i=s.getParameters();i.encodings||(i.encodings=[{rid:"h"}]),R.info("Parameters: ",i),R.info("Setting max ","audio"===t?"audio":"video"," bandwidth to: ",e," [bps]"),i.encodings[0].maxBitrate=e,yield s.setParameters(i).then((()=>{R.info("audio"===t?"New audio":"New video"," bandwidth settings in use: ",s.getParameters())})).catch((e=>R.error(e)))}else R.error("Could not set bandwidth (reason: no "+t+" 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=Z[this._state].toLowerCase(),this.prevState=Z[this._prevState].toLowerCase(),R.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:Q.callUpdate,call:this}),e){case Z.Purge:R.debug(`Call ${this.id} hangup call due to purge state`),this.hangup({cause:"PURGE",causeCode:1},!1);break;case Z.Active:performance.mark("call-active"),null===(t=this.peer)||void 0===t||t.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,R.debug(`[${this.id}] Recovery complete, call is active`)),setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&Ve(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 Z.Destroy:this._finalize()}}handleMessage(t){const{method:i,params:n}=t;switch(i){case J.Answer:if(performance.mark("telnyx-rtc-answer"),this.gotAnswer=!0,n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id),this._state>=Z.Active)return;this._state>=Z.Early&&this.setState(Z.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case J.Media:if(performance.mark("telnyx-rtc-media"),this._state>=Z.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case J.Display:{const{display_name:t,display_number:s,display_direction:o}=n;this.extension=s;const r=o===Y.Inbound?Y.Outbound:Y.Inbound,a={type:Q[i],call:this,displayName:t,displayNumber:s,displayDirection:r};ue(e.SwEvent.Notification,a,this.id)||ue(e.SwEvent.Notification,a,this.session.uuid);break}case J.Candidate:this._addIceCandidate(n);break;case J.Info:case J.Event:{const t=Object.assign(Object.assign({},n),{type:Q.generic,call:this});ue(e.SwEvent.Notification,t,this.id)||ue(e.SwEvent.Notification,t,this.session.uuid);break}case J.Ringing:performance.mark("ringing"),this.playRingback(),n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id);break;case J.Bye:const t=n.client_state||n.clientState;t&&(this.options.clientState=t),this.stopRingback(),this.stopRingtone(),this.hangup(n,!1)}}handleConferenceUpdate(e,t){return i(this,void 0,void 0,(function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==t.laName)return R.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:i,data:n,hashKey:s=String(this._lastSerno),arrIndex:o}=e;switch(i){case"bootObj":{this._lastSerno=0;const{chatChannel:e,infoChannel:i,modChannel:s,laName:o,conferenceMemberID:r,role:a}=t;this._dispatchConferenceUpdate({action:te.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),i&&(yield this._subscribeConferenceInfo(i));const c=[];for(const e in n)c.push(Object.assign({callId:n[e][0],index:Number(e)},L(n[e][1])));this._dispatchConferenceUpdate({action:te.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:te.Add,callId:s,index:o},L(n)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:te.Modify,callId:s,index:o},L(n)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:te.Delete,callId:s,index:o},L(n)));break;case"clear":this._dispatchConferenceUpdate({action:te.Clear});break;default:this._dispatchConferenceUpdate({action:i,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 i(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:te.ChatMessage,direction:t,participantNumber:i,participantName:n,messageText:s,messageType:o,messageId:e.eventSerno})}},i=yield this.session.vertoSubscribe(t).catch((e=>{R.error("ConfChat subscription error:",e)}));Ze(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 i(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,Et(this.session,t);else R.error("Conference-Info unknown contentType",e)}},i=yield this.session.vertoSubscribe(t).catch((e=>{R.error("ConfInfo subscription error:",e)}));Ze(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(Z.Active):this.setState(Z.Held),!0}_handleChangeHoldStateError(t){R.error(`Failed to ${t.action} on call ${this.id}`);const i=S(44001,t);return ue(e.SwEvent.Error,{error:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_onRemoteSdp(t){return i(this,void 0,void 0,(function*(){const n=new RTCSessionDescription({sdp:t,type:K.Answer});yield this.peer.instance.setRemoteDescription(n).then((()=>{performance.mark("set-remote-description"),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(Z.Early),this.gotAnswer&&this.setState(Z.Active)})).catch((t=>i(this,void 0,void 0,(function*(){R.error("Call setRemoteDescription Error: ",t);const i=S(40004,t);ue(e.SwEvent.Error,{error:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17},!0)}catch(e){R.error("Error during hangup after setRemoteDescription failure:",e)}}))))}))}_requestAnotherLocalDescription(){P(this.peer.onSdpReadyTwice)?ue(e.SwEvent.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._iceDone=!1,this.peer.startNegotiation())}_onIceSdp(t){var n,s;if(this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0,!t)return void R.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:o,type:r}=t;if(-1===o.indexOf("candidate"))return R.info("No candidate - retry \n"),void this._requestAnotherLocalDescription();if(null===(s=null===(n=this.peer)||void 0===n?void 0:n.instance)||void 0===s||s.removeEventListener("icecandidate",this._onIce),!d.test(o)){const t=y(33005);R.warn(`[${this.id}] Warning ${t.code}: ${t.message}`),ue(e.SwEvent.Warning,{warning:t,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-${Nt}`};switch(r){case K.Offer:this.setState(Z.Requesting),a=new Oe(c);break;case K.Answer:this._isRecovering||this.setState(Z.Answering),a=!0===this.options.attach?new xe(c):new Ne(c);break;default:return R.error(`${this.id} - Unknown local SDP type:`,t),void this.hangup({},!1)}performance.mark("send-sdp"),this._execute(a).then((e=>{const{node_id:t=null}=e;this._targetNodeId=t,r===K.Offer?this.setState(Z.Trying):this.setState(Z.Active)})).catch((t=>i(this,void 0,void 0,(function*(){R.error(`${this.id} - Sending ${r} error:`,t);const i=S(40005,t);ue(e.SwEvent.Error,{error:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17},!0)}catch(e){R.error("Error during hangup after SDP send failure:",e)}}))))}_onTrickleIceSdp(t){if(!t)return R.error("No SDP data provided"),void this.hangup({},!1);const{sdp:n,type:s}=t;let o=null;const r={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${Nt}`};switch(s){case K.Offer:this.setState(Z.Requesting),o=new Oe(r);break;case K.Answer:this._isRecovering||this.setState(Z.Answering),o=!0===this.options.attach?new xe(r):new Ne(r);break;default:return R.error(`${this.id} - Unknown local SDP type:`,t),void this.hangup({},!1)}performance.mark("send-sdp"),this._execute(o).then((e=>{const{node_id:t=null}=e;this._targetNodeId=t,s===K.Offer?this.setState(Z.Trying):this.setState(Z.Active)})).catch((t=>i(this,void 0,void 0,(function*(){R.error(`${this.id} - Sending ${s} error:`,t);const i=S(40005,t);ue(e.SwEvent.Error,{error:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17},!0)}catch(e){R.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?(R.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?(R.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 Le({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 R.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((()=>{R.debug("Successfully added ICE candidate:",e)})).catch((t=>{R.error("Failed to add ICE candidate:",t,e)}))}_sendEndOfCandidates(){const e=new De({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){this._iceDone=!1,e.onicecandidate=e=>{this._iceDone||this._onIce(e)},e.onicegatheringstatechange=()=>{"complete"===e.iceGatheringState&&performance.mark("ice-gathering-completed")},e.onicecandidateerror=t=>{var i;if(R.debug("ICE candidate error:",t),null===(i=this.peer)||void 0===i?void 0:i.statsReporter){const i=wt(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&&We(t,i)}))}_registerTrickleIcePeerEvents(e){e.onicecandidate=e=>{this._onTrickleIce(e)},e.onicegatheringstatechange=t=>{R.debug("ICE gathering state changed:",e.iceGatheringState,t),"complete"===e.iceGatheringState&&(R.debug("Finished gathering candidates"),performance.mark("ice-gathering-completed"))},e.onicecandidateerror=t=>{var i;if(R.debug("ICE candidate error:",t),null===(i=this.peer)||void 0===i?void 0:i.statsReporter){const i=wt(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&&We(t,i)}))}_onMediaError(t){const i=(null==t?void 0:t.name)||"UnknownError",n=(null==t?void 0:t.message)||"Unknown media error",s=(null==t?void 0:t.originalError)||t;this._dispatchNotification({type:Q.userMediaError,error:s,call:this,errorName:i,errorMessage:n}),R.error(`Media error (${i}): ${n}`,t),ue(e.SwEvent.Error,{error:t,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),this.hangup({},!1)}_onPeerConnectionFailureError(t){this._dispatchNotification({type:Q.peerConnectionFailureError,error:t.error}),R.error("Peer connection failure error"),t.warning&&ue(e.SwEvent.Warning,{warning:t.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:Q.signalingStateClosed},e)),R.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:Q.conferenceUpdate,call:this},e))}_dispatchNotification(t){!0!==this.options.screenShare&&(ue(e.SwEvent.Notification,t,this.id,!1)||ue(e.SwEvent.Notification,t,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){const{id:t,userVariables:i,remoteCallerNumber:n,onNotification:s,recoveredCallId:o}=this.options;var r;this.options.id=t?t.toString():c(),this.id=this.options.id,o&&(this.recoveredCallId=o,this._isRecovering=!0),i&&(r=i,0!==Object.keys(r).length)||(this.options.userVariables=this.session.options.userVariables||{}),n||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,ce(e.SwEvent.MediaError,this._onMediaError,this.id),ce(e.SwEvent.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),ce(e.SwEvent.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),P(s)&&ce(e.SwEvent.Notification,s.bind(this),this.id);const a=!1!==this.session.options.enableCallReports,d=this.session.options.callReportInterval||5e3,l=this.session.options.debugLogLevel||"debug",u=this.session.options.debugLogMaxEntries||1e3;a&&(this._callReportCollector=new pt({enabled:!0,interval:d},{enabled:!0,level:l,maxEntries:u}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=t=>{ue(e.SwEvent.Warning,{warning:t,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}),this._isRecovering?this.setState(Z.Recovering):this.setState(Z.New),R.info("New Call with Options:",this.options)}_finalize(){var t;this._stopStats(),R.debug(`[${this.id}] Closing peer from _finalize`),null===(t=this.peer)||void 0===t||t.close();const{remoteStream:i,localStream:n}=this.options;Ke(i),Ke(n),le(e.SwEvent.MediaError,null,this.id),le(e.SwEvent.PeerConnectionFailureError,null,this.id),le(e.SwEvent.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id],this._postCallReport().catch((e=>{R.error("Unexpected error in _postCallReport",{error:e})}))}_flushIntermediateReport(){var e;if(!this._callReportCollector)return;const t=this.session.callReportId;if(!t)return void R.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 R.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===Y.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Nt},s=this._callReportCollector.flush(n);if(!s)return;const o=q()||void 0;this._callReportCollector.sendPayload(s,t,i,o).catch((e=>{R.error("Failed to post intermediate call report segment",{error:e})}))}_postCallReport(){var e;return i(this,void 0,void 0,(function*(){if(!this._callReportCollector)return void R.warn("Call report collector not initialized");yield this._callReportCollector.stop();const t=this.session.callReportId;if(!t)return R.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===Y.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Nt},n=null===(e=this.session.connection)||void 0===e?void 0:e.host;if(!n)return void R.error("Cannot post call report: connection host not available");const s=q()||void 0;this._callReportCollector.postReport(i,t,n,s).catch((e=>{R.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),R.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),R.debug("Stats stopped")}}xt.setStateTelnyx=e=>{if(e){switch(e._state){case Z.Recovering:e.state="recovering";break;case Z.Requesting:case Z.Trying:case Z.Early:e.state="connecting";break;case Z.Active:e.state="active";break;case Z.Held:e.state="held";break;case Z.Hangup:case Z.Destroy:e.state="done";break;case Z.Answering:e.state="ringing";break;case Z.New:e.state="new"}return e}};class At extends xt{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,t)=>this.session.execute(new ht(e,t))}hangup(e={},t=!0){const n=Object.create(null,{hangup:{get:()=>super.hangup}});return i(this,void 0,void 0,(function*(){this.screenShare instanceof At&&(yield this.screenShare.hangup(e,t)),yield n.hangup.call(this,e,t)}))}startScreenShare(e){return i(this,void 0,void 0,(function*(){const t=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;t.getTracks().forEach((e=>{e.addEventListener("ended",(()=>i(this,void 0,void 0,(function*(){this.screenShare&&(yield this.screenShare.hangup())}))))}));const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,c=Object.assign({screenShare:!0,localStream:t,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new At(this.session,c),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){return i(this,void 0,void 0,(function*(){this.screenShare instanceof At&&(yield this.screenShare.hangup())}))}setAudioOutDevice(e){return i(this,void 0,void 0,(function*(){this.options.speakerId=e;const{remoteElement:t,speakerId:i}=this.options;return!(!t||!i)&&Ve(t,i)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval((()=>i(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`)})))})),R.info(t)}))),2e3)}}class Lt extends Be{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 i(this,void 0,void 0,(function*(){return e.getIsRegistered.call(this)}))}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return i(this,void 0,void 0,(function*(){e.connect.call(this)}))}checkPermissions(e=!0,t=!0){return i(this,void 0,void 0,(function*(){try{const i=yield Ye({audio:e,video:t});return Ke(i),!0}catch(e){return!1}}))}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return i(this,void 0,void 0,(function*(){Object.keys(this.calls).forEach((e=>this.calls[e].setState(Z.Purge))),this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)}))}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(t){return new Promise(((i,n)=>{if(de(e.SwEvent.SpeedTest,(e=>{const{upDur:n,downDur:s}=e,o=s?8*t/(s/1e3)/1024:0;i({upDur:n,downDur:s,upKps:(n?8*t/(n/1e3)/1024:0).toFixed(0),downKps:o.toFixed(0)})}),this.uuid),!(t=Number(t)))return n(`Invalid parameter 'bytes': ${t}`);this.executeRaw(`#SPU ${t}`);let s=t/1024;t%1024&&s++;const o=".".repeat(1024);for(let e=0;e<s;e++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")}))}getDevices(){return Je().catch((t=>{const i=S(_(t),t);return ue(e.SwEvent.MediaError,i,this.uuid),[]}))}getVideoDevices(){return Je(ie.Video).catch((t=>(ue(e.SwEvent.MediaError,t,this.uuid),[])))}getAudioInDevices(){return Je(ie.AudioIn).catch((t=>{const i=S(_(t),t);return ue(e.SwEvent.MediaError,i,this.uuid),[]}))}getAudioOutDevices(){return Je(ie.AudioOut).catch((t=>(R.error("getAudioOutDevices",t),ue(e.SwEvent.MediaError,t,this.uuid),[])))}validateDeviceId(e,t,i){return ze(e,t,i)}getDeviceResolutions(e){return i(this,void 0,void 0,(function*(){try{return yield(e=>i(void 0,void 0,void 0,(function*(){const t=[],i=yield Ye({video:{deviceId:{exact:e}}}),n=i.getVideoTracks()[0];for(let e=0;e<Qe.length;e++){const[i,s]=Qe[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 Ke(i),t})))(e)}catch(e){throw e}}))}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return i(this,void 0,void 0,(function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:s}=e,o=t(e,["micId","micLabel"]);return Xe(o),this._audioConstraints=yield((e,t,n,s)=>i(void 0,void 0,void 0,(function*(){const{deviceId:i}=s;if(void 0===i&&(e||t)){const i=yield ze(e,t,n).catch((e=>null));i&&(s.deviceId={exact:i})}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?g:p}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=M(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=M(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 Ue({sessid:this.sessionid,eventChannel:t,data:i});e&&(n.targetNodeId=e),this.execute(n).catch((e=>e))}vertoSubscribe({nodeId:e,channels:t=[],handler:n}){return i(this,void 0,void 0,(function*(){if(!(t=t.filter((e=>e&&!this._existsSubscription(this.relayProtocol,e)))).length)return{};const i=new je({sessid:this.sessionid,eventChannel:t});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unauthorized:o=[],subscribed:r=[]}=et(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:t=[]}){return i(this,void 0,void 0,(function*(){if(!(t=t.filter((e=>e&&this._existsSubscription(this.relayProtocol,e)))).length)return{};const i=new Fe({sessid:this.sessionid,eventChannel:t});e&&(i.targetNodeId=e);const n=yield this.execute(i),{unsubscribed:s=[],notSubscribed:o=[]}=et(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&&(R.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,R.debug(`Network connectivity lost for session ${this.sessionid}`);const t=S(48001);ue(e.SwEvent.Error,{error:t,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 At.setStateTelnyx(e)}}class Dt{constructor(e,t){this.code=t,this.message=e}}class Pt{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,t){const i=new Re(e,t);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*F(2,6)}handleMessage(t){var i,n,s,o,r,a,c;const{session:d}=this;d.setPingReceived();const{id:l,method:u,params:h={},voice_sdk_id:p}=t,g=null==h?void 0:h.callID,v=null==h?void 0:h.eventChannel,m=null==h?void 0:h.eventType,f=d.calls[g],b=null===(i=null==f?void 0:f.peer)||void 0===i?void 0:i.isConnectionHealthy();if(Array.isArray(null==h?void 0:h.reattached_sessions)&&0===h.reattached_sessions.length&&Object.keys(d.calls).length>0){const t=y(35001);ue(e.SwEvent.Warning,{warning:t,sessionId:d.sessionid},d.uuid)}if("channelPvtData"===m)return this._handlePvtEvent(h.pvtData);const _=e=>{var t,i,n,s,o,r;const a={audio:!0,video:d.options.video,remoteSdp:h.sdp,destinationNumber:h.callee_id_number,remoteCallerName:h.caller_id_name,remoteCallerNumber:h.caller_id_number,callerName:h.callee_id_name,callerNumber:h.callee_id_number,attach:u===J.Attach,mediaSettings:h.mediaSettings,debug:null!==(t=d.options.debug)&&void 0!==t&&t,debugOutput:null!==(i=d.options.debugOutput)&&void 0!==i?i:"socket",trickleIce:u!==J.Attach&&(null!==(n=d.options.trickleIce)&&void 0!==n&&n),prefetchIceCandidates:null===(s=d.options.prefetchIceCandidates)||void 0===s||s,forceRelayCandidate:null!==(o=d.options.forceRelayCandidate)&&void 0!==o&&o,keepConnectionAliveOnSocketClose:null!==(r=d.options.keepConnectionAliveOnSocketClose)&&void 0!==r&&r};g&&(a.id=g),h.telnyx_call_control_id&&(a.telnyxCallControlId=h.telnyx_call_control_id),h.telnyx_session_id&&(a.telnyxSessionId=h.telnyx_session_id),h.telnyx_leg_id&&(a.telnyxLegId=h.telnyx_leg_id),h.client_state&&(a.clientState=h.client_state),h.dialogParams&&h.dialogParams.custom_headers&&h.dialogParams.custom_headers.length&&(a.customHeaders=h.dialogParams.custom_headers),e&&(a.recoveredCallId=e),performance.mark("new-call-start");const c=new At(d,a);return c.nodeId=this.nodeId,c},w=new we(p),C=new Ee(p);switch(u){case J.Answer:case J.Display:case J.Candidate:case J.Ringing:case J.Bye:case J.Media:if(!g||!f)return void R.error(`Received ${u} for non existing call:`,h);f.handleMessage(t),this._ack(l,u);break;case J.Ping:this.session.setPingReceived(),this.session.execute(C);break;case J.Punt:d.options.keepConnectionAliveOnSocketClose&&b?(R.info(`[${(new Date).toISOString()}][${g}] keeping session calls alive due to PUNT and keepConnectionAliveOnSocketClose. Disconnecting base session...`),d.socketDisconnect(),this._ack(l,u)):d.disconnect();break;case J.Invite:{const e=_();e.direction=Y.Inbound,e.playRingtone(),e.setState(Z.Ringing),this._ack(l,u);break}case J.Attach:{if(!f){return _().answer(),void this._ack(l,u)}const e=f.id;R.info(`[${(new Date).toISOString()}][${g}] closing existing call on ATTACH.`),f.hangup({isRecovering:!0},!1),R.info(`[${(new Date).toISOString()}][${g}] Attach: Creating new call for recovery (recoveredCallId: ${e})`);_(e).answer(),this._ack(l,u);break}case J.Event:case"webrtc.event":if(!v)return void R.error("Verto received an unknown event:",h);const i=d.relayProtocol,p=v.split(".")[0];d._existsSubscription(i,v)?ue(i,h,v):v===d.sessionid?this._handleSessionEvent(h.eventData):d._existsSubscription(i,p)?ue(i,h,p):d.calls.hasOwnProperty(v)?d.calls[v].handleMessage(t):ue(e.SwEvent.Notification,h,d.uuid);break;case J.Info:h.type=Q.generic,ue(e.SwEvent.Notification,h,d.uuid);break;case J.ClientReady:this.session.execute(w);break;default:{const i=G(t);if(i){switch(i){case ne.REGISTER:case ne.REGED:if(d.connection.previousGatewayState!==ne.REGED&&d.connection.previousGatewayState!==ne.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0;const i=null===(s=null===(n=null==t?void 0:t.result)||void 0===n?void 0:n.params)||void 0===s?void 0:s.call_report_id;i&&(d.callReportId=i,R.debug("Captured call_report_id from REGED:",i));const l=null===(r=null===(o=null==t?void 0:t.result)||void 0===o?void 0:o.params)||void 0===r?void 0:r.dc;l&&(d.dc=l,R.debug("Captured dc from REGED:",{dc:l}));const u=null===(c=null===(a=null==t?void 0:t.result)||void 0===a?void 0:a.params)||void 0===c?void 0:c.region;u&&(d.region=u,R.debug("Captured region from REGED:",{region:u})),h.type=Q.vertoClientReady,ue(e.SwEvent.Ready,h,d.uuid)}break;case ne.UNREGED:case ne.NOREG:if(this.retriedRegister+=1,5===this.retriedRegister){this.retriedRegister=0;const t=S(46001,new Dt("Fail to register the user, the server tried 5 times","UNREGED|NOREG"));ue(e.SwEvent.Error,{error:t,sessionId:d.sessionid},d.uuid);break}setTimeout((()=>{this.session.execute(w)}),this.reconnectDelay());break;case ne.FAILED:case ne.FAIL_WAIT:if(d.connection.previousGatewayState!==ne.FAILED&&d.connection.previousGatewayState!==ne.FAIL_WAIT){const t=S(45004,new Error(`Gateway state: ${i}`));if(ue(e.SwEvent.Error,{error:t,sessionId:d.sessionid},d.uuid),!this.session.hasAutoReconnect()){this.retriedConnect=0;const t=S(45003,new Dt("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"));ue(e.SwEvent.Error,{error:t,sessionId:d.sessionid},d.uuid);break}if(this.retriedConnect+=1,5===this.retriedConnect){this.retriedConnect=0;const t=S(45003,new Error("Connection Retry Failed"));ue(e.SwEvent.Error,{error:t,sessionId:d.sessionid},d.uuid);break}setTimeout((()=>{if(R.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){const e=Object.values(d.calls).some((e=>{var t;return(null===(t=e.peer)||void 0===t?void 0:t.instance)&&!e.signalingStateClosed}));if(e)return R.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();R.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:R.warn("GatewayState message unknown method:",t)}break}R.debug("Verto message unknown method:",t);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(t){return i(this,void 0,void 0,(function*(){const{session:i}=this,n=i.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:c,modChannel:d,conferenceMemberID:l,role:u,callID:h}=t;switch(s){case"conference-liveArray-join":{const n=()=>{i.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},s={nodeId:this.nodeId,channels:[o],handler:({data:e})=>{const s=h||this._retrieveCallId(e,o);if(s&&i.calls.hasOwnProperty(s)){const a=i.calls[s];a._addChannel(o),a.extension=r,a.handleConferenceUpdate(e,t).then((e=>{"INVALID_PACKET"===e&&n()}))}}},a=yield i.vertoSubscribe(s).catch((t=>{R.error("liveArray subscription error:",t);const n=S(44004,t);ue(e.SwEvent.Error,{error:n,sessionId:i.sessionid},i.uuid)}));Ze(a,o)&&n();break}case"conference-liveArray-part":{let t=null;if(o&&i._existsSubscription(n,o)){const{callId:s=null}=i.subscriptions[n][o];if(t=i.calls[s]||null,null!==s){const n={type:Q.conferenceUpdate,action:te.Leave,conferenceName:r,participantId:Number(l),role:u};ue(e.SwEvent.Notification,n,s,!1)||ue(e.SwEvent.Notification,n,i.uuid),null===t&&le(e.SwEvent.Notification,null,s)}}const s=[o,a,c,d];i.vertoUnsubscribe({nodeId:this.nodeId,channels:s}).then((({unsubscribedChannels:e=[]})=>{t&&(t.channels=t.channels.filter((t=>!e.includes(t))))})).catch((e=>{R.error("liveArray unsubscribe error:",e)}));break}}}))}_handleSessionEvent(t){switch(t.contentType){case"layout-info":case"layer-info":Et(this.session,t);break;case"logo-info":{const i={type:Q.conferenceUpdate,action:te.LogoInfo,logo:t.logoURL};ue(e.SwEvent.Notification,i,this.session.uuid);break}}}}class Mt extends Lt{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>i(this,void 0,void 0,(function*(){this._idle=!1;const{autoReconnect:e=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=e}})})),this.handleAnonymousLoginOnSocketOpen=()=>i(this,void 0,void 0,(function*(){this._idle=!1,yield this.login()})),this._vertoHandler=new Pt(this),window.addEventListener("beforeunload",(e=>{this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&(R.info(`Hanging up call due to window unload: ${e}`),this.calls[e].hangup({},!0))}))}))}validateOptions(){return $(this.options)||B(this.options)}newCall(e){if(!this.validateCallOptions(e)){throw S(44002,void 0,"Error: destinationNumber is required")}const t=new At(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!!B(this.options)||Boolean(e.destinationNumber)}_onSocketOpen(){return i(this,void 0,void 0,(function*(){return $(this.options)?this.handleLoginOnSocketOpen():B(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0}))}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class Ut extends Mt{constructor(e){super(e),R.info(`SDK version: ${ke}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return rt()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:at.full},{browserName:"Firefox",features:["audio"],supported:at.partial},{browserName:"Safari",supported:at.not_supported},{browserName:"Edge",supported:at.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:at.not_supported},{browserName:"Firefox",supported:at.not_supported},{browserName:"Safari",features:["video","audio"],supported:at.full},{browserName:"Edge",supported:at.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:at.full},{browserName:"Firefox",features:["audio"],supported:at.partial},{browserName:"Safari",supported:at.not_supported},{browserName:"Edge",supported:at.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:at.full},{browserName:"Firefox",features:["audio"],supported:at.partial},{browserName:"Safari",features:["video","audio"],supported:at.full},{browserName:"Edge",features:["audio"],supported:at.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:at.full},{browserName:"Firefox",features:["audio"],supported:at.partial},{browserName:"Safari",supported:at.not_supported},{browserName:"Edge",features:["audio"],supported:at.partial}]}]}}class jt{static run(t){return i(this,void 0,void 0,(function*(){const i=H({}),n=H({}),s=new Ut(t.credentials);yield s.connect(),s.on(e.SwEvent.Ready,i.resolve),s.on(e.SwEvent.Error,i.reject),s.on(e.SwEvent.MediaError,i.reject),s.on(e.SwEvent.MediaError,i.reject),s.on(e.SwEvent.Notification,(e=>{e.call&&e.call.sipCode>=400&&n.reject(new Error(e.call.sipReason))})),ce(e.SwEvent.StatsReport,(e=>{n.resolve(jt.mapReport(e))})),yield i.promise,yield s.newCall({destinationNumber:t.texMLApplicationNumber,debug:!0});const o=yield n.promise;return yield s.disconnect(),o}))}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,y=-1/0,b=0,_=1/0,S=-1/0,w=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;b+=s,w+=o,y=Math.max(y,s),f=Math.min(f,s),S=Math.max(S,o),_=Math.min(_,o)}));const C=w/m,E=b/m,k=v[v.length-1],I=ft({jitter:1e3*E,rtt:1e3*C,packetsReceived:null!==(n=null===(i=null===(t=k.audio.inbound)||void 0===t?void 0:t[0])||void 0===i?void 0:i.packetsReceived)&&void 0!==n?n:0,packetsLost:null!==(r=null===(o=null===(s=k.audio.inbound)||void 0===s?void 0:s[0])||void 0===o?void 0:o.packetsLost)&&void 0!==r?r:0});return{iceCandidatePairStats:v[v.length-1].connection,summaryStats:{mos:I,jitter:{average:E,max:y,min:f},rtt:{average:C,max:S,min:_},quality:yt(I)},sessionStats:{packetsSent:null!==(a=k.connection.packetsSent)&&void 0!==a?a:0,bytesSent:null!==(c=k.connection.bytesSent)&&void 0!==c?c:0,bytesReceived:null!==(d=k.connection.bytesReceived)&&void 0!==d?d:0,packetsLost:null!==(h=null===(u=null===(l=k.remote.audio.inbound)||void 0===l?void 0:l[0])||void 0===u?void 0:u.packetsLost)&&void 0!==h?h:0,packetsReceived:null!==(p=k.connection.packetsReceived)&&void 0!==p?p:0},iceCandidateStats:g}}getTelnyxIds(){return{telnyxCallControlId:"",telnyxSessionId:"",telnyxLegId:""}}}e.Call=At,e.ERROR_TYPE=z,e.NOTIFICATION_TYPE=Q,e.PreCallDiagnosis=jt,e.TelnyxRTC=Ut,Object.defineProperty(e,"__esModule",{value:!0})}));
|