@telnyx/webrtc 2.25.19 → 2.25.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/bundle.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function e(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}function t(e,t,i,n){return new(i||(i=Promise))((function(s,o){function r(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var i="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),n=new Uint8Array(16);function s(){if(!i)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return i(n)}for(var o=[],r=0;r<256;++r)o[r]=(r+256).toString(16).substr(1);function a(e,t,i){var n=t&&i||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var r=(e=e||{}).random||(e.rng||s)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t)for(var a=0;a<16;++a)t[n+a]=r[a];return t||function(e,t){var i=t||0,n=o;return[n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]]].join("")}(r)}const c="wss://rtc.telnyx.com",d=1006,l={urls:"stun:stun.l.google.com:19302"},u=[{urls:"stun:stun.telnyx.com:3478"},l,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],h=[{urls:"stun:stundev.telnyx.com:3478"},l,{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 p;!function(e){e.SocketOpen="telnyx.socket.open",e.SocketClose="telnyx.socket.close",e.SocketError="telnyx.socket.error",e.SocketMessage="telnyx.socket.message",e.SpeedTest="telnyx.internal.speedtest",e.Ready="telnyx.ready",e.Error="telnyx.error",e.Notification="telnyx.notification",e.StatsFrame="telnyx.stats.frame",e.StatsReport="telnyx.stats.report",e.Messages="telnyx.messages",e.Calls="telnyx.calls",e.MediaError="telnyx.rtc.mediaError",e.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError",e.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed"}(p||(p={}));var g="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function v(e,t){return e(t={exports:{}},t.exports),t.exports}var f=v((function(e){var t,i;t=g,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 m={debug:0,info:1,warn:2,error:3};class b{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(m[e]<m[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 _(){return y}function S(e){y=e}const C=f.getLogger("telnyx"),w={trace:0,debug:1,info:2,warn:3,error:4};let I=w.info;const k=C.methodFactory;C.methodFactory=(e,t,i)=>{const n=k(e,t,i);return function(...t){if(w[e]>=I){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(const i of t)e.push(i);n(...e)}const i=_();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]?s[0]:{args:s}),i.addEntry(e,o,r)}}},C.setLevel("debug",!1);const E=e=>{const[t,i,n,s,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){C.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},T=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},R=e=>e instanceof Function||"function"==typeof e,x=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,O=/^(ws|wss):\/\//,A=(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?A(a,r):{result:s}},L=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),P=({login:e,passwd:t,password:i,login_token:n})=>Boolean(e&&(t||i)||n),N=({anonymous_login:e})=>Boolean(e)&&Boolean(e.target_id)&&Boolean(e.target_type),D=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 M({debounceTime:e}){let t,i;return{promise:new Promise(((n,s)=>{t=e?j(n,e):n,i=s})),resolve:t,reject:i}}const j=(e,t)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout((()=>{e(...n)}),t)}},U="telnyx-voice-sdk-id";function $(){return sessionStorage.getItem(U)}var F,B,G;"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{sessionStorage.removeItem(U)})),function(e){e.Offer="offer",e.Answer="answer"}(F||(F={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(B||(B={})),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"}(G||(G={}));const V={generic:"event",[G.Display]:"participantData",[G.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},H={invalidCredentialsOptions:"InvalidCredentialsOptions"},q={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 W,J,K,z,Y;!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"}(W||(W={})),function(e){e.Participant="participant",e.Moderator="moderator"}(J||(J={})),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"}(K||(K={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(z||(z={})),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"}(Y||(Y={}));const Q="GLOBAL",X={},Z=(e,t)=>`${e}|${t}`,ee=(e,t=Q)=>Z(e,t)in X,te=(e,t,i=Q)=>{const n=Z(e,i);n in X||(X[n]=[]),X[n].push(t)},ie=(e,t,i=Q)=>{const n=function(s){ne(e,n,i),t(s)};return n.prototype.targetRef=t,te(e,n,i)},ne=(e,t,i=Q)=>{if(!ee(e,i))return!1;const n=Z(e,i);if(R(t)){for(let e=X[n].length-1;e>=0;e--){const i=X[n][e];(t===i||i.prototype&&t===i.prototype.targetRef)&&X[n].splice(e,1)}}else X[n]=[];return 0===X[n].length&&delete X[n],!0},se=(e,t,i=Q,n=!0)=>{const s=n&&i!==Q;if(!ee(e,i))return s&&se(e,t),!1;const o=Z(e,i),r=X[o].length;if(!r)return s&&se(e,t),!1;for(let e=r-1;e>=0;e--)X[o][e](t);return s&&se(e,t),!0},oe=e=>{const t=Z(e,"");Object.keys(X).filter((e=>0===e.indexOf(t))).forEach((e=>delete X[e]))};let re="undefined"!=typeof WebSocket?WebSocket:null;const ae=0,ce=1,de=2,le=3;class ue{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=c,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":c),t&&(this._host=(e=>`${O.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===ce}get connecting(){return!!this._wsClient&&this._wsClient.readyState===ae}get closing(){return!!this._wsClient&&this._wsClient.readyState===de}get closed(){return!!this._wsClient&&this._wsClient.readyState===le}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){const e=new URL(this._host);let t=$();this.session.options.rtcIp&&this.session.options.rtcPort&&(t=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),t&&e.searchParams.set("voice_sdk_id",t),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),t&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),C.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0);try{this._wsClient=new re(e.toString()),this._registerSocketEvents(this._wsClient)}catch(e){const t=e instanceof Error?e:new Error(`Failed to create WebSocket: ${String(e)}`);se(p.Error,{error:t},this.session.uuid),C.error("WebSocket connection failed:",t)}}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();ie(i.id,(i=>{const{result:n,error:s}=A(i);return s?t(s):e(n)}))}));return C.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;R(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout((()=>this._handleCloseTimeout(e)),5e3))}_registerSocketEvents(e){e.onopen=e=>se(p.SocketOpen,e,this.session.uuid),e.onclose=t=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),se(p.SocketClose,t,this.session.uuid)),e.onerror=t=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error"),se(p.SocketError,{error:t,sessionId:this.session.sessionid},this.session.uuid)),e.onmessage=e=>{var t,i;const n=T(e.data);var s;if("string"!=typeof n){if(n.voice_sdk_id&&(s=n.voice_sdk_id,sessionStorage.setItem(U,s)),this._unsetTimer(n.id),C.debug("RECV: \n",JSON.stringify(n,null,2),"\n"),Y[`${null===(i=null===(t=null==n?void 0:n.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state}`]||!se(n.id,n)){const e=D(n);se(p.SocketMessage,n,this.session.uuid),Boolean(e)&&(this.previousGatewayState=e)}}else this._handleStringResponse(n)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(e){this._safetyTimeoutId=null,e&&e.readyState!==le?(C.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e||se(p.SocketClose,{code:d,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1},this.session.uuid)):C.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(C.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,t){this._wsClient===e?(C.debug(`Nulling socket reference (reason: ${t})`),this._wsClient=null):C.debug(`Skipping socket cleanup - old socket already replaced (reason: ${t})`)}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),se(p.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else C.warn("Unknown message from socket",e)}}class he{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:a()},e)}}const pe={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 ge extends he{constructor(t={}){if(super(),t.hasOwnProperty("dialogParams")){const i=e(t.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const e in pe)e&&i.hasOwnProperty(e)&&(i[pe[e]]=i[e],delete i[e]);t.dialogParams=i}this.buildRequest({method:this.toString(),params:t})}}class ve extends ge{constructor(e){super(),this.method=G.GatewayState;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class fe{constructor(e){this.pendingRequestId=null,this.onSocketMessage=e=>t(this,void 0,void 0,(function*(){e.id===this.pendingRequestId&&this.gatewayStateTask.resolve(D(e))})),this.getIsRegistered=()=>t(this,void 0,void 0,(function*(){const e=new ve($());this.pendingRequestId=e.request.id,this.gatewayStateTask=M({}),this.session.execute(e);const t=yield this.gatewayStateTask.promise;return!!t&&[Y.REGISTER,Y.REGED].includes(t)})),this.session=e,this.gatewayStateTask=M({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class me extends ge{constructor(e){super(),this.method=G.Ping;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}var be="2.25.19",ye=be;class _e extends ge{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:ye,data:navigator.userAgent}};n&&(r.sessid=n),this.buildRequest({method:this.method,params:r})}}class Se extends ge{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Ce extends ge{toString(){return G.Invite}}class we extends ge{toString(){return G.Answer}}class Ie extends ge{toString(){return G.Attach}}class ke extends ge{toString(){return G.Bye}}class Ee extends ge{toString(){return G.Candidate}}class Te extends ge{toString(){return G.EndOfCandidates}}class Re extends ge{toString(){return G.Modify}}class xe extends ge{toString(){return G.Info}}class Oe extends ge{toString(){return G.Broadcast}}class Ae extends ge{toString(){return G.Subscribe}}class Le extends ge{toString(){return G.Unsubscribe}}class Pe extends ge{constructor(e){super(),this.method="anonymous_login";const{target_type:t,target_id:i,target_version_id:n,userVariables:s,sessionId:o,reconnection:r}=e,a={target_type:t,target_id:i,userVariables:s,reconnection:r,"User-Agent":{sdkVersion:ye,data:navigator.userAgent}};o&&(a.sessid=o),n&&(a.target_version_id=n),this.buildRequest({method:this.method,params:a})}}class Ne{constructor(e){if(this.options=e,this.uuid=a(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.callReportId=null,this.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",I=null!==(i=w[t])&&void 0!==i?i:w.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 ue(this),this.registerAgent=new fe(this)}get __logger(){return C}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return t(this,void 0,void 0,(function*(){return this.registerAgent.getIsRegistered()}))}get reconnectDelay(){return 1e3*L(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}),C.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 P(this.options)||N(this.options)}broadcast(e){}disconnect(){return t(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(),C.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")}))}on(e,t){return te(e,t,this.uuid),this}off(e,t){return ne(e,t,this.uuid),this}connect(){return t(this,void 0,void 0,(function*(){this.connection||(C.debug("No existing connection found, creating a new one."),this.connection=new ue(this)),this._attachListeners(),this._autoReconnect=!0,this.connection.isAlive||(C.debug("Initiating connection to the server..."),this.connection.connect()),C.debug("Connect method called. Connection initiated.")}))}_handleLoginError(e){se(p.Error,{error:e,sessionId:this.sessionid},this.uuid)}login({creds:e,onSuccess:i,onError:n}={}){return t(this,void 0,void 0,(function*(){if(this.connection&&this.connection.isAlive){if(e&&(void 0!==e.login&&(this.options.login=e.login),void 0!==e.password&&(this.options.password=e.password),void 0!==e.passwd&&(this.options.passwd=e.passwd),void 0!==e.login_token&&(this.options.login_token=e.login_token),void 0!==e.userVariables&&(this.options.userVariables=e.userVariables),void 0!==e.anonymous_login&&(this.options.anonymous_login=e.anonymous_login)),P(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(N(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const e="Invalid login options provided for authentication.";return C.error(e),void se(p.Error,{error:new Error(e),type:H.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}}))}_login({type:e,onSuccess:i,onError:n}){return t(this,void 0,void 0,(function*(){let t;t="login"===e?new _e(this.options.login,this.options.password||this.options.passwd,this.options.login_token,this.sessionid,this.options.userVariables,!!$()):new Pe({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,sessionId:this.sessionid,userVariables:this.options.userVariables,reconnection:!!$()});const s=yield this.execute(t).catch((e=>{this._handleLoginError(e),n&&n(e)}));s&&(this.sessionid=s.sessid,i&&i())}))}_onSocketOpen(){return t(this,void 0,void 0,(function*(){}))}onNetworkClose(){this.relayProtocol&&oe(this.relayProtocol);for(const e in this.subscriptions)oe(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect&&(this._reconnectTimeout=setTimeout((()=>{C.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],ne(e,null,t)):(delete this.subscriptions[e],oe(e)))}_addSubscription(e,t=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},R(t)&&te(e,t,i))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(p.SocketOpen,this._onSocketOpen),this.on(p.SocketClose,this.onNetworkClose),this.on(p.SocketError,this.onNetworkClose),this.on(p.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(p.SocketOpen,this._onSocketOpen),this.off(p.SocketClose,this.onNetworkClose),this.off(p.SocketError,this.onNetworkClose),this.off(p.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&&(C.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new me($()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout((()=>this._resetKeepAlive()),35e3)}setPingReceived(){C.debug("Ping received"),this._pong=!0}static on(e,t){te(e,t)}static off(e){ne(e)}static uuid(){return a()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const De=e=>navigator.mediaDevices.getUserMedia(e),Me=e=>e&&e instanceof MediaStream,je=(e,t)=>{const i=x(e);null!==i&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=t)},Ue=(e,i)=>t(void 0,void 0,void 0,(function*(){const t=x(e);if(null===t)return C.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof i)return C.info(`Invalid speaker deviceId: '${i}'`),!1;try{return yield t.setSinkId(i),!0}catch(e){return!1}})),$e=e=>{e&&"live"===e.readyState&&e.stop()},Fe=e=>{Me(e)&&e.getTracks().forEach($e),e=null},Be=i=>t(void 0,void 0,void 0,(function*(){C.info("RTCService.getUserMedia",i);const{audio:t,video:n}=i;if(!t&&!n)return null;try{return yield De(i)}catch(t){if(C.error("getUserMedia error: ",t),(e=>"NotReadableError"===e.name||"NotFoundError"===e.name||"OverconstrainedError"===e.name)(t)){const n=(t=>{const{audio:i,video:n}=t;let s=!1,o=i,r=n;if("object"==typeof i&&null!==i&&"deviceId"in i){s=!0;const t=e(i,["deviceId"]);o=0===Object.keys(t).length||t}if("object"==typeof n&&null!==n&&"deviceId"in n){s=!0;const t=e(n,["deviceId"]);r=0===Object.keys(t).length||t}return s?{audio:o,video:r}:null})(i);if(n){C.warn("Device not found or not readable, falling back to default device");try{return yield De(n)}catch(e){throw C.error("Fallback getUserMedia also failed: ",e),t}}}throw t}})),Ge=(e=null,i=!1)=>t(void 0,void 0,void 0,(function*(){let t=[];const n=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===z.AudioIn||e===z.AudioOut,video:!e||e===z.Video}))(e)).catch((e=>(C.error(e),null)));if(n){if(Fe(n),t=yield navigator.mediaDevices.enumerateDevices(),e&&(t=t.filter((t=>t.kind===e))),!0===i)return t;const s=[];t=t.filter((e=>{if(!e.groupId)return!0;const t=`${e.kind}-${e.groupId}`;return!s.includes(t)&&(s.push(t),!0)}))}return t})),Ve=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],He=(e,i,n)=>t(void 0,void 0,void 0,(function*(){const t=yield Ge(n,!0);for(let n=0;n<t.length;n++){const{deviceId:s,label:o}=t[n];if(e===s||i===o)return s}return null})),qe=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((i=>{t.hasOwnProperty(i)&&null!==e[i]&&void 0!==e[i]||delete e[i]}))},We=(e,t)=>{if(!e)return!1;const{subscribed:i,alreadySubscribed:n}=Je(e);return i.includes(t)||n.includes(t)},Je=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((i=>{t[i]=e[`${i}Channels`]||[]})),t},Ke=(e,t=null,i=null)=>{if(!Me(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}}))},ze=e=>{Ke(e,"audio",!0)},Ye=e=>{Ke(e,"audio",!1)},Qe=e=>{Ke(e,"audio",null)},Xe=e=>((e,t=null)=>{if(!Me(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 Ze(){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:!!Be}}catch(e){return e.message}}var et;function tt(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 it(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then((()=>{e._playFulfilled=!0})).catch((t=>{C.error("playAudio",t),e._playFulfilled=!0})))}function nt(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"}(et||(et={}));class st extends he{constructor(e,t){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:a(),type:"message",role:"user",content:[{type:"input_text",text:e},...null==t?void 0:t.map((e=>({type:"image_url",image_url:{url:e}})))]}}})}}class ot{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.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 b(e)}(this.logCollectorOptions),this.logCollector.start(),S(this.logCollector))}start(e){var t,i;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,C.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;this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&this._collectStats();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(),C.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 C.info("CallReportCollector: Flushed intermediate segment",{segment:n,intervals:s.length,logEntries:o.length,callId:e.callId}),a}finally{this._flushing=!1}}postReport(e,i,n,s){var o,r;return t(this,void 0,void 0,(function*(){if(!this.options.enabled||0===this.statsBuffer.length)return;const t=null===(o=this.logCollector)||void 0===o?void 0:o.getLogs(),a=this._segmentIndex>0,c=this._segmentIndex,d=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:this.callEndTime&&this.callStartTime?(this.callEndTime.getTime()-this.callStartTime.getTime())/1e3:void 0,startTimestamp:this.callStartTime.toISOString(),endTimestamp:null===(r=this.callEndTime)||void 0===r?void 0:r.toISOString()}),stats:this.statsBuffer},t&&t.length>0?{logs:t}:{}),a?{segment:c}:{});yield this._sendPayload(d,i,n,s)}))}sendPayload(e,i,n,s){return t(this,void 0,void 0,(function*(){yield this._sendPayload(e,i,n,s)}))}_sendPayload(e,i,n,s){var o,r;return t(this,void 0,void 0,(function*(){try{const t=new URL(n),a=`${t.protocol.replace(/^ws/,"http")}//${t.host}/call_report`,c=void 0!==e.segment&&!e.summary.endTimestamp?`intermediate segment ${e.segment}`:"final report";C.info(`CallReportCollector: Posting ${c}`,{endpoint:a,intervals:e.stats.length,logEntries:null!==(r=null===(o=e.logs)||void 0===o?void 0:o.length)&&void 0!==r?r:0,callId:e.summary.callId,segment:e.segment});const d={"Content-Type":"application/json","x-call-report-id":i,"x-call-id":e.summary.callId};s&&(d["x-voice-sdk-id"]=s);const l=yield fetch(a,{method:"POST",headers:d,body:JSON.stringify(e)});if(l.ok)C.info(`CallReportCollector: Successfully posted ${c}`);else{const e=yield l.text();C.error(`CallReportCollector: Failed to post ${c}`,{status:l.status,error:e})}}catch(e){C.error("CallReportCollector: Error posting report",{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&&S(null),this.logCollector=null)}_collectStats(){var e,i;return t(this,void 0,void 0,(function*(){if(this.peerConnection&&this.intervalStartTime)try{const t=yield this.peerConnection.getStats(),n=new Date;let s=null,o=null,r=null;if(t.forEach((e=>{switch(e.type){case"outbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(s=e);break;case"inbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(o=e);break;case"candidate-pair":(e.nominated||"succeeded"===e.state)&&(r=e)}})),s){const e=this._getTrackAudioLevel(t,s.trackId);if(null!==e&&this.intervalAudioLevels.outbound.push(e),void 0!==this.previousStats.outboundBytes&&void 0!==this.previousStats.timestamp){const e=(s.bytesSent||0)-this.previousStats.outboundBytes,t=(s.timestamp||n.getTime())-this.previousStats.timestamp;if(t>0){const i=8*e*1e3/t;this.intervalBitrates.outbound.push(i)}}this.previousStats.outboundBytes=s.bytesSent}if(o){const e=this._getTrackAudioLevel(t,o.trackId);if(null!==e&&this.intervalAudioLevels.inbound.push(e),void 0!==o.jitter&&this.intervalJitters.push(1e3*o.jitter),void 0!==this.previousStats.inboundBytes&&void 0!==this.previousStats.timestamp){const e=(o.bytesReceived||0)-this.previousStats.inboundBytes,t=(o.timestamp||n.getTime())-this.previousStats.timestamp;if(t>0){const i=8*e*1e3/t;this.intervalBitrates.inbound.push(i)}}this.previousStats.inboundBytes=o.bytesReceived}r&&void 0!==r.currentRoundTripTime&&this.intervalRTTs.push(r.currentRoundTripTime),this.previousStats.timestamp=n.getTime();if(n.getTime()-this.intervalStartTime.getTime()>=this.options.interval){const t=this._createStatsEntry(this.intervalStartTime,n,s,o,r);if(this.statsBuffer.push(t),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),C.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this.onFlushNeeded&&!this._flushing){const t=this.statsBuffer.length,n=null!==(i=null===(e=this.logCollector)||void 0===e?void 0:e.getLogCount())&&void 0!==i?i:0;if(t>=ot.STATS_FLUSH_THRESHOLD||n>=ot.LOGS_FLUSH_THRESHOLD){C.info("CallReportCollector: Approaching buffer limits, requesting flush",{statsIntervals:t,logEntries:n});try{this.onFlushNeeded()}catch(e){C.error("CallReportCollector: onFlushNeeded callback error",{error:e})}}}this.intervalStartTime=n,this._resetIntervalAccumulators()}}catch(e){C.error("CallReportCollector: Error collecting stats",{error:e})}}))}_createStatsEntry(e,t,i,n,s){const o={intervalStartUtc:e.toISOString(),intervalEndUtc:t.toISOString(),audio:{}};return i&&(o.audio.outbound={packetsSent:i.packetsSent,bytesSent:i.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)}),n&&(o.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&&(o.connection={roundTripTimeAvg:this._average(this.intervalRTTs),packetsSent:s.packetsSent,packetsReceived:s.packetsReceived,bytesSent:s.bytesSent,bytesReceived:s.bytesReceived}),o}_getTrackAudioLevel(e,t){if(!t)return null;const i=e.get(t);return i&&i.audioLevel||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:[]}}}ot.STATS_FLUSH_THRESHOLD=300,ot.LOGS_FLUSH_THRESHOLD=800;var rt,at=v((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 y(e,t,i){return 8*function(e,t,i){const n=e[i],s=t?t[i]:null;return null===n||null===s?null:(n-s)/(e.timestamp-t.timestamp)*1e3}(e,t,i)}function _(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=y(e,i,"bytesReceived"),e.packetRate=y(e,i,"packetsReceived")})),e.audio.outbound.map((e=>{let i=t.audio.outbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesSent"),e.packetRate=y(e,i,"packetsSent")})),e.video.inbound.map((e=>{let i=t.video.inbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesReceived"),e.packetRate=y(e,i,"packetsReceived")})),e.video.outbound.map((e=>{let i=t.video.outbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesSent"),e.packetRate=y(e,i,"packetsSent")})),e):e}(n,t),n}let C,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=_(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)}}}}));(rt=at)&&rt.__esModule&&Object.prototype.hasOwnProperty.call(rt,"default")&&rt.default;var ct=at.WebRTCStats;function dt(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 lt(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 ut extends he{constructor(e,t){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:t})}}class ht extends he{constructor(e,t){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:t})}}class pt extends he{constructor(e,t){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:t})}}function gt(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 vt(e,i){const n=a();let s=!1;const o=new ct({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),r=i=>t(this,void 0,void 0,(function*(){"stats"===i.event&&se(p.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=dt({jitter:1e3*h,rtt:1e3*p,packetsLost:v,packetsReceived:g});return{jitter:h,rtt:p,mos:f,quality:lt(f),inboundAudio:d.inbound[0],outboundAudio:d.outbound[0],remoteInboundAudio:u.inbound[0],remoteOutboundAudio:u.outbound[0]}}(i),e.uuid),yield e.execute(new pt(n,i))}));return{get isRunning(){return s},start:(a,c,d)=>t(this,void 0,void 0,(function*(){if(s)C.debug(`[${i}] Stats reporter already running, skipping start`);else{yield e.execute(new ut(n,i)),o.on("timeline",r);try{yield o.addConnection({pc:a,peerId:c,connectionId:d}),s=!0}catch(e){C.error(`[${i}] Failed to start stats reporter:`,e),o.removeAllPeers(),o.destroy()}}})),stop:r=>t(this,void 0,void 0,(function*(){const t=o.getTimeline();if(se(p.StatsReport,t,e.uuid),"file"===r){!function(e,t){const i=new Blob([JSON.stringify(e)],{type:"application/json"}),n=URL.createObjectURL(i),s=document.createElement("a");s.href=n,s.download=`${t}.json`,s.click(),URL.revokeObjectURL(n)}(t,`webrtc-stats-${n}-${Date.now()}`)}yield e.execute(new ht(n,i)),o.removeAllPeers(),o.destroy(),s=!1})),reportConnectionStateChange:e=>{const t={event:"connectionstatechange-detailed",tag:"connection",timestamp:(new Date).toISOString(),data:e};r(t)},reportIceCandidateError:e=>{const t={event:"icecandidateerror-detailed",tag:"connection",timestamp:(new Date).toISOString(),data:e};r(t)}}}const ft=(e,t)=>{const{contentType:i,canvasType:n,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&"mcu-personal-canvas"!==n&&delete o.memberID;const a={type:V.conferenceUpdate,call:e.calls[s],canvasInfo:mt(o),currentLayerIdx:r};switch(i){case"layer-info":{const t=Object.assign({action:K.LayerInfo},a);se(p.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:K.LayoutInfo},a);se(p.Notification,t,e.uuid);break}}},mt=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return T(t)};class bt{constructor(e,i,n,s,o){this.type=e,this.options=i,this.onSdpReadyTwice=null,this.statsReporter=null,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this.handleConnectionStateChange=()=>t(this,void 0,void 0,(function*(){const{connectionState:e}=this.instance;if(C.info(`[${(new Date).toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${e}`),"failed"===e||"disconnected"===e){const e=()=>t(this,void 0,void 0,(function*(){if(this.isDebugEnabled&&this.statsReporter){const e=yield function(e,i){return t(this,void 0,void 0,(function*(){const t={connectionState:e.connectionState,previousConnectionState:i,iceConnectionState:e.iceConnectionState,iceGatheringState:e.iceGatheringState,signalingState:e.signalingState},n=e.getTransceivers();if(n.length>0){const e=n[0].sender,i=null==e?void 0:e.transport;i&&(t.dtlsState=i.state)}e.sctp&&(t.sctpState=e.sctp.state);try{const i=yield e.getStats();i.forEach((e=>{"candidate-pair"===e.type&&"succeeded"===e.state&&(t.candidatePairState=e.state,i.forEach((i=>{"local-candidate"===i.type&&i.id===e.localCandidateId&&(t.localCandidateType=i.candidateType,t.selectedCandidatePair=t.selectedCandidatePair||{local:{},remote:{}},t.selectedCandidatePair.local={address:i.address,port:i.port,protocol:i.protocol,candidateType:i.candidateType}),"remote-candidate"===i.type&&i.id===e.remoteCandidateId&&(t.remoteCandidateType=i.candidateType,t.selectedCandidatePair=t.selectedCandidatePair||{local:{},remote:{}},t.selectedCandidatePair.remote={address:i.address,port:i.port,protocol:i.protocol,candidateType:i.candidateType})}))),"transport"===e.type&&(t.dtlsCipher=e.dtlsCipher,t.srtpCipher=e.srtpCipher,t.tlsVersion=e.tlsVersion,e.dtlsState&&(t.dtlsState=e.dtlsState))}))}catch(e){C.error("Error gathering connection state details:",e)}return t}))}(this.instance,this._prevConnectionState);this.statsReporter.reportConnectionStateChange(e)}window.removeEventListener("online",e)}));navigator.onLine?e():window.addEventListener("online",e)}"failed"===e&&se(p.PeerConnectionFailureError,{error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${e}`),sessionId:this._session.sessionid},this.options.id),this._prevConnectionState=e,this._isTrickleIce()&&("connecting"===e&&performance.mark("peer-connection-connecting"),"connected"===e&&(performance.mark("peer-connection-connected"),console.group("Performance Metrics"),console.table(this.trickleIcePerformanceMetrics),console.groupEnd(),performance.clearMarks()))})),this._handleIceConnectionStateChange=()=>{C.debug(`[${(new Date).toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=()=>{C.debug(`[${(new Date).toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setCodecs=(e,t)=>{if(e.setCodecPreferences)return e.setCodecPreferences(t)},C.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!i.video},this._sdpReady=this._sdpReady.bind(this),this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this._session=n,this._trickleIceSdpFn=s,this._registerPeerEvents=o}get isOffer(){return this.type===F.Offer}get isAnswer(){return this.type===F.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 t(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(){C.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach(((e,t)=>{C.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),C.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))}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(C.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":se(p.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(C.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){C.info("Negotiation needed event"),"stable"!==this.instance.signalingState||this._negotiating?C.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&&je(i,this.options.remoteStream)}createPeerConnection(){return t(this,void 0,void 0,(function*(){var e;this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",(e=>{this.options.remoteStream=e.stream})),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:F.Offer})),this.options.localStream=yield this._retrieveLocalStream().catch((e=>(se(p.MediaError,e,this.options.id),null))),this.options.mutedMicOnStart&&Me(this.options.localStream)&&(C.info("Muting local audio tracks on start"),Ye(this.options.localStream)),performance.mark("peer-creation-end")}))}init(){var e;return t(this,void 0,void 0,(function*(){yield this.createPeerConnection(),this.isDebugEnabled&&(this.statsReporter=vt(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(Me(i)){const e=i.getAudioTracks();let s=[...e];if(C.info("Local audio tracks: ",e),"object"==typeof this.options.audio&&e.forEach((e=>{C.info("Local audio tracks constraints: ",e.getConstraints())})),this.options.video){const t=i.getVideoTracks();s=[...e,...t],C.info("Local video tracks: ",t),"object"==typeof this.options.video&&t.forEach((e=>{C.info("Local video tracks constraints: ",e.getConstraints())}))}const{audioCodecs:o,videoCodecs:r}=(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}})(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&&je(t,i)}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);C.info("Add transceiver",e,t)}}_createOffer(){return t(this,void 0,void 0,(function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=!1!==this.options.audio,this._constraints.offerToReceiveVideo=Boolean(this.options.video),C.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){C.error("Peer _createOffer error:",e)}}}))}_setRemoteDescription(e){return t(this,void 0,void 0,(function*(){C.debug("Setting remote description",e),yield this.instance.setRemoteDescription(e)}))}_createAnswer(){return t(this,void 0,void 0,(function*(){if(this._isAnswer()){if("stable"!==this.instance.signalingState&&"have-remote-offer"!==this.instance.signalingState)return C.debug("Skipping negotiation, state:",this.instance.signalingState),C.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:F.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return yield this._setLocalDescription(e),e}catch(e){C.error("Peer _createAnswer error:",e)}}}))}_setLocalDescription(e){return t(this,void 0,void 0,(function*(){yield this.instance.setLocalDescription(e)}))}_sdpReady(){R(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return t(this,void 0,void 0,(function*(){if(Me(this.options.localStream))return this.options.localStream;const e=yield(i=this.options,t(void 0,void 0,void 0,(function*(){let{audio:e=!0,micId:t,video:n=!1,camId:s}=i;const{micLabel:o="",camLabel:r=""}=i;return t&&(t=yield He(t,o,z.AudioIn).catch((e=>null)),t&&("boolean"==typeof e&&(e={}),e.deviceId={exact:t})),s&&(s=yield He(s,r,z.Video).catch((e=>null)),s&&("boolean"==typeof n&&(n={}),n.deviceId={exact:s})),{audio:e,video:n}})));var i;return Be(e)}))}_isOffer(){return this.type===F.Offer}_isAnswer(){return this.type===F.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 C.info("RTC config",n),n}restartStatsReporter(){return t(this,void 0,void 0,(function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?C.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(C.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):C.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))}))}close(){return t(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)}))}}const yt=ye;class _t{constructor(e,t,i=!1){this.session=e,this._isRecovering=i,this._callReportCollector=null,this.id="",this.state=W[W.New],this.prevState="",this.channels=[],this.role=J.Participant,this.extension=null,this._state=W.New,this._prevState=W.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._iceDone=!1,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!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:n,speaker:s,micId:o,micLabel:r,camId:a,camLabel:c,localElement:d,remoteElement:l,options:u,mediaConstraints:{audio:h,video:p},ringtoneFile:g,ringbackFile:v}=e;this.options=Object.assign({},q,{audio:h,video:p,iceServers:(null==t?void 0:t.iceServers)&&Array.isArray(t.iceServers)?t.iceServers:n,localElement:d,remoteElement:l,micId:o,micLabel:r,camId:a,camLabel:c,speakerId:s,ringtoneFile:g,ringbackFile:v,debug:u.debug,debugOutput:u.debugOutput,trickleIce:u.trickleIce,prefetchIceCandidates:u.prefetchIceCandidates,forceRelayCandidate:u.forceRelayCandidate,keepConnectionAliveOnSocketClose:u.keepConnectionAliveOnSocketClose,mutedMicOnStart:u.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=tt(this.options.ringtoneFile,"_ringtone"),this._ringback=tt(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!Xe(this.options.localStream)}invite(){return t(this,void 0,void 0,(function*(){this._creatingPeer=!0,this.direction=B.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new bt(F.Offer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),this._creatingPeer=!1}))}answer(e={}){var i;return t(this,void 0,void 0,(function*(){this._creatingPeer=!0,performance.mark("new-call-start"),this.stopRingtone(),this.direction=B.Inbound,(null===(i=null==e?void 0:e.customHeaders)||void 0===i?void 0:i.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 bt(F.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(){it(this._ringtone)}stopRingtone(){nt(this._ringtone)}playRingback(){it(this._ringback)}stopRingback(){nt(this._ringback)}hangup(e,t){var i,n,s;const o=e||{},r=!1!==t;if(this.cause=o.cause||"NORMAL_CLEARING",this.causeCode=o.causeCode||16,this.sipCode=o.sipCode||null,this.sipReason=o.sipReason||null,this.sipCallId=o.sip_call_id||null,this.options.customHeaders=[...null!==(i=this.options.customHeaders)&&void 0!==i?i:[],...null!==(s=null===(n=null==o?void 0:o.dialogParams)||void 0===n?void 0:n.customHeaders)&&void 0!==s?s:[]],o.isRecovering)return this._isRecovering=!0,this.setState(W.Recovering),void this._finalize();this.setState(W.Hangup);const a=()=>{var e;C.debug(`[${this.id}] Closing peer from hangup`),null===(e=this.peer)||void 0===e||e.close(),this.setState(W.Destroy)};if(this.stopRingtone(),this.stopRingback(),r){const e=new ke({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});this._execute(e).catch((e=>{C.error("telnyx_rtc.bye failed!",e),se(p.Error,{error:e,sessionId:this.session.sessionid},this.session.uuid)})).then(a.bind(this))}else a()}hold(){const e=new Re({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 Re({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 Re({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 xe({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 xe({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(n)}muteAudio(){Ye(this.options.localStream)}unmuteAudio(){ze(this.options.localStream)}toggleAudioMute(){Qe(this.options.localStream)}setAudioInDevice(e,i=this.options.mutedMicOnStart){return t(this,void 0,void 0,(function*(){const{instance:t}=this.peer,n=t.getSenders().find((({track:{kind:e}})=>"audio"===e));if(n){const t=yield De({audio:{deviceId:{exact:e}}}),s=t.getAudioTracks()[0];s.enabled=!i,n.replaceTrack(s),this.options.micId=e;const{localStream:o}=this.options;o.getAudioTracks().forEach((e=>e.stop())),o.getVideoTracks().forEach((e=>t.addTrack(e))),this.options.localStream=t}}))}muteVideo(){var e;e=this.options.localStream,Ke(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Ke(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Ke(e,"video",null)}setVideoDevice(e){return t(this,void 0,void 0,(function*(){const{instance:t}=this.peer,i=t.getSenders().find((({track:{kind:e}})=>"video"===e));if(i){const t=yield De({video:{deviceId:{exact:e}}}),n=t.getVideoTracks()[0];i.replaceTrack(n);const{localElement:s,localStream:o}=this.options;je(s,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t}}))}deaf(){Ye(this.options.remoteStream)}undeaf(){ze(this.options.remoteStream)}toggleDeaf(){Qe(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,i){return t(this,void 0,void 0,(function*(){if(!this||!this.peer)return void C.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:t}=this.peer,n=t.getSenders();if(!n)return void C.error("Could not set bandwidth (reason: no senders). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const s=n.find((({track:{kind:e}})=>e===i));if(s){const t=s.getParameters();t.encodings||(t.encodings=[{rid:"h"}]),C.info("Parameters: ",t),C.info("Setting max ","audio"===i?"audio":"video"," bandwidth to: ",e," [bps]"),t.encodings[0].maxBitrate=e,yield s.setParameters(t).then((()=>{C.info("audio"===i?"New audio":"New video"," bandwidth settings in use: ",s.getParameters())})).catch((e=>C.error(e)))}else C.error("Could not set bandwidth (reason: no "+i+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")}))}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,t){if(!e)return;const i={callback:e,constraints:t};if(this._statsBindings.push(i),!this._statsIntervalId){const e=2e3;this._startStats(e)}}setState(e){var t;switch(this._prevState=this._state,this._state=e,this.state=W[this._state].toLowerCase(),this.prevState=W[this._prevState].toLowerCase(),C.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:V.callUpdate,call:this}),e){case W.Purge:C.debug(`Call ${this.id} hangup call due to purge state`),this.hangup({cause:"PURGE",causeCode:1},!1);break;case W.Active:this._isRecovering&&(this._isRecovering=!1,C.debug(`[${this.id}] Recovery complete, call is active`)),setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&Ue(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 W.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:i}=e;switch(t){case G.Answer:if(this.gotAnswer=!0,this._state>=W.Active)return;this._state>=W.Early&&this.setState(W.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case G.Media:if(this._state>=W.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case G.Display:{const{display_name:e,display_number:n,display_direction:s}=i;this.extension=n;const o=s===B.Inbound?B.Outbound:B.Inbound,r={type:V[t],call:this,displayName:e,displayNumber:n,displayDirection:o};se(p.Notification,r,this.id)||se(p.Notification,r,this.session.uuid);break}case G.Candidate:this._addIceCandidate(i);break;case G.Info:case G.Event:{const e=Object.assign(Object.assign({},i),{type:V.generic,call:this});se(p.Notification,e,this.id)||se(p.Notification,e,this.session.uuid);break}case G.Ringing:this.playRingback(),i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id);break;case G.Bye:const e=i.client_state||i.clientState;e&&(this.options.clientState=e),this.stopRingback(),this.stopRingtone(),this.hangup(i,!1)}}handleConferenceUpdate(e,i){return t(this,void 0,void 0,(function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==i.laName)return C.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:t,data:n,hashKey:s=String(this._lastSerno),arrIndex:o}=e;switch(t){case"bootObj":{this._lastSerno=0;const{chatChannel:e,infoChannel:t,modChannel:s,laName:o,conferenceMemberID:r,role:a}=i;this._dispatchConferenceUpdate({action:K.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),t&&(yield this._subscribeConferenceInfo(t));const c=[];for(const e in n)c.push(Object.assign({callId:n[e][0],index:Number(e)},E(n[e][1])));this._dispatchConferenceUpdate({action:K.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:K.Add,callId:s,index:o},E(n)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:K.Modify,callId:s,index:o},E(n)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:K.Delete,callId:s,index:o},E(n)));break;case"clear":this._dispatchConferenceUpdate({action:K.Clear});break;default:this._dispatchConferenceUpdate({action:t,data:n,callId:s,index:o})}}))}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const t=this.session.relayProtocol;this.session._existsSubscription(t,e)&&(this.session.subscriptions[t][e]=Object.assign(Object.assign({},this.session.subscriptions[t][e]),{callId:this.id}))}_subscribeConferenceChat(e){return t(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{direction:t,from:i,fromDisplay:n,message:s,type:o}=e.data;this._dispatchConferenceUpdate({action:K.ChatMessage,direction:t,participantNumber:i,participantName:n,messageText:s,messageType:o,messageId:e.eventSerno})}},i=yield this.session.vertoSubscribe(t).catch((e=>{C.error("ConfChat subscription error:",e)}));We(i,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(t,i)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:t,type:i}})}}}))}))}_subscribeConferenceInfo(e){return t(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{eventData:t}=e;if("layout-info"===t.contentType)t.callID=this.id,ft(this.session,t);else C.error("Conference-Info unknown contentType",e)}},i=yield this.session.vertoSubscribe(t).catch((e=>{C.error("ConfInfo subscription error:",e)}));We(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(W.Active):this.setState(W.Held),!0}_handleChangeHoldStateError(e){return C.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){return t(this,void 0,void 0,(function*(){const t=new RTCSessionDescription({sdp:e,type:F.Answer});yield this.peer.instance.setRemoteDescription(t).then((()=>{this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(W.Early),this.gotAnswer&&this.setState(W.Active)})).catch((e=>{C.error("Call setRemoteDescription Error: ",e),this.hangup({cause:"USER_BUSY",causeCode:17},!0)}))}))}_requestAnotherLocalDescription(){R(this.peer.onSdpReadyTwice)?se(p.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 C.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-${yt}`};switch(s){case F.Offer:this.setState(W.Requesting),o=new Ce(r);break;case F.Answer:this._isRecovering||this.setState(W.Answering),o=!0===this.options.attach?new Ie(r):new we(r);break;default:return C.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===F.Offer?this.setState(W.Trying):this.setState(W.Active)})).catch((e=>{C.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 C.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-${yt}`};switch(i){case F.Offer:this.setState(W.Requesting),n=new Ce(s);break;case F.Answer:this._isRecovering||this.setState(W.Answering),n=!0===this.options.attach?new Ie(s):new we(s);break;default:return C.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===F.Offer?this.setState(W.Trying):this.setState(W.Active)})).catch((e=>{C.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;null===this._iceTimeout&&(this._iceTimeout=setTimeout((()=>this._onIceSdp(t.localDescription)),1e3)),e.candidate?C.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(t.localDescription)}_onTrickleIce(e){e.candidate&&e.candidate.candidate?(C.debug("RTCPeer Candidate:",e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const t=new Ee({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 C.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((()=>{C.debug("Successfully added ICE candidate:",e)})).catch((t=>{C.error("Failed to add ICE candidate:",t,e)}))}_sendEndOfCandidates(){const e=new Te({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e),performance.mark("ice-gathering-end")}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!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.onicecandidateerror=t=>{var i;if(C.debug("ICE candidate error:",t),null===(i=this.peer)||void 0===i?void 0:i.statsReporter){const i=gt(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&&je(t,i)}))}_registerTrickleIcePeerEvents(e){e.onicecandidate=e=>{this._onTrickleIce(e)},e.onicegatheringstatechange=t=>{C.debug("ICE gathering state changed:",e.iceGatheringState),"complete"===e.iceGatheringState&&C.debug("Finished gathering candidates")},e.onicecandidateerror=t=>{var i;if(C.debug("ICE candidate error:",t),null===(i=this.peer)||void 0===i?void 0:i.statsReporter){const i=gt(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&&je(t,i)}))}_onMediaError(e){this._dispatchNotification({type:V.userMediaError,error:e}),C.error("Media error, hanging up call",e),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:V.peerConnectionFailureError,error:e}),C.error("Peer connection failure error")}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:V.signalingStateClosed},e)),C.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:V.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(se(p.Notification,e,this.id,!1)||se(p.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){const{id:e,userVariables:t,remoteCallerNumber:i,onNotification:n}=this.options;var s;this.options.id=e?e.toString():a(),this.id=this.options.id,t&&(s=t,0!==Object.keys(s).length)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,te(p.MediaError,this._onMediaError,this.id),te(p.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),te(p.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),R(n)&&te(p.Notification,n.bind(this),this.id);const o=!1!==this.session.options.enableCallReports,r=this.session.options.callReportInterval||5e3,c=this.session.options.debugLogLevel||"debug",d=this.session.options.debugLogMaxEntries||1e3;o&&(this._callReportCollector=new ot({enabled:!0,interval:r},{enabled:!0,level:c,maxEntries:d}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()}),this._isRecovering?this.setState(W.Recovering):this.setState(W.New),C.info("New Call with Options:",this.options)}_finalize(){var e;this._stopStats(),C.debug(`[${this.id}] Closing peer from _finalize`),null===(e=this.peer)||void 0===e||e.close();const{remoteStream:t,localStream:i}=this.options;Fe(t),Fe(i),ne(p.MediaError,null,this.id),ne(p.PeerConnectionFailureError,null,this.id),ne(p.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id],this._postCallReport()}_flushIntermediateReport(){var e;if(!this._callReportCollector)return;const t=this.session.callReportId;if(!t)return void C.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 C.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===B.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:yt},s=this._callReportCollector.flush(n);if(!s)return;const o=$()||void 0;this._callReportCollector.sendPayload(s,t,i,o).catch((e=>{C.error("Failed to post intermediate call report segment",{error:e})}))}_postCallReport(){var e;if(!this._callReportCollector)return void C.warn("Call report collector not initialized");this._callReportCollector.stop();const t=this.session.callReportId;if(!t)return C.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===B.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:yt},n=null===(e=this.session.connection)||void 0===e?void 0:e.host;if(!n)return void C.error("Cannot post call report: connection host not available");const s=$()||void 0;this._callReportCollector.postReport(i,t,n,s).catch((e=>{C.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),C.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),C.debug("Stats stopped")}}_t.setStateTelnyx=e=>{if(e){switch(e._state){case W.Recovering:e.state="recovering";break;case W.Requesting:case W.Trying:case W.Early:e.state="connecting";break;case W.Active:e.state="active";break;case W.Held:e.state="held";break;case W.Hangup:case W.Destroy:e.state="done";break;case W.Answering:e.state="ringing";break;case W.New:e.state="new"}return e}};class St extends _t{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,t)=>this.session.execute(new st(e,t))}hangup(e={},t=!0){this.screenShare instanceof St&&this.screenShare.hangup(e,t),super.hangup(e,t)}startScreenShare(e){return t(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 St(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof St&&this.screenShare.hangup()}setAudioOutDevice(e){return t(this,void 0,void 0,(function*(){this.options.speakerId=e;const{remoteElement:t,speakerId:i}=this.options;return!(!t||!i)&&Ue(t,i)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval((()=>t(this,void 0,void 0,(function*(){const e=yield this.peer.instance.getStats(null);let t="";const i=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],n=["id","type","timestamp"];e.forEach((e=>{i.includes(e.type)||(t+=`\n${e.type}\n`,Object.keys(e).forEach((i=>{n.includes(i)||(t+=`\t${i}: ${e[i]}\n`)})))})),C.info(t)}))),2e3)}}class Ct extends Ne{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._onlineHandler=null,this._offlineHandler=null,this._wasOffline=!1,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile,this._setupNetworkListeners()}get reconnectDelay(){return 1e3}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return t(this,void 0,void 0,(function*(){return e.getIsRegistered.call(this)}))}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return t(this,void 0,void 0,(function*(){e.connect.call(this)}))}checkPermissions(e=!0,i=!0){return t(this,void 0,void 0,(function*(){try{const t=yield Be({audio:e,video:i});return Fe(t),!0}catch(e){return!1}}))}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return t(this,void 0,void 0,(function*(){Object.keys(this.calls).forEach((e=>this.calls[e].setState(W.Purge))),this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)}))}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise(((t,i)=>{if(ie(p.SpeedTest,(i=>{const{upDur:n,downDur:s}=i,o=s?8*e/(s/1e3)/1024:0;t({upDur:n,downDur:s,upKps:(n?8*e/(n/1e3)/1024:0).toFixed(0),downKps:o.toFixed(0)})}),this.uuid),!(e=Number(e)))return i(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let n=e/1024;e%1024&&n++;const s=".".repeat(1024);for(let e=0;e<n;e++)this.executeRaw(`#SPB ${s}`);this.executeRaw("#SPE")}))}getDevices(){return Ge().catch((e=>(se(p.MediaError,e,this.uuid),[])))}getVideoDevices(){return Ge(z.Video).catch((e=>(se(p.MediaError,e,this.uuid),[])))}getAudioInDevices(){return Ge(z.AudioIn).catch((e=>(se(p.MediaError,e,this.uuid),[])))}getAudioOutDevices(){return Ge(z.AudioOut).catch((e=>(C.error("getAudioOutDevices",e),se(p.MediaError,e,this.uuid),[])))}validateDeviceId(e,t,i){return He(e,t,i)}getDeviceResolutions(e){return t(this,void 0,void 0,(function*(){try{return yield(e=>t(void 0,void 0,void 0,(function*(){const t=[],i=yield Be({video:{deviceId:{exact:e}}}),n=i.getVideoTracks()[0];for(let e=0;e<Ve.length;e++){const[i,s]=Ve[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 Fe(i),t})))(e)}catch(e){throw e}}))}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(i){return t(this,void 0,void 0,(function*(){if(!i)throw new Error("You need to provide the settings object");const{micId:n,micLabel:s}=i,o=e(i,["micId","micLabel"]);return qe(o),this._audioConstraints=yield((e,i,n,s)=>t(void 0,void 0,void 0,(function*(){const{deviceId:t}=s;if(void 0===t&&(e||i)){const t=yield He(e,i,n).catch((e=>null));t&&(s.deviceId={exact:t})}return s})))(n,s,"audioinput",o),this.micId=n,this.micLabel=s,this._audioConstraints}))}disableMicrophone(){this._previousAudioConstraints=this._audioConstraints,this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=this._previousAudioConstraints||!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const e="development"===this.options.env;this._iceServers=e?h:u}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=x(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=x(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 Oe({sessid:this.sessionid,eventChannel:t,data:i});e&&(n.targetNodeId=e),this.execute(n).catch((e=>e))}vertoSubscribe({nodeId:e,channels:i=[],handler:n}){return t(this,void 0,void 0,(function*(){if(!(i=i.filter((e=>e&&!this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new Ae({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const s=yield this.execute(t),{unauthorized:o=[],subscribed:r=[]}=Je(s);return o.length&&o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),r.forEach((e=>this._addSubscription(this.relayProtocol,n,e))),s}))}vertoUnsubscribe({nodeId:e,channels:i=[]}){return t(this,void 0,void 0,(function*(){if(!(i=i.filter((e=>e&&this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new Le({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const n=yield this.execute(t),{unsubscribed:s=[],notSubscribed:o=[]}=Je(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&&(C.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,C.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 St.setStateTelnyx(e)}}class wt{constructor(e,t){this.code=t,this.message=e}}class It{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0,this.receivedAuthenticationRequired=0}_ack(e,t){const i=new Se(e,t);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*L(2,6)}handleMessage(e){var i,n,s;const{session:o}=this,{id:r,method:a,params:c={},voice_sdk_id:d}=e,l=null==c?void 0:c.callID,u=null==c?void 0:c.eventChannel,h=null==c?void 0:c.eventType,g=o.calls[l],v=null===(i=null==g?void 0:g.peer)||void 0===i?void 0:i.isConnectionHealthy();if("channelPvtData"===h)return this._handlePvtEvent(c.pvtData);const f=(e=!1)=>{var t,i,n,s,r,d;const u={audio:!0,video:o.options.video,remoteSdp:c.sdp,destinationNumber:c.callee_id_number,remoteCallerName:c.caller_id_name,remoteCallerNumber:c.caller_id_number,callerName:c.callee_id_name,callerNumber:c.callee_id_number,attach:a===G.Attach,mediaSettings:c.mediaSettings,debug:null!==(t=o.options.debug)&&void 0!==t&&t,debugOutput:null!==(i=o.options.debugOutput)&&void 0!==i?i:"socket",trickleIce:null!==(n=o.options.trickleIce)&&void 0!==n&&n,prefetchIceCandidates:null===(s=o.options.prefetchIceCandidates)||void 0===s||s,forceRelayCandidate:null!==(r=o.options.forceRelayCandidate)&&void 0!==r&&r,keepConnectionAliveOnSocketClose:null!==(d=o.options.keepConnectionAliveOnSocketClose)&&void 0!==d&&d};l&&(u.id=l),c.telnyx_call_control_id&&(u.telnyxCallControlId=c.telnyx_call_control_id),c.telnyx_session_id&&(u.telnyxSessionId=c.telnyx_session_id),c.telnyx_leg_id&&(u.telnyxLegId=c.telnyx_leg_id),c.client_state&&(u.clientState=c.client_state),c.dialogParams&&c.dialogParams.custom_headers&&c.dialogParams.custom_headers.length&&(u.customHeaders=c.dialogParams.custom_headers);const h=new St(o,u,e);return h.nodeId=this.nodeId,h},m=new ve(d),b=new me(d);switch(a){case G.Answer:case G.Display:case G.Candidate:case G.Ringing:case G.Bye:case G.Media:if(!l||!g)return void C.error(`Received ${a} for non existing call:`,c);g.handleMessage(e),this._ack(r,a);break;case G.Ping:this.session.setPingReceived(),this.session.execute(b).then((()=>{this.receivedAuthenticationRequired=0})).catch((e=>t(this,void 0,void 0,(function*(){e.code===this.session.authenticationRequiredErrorCode&&this.receivedAuthenticationRequired>=0&&(this.receivedAuthenticationRequired+=1,this.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(C.warn("Ping failed twice with Authentication Required. Re-logging in..."),this.session.login(),this.receivedAuthenticationRequired=-1))}))));break;case G.Punt:o.options.keepConnectionAliveOnSocketClose&&v?(C.info(`[${(new Date).toISOString()}][${l}] keeping session calls alive due to PUNT and keepConnectionAliveOnSocketClose. Disconnecting base session...`),o.socketDisconnect(),this._ack(r,a)):o.disconnect();break;case G.Invite:{const e=f();e.playRingtone(),e.setState(W.Ringing),e.direction=B.Inbound,this._ack(r,a);break}case G.Attach:{if(!g){return f().answer(),void this._ack(r,a)}const e=!!g;C.info(`[${(new Date).toISOString()}][${l}] closing existing call on ATTACH.`),g.hangup({isRecovering:e},!1),C.info(`[${(new Date).toISOString()}][${l}] Attach: Creating new call for recovery`);f(e).answer(),this._ack(r,a);break}case G.Event:case"webrtc.event":if(!u)return void C.error("Verto received an unknown event:",c);const i=o.relayProtocol,d=u.split(".")[0];o._existsSubscription(i,u)?se(i,c,u):u===o.sessionid?this._handleSessionEvent(c.eventData):o._existsSubscription(i,d)?se(i,c,d):o.calls.hasOwnProperty(u)?o.calls[u].handleMessage(e):se(p.Notification,c,o.uuid);break;case G.Info:c.type=V.generic,se(p.Notification,c,o.uuid);break;case G.ClientReady:this.session.execute(m);break;default:{const t=D(e);if(t){switch(t){case Y.REGISTER:case Y.REGED:if(o.connection.previousGatewayState!==Y.REGED&&o.connection.previousGatewayState!==Y.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0;const t=null===(s=null===(n=null==e?void 0:e.result)||void 0===n?void 0:n.params)||void 0===s?void 0:s.call_report_id;t&&(o.callReportId=t,C.debug("Captured call_report_id from REGED:",t)),c.type=V.vertoClientReady,se(p.Ready,c,o.uuid)}break;case Y.UNREGED:case Y.NOREG:if(this.retriedRegister+=1,5===this.retriedRegister){this.retriedRegister=0,se(p.Error,{error:new wt("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:o.sessionid},o.uuid);break}setTimeout((()=>{this.session.execute(m)}),this.reconnectDelay());break;case Y.FAILED:case Y.FAIL_WAIT:if(o.connection.previousGatewayState!==Y.FAILED&&o.connection.previousGatewayState!==Y.FAIL_WAIT){if(!this.session.hasAutoReconnect()){this.retriedConnect=0,se(p.Error,{error:new wt("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:o.sessionid},o.uuid);break}if(this.retriedConnect+=1,5===this.retriedConnect){this.retriedConnect=0,se(p.Error,{error:new Error("Connection Retry Failed"),sessionId:o.sessionid},o.uuid);break}setTimeout((()=>{if(C.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){const e=Object.values(o.calls).some((e=>{var t;return(null===(t=e.peer)||void 0===t?void 0:t.instance)&&!e.signalingStateClosed}));if(e)return C.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();C.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:C.warn("GatewayState message unknown method:",e)}break}C.debug("Verto message unknown method:",e);break}}}_retrieveCallId(e,t){const i=Object.keys(this.session.calls);if("bootObj"!==e.action)return i.find((e=>this.session.calls[e].channels.includes(t)));{const t=e.data.find((e=>i.includes(e[0])));if(t instanceof Array)return t[0]}}_handlePvtEvent(e){return t(this,void 0,void 0,(function*(){const{session:t}=this,i=t.relayProtocol,{action:n,laChannel:s,laName:o,chatChannel:r,infoChannel:a,modChannel:c,conferenceMemberID:d,role:l,callID:u}=e;switch(n){case"conference-liveArray-join":{const i=()=>{t.vertoBroadcast({nodeId:this.nodeId,channel:s,data:{liveArray:{command:"bootstrap",context:s,name:o}}})},n={nodeId:this.nodeId,channels:[s],handler:({data:n})=>{const r=u||this._retrieveCallId(n,s);if(r&&t.calls.hasOwnProperty(r)){const a=t.calls[r];a._addChannel(s),a.extension=o,a.handleConferenceUpdate(n,e).then((e=>{"INVALID_PACKET"===e&&i()}))}}},r=yield t.vertoSubscribe(n).catch((e=>{C.error("liveArray subscription error:",e)}));We(r,s)&&i();break}case"conference-liveArray-part":{let e=null;if(s&&t._existsSubscription(i,s)){const{callId:n=null}=t.subscriptions[i][s];if(e=t.calls[n]||null,null!==n){const i={type:V.conferenceUpdate,action:K.Leave,conferenceName:o,participantId:Number(d),role:l};se(p.Notification,i,n,!1)||se(p.Notification,i,t.uuid),null===e&&ne(p.Notification,null,n)}}const n=[s,r,a,c];t.vertoUnsubscribe({nodeId:this.nodeId,channels:n}).then((({unsubscribedChannels:t=[]})=>{e&&(e.channels=e.channels.filter((e=>!t.includes(e))))})).catch((e=>{C.error("liveArray unsubscribe error:",e)}));break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":ft(this.session,e);break;case"logo-info":{const t={type:V.conferenceUpdate,action:K.LogoInfo,logo:e.logoURL};se(p.Notification,t,this.session.uuid);break}}}}class kt extends Ct{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>t(this,void 0,void 0,(function*(){this._idle=!1;const{autoReconnect:e=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=e}})})),this.handleAnonymousLoginOnSocketOpen=()=>t(this,void 0,void 0,(function*(){this._idle=!1,yield this.login()})),this._vertoHandler=new It(this),window.addEventListener("beforeunload",(e=>{this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&(C.info(`Hanging up call due to window unload: ${e}`),this.calls[e].hangup({},!0))}))}))}validateOptions(){return P(this.options)||N(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 St(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!!N(this.options)||Boolean(e.destinationNumber)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){return P(this.options)?this.handleLoginOnSocketOpen():N(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0}))}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class Et extends kt{constructor(e){super(e),C.info(`SDK version: ${be}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Ze()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:et.full},{browserName:"Firefox",features:["audio"],supported:et.partial},{browserName:"Safari",supported:et.not_supported},{browserName:"Edge",supported:et.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:et.not_supported},{browserName:"Firefox",supported:et.not_supported},{browserName:"Safari",features:["video","audio"],supported:et.full},{browserName:"Edge",supported:et.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:et.full},{browserName:"Firefox",features:["audio"],supported:et.partial},{browserName:"Safari",supported:et.not_supported},{browserName:"Edge",supported:et.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:et.full},{browserName:"Firefox",features:["audio"],supported:et.partial},{browserName:"Safari",features:["video","audio"],supported:et.full},{browserName:"Edge",features:["audio"],supported:et.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:et.full},{browserName:"Firefox",features:["audio"],supported:et.partial},{browserName:"Safari",supported:et.not_supported},{browserName:"Edge",features:["audio"],supported:et.partial}]}]}}class Tt{static run(e){return t(this,void 0,void 0,(function*(){const t=M({}),i=M({}),n=new Et(e.credentials);yield n.connect(),n.on(p.Ready,t.resolve),n.on(p.Error,t.reject),n.on(p.MediaError,t.reject),n.on(p.MediaError,t.reject),n.on(p.Notification,(e=>{e.call&&e.call.sipCode>=400&&i.reject(new Error(e.call.sipReason))})),te(p.StatsReport,(e=>{i.resolve(Tt.mapReport(e))})),yield t.promise,yield n.newCall({destinationNumber:e.texMLApplicationNumber,debug:!0});const s=yield i.promise;return yield n.disconnect(),s}))}static mapReport(e){var t,i,n,s,o,r,a,c,d,l,u,h,p;const g=[],v=[];for(const t of e)switch(t.event){case"onicecandidate":t.data&&g.push(t.data);break;case"stats":v.push(t.data)}let f=0,m=1/0,b=-1/0,y=0,_=1/0,S=-1/0,C=0;v.forEach((e=>{var t,i,n;if(!(null===(t=e.remote.audio.inbound)||void 0===t?void 0:t[0]))return;f+=1;const s=null!==(i=e.remote.audio.inbound[0].jitter)&&void 0!==i?i:0,o=null!==(n=e.remote.audio.inbound[0].roundTripTime)&&void 0!==n?n:0;y+=s,C+=o,b=Math.max(b,s),m=Math.min(m,s),S=Math.max(S,o),_=Math.min(_,o)}));const w=C/f,I=y/f,k=v[v.length-1],E=dt({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:_},quality:lt(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:""}}}export{St as Call,H as ERROR_TYPE,V as NOTIFICATION_TYPE,Tt as PreCallDiagnosis,p as SwEvent,Et as TelnyxRTC};
|
|
1
|
+
function e(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(i[n[s]]=e[n[s]])}return i}function t(e,t,i,n){return new(i||(i=Promise))((function(s,o){function r(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var i="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),n=new Uint8Array(16);function s(){if(!i)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return i(n)}for(var o=[],r=0;r<256;++r)o[r]=(r+256).toString(16).substr(1);function a(e,t,i){var n=t&&i||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var r=(e=e||{}).random||(e.rng||s)();if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,t)for(var a=0;a<16;++a)t[n+a]=r[a];return t||function(e,t){var i=t||0,n=o;return[n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]]].join("")}(r)}const c="wss://rtc.telnyx.com",d=1006,l={urls:"stun:stun.l.google.com:19302"},u=[{urls:"stun:stun.telnyx.com:3478"},l,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],h=[{urls:"stun:stundev.telnyx.com:3478"},l,{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 p;!function(e){e.SocketOpen="telnyx.socket.open",e.SocketClose="telnyx.socket.close",e.SocketError="telnyx.socket.error",e.SocketMessage="telnyx.socket.message",e.SpeedTest="telnyx.internal.speedtest",e.Ready="telnyx.ready",e.Error="telnyx.error",e.Notification="telnyx.notification",e.StatsFrame="telnyx.stats.frame",e.StatsReport="telnyx.stats.report",e.Messages="telnyx.messages",e.Calls="telnyx.calls",e.MediaError="telnyx.rtc.mediaError",e.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError",e.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed"}(p||(p={}));var g="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function v(e,t){return e(t={exports:{}},t.exports),t.exports}var f=v((function(e){var t,i;t=g,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 m={debug:0,info:1,warn:2,error:3};class b{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(m[e]<m[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 _(){return y}function S(e){y=e}const C=f.getLogger("telnyx"),w={trace:0,debug:1,info:2,warn:3,error:4};let I=w.info;function k(e){if(null==e)return e;if("object"!=typeof e)return e;try{const t=JSON.stringify(e),i=JSON.parse(t);if("object"==typeof i&&null!==i&&Object.keys(i).length>1)return i}catch(e){}const t={};for(const i in e)try{const n=e[i];if("function"==typeof n)continue;if("object"==typeof n&&null!==n)try{t[i]=JSON.parse(JSON.stringify(n))}catch(e){t[i]=String(n)}else t[i]=n}catch(e){}return Object.keys(t).length>0?t:{value:String(e)}}const E=C.methodFactory;C.methodFactory=(e,t,i)=>{const n=E(e,t,i);return function(...t){if(w[e]>=I){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(const i of t)e.push(i);n(...e)}const i=_();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]?k(s[0]):{args:s.map(k)}),i.addEntry(e,o,r)}}},C.setLevel("debug",!1);const T=e=>{const[t,i,n,s,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){C.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},R=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},x=e=>e instanceof Function||"function"==typeof e,O=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,A=/^(ws|wss):\/\//,L=(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?L(a,r):{result:s}},P=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),N=({login:e,passwd:t,password:i,login_token:n})=>Boolean(e&&(t||i)||n),D=({anonymous_login:e})=>Boolean(e)&&Boolean(e.target_id)&&Boolean(e.target_type),M=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 j({debounceTime:e}){let t,i;return{promise:new Promise(((n,s)=>{t=e?U(n,e):n,i=s})),resolve:t,reject:i}}const U=(e,t)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout((()=>{e(...n)}),t)}},$="telnyx-voice-sdk-id";function F(){return sessionStorage.getItem($)}var B,G,V;"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{sessionStorage.removeItem($)})),function(e){e.Offer="offer",e.Answer="answer"}(B||(B={})),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"}(V||(V={}));const H={generic:"event",[V.Display]:"participantData",[V.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},q={invalidCredentialsOptions:"InvalidCredentialsOptions"},W={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 J,K,z,Y,Q;!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"}(J||(J={})),function(e){e.Participant="participant",e.Moderator="moderator"}(K||(K={})),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"}(Y||(Y={})),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"}(Q||(Q={}));const X="GLOBAL",Z={},ee=(e,t)=>`${e}|${t}`,te=(e,t=X)=>ee(e,t)in Z,ie=(e,t,i=X)=>{const n=ee(e,i);n in Z||(Z[n]=[]),Z[n].push(t)},ne=(e,t,i=X)=>{const n=function(s){se(e,n,i),t(s)};return n.prototype.targetRef=t,ie(e,n,i)},se=(e,t,i=X)=>{if(!te(e,i))return!1;const n=ee(e,i);if(x(t)){for(let e=Z[n].length-1;e>=0;e--){const i=Z[n][e];(t===i||i.prototype&&t===i.prototype.targetRef)&&Z[n].splice(e,1)}}else Z[n]=[];return 0===Z[n].length&&delete Z[n],!0},oe=(e,t,i=X,n=!0)=>{const s=n&&i!==X;if(!te(e,i))return s&&oe(e,t),!1;const o=ee(e,i),r=Z[o].length;if(!r)return s&&oe(e,t),!1;for(let e=r-1;e>=0;e--)Z[o][e](t);return s&&oe(e,t),!0},re=e=>{const t=ee(e,"");Object.keys(Z).filter((e=>0===e.indexOf(t))).forEach((e=>delete Z[e]))};let ae="undefined"!=typeof WebSocket?WebSocket:null;const ce=0,de=1,le=2,ue=3;class he{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=c,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":c),t&&(this._host=(e=>`${A.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===de}get connecting(){return!!this._wsClient&&this._wsClient.readyState===ce}get closing(){return!!this._wsClient&&this._wsClient.readyState===le}get closed(){return!!this._wsClient&&this._wsClient.readyState===ue}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){const e=new URL(this._host);let t=F();this.session.options.rtcIp&&this.session.options.rtcPort&&(t=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),t&&e.searchParams.set("voice_sdk_id",t),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),t&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),C.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0);try{this._wsClient=new ae(e.toString()),this._registerSocketEvents(this._wsClient)}catch(e){const t=e instanceof Error?e:new Error(`Failed to create WebSocket: ${String(e)}`);oe(p.Error,{error:t},this.session.uuid),C.error("WebSocket connection failed:",t)}}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();ne(i.id,(i=>{const{result:n,error:s}=L(i);return s?t(s):e(n)}))}));return C.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;x(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout((()=>this._handleCloseTimeout(e)),5e3))}_registerSocketEvents(e){e.onopen=e=>oe(p.SocketOpen,e,this.session.uuid),e.onclose=t=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),oe(p.SocketClose,t,this.session.uuid)),e.onerror=t=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error"),oe(p.SocketError,{error:t,sessionId:this.session.sessionid},this.session.uuid)),e.onmessage=e=>{var t,i;const n=R(e.data);var s;if("string"!=typeof n){if(n.voice_sdk_id&&(s=n.voice_sdk_id,sessionStorage.setItem($,s)),this._unsetTimer(n.id),C.debug("RECV: \n",JSON.stringify(n,null,2),"\n"),Q[`${null===(i=null===(t=null==n?void 0:n.result)||void 0===t?void 0:t.params)||void 0===i?void 0:i.state}`]||!oe(n.id,n)){const e=M(n);oe(p.SocketMessage,n,this.session.uuid),Boolean(e)&&(this.previousGatewayState=e)}}else this._handleStringResponse(n)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(e){this._safetyTimeoutId=null,e&&e.readyState!==ue?(C.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e||oe(p.SocketClose,{code:d,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1},this.session.uuid)):C.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(C.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,t){this._wsClient===e?(C.debug(`Nulling socket reference (reason: ${t})`),this._wsClient=null):C.debug(`Skipping socket cleanup - old socket already replaced (reason: ${t})`)}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),oe(p.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else C.warn("Unknown message from socket",e)}}class pe{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:a()},e)}}const ge={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 ve extends pe{constructor(t={}){if(super(),t.hasOwnProperty("dialogParams")){const i=e(t.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const e in ge)e&&i.hasOwnProperty(e)&&(i[ge[e]]=i[e],delete i[e]);t.dialogParams=i}this.buildRequest({method:this.toString(),params:t})}}class fe extends ve{constructor(e){super(),this.method=V.GatewayState;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class me{constructor(e){this.pendingRequestId=null,this.onSocketMessage=e=>t(this,void 0,void 0,(function*(){e.id===this.pendingRequestId&&this.gatewayStateTask.resolve(M(e))})),this.getIsRegistered=()=>t(this,void 0,void 0,(function*(){const e=new fe(F());this.pendingRequestId=e.request.id,this.gatewayStateTask=j({}),this.session.execute(e);const t=yield this.gatewayStateTask.promise;return!!t&&[Q.REGISTER,Q.REGED].includes(t)})),this.session=e,this.gatewayStateTask=j({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class be extends ve{constructor(e){super(),this.method=V.Ping;this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}var ye="2.25.21",_e=ye;class Se extends ve{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:_e,data:navigator.userAgent}};n&&(r.sessid=n),this.buildRequest({method:this.method,params:r})}}class Ce extends ve{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class we extends ve{toString(){return V.Invite}}class Ie extends ve{toString(){return V.Answer}}class ke extends ve{toString(){return V.Attach}}class Ee extends ve{toString(){return V.Bye}}class Te extends ve{toString(){return V.Candidate}}class Re extends ve{toString(){return V.EndOfCandidates}}class xe extends ve{toString(){return V.Modify}}class Oe extends ve{toString(){return V.Info}}class Ae extends ve{toString(){return V.Broadcast}}class Le extends ve{toString(){return V.Subscribe}}class Pe extends ve{toString(){return V.Unsubscribe}}class Ne extends ve{constructor(e){super(),this.method="anonymous_login";const{target_type:t,target_id:i,target_version_id:n,userVariables:s,sessionId:o,reconnection:r}=e,a={target_type:t,target_id:i,userVariables:s,reconnection:r,"User-Agent":{sdkVersion:_e,data:navigator.userAgent}};o&&(a.sessid=o),n&&(a.target_version_id=n),this.buildRequest({method:this.method,params:a})}}class De{constructor(e){if(this.options=e,this.uuid=a(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.callReportId=null,this.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",I=null!==(i=w[t])&&void 0!==i?i:w.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 he(this),this.registerAgent=new me(this)}get __logger(){return C}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return t(this,void 0,void 0,(function*(){return this.registerAgent.getIsRegistered()}))}get reconnectDelay(){return 1e3*P(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}),C.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 N(this.options)||D(this.options)}broadcast(e){}disconnect(){return t(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(),C.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")}))}on(e,t){return ie(e,t,this.uuid),this}off(e,t){return se(e,t,this.uuid),this}connect(){return t(this,void 0,void 0,(function*(){this.connection||(C.debug("No existing connection found, creating a new one."),this.connection=new he(this)),this._attachListeners(),this._autoReconnect=!0,this.connection.isAlive||(C.debug("Initiating connection to the server..."),this.connection.connect()),C.debug("Connect method called. Connection initiated.")}))}_handleLoginError(e){oe(p.Error,{error:e,sessionId:this.sessionid},this.uuid)}login({creds:e,onSuccess:i,onError:n}={}){return t(this,void 0,void 0,(function*(){if(this.connection&&this.connection.isAlive){if(e&&(void 0!==e.login&&(this.options.login=e.login),void 0!==e.password&&(this.options.password=e.password),void 0!==e.passwd&&(this.options.passwd=e.passwd),void 0!==e.login_token&&(this.options.login_token=e.login_token),void 0!==e.userVariables&&(this.options.userVariables=e.userVariables),void 0!==e.anonymous_login&&(this.options.anonymous_login=e.anonymous_login)),N(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(D(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const e="Invalid login options provided for authentication.";return C.error(e),void oe(p.Error,{error:new Error(e),type:q.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}}))}_login({type:e,onSuccess:i,onError:n}){return t(this,void 0,void 0,(function*(){let t;t="login"===e?new Se(this.options.login,this.options.password||this.options.passwd,this.options.login_token,this.sessionid,this.options.userVariables,!!F()):new Ne({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,sessionId:this.sessionid,userVariables:this.options.userVariables,reconnection:!!F()});const s=yield this.execute(t).catch((e=>{this._handleLoginError(e),n&&n(e)}));s&&(this.sessionid=s.sessid,i&&i())}))}_onSocketOpen(){return t(this,void 0,void 0,(function*(){}))}onNetworkClose(){this.relayProtocol&&re(this.relayProtocol);for(const e in this.subscriptions)re(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect&&(this._reconnectTimeout=setTimeout((()=>{C.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],se(e,null,t)):(delete this.subscriptions[e],re(e)))}_addSubscription(e,t=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},x(t)&&ie(e,t,i))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(p.SocketOpen,this._onSocketOpen),this.on(p.SocketClose,this.onNetworkClose),this.on(p.SocketError,this.onNetworkClose),this.on(p.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(p.SocketOpen,this._onSocketOpen),this.off(p.SocketClose,this.onNetworkClose),this.off(p.SocketError,this.onNetworkClose),this.off(p.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&&(C.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new be(F()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout((()=>this._resetKeepAlive()),35e3)}setPingReceived(){C.debug("Ping received"),this._pong=!0}static on(e,t){ie(e,t)}static off(e){se(e)}static uuid(){return a()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const Me=e=>navigator.mediaDevices.getUserMedia(e),je=e=>e&&e instanceof MediaStream,Ue=(e,t)=>{const i=O(e);null!==i&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=t)},$e=(e,i)=>t(void 0,void 0,void 0,(function*(){const t=O(e);if(null===t)return C.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof i)return C.info(`Invalid speaker deviceId: '${i}'`),!1;try{return yield t.setSinkId(i),!0}catch(e){return!1}})),Fe=e=>{e&&"live"===e.readyState&&e.stop()},Be=e=>{je(e)&&e.getTracks().forEach(Fe),e=null},Ge=i=>t(void 0,void 0,void 0,(function*(){C.info("RTCService.getUserMedia",i);const{audio:t,video:n}=i;if(!t&&!n)return null;try{return yield Me(i)}catch(t){if(C.error("getUserMedia error: ",t),(e=>"NotReadableError"===e.name||"NotFoundError"===e.name||"OverconstrainedError"===e.name)(t)){const n=(t=>{const{audio:i,video:n}=t;let s=!1,o=i,r=n;if("object"==typeof i&&null!==i&&"deviceId"in i){s=!0;const t=e(i,["deviceId"]);o=0===Object.keys(t).length||t}if("object"==typeof n&&null!==n&&"deviceId"in n){s=!0;const t=e(n,["deviceId"]);r=0===Object.keys(t).length||t}return s?{audio:o,video:r}:null})(i);if(n){C.warn("Device not found or not readable, falling back to default device");try{return yield Me(n)}catch(e){throw C.error("Fallback getUserMedia also failed: ",e),t}}}throw t}})),Ve=(e=null,i=!1)=>t(void 0,void 0,void 0,(function*(){let t=[];const n=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===Y.AudioIn||e===Y.AudioOut,video:!e||e===Y.Video}))(e)).catch((e=>(C.error(e),null)));if(n){if(Be(n),t=yield navigator.mediaDevices.enumerateDevices(),e&&(t=t.filter((t=>t.kind===e))),!0===i)return t;const s=[];t=t.filter((e=>{if(!e.groupId)return!0;const t=`${e.kind}-${e.groupId}`;return!s.includes(t)&&(s.push(t),!0)}))}return t})),He=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],qe=(e,i,n)=>t(void 0,void 0,void 0,(function*(){const t=yield Ve(n,!0);for(let n=0;n<t.length;n++){const{deviceId:s,label:o}=t[n];if(e===s||i===o)return s}return null})),We=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((i=>{t.hasOwnProperty(i)&&null!==e[i]&&void 0!==e[i]||delete e[i]}))},Je=(e,t)=>{if(!e)return!1;const{subscribed:i,alreadySubscribed:n}=Ke(e);return i.includes(t)||n.includes(t)},Ke=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(!je(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}}))},Ye=e=>{ze(e,"audio",!0)},Qe=e=>{ze(e,"audio",!1)},Xe=e=>{ze(e,"audio",null)},Ze=e=>((e,t=null)=>{if(!je(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 et(){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 tt;function it(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 nt(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then((()=>{e._playFulfilled=!0})).catch((t=>{C.error("playAudio",t),e._playFulfilled=!0})))}function st(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"}(tt||(tt={}));class ot extends pe{constructor(e,t){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:a(),type:"message",role:"user",content:[{type:"input_text",text:e},...null==t?void 0:t.map((e=>({type:"image_url",image_url:{url:e}})))]}}})}}class rt{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.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 b(e)}(this.logCollectorOptions),this.logCollector.start(),S(this.logCollector))}start(e){var t,i;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,C.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,logCollectorActive:null!==(i=null===(t=this.logCollector)||void 0===t?void 0:t.isActive())&&void 0!==i&&i}),this.intervalId=setInterval((()=>{this._collectStats()}),this.options.interval))}stop(){var e,i;return t(this,void 0,void 0,(function*(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&(yield this._collectStats(!0));const t=null!==(i=null===(e=this.logCollector)||void 0===e?void 0:e.getLogCount())&&void 0!==i?i:0;this.logCollector&&this.logCollector.stop(),C.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:t,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})}))}flush(e){var t,i;if(this._flushing||0===this.statsBuffer.length)return null;this._flushing=!0;try{const n=this._segmentIndex++,s=this.statsBuffer;this.statsBuffer=[];const o=null!==(i=null===(t=this.logCollector)||void 0===t?void 0:t.drain())&&void 0!==i?i:[],r=new Date,a=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(r.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:r.toISOString()}),stats:s},o.length>0?{logs:o}:{}),{segment:n});return C.info("CallReportCollector: Flushed intermediate segment",{segment:n,intervals:s.length,logEntries:o.length,callId:e.callId}),a}finally{this._flushing=!1}}postReport(e,i,n,s){var o,r;return t(this,void 0,void 0,(function*(){const t=null===(o=this.logCollector)||void 0===o?void 0:o.getLogs(),a=t&&t.length>0;if(!this.options.enabled)return void C.info("CallReportCollector: Skipping report — call reports disabled");if(0===this.statsBuffer.length&&!a)return void C.info("CallReportCollector: Skipping report — no stats or logs collected");const c=this._segmentIndex>0,d=this._segmentIndex,l=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:this.callEndTime&&this.callStartTime?(this.callEndTime.getTime()-this.callStartTime.getTime())/1e3:void 0,startTimestamp:this.callStartTime.toISOString(),endTimestamp:null===(r=this.callEndTime)||void 0===r?void 0:r.toISOString()}),stats:this.statsBuffer},t&&t.length>0?{logs:t}:{}),c?{segment:d}:{});yield this._sendPayload(l,i,n,s)}))}sendPayload(e,i,n,s){return t(this,void 0,void 0,(function*(){yield this._sendPayload(e,i,n,s)}))}_sendPayload(e,i,n,s){var o,r;return t(this,void 0,void 0,(function*(){try{const t=new URL(n),a=`${t.protocol.replace(/^ws/,"http")}//${t.host}/call_report`,c=void 0!==e.segment&&!e.summary.endTimestamp?`intermediate segment ${e.segment}`:"final report";C.info(`CallReportCollector: Posting ${c}`,{endpoint:a,intervals:e.stats.length,logEntries:null!==(r=null===(o=e.logs)||void 0===o?void 0:o.length)&&void 0!==r?r:0,callId:e.summary.callId,segment:e.segment});const d={"Content-Type":"application/json","x-call-report-id":i,"x-call-id":e.summary.callId};s&&(d["x-voice-sdk-id"]=s);const l=yield fetch(a,{method:"POST",headers:d,body:JSON.stringify(e)});if(l.ok)C.info(`CallReportCollector: Successfully posted ${c}`);else{const e=yield l.text();C.error(`CallReportCollector: Failed to post ${c}`,{status:l.status,error:e})}}catch(e){C.error("CallReportCollector: Error posting report",{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&&S(null),this.logCollector=null)}_collectStats(e=!1){var i,n;return t(this,void 0,void 0,(function*(){if(this.peerConnection&&this.intervalStartTime)try{const t=yield this.peerConnection.getStats(),s=new Date;let o=null,r=null,a=null;if(t.forEach((e=>{switch(e.type){case"outbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(o=e);break;case"inbound-rtp":"audio"===e.kind&&"audio"===e.mediaType&&(r=e);break;case"candidate-pair":(e.nominated||"succeeded"===e.state)&&(a=e)}})),o){const e=this._getTrackAudioLevel(t,o.trackId);if(null!==e&&this.intervalAudioLevels.outbound.push(e),void 0!==this.previousStats.outboundBytes&&void 0!==this.previousStats.timestamp){const e=(o.bytesSent||0)-this.previousStats.outboundBytes,t=(o.timestamp||s.getTime())-this.previousStats.timestamp;if(t>0){const i=8*e*1e3/t;this.intervalBitrates.outbound.push(i)}}this.previousStats.outboundBytes=o.bytesSent}if(r){const e=this._getTrackAudioLevel(t,r.trackId);if(null!==e&&this.intervalAudioLevels.inbound.push(e),void 0!==r.jitter&&this.intervalJitters.push(1e3*r.jitter),void 0!==this.previousStats.inboundBytes&&void 0!==this.previousStats.timestamp){const e=(r.bytesReceived||0)-this.previousStats.inboundBytes,t=(r.timestamp||s.getTime())-this.previousStats.timestamp;if(t>0){const i=8*e*1e3/t;this.intervalBitrates.inbound.push(i)}}this.previousStats.inboundBytes=r.bytesReceived}a&&void 0!==a.currentRoundTripTime&&this.intervalRTTs.push(a.currentRoundTripTime),this.previousStats.timestamp=s.getTime();const c=s.getTime()-this.intervalStartTime.getTime();if(e||c>=this.options.interval){const e=this._createStatsEntry(this.intervalStartTime,s,o,r,a);if(this.statsBuffer.push(e),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),C.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this.onFlushNeeded&&!this._flushing){const e=this.statsBuffer.length,t=null!==(n=null===(i=this.logCollector)||void 0===i?void 0:i.getLogCount())&&void 0!==n?n:0;if(e>=rt.STATS_FLUSH_THRESHOLD||t>=rt.LOGS_FLUSH_THRESHOLD){C.info("CallReportCollector: Approaching buffer limits, requesting flush",{statsIntervals:e,logEntries:t});try{this.onFlushNeeded()}catch(e){C.error("CallReportCollector: onFlushNeeded callback error",{error:e})}}}this.intervalStartTime=s,this._resetIntervalAccumulators()}}catch(e){C.error("CallReportCollector: Error collecting stats",{error:e})}}))}_createStatsEntry(e,t,i,n,s){const o={intervalStartUtc:e.toISOString(),intervalEndUtc:t.toISOString(),audio:{}};return i&&(o.audio.outbound={packetsSent:i.packetsSent,bytesSent:i.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)}),n&&(o.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&&(o.connection={roundTripTimeAvg:this._average(this.intervalRTTs),packetsSent:s.packetsSent,packetsReceived:s.packetsReceived,bytesSent:s.bytesSent,bytesReceived:s.bytesReceived}),o}_getTrackAudioLevel(e,t){if(!t)return null;const i=e.get(t);return i&&i.audioLevel||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:[]}}}rt.STATS_FLUSH_THRESHOLD=300,rt.LOGS_FLUSH_THRESHOLD=800;var at,ct=v((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 y(e,t,i){return 8*function(e,t,i){const n=e[i],s=t?t[i]:null;return null===n||null===s?null:(n-s)/(e.timestamp-t.timestamp)*1e3}(e,t,i)}function _(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=y(e,i,"bytesReceived"),e.packetRate=y(e,i,"packetsReceived")})),e.audio.outbound.map((e=>{let i=t.audio.outbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesSent"),e.packetRate=y(e,i,"packetsSent")})),e.video.inbound.map((e=>{let i=t.video.inbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesReceived"),e.packetRate=y(e,i,"packetsReceived")})),e.video.outbound.map((e=>{let i=t.video.outbound.find((t=>t.id===e.id));e.bitrate=y(e,i,"bytesSent"),e.packetRate=y(e,i,"packetsSent")})),e):e}(n,t),n}let C,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=_(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)}}}}));(at=ct)&&at.__esModule&&Object.prototype.hasOwnProperty.call(at,"default")&&at.default;var dt=ct.WebRTCStats;function lt(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 ut(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 ht extends pe{constructor(e,t){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:t})}}class pt extends pe{constructor(e,t){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:t})}}class gt extends pe{constructor(e,t){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:t})}}function vt(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 ft(e,i){const n=a();let s=!1;const o=new dt({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),r=i=>t(this,void 0,void 0,(function*(){"stats"===i.event&&oe(p.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=lt({jitter:1e3*h,rtt:1e3*p,packetsLost:v,packetsReceived:g});return{jitter:h,rtt:p,mos:f,quality:ut(f),inboundAudio:d.inbound[0],outboundAudio:d.outbound[0],remoteInboundAudio:u.inbound[0],remoteOutboundAudio:u.outbound[0]}}(i),e.uuid),yield e.execute(new gt(n,i))}));return{get isRunning(){return s},start:(a,c,d)=>t(this,void 0,void 0,(function*(){if(s)C.debug(`[${i}] Stats reporter already running, skipping start`);else{yield e.execute(new ht(n,i)),o.on("timeline",r);try{yield o.addConnection({pc:a,peerId:c,connectionId:d}),s=!0}catch(e){C.error(`[${i}] Failed to start stats reporter:`,e),o.removeAllPeers(),o.destroy()}}})),stop:r=>t(this,void 0,void 0,(function*(){const t=o.getTimeline();if(oe(p.StatsReport,t,e.uuid),"file"===r){!function(e,t){const i=new Blob([JSON.stringify(e)],{type:"application/json"}),n=URL.createObjectURL(i),s=document.createElement("a");s.href=n,s.download=`${t}.json`,s.click(),URL.revokeObjectURL(n)}(t,`webrtc-stats-${n}-${Date.now()}`)}yield e.execute(new pt(n,i)),o.removeAllPeers(),o.destroy(),s=!1})),reportConnectionStateChange:e=>{const t={event:"connectionstatechange-detailed",tag:"connection",timestamp:(new Date).toISOString(),data:e};r(t)},reportIceCandidateError:e=>{const t={event:"icecandidateerror-detailed",tag:"connection",timestamp:(new Date).toISOString(),data:e};r(t)}}}const mt=(e,t)=>{const{contentType:i,canvasType:n,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&"mcu-personal-canvas"!==n&&delete o.memberID;const a={type:H.conferenceUpdate,call:e.calls[s],canvasInfo:bt(o),currentLayerIdx:r};switch(i){case"layer-info":{const t=Object.assign({action:z.LayerInfo},a);oe(p.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:z.LayoutInfo},a);oe(p.Notification,t,e.uuid);break}}},bt=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return R(t)};class yt{constructor(e,i,n,s,o){this.type=e,this.options=i,this.onSdpReadyTwice=null,this.statsReporter=null,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this.handleConnectionStateChange=()=>t(this,void 0,void 0,(function*(){const{connectionState:e}=this.instance;if(C.info(`[${(new Date).toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${e}`),"failed"===e||"disconnected"===e){const e=()=>t(this,void 0,void 0,(function*(){if(this.isDebugEnabled&&this.statsReporter){const e=yield function(e,i){return t(this,void 0,void 0,(function*(){const t={connectionState:e.connectionState,previousConnectionState:i,iceConnectionState:e.iceConnectionState,iceGatheringState:e.iceGatheringState,signalingState:e.signalingState},n=e.getTransceivers();if(n.length>0){const e=n[0].sender,i=null==e?void 0:e.transport;i&&(t.dtlsState=i.state)}e.sctp&&(t.sctpState=e.sctp.state);try{const i=yield e.getStats();i.forEach((e=>{"candidate-pair"===e.type&&"succeeded"===e.state&&(t.candidatePairState=e.state,i.forEach((i=>{"local-candidate"===i.type&&i.id===e.localCandidateId&&(t.localCandidateType=i.candidateType,t.selectedCandidatePair=t.selectedCandidatePair||{local:{},remote:{}},t.selectedCandidatePair.local={address:i.address,port:i.port,protocol:i.protocol,candidateType:i.candidateType}),"remote-candidate"===i.type&&i.id===e.remoteCandidateId&&(t.remoteCandidateType=i.candidateType,t.selectedCandidatePair=t.selectedCandidatePair||{local:{},remote:{}},t.selectedCandidatePair.remote={address:i.address,port:i.port,protocol:i.protocol,candidateType:i.candidateType})}))),"transport"===e.type&&(t.dtlsCipher=e.dtlsCipher,t.srtpCipher=e.srtpCipher,t.tlsVersion=e.tlsVersion,e.dtlsState&&(t.dtlsState=e.dtlsState))}))}catch(e){C.error("Error gathering connection state details:",e)}return t}))}(this.instance,this._prevConnectionState);this.statsReporter.reportConnectionStateChange(e)}window.removeEventListener("online",e)}));navigator.onLine?e():window.addEventListener("online",e)}"failed"===e&&oe(p.PeerConnectionFailureError,{error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${e}`),sessionId:this._session.sessionid},this.options.id),this._prevConnectionState=e,this._isTrickleIce()&&("connecting"===e&&performance.mark("peer-connection-connecting"),"connected"===e&&(performance.mark("peer-connection-connected"),console.group("Performance Metrics"),console.table(this.trickleIcePerformanceMetrics),console.groupEnd(),performance.clearMarks()))})),this._handleIceConnectionStateChange=()=>{C.debug(`[${(new Date).toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=()=>{C.debug(`[${(new Date).toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setCodecs=(e,t)=>{if(e.setCodecPreferences)return e.setCodecPreferences(t)},C.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!i.video},this._sdpReady=this._sdpReady.bind(this),this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this._session=n,this._trickleIceSdpFn=s,this._registerPeerEvents=o}get isOffer(){return this.type===B.Offer}get isAnswer(){return this.type===B.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 t(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(){C.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach(((e,t)=>{C.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),C.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))}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(C.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":oe(p.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(C.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){C.info("Negotiation needed event"),"stable"!==this.instance.signalingState||this._negotiating?C.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&&Ue(i,this.options.remoteStream)}createPeerConnection(){return t(this,void 0,void 0,(function*(){var e;this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",(e=>{this.options.remoteStream=e.stream})),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:B.Offer})),this.options.localStream=yield this._retrieveLocalStream().catch((e=>(oe(p.MediaError,e,this.options.id),null))),this.options.mutedMicOnStart&&je(this.options.localStream)&&(C.info("Muting local audio tracks on start"),Qe(this.options.localStream)),performance.mark("peer-creation-end")}))}init(){var e;return t(this,void 0,void 0,(function*(){yield this.createPeerConnection(),this.isDebugEnabled&&(this.statsReporter=ft(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(je(i)){const e=i.getAudioTracks();let s=[...e];if(C.info("Local audio tracks: ",e),"object"==typeof this.options.audio&&e.forEach((e=>{C.info("Local audio tracks constraints: ",e.getConstraints())})),this.options.video){const t=i.getVideoTracks();s=[...e,...t],C.info("Local video tracks: ",t),"object"==typeof this.options.video&&t.forEach((e=>{C.info("Local video tracks constraints: ",e.getConstraints())}))}const{audioCodecs:o,videoCodecs:r}=(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}})(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&&Ue(t,i)}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);C.info("Add transceiver",e,t)}}_createOffer(){return t(this,void 0,void 0,(function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=!1!==this.options.audio,this._constraints.offerToReceiveVideo=Boolean(this.options.video),C.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){C.error("Peer _createOffer error:",e)}}}))}_setRemoteDescription(e){return t(this,void 0,void 0,(function*(){C.debug("Setting remote description",e),yield this.instance.setRemoteDescription(e)}))}_createAnswer(){return t(this,void 0,void 0,(function*(){if(this._isAnswer()){if("stable"!==this.instance.signalingState&&"have-remote-offer"!==this.instance.signalingState)return C.debug("Skipping negotiation, state:",this.instance.signalingState),C.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:B.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return yield this._setLocalDescription(e),e}catch(e){C.error("Peer _createAnswer error:",e)}}}))}_setLocalDescription(e){return t(this,void 0,void 0,(function*(){yield this.instance.setLocalDescription(e)}))}_sdpReady(){x(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return t(this,void 0,void 0,(function*(){if(je(this.options.localStream))return this.options.localStream;const e=yield(i=this.options,t(void 0,void 0,void 0,(function*(){let{audio:e=!0,micId:t,video:n=!1,camId:s}=i;const{micLabel:o="",camLabel:r=""}=i;return t&&(t=yield qe(t,o,Y.AudioIn).catch((e=>null)),t&&("boolean"==typeof e&&(e={}),e.deviceId={exact:t})),s&&(s=yield qe(s,r,Y.Video).catch((e=>null)),s&&("boolean"==typeof n&&(n={}),n.deviceId={exact:s})),{audio:e,video:n}})));var i;return Ge(e)}))}_isOffer(){return this.type===B.Offer}_isAnswer(){return this.type===B.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 C.info("RTC config",n),n}restartStatsReporter(){return t(this,void 0,void 0,(function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?C.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(C.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):C.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))}))}close(){return t(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)}))}}const _t=_e;class St{constructor(e,t,i=!1){this.session=e,this._isRecovering=i,this._callReportCollector=null,this.id="",this.state=J[J.New],this.prevState="",this.channels=[],this.role=K.Participant,this.extension=null,this._state=J.New,this._prevState=J.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._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:n,speaker:s,micId:o,micLabel:r,camId:a,camLabel:c,localElement:d,remoteElement:l,options:u,mediaConstraints:{audio:h,video:p},ringtoneFile:g,ringbackFile:v}=e;this.options=Object.assign({},W,{audio:h,video:p,iceServers:(null==t?void 0:t.iceServers)&&Array.isArray(t.iceServers)?t.iceServers:n,localElement:d,remoteElement:l,micId:o,micLabel:r,camId:a,camLabel:c,speakerId:s,ringtoneFile:g,ringbackFile:v,debug:u.debug,debugOutput:u.debugOutput,trickleIce:u.trickleIce,prefetchIceCandidates:u.prefetchIceCandidates,forceRelayCandidate:u.forceRelayCandidate,keepConnectionAliveOnSocketClose:u.keepConnectionAliveOnSocketClose,mutedMicOnStart:u.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=it(this.options.ringtoneFile,"_ringtone"),this._ringback=it(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!Ze(this.options.localStream)}invite(){return t(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 yt(B.Offer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),this._creatingPeer=!1}))}answer(e={}){var i;return t(this,void 0,void 0,(function*(){this._creatingPeer=!0,performance.mark("new-call-start"),this.stopRingtone(),this.direction=G.Inbound,(null===(i=null==e?void 0:e.customHeaders)||void 0===i?void 0:i.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 yt(B.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(){nt(this._ringtone)}stopRingtone(){st(this._ringtone)}playRingback(){nt(this._ringback)}stopRingback(){st(this._ringback)}hangup(e,t){var i,n,s;const o=e||{},r=!1!==t,a=this._state<J.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=o.cause||a.cause,this.causeCode=o.causeCode||a.causeCode,this.sipCode=o.sipCode||null,this.sipReason=o.sipReason||null,this.sipCallId=o.sip_call_id||null,this.options.customHeaders=[...null!==(i=this.options.customHeaders)&&void 0!==i?i:[],...null!==(s=null===(n=null==o?void 0:o.dialogParams)||void 0===n?void 0:n.customHeaders)&&void 0!==s?s:[]],o.isRecovering)return this._isRecovering=!0,this.setState(J.Recovering),void this._finalize();this.setState(J.Hangup);const c=()=>{var e;C.debug(`[${this.id}] Closing peer from hangup`),null===(e=this.peer)||void 0===e||e.close(),this.setState(J.Destroy)};if(this.stopRingtone(),this.stopRingback(),r){const e=new Ee({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});this._execute(e).catch((e=>{C.error("telnyx_rtc.bye failed!",e),oe(p.Error,{error:e,sessionId:this.session.sessionid},this.session.uuid)})).then(c.bind(this))}else c()}hold(){const e=new xe({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 xe({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 xe({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 Oe({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 Oe({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(n)}muteAudio(){Qe(this.options.localStream)}unmuteAudio(){Ye(this.options.localStream)}toggleAudioMute(){Xe(this.options.localStream)}setAudioInDevice(e,i=this.options.mutedMicOnStart){return t(this,void 0,void 0,(function*(){const{instance:t}=this.peer,n=t.getSenders().find((({track:{kind:e}})=>"audio"===e));if(n){const t=yield Me({audio:{deviceId:{exact:e}}}),s=t.getAudioTracks()[0];s.enabled=!i,n.replaceTrack(s),this.options.micId=e;const{localStream:o}=this.options;o.getAudioTracks().forEach((e=>e.stop())),o.getVideoTracks().forEach((e=>t.addTrack(e))),this.options.localStream=t}}))}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 t(this,void 0,void 0,(function*(){const{instance:t}=this.peer,i=t.getSenders().find((({track:{kind:e}})=>"video"===e));if(i){const t=yield Me({video:{deviceId:{exact:e}}}),n=t.getVideoTracks()[0];i.replaceTrack(n);const{localElement:s,localStream:o}=this.options;Ue(s,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t}}))}deaf(){Qe(this.options.remoteStream)}undeaf(){Ye(this.options.remoteStream)}toggleDeaf(){Xe(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,i){return t(this,void 0,void 0,(function*(){if(!this||!this.peer)return void C.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:t}=this.peer,n=t.getSenders();if(!n)return void C.error("Could not set bandwidth (reason: no senders). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const s=n.find((({track:{kind:e}})=>e===i));if(s){const t=s.getParameters();t.encodings||(t.encodings=[{rid:"h"}]),C.info("Parameters: ",t),C.info("Setting max ","audio"===i?"audio":"video"," bandwidth to: ",e," [bps]"),t.encodings[0].maxBitrate=e,yield s.setParameters(t).then((()=>{C.info("audio"===i?"New audio":"New video"," bandwidth settings in use: ",s.getParameters())})).catch((e=>C.error(e)))}else C.error("Could not set bandwidth (reason: no "+i+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")}))}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,t){if(!e)return;const i={callback:e,constraints:t};if(this._statsBindings.push(i),!this._statsIntervalId){const e=2e3;this._startStats(e)}}setState(e){var t;switch(this._prevState=this._state,this._state=e,this.state=J[this._state].toLowerCase(),this.prevState=J[this._prevState].toLowerCase(),C.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:H.callUpdate,call:this}),e){case J.Purge:C.debug(`Call ${this.id} hangup call due to purge state`),this.hangup({cause:"PURGE",causeCode:1},!1);break;case J.Active:this._isRecovering&&(this._isRecovering=!1,C.debug(`[${this.id}] Recovery complete, call is active`)),setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&$e(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 J.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:i}=e;switch(t){case V.Answer:if(this.gotAnswer=!0,this._state>=J.Active)return;this._state>=J.Early&&this.setState(J.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case V.Media:if(this._state>=J.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case V.Display:{const{display_name:e,display_number:n,display_direction:s}=i;this.extension=n;const o=s===G.Inbound?G.Outbound:G.Inbound,r={type:H[t],call:this,displayName:e,displayNumber:n,displayDirection:o};oe(p.Notification,r,this.id)||oe(p.Notification,r,this.session.uuid);break}case V.Candidate:this._addIceCandidate(i);break;case V.Info:case V.Event:{const e=Object.assign(Object.assign({},i),{type:H.generic,call:this});oe(p.Notification,e,this.id)||oe(p.Notification,e,this.session.uuid);break}case V.Ringing:this.playRingback(),i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id);break;case V.Bye:const e=i.client_state||i.clientState;e&&(this.options.clientState=e),this.stopRingback(),this.stopRingtone(),this.hangup(i,!1)}}handleConferenceUpdate(e,i){return t(this,void 0,void 0,(function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==i.laName)return C.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:t,data:n,hashKey:s=String(this._lastSerno),arrIndex:o}=e;switch(t){case"bootObj":{this._lastSerno=0;const{chatChannel:e,infoChannel:t,modChannel:s,laName:o,conferenceMemberID:r,role:a}=i;this._dispatchConferenceUpdate({action:z.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),t&&(yield this._subscribeConferenceInfo(t));const c=[];for(const e in n)c.push(Object.assign({callId:n[e][0],index:Number(e)},T(n[e][1])));this._dispatchConferenceUpdate({action:z.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:z.Add,callId:s,index:o},T(n)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:z.Modify,callId:s,index:o},T(n)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:z.Delete,callId:s,index:o},T(n)));break;case"clear":this._dispatchConferenceUpdate({action:z.Clear});break;default:this._dispatchConferenceUpdate({action:t,data:n,callId:s,index:o})}}))}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const t=this.session.relayProtocol;this.session._existsSubscription(t,e)&&(this.session.subscriptions[t][e]=Object.assign(Object.assign({},this.session.subscriptions[t][e]),{callId:this.id}))}_subscribeConferenceChat(e){return t(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{direction:t,from:i,fromDisplay:n,message:s,type:o}=e.data;this._dispatchConferenceUpdate({action:z.ChatMessage,direction:t,participantNumber:i,participantName:n,messageText:s,messageType:o,messageId:e.eventSerno})}},i=yield this.session.vertoSubscribe(t).catch((e=>{C.error("ConfChat subscription error:",e)}));Je(i,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(t,i)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:t,type:i}})}}}))}))}_subscribeConferenceInfo(e){return t(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{eventData:t}=e;if("layout-info"===t.contentType)t.callID=this.id,mt(this.session,t);else C.error("Conference-Info unknown contentType",e)}},i=yield this.session.vertoSubscribe(t).catch((e=>{C.error("ConfInfo subscription error:",e)}));Je(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(J.Active):this.setState(J.Held),!0}_handleChangeHoldStateError(e){return C.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){return t(this,void 0,void 0,(function*(){const t=new RTCSessionDescription({sdp:e,type:B.Answer});yield this.peer.instance.setRemoteDescription(t).then((()=>{this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(J.Early),this.gotAnswer&&this.setState(J.Active)})).catch((e=>{C.error("Call setRemoteDescription Error: ",e),this.hangup({cause:"USER_BUSY",causeCode:17},!0)}))}))}_requestAnotherLocalDescription(){x(this.peer.onSdpReadyTwice)?oe(p.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 C.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-${_t}`};switch(s){case B.Offer:this.setState(J.Requesting),o=new we(r);break;case B.Answer:this._isRecovering||this.setState(J.Answering),o=!0===this.options.attach?new ke(r):new Ie(r);break;default:return C.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===B.Offer?this.setState(J.Trying):this.setState(J.Active)})).catch((e=>{C.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 C.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-${_t}`};switch(i){case B.Offer:this.setState(J.Requesting),n=new we(s);break;case B.Answer:this._isRecovering||this.setState(J.Answering),n=!0===this.options.attach?new ke(s):new Ie(s);break;default:return C.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===B.Offer?this.setState(J.Trying):this.setState(J.Active)})).catch((e=>{C.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;null===this._iceTimeout&&(this._iceTimeout=setTimeout((()=>this._onIceSdp(t.localDescription)),1e3)),e.candidate?C.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(t.localDescription)}_onTrickleIce(e){e.candidate&&e.candidate.candidate?(C.debug("RTCPeer Candidate:",e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const t=new Te({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 C.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((()=>{C.debug("Successfully added ICE candidate:",e)})).catch((t=>{C.error("Failed to add ICE candidate:",t,e)}))}_sendEndOfCandidates(){const e=new Re({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e),performance.mark("ice-gathering-end")}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!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.onicecandidateerror=t=>{var i;if(C.debug("ICE candidate error:",t),null===(i=this.peer)||void 0===i?void 0:i.statsReporter){const i=vt(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&&Ue(t,i)}))}_registerTrickleIcePeerEvents(e){e.onicecandidate=e=>{this._onTrickleIce(e)},e.onicegatheringstatechange=t=>{C.debug("ICE gathering state changed:",e.iceGatheringState),"complete"===e.iceGatheringState&&C.debug("Finished gathering candidates")},e.onicecandidateerror=t=>{var i;if(C.debug("ICE candidate error:",t),null===(i=this.peer)||void 0===i?void 0:i.statsReporter){const i=vt(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&&Ue(t,i)}))}_onMediaError(e){this._dispatchNotification({type:H.userMediaError,error:e}),C.error("Media error, hanging up call",e),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:H.peerConnectionFailureError,error:e}),C.error("Peer connection failure error")}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:H.signalingStateClosed},e)),C.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:H.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(oe(p.Notification,e,this.id,!1)||oe(p.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){const{id:e,userVariables:t,remoteCallerNumber:i,onNotification:n}=this.options;var s;this.options.id=e?e.toString():a(),this.id=this.options.id,t&&(s=t,0!==Object.keys(s).length)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,ie(p.MediaError,this._onMediaError,this.id),ie(p.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),ie(p.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),x(n)&&ie(p.Notification,n.bind(this),this.id);const o=!1!==this.session.options.enableCallReports,r=this.session.options.callReportInterval||5e3,c=this.session.options.debugLogLevel||"debug",d=this.session.options.debugLogMaxEntries||1e3;o&&(this._callReportCollector=new rt({enabled:!0,interval:r},{enabled:!0,level:c,maxEntries:d}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()}),this._isRecovering?this.setState(J.Recovering):this.setState(J.New),C.info("New Call with Options:",this.options)}_finalize(){var e;this._stopStats(),C.debug(`[${this.id}] Closing peer from _finalize`),null===(e=this.peer)||void 0===e||e.close();const{remoteStream:t,localStream:i}=this.options;Be(t),Be(i),se(p.MediaError,null,this.id),se(p.PeerConnectionFailureError,null,this.id),se(p.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id],this._postCallReport().catch((e=>{C.error("Unexpected error in _postCallReport",{error:e})}))}_flushIntermediateReport(){var e;if(!this._callReportCollector)return;const t=this.session.callReportId;if(!t)return void C.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 C.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:_t},s=this._callReportCollector.flush(n);if(!s)return;const o=F()||void 0;this._callReportCollector.sendPayload(s,t,i,o).catch((e=>{C.error("Failed to post intermediate call report segment",{error:e})}))}_postCallReport(){var e;return t(this,void 0,void 0,(function*(){if(!this._callReportCollector)return void C.warn("Call report collector not initialized");yield this._callReportCollector.stop();const t=this.session.callReportId;if(!t)return C.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:_t},n=null===(e=this.session.connection)||void 0===e?void 0:e.host;if(!n)return void C.error("Cannot post call report: connection host not available");const s=F()||void 0;this._callReportCollector.postReport(i,t,n,s).catch((e=>{C.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),C.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),C.debug("Stats stopped")}}St.setStateTelnyx=e=>{if(e){switch(e._state){case J.Recovering:e.state="recovering";break;case J.Requesting:case J.Trying:case J.Early:e.state="connecting";break;case J.Active:e.state="active";break;case J.Held:e.state="held";break;case J.Hangup:case J.Destroy:e.state="done";break;case J.Answering:e.state="ringing";break;case J.New:e.state="new"}return e}};class Ct extends St{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,t)=>this.session.execute(new ot(e,t))}hangup(e={},t=!0){this.screenShare instanceof Ct&&this.screenShare.hangup(e,t),super.hangup(e,t)}startScreenShare(e){return t(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 Ct(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof Ct&&this.screenShare.hangup()}setAudioOutDevice(e){return t(this,void 0,void 0,(function*(){this.options.speakerId=e;const{remoteElement:t,speakerId:i}=this.options;return!(!t||!i)&&$e(t,i)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval((()=>t(this,void 0,void 0,(function*(){const e=yield this.peer.instance.getStats(null);let t="";const i=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],n=["id","type","timestamp"];e.forEach((e=>{i.includes(e.type)||(t+=`\n${e.type}\n`,Object.keys(e).forEach((i=>{n.includes(i)||(t+=`\t${i}: ${e[i]}\n`)})))})),C.info(t)}))),2e3)}}class wt extends De{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._onlineHandler=null,this._offlineHandler=null,this._wasOffline=!1,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile,this._setupNetworkListeners()}get reconnectDelay(){return 1e3}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return t(this,void 0,void 0,(function*(){return e.getIsRegistered.call(this)}))}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return t(this,void 0,void 0,(function*(){e.connect.call(this)}))}checkPermissions(e=!0,i=!0){return t(this,void 0,void 0,(function*(){try{const t=yield Ge({audio:e,video:i});return Be(t),!0}catch(e){return!1}}))}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return t(this,void 0,void 0,(function*(){Object.keys(this.calls).forEach((e=>this.calls[e].setState(J.Purge))),this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)}))}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise(((t,i)=>{if(ne(p.SpeedTest,(i=>{const{upDur:n,downDur:s}=i,o=s?8*e/(s/1e3)/1024:0;t({upDur:n,downDur:s,upKps:(n?8*e/(n/1e3)/1024:0).toFixed(0),downKps:o.toFixed(0)})}),this.uuid),!(e=Number(e)))return i(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let n=e/1024;e%1024&&n++;const s=".".repeat(1024);for(let e=0;e<n;e++)this.executeRaw(`#SPB ${s}`);this.executeRaw("#SPE")}))}getDevices(){return Ve().catch((e=>(oe(p.MediaError,e,this.uuid),[])))}getVideoDevices(){return Ve(Y.Video).catch((e=>(oe(p.MediaError,e,this.uuid),[])))}getAudioInDevices(){return Ve(Y.AudioIn).catch((e=>(oe(p.MediaError,e,this.uuid),[])))}getAudioOutDevices(){return Ve(Y.AudioOut).catch((e=>(C.error("getAudioOutDevices",e),oe(p.MediaError,e,this.uuid),[])))}validateDeviceId(e,t,i){return qe(e,t,i)}getDeviceResolutions(e){return t(this,void 0,void 0,(function*(){try{return yield(e=>t(void 0,void 0,void 0,(function*(){const t=[],i=yield Ge({video:{deviceId:{exact:e}}}),n=i.getVideoTracks()[0];for(let e=0;e<He.length;e++){const[i,s]=He[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 Be(i),t})))(e)}catch(e){throw e}}))}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(i){return t(this,void 0,void 0,(function*(){if(!i)throw new Error("You need to provide the settings object");const{micId:n,micLabel:s}=i,o=e(i,["micId","micLabel"]);return We(o),this._audioConstraints=yield((e,i,n,s)=>t(void 0,void 0,void 0,(function*(){const{deviceId:t}=s;if(void 0===t&&(e||i)){const t=yield qe(e,i,n).catch((e=>null));t&&(s.deviceId={exact:t})}return s})))(n,s,"audioinput",o),this.micId=n,this.micLabel=s,this._audioConstraints}))}disableMicrophone(){this._previousAudioConstraints=this._audioConstraints,this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=this._previousAudioConstraints||!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const e="development"===this.options.env;this._iceServers=e?h:u}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=O(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=O(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 Ae({sessid:this.sessionid,eventChannel:t,data:i});e&&(n.targetNodeId=e),this.execute(n).catch((e=>e))}vertoSubscribe({nodeId:e,channels:i=[],handler:n}){return t(this,void 0,void 0,(function*(){if(!(i=i.filter((e=>e&&!this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new Le({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const s=yield this.execute(t),{unauthorized:o=[],subscribed:r=[]}=Ke(s);return o.length&&o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),r.forEach((e=>this._addSubscription(this.relayProtocol,n,e))),s}))}vertoUnsubscribe({nodeId:e,channels:i=[]}){return t(this,void 0,void 0,(function*(){if(!(i=i.filter((e=>e&&this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new Pe({sessid:this.sessionid,eventChannel:i});e&&(t.targetNodeId=e);const n=yield this.execute(t),{unsubscribed:s=[],notSubscribed:o=[]}=Ke(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&&(C.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,C.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 Ct.setStateTelnyx(e)}}class It{constructor(e,t){this.code=t,this.message=e}}class kt{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0,this.receivedAuthenticationRequired=0}_ack(e,t){const i=new Ce(e,t);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*P(2,6)}handleMessage(e){var i,n,s;const{session:o}=this,{id:r,method:a,params:c={},voice_sdk_id:d}=e,l=null==c?void 0:c.callID,u=null==c?void 0:c.eventChannel,h=null==c?void 0:c.eventType,g=o.calls[l],v=null===(i=null==g?void 0:g.peer)||void 0===i?void 0:i.isConnectionHealthy();if("channelPvtData"===h)return this._handlePvtEvent(c.pvtData);const f=(e=!1)=>{var t,i,n,s,r,d;const u={audio:!0,video:o.options.video,remoteSdp:c.sdp,destinationNumber:c.callee_id_number,remoteCallerName:c.caller_id_name,remoteCallerNumber:c.caller_id_number,callerName:c.callee_id_name,callerNumber:c.callee_id_number,attach:a===V.Attach,mediaSettings:c.mediaSettings,debug:null!==(t=o.options.debug)&&void 0!==t&&t,debugOutput:null!==(i=o.options.debugOutput)&&void 0!==i?i:"socket",trickleIce:null!==(n=o.options.trickleIce)&&void 0!==n&&n,prefetchIceCandidates:null===(s=o.options.prefetchIceCandidates)||void 0===s||s,forceRelayCandidate:null!==(r=o.options.forceRelayCandidate)&&void 0!==r&&r,keepConnectionAliveOnSocketClose:null!==(d=o.options.keepConnectionAliveOnSocketClose)&&void 0!==d&&d};l&&(u.id=l),c.telnyx_call_control_id&&(u.telnyxCallControlId=c.telnyx_call_control_id),c.telnyx_session_id&&(u.telnyxSessionId=c.telnyx_session_id),c.telnyx_leg_id&&(u.telnyxLegId=c.telnyx_leg_id),c.client_state&&(u.clientState=c.client_state),c.dialogParams&&c.dialogParams.custom_headers&&c.dialogParams.custom_headers.length&&(u.customHeaders=c.dialogParams.custom_headers);const h=new Ct(o,u,e);return h.nodeId=this.nodeId,h},m=new fe(d),b=new be(d);switch(a){case V.Answer:case V.Display:case V.Candidate:case V.Ringing:case V.Bye:case V.Media:if(!l||!g)return void C.error(`Received ${a} for non existing call:`,c);g.handleMessage(e),this._ack(r,a);break;case V.Ping:this.session.setPingReceived(),this.session.execute(b).then((()=>{this.receivedAuthenticationRequired=0})).catch((e=>t(this,void 0,void 0,(function*(){e.code===this.session.authenticationRequiredErrorCode&&this.receivedAuthenticationRequired>=0&&(this.receivedAuthenticationRequired+=1,this.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(C.warn("Ping failed twice with Authentication Required. Re-logging in..."),this.session.login(),this.receivedAuthenticationRequired=-1))}))));break;case V.Punt:o.options.keepConnectionAliveOnSocketClose&&v?(C.info(`[${(new Date).toISOString()}][${l}] keeping session calls alive due to PUNT and keepConnectionAliveOnSocketClose. Disconnecting base session...`),o.socketDisconnect(),this._ack(r,a)):o.disconnect();break;case V.Invite:{const e=f();e.direction=G.Inbound,e.playRingtone(),e.setState(J.Ringing),this._ack(r,a);break}case V.Attach:{if(!g){return f().answer(),void this._ack(r,a)}const e=!!g;C.info(`[${(new Date).toISOString()}][${l}] closing existing call on ATTACH.`),g.hangup({isRecovering:e},!1),C.info(`[${(new Date).toISOString()}][${l}] Attach: Creating new call for recovery`);f(e).answer(),this._ack(r,a);break}case V.Event:case"webrtc.event":if(!u)return void C.error("Verto received an unknown event:",c);const i=o.relayProtocol,d=u.split(".")[0];o._existsSubscription(i,u)?oe(i,c,u):u===o.sessionid?this._handleSessionEvent(c.eventData):o._existsSubscription(i,d)?oe(i,c,d):o.calls.hasOwnProperty(u)?o.calls[u].handleMessage(e):oe(p.Notification,c,o.uuid);break;case V.Info:c.type=H.generic,oe(p.Notification,c,o.uuid);break;case V.ClientReady:this.session.execute(m);break;default:{const t=M(e);if(t){switch(t){case Q.REGISTER:case Q.REGED:if(o.connection.previousGatewayState!==Q.REGED&&o.connection.previousGatewayState!==Q.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0;const t=null===(s=null===(n=null==e?void 0:e.result)||void 0===n?void 0:n.params)||void 0===s?void 0:s.call_report_id;t&&(o.callReportId=t,C.debug("Captured call_report_id from REGED:",t)),c.type=H.vertoClientReady,oe(p.Ready,c,o.uuid)}break;case Q.UNREGED:case Q.NOREG:if(this.retriedRegister+=1,5===this.retriedRegister){this.retriedRegister=0,oe(p.Error,{error:new It("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:o.sessionid},o.uuid);break}setTimeout((()=>{this.session.execute(m)}),this.reconnectDelay());break;case Q.FAILED:case Q.FAIL_WAIT:if(o.connection.previousGatewayState!==Q.FAILED&&o.connection.previousGatewayState!==Q.FAIL_WAIT){if(!this.session.hasAutoReconnect()){this.retriedConnect=0,oe(p.Error,{error:new It("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:o.sessionid},o.uuid);break}if(this.retriedConnect+=1,5===this.retriedConnect){this.retriedConnect=0,oe(p.Error,{error:new Error("Connection Retry Failed"),sessionId:o.sessionid},o.uuid);break}setTimeout((()=>{if(C.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){const e=Object.values(o.calls).some((e=>{var t;return(null===(t=e.peer)||void 0===t?void 0:t.instance)&&!e.signalingStateClosed}));if(e)return C.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();C.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:C.warn("GatewayState message unknown method:",e)}break}C.debug("Verto message unknown method:",e);break}}}_retrieveCallId(e,t){const i=Object.keys(this.session.calls);if("bootObj"!==e.action)return i.find((e=>this.session.calls[e].channels.includes(t)));{const t=e.data.find((e=>i.includes(e[0])));if(t instanceof Array)return t[0]}}_handlePvtEvent(e){return t(this,void 0,void 0,(function*(){const{session:t}=this,i=t.relayProtocol,{action:n,laChannel:s,laName:o,chatChannel:r,infoChannel:a,modChannel:c,conferenceMemberID:d,role:l,callID:u}=e;switch(n){case"conference-liveArray-join":{const i=()=>{t.vertoBroadcast({nodeId:this.nodeId,channel:s,data:{liveArray:{command:"bootstrap",context:s,name:o}}})},n={nodeId:this.nodeId,channels:[s],handler:({data:n})=>{const r=u||this._retrieveCallId(n,s);if(r&&t.calls.hasOwnProperty(r)){const a=t.calls[r];a._addChannel(s),a.extension=o,a.handleConferenceUpdate(n,e).then((e=>{"INVALID_PACKET"===e&&i()}))}}},r=yield t.vertoSubscribe(n).catch((e=>{C.error("liveArray subscription error:",e)}));Je(r,s)&&i();break}case"conference-liveArray-part":{let e=null;if(s&&t._existsSubscription(i,s)){const{callId:n=null}=t.subscriptions[i][s];if(e=t.calls[n]||null,null!==n){const i={type:H.conferenceUpdate,action:z.Leave,conferenceName:o,participantId:Number(d),role:l};oe(p.Notification,i,n,!1)||oe(p.Notification,i,t.uuid),null===e&&se(p.Notification,null,n)}}const n=[s,r,a,c];t.vertoUnsubscribe({nodeId:this.nodeId,channels:n}).then((({unsubscribedChannels:t=[]})=>{e&&(e.channels=e.channels.filter((e=>!t.includes(e))))})).catch((e=>{C.error("liveArray unsubscribe error:",e)}));break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":mt(this.session,e);break;case"logo-info":{const t={type:H.conferenceUpdate,action:z.LogoInfo,logo:e.logoURL};oe(p.Notification,t,this.session.uuid);break}}}}class Et extends wt{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>t(this,void 0,void 0,(function*(){this._idle=!1;const{autoReconnect:e=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=e}})})),this.handleAnonymousLoginOnSocketOpen=()=>t(this,void 0,void 0,(function*(){this._idle=!1,yield this.login()})),this._vertoHandler=new kt(this),window.addEventListener("beforeunload",(e=>{this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&(C.info(`Hanging up call due to window unload: ${e}`),this.calls[e].hangup({},!0))}))}))}validateOptions(){return N(this.options)||D(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 Ct(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!!D(this.options)||Boolean(e.destinationNumber)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){return N(this.options)?this.handleLoginOnSocketOpen():D(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0}))}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class Tt extends Et{constructor(e){super(e),C.info(`SDK version: ${ye}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return et()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:tt.full},{browserName:"Firefox",features:["audio"],supported:tt.partial},{browserName:"Safari",supported:tt.not_supported},{browserName:"Edge",supported:tt.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:tt.not_supported},{browserName:"Firefox",supported:tt.not_supported},{browserName:"Safari",features:["video","audio"],supported:tt.full},{browserName:"Edge",supported:tt.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:tt.full},{browserName:"Firefox",features:["audio"],supported:tt.partial},{browserName:"Safari",supported:tt.not_supported},{browserName:"Edge",supported:tt.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:tt.full},{browserName:"Firefox",features:["audio"],supported:tt.partial},{browserName:"Safari",features:["video","audio"],supported:tt.full},{browserName:"Edge",features:["audio"],supported:tt.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:tt.full},{browserName:"Firefox",features:["audio"],supported:tt.partial},{browserName:"Safari",supported:tt.not_supported},{browserName:"Edge",features:["audio"],supported:tt.partial}]}]}}class Rt{static run(e){return t(this,void 0,void 0,(function*(){const t=j({}),i=j({}),n=new Tt(e.credentials);yield n.connect(),n.on(p.Ready,t.resolve),n.on(p.Error,t.reject),n.on(p.MediaError,t.reject),n.on(p.MediaError,t.reject),n.on(p.Notification,(e=>{e.call&&e.call.sipCode>=400&&i.reject(new Error(e.call.sipReason))})),ie(p.StatsReport,(e=>{i.resolve(Rt.mapReport(e))})),yield t.promise,yield n.newCall({destinationNumber:e.texMLApplicationNumber,debug:!0});const s=yield i.promise;return yield n.disconnect(),s}))}static mapReport(e){var t,i,n,s,o,r,a,c,d,l,u,h,p;const g=[],v=[];for(const t of e)switch(t.event){case"onicecandidate":t.data&&g.push(t.data);break;case"stats":v.push(t.data)}let f=0,m=1/0,b=-1/0,y=0,_=1/0,S=-1/0,C=0;v.forEach((e=>{var t,i,n;if(!(null===(t=e.remote.audio.inbound)||void 0===t?void 0:t[0]))return;f+=1;const s=null!==(i=e.remote.audio.inbound[0].jitter)&&void 0!==i?i:0,o=null!==(n=e.remote.audio.inbound[0].roundTripTime)&&void 0!==n?n:0;y+=s,C+=o,b=Math.max(b,s),m=Math.min(m,s),S=Math.max(S,o),_=Math.min(_,o)}));const w=C/f,I=y/f,k=v[v.length-1],E=lt({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:_},quality:ut(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:""}}}export{Ct as Call,q as ERROR_TYPE,H as NOTIFICATION_TYPE,Rt as PreCallDiagnosis,p as SwEvent,Tt as TelnyxRTC};
|