@telnyx/webrtc 2.22.5 → 2.22.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/bundle.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).TelnyxWebRTC={})}(this,(function(e){"use strict";function t(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(n[i[s]]=e[i[s]])}return n}function n(e,t,n,i){return new(n||(n=Promise))((function(s,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((i=i.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),s=new Uint8Array(16);function o(){if(!i)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return i(s)}for(var r=[],a=0;a<256;++a)r[a]=(a+256).toString(16).substr(1);function c(e,t,n){var i=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var s=(e=e||{}).random||(e.rng||o)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var a=0;a<16;++a)t[i+a]=s[a];return t||function(e,t){var n=t||0,i=r;return[i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]]].join("")}(s)}var d="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function l(e,t){return e(t={exports:{}},t.exports),t.exports}var u=l((function(e){var t,n;t=d,n=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function s(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[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,n){for(var s=0;s<i.length;s++){var o=i[s];this[o]=s<t?e:this.methodFactory(o,t,n)}this.log=this.debug}function a(e,n,i){return function(){typeof console!==t&&(r.call(this,n,i),this[e].apply(this,arguments))}}function c(i,r,c){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?o:void 0!==console[i]?s(console,i):void 0!==console.log?s(console,"log"):e)}(i)||a.apply(this,arguments)}function d(e,n,s){var o,a=this;n=null==n?"WARN":n;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 n=window.document.cookie,i=n.indexOf(encodeURIComponent(d)+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i))[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(n,s){if("string"==typeof n&&void 0!==a.levels[n.toUpperCase()]&&(n=a.levels[n.toUpperCase()]),!("number"==typeof n&&n>=0&&n<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(o=n,!1!==s&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+n+";"}catch(e){}}}(n),r.call(a,n,e),typeof console===t&&n<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){n=e,l()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(n,!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=n),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=n():t.log=n()}));const h=u.getLogger("telnyx"),p=h.methodFactory;h.methodFactory=(e,t,n)=>{const i=p(e,t,n);return function(){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(let t=0;t<arguments.length;t++)e.push(arguments[t]);i.apply(void 0,e)}},h.setLevel(h.getLevel());const g="Time to call invite",f="wss://rtc.telnyx.com",v={urls:"stun:stun.telnyx.com:3478"},m={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var b;!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.Messages="telnyx.messages",e.Calls="telnyx.calls",e.MediaError="telnyx.rtc.mediaError"}(b||(b={}));const y=e=>0===Object.keys(e).length,_=e=>{const[t,n,i,s,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){h.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},w=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},S=e=>e instanceof Function||"function"==typeof e,I=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,C=/^(ws|wss):\/\//,E=(e,t=null)=>{const{result:n={},error:i}=e;if(i)return{error:i};const{result:s=null}=n;if(null===s)return null!==t&&(n.node_id=t),{result:n};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&"200"!==o?{error:s}:a?E(a,r):{result:s}},k=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),T=({login:e,passwd:t,password:n,login_token:i})=>Boolean(e&&(t||n)||i),x=e=>{var t,n,i,s,o,r;let a="",c="";(null===(n=null===(t=null==e?void 0:e.result)||void 0===t?void 0:t.params)||void 0===n?void 0:n.state)&&(a=null===(s=null===(i=null==e?void 0:e.result)||void 0===i?void 0:i.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 R({debounceTime:e}){let t,n;return{promise:new Promise(((i,s)=>{t=e?M(i,e):i,n=s})),resolve:t,reject:n}}const M=(e,t)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout((()=>{e(...i)}),t)}},D="GLOBAL",A={},L=(e,t)=>`${e}|${t}`,N=(e,t=D)=>L(e,t)in A,O=(e,t,n=D)=>{const i=L(e,n);i in A||(A[i]=[]),A[i].push(t)},P=(e,t,n=D)=>{const i=function(s){U(e,i,n),t(s)};return i.prototype.targetRef=t,O(e,i,n)},U=(e,t,n=D)=>{if(!N(e,n))return!1;const i=L(e,n);if(S(t)){for(let e=A[i].length-1;e>=0;e--){const n=A[i][e];(t===n||n.prototype&&t===n.prototype.targetRef)&&A[i].splice(e,1)}}else A[i]=[];return 0===A[i].length&&delete A[i],!0},j=(e,t,n=D,i=!0)=>{const s=i&&n!==D;if(!N(e,n))return s&&j(e,t),!1;const o=L(e,n),r=A[o].length;if(!r)return s&&j(e,t),!1;for(let e=r-1;e>=0;e--)A[o][e](t);return s&&j(e,t),!0},$=e=>{const t=L(e,"");Object.keys(A).filter((e=>0===e.indexOf(t))).forEach((e=>delete A[e]))};var V,G,B;!function(e){e.Offer="offer",e.Answer="answer"}(V||(V={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(G||(G={})),function(e){e.Invite="telnyx_rtc.invite",e.Attach="telnyx_rtc.attach",e.Answer="telnyx_rtc.answer",e.Info="telnyx_rtc.info",e.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"}(B||(B={}));const F={generic:"event",[B.Display]:"participantData",[B.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError"},H={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,video:!1,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0}};var W,q,K,J,z;!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"}(q||(q={})),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"}(J||(J={})),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"}(z||(z={}));const Y="telnyx-voice-sdk-id";function Q(){return sessionStorage.getItem(Y)}"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{sessionStorage.removeItem(Y)}));let X="undefined"!=typeof WebSocket?WebSocket:null;const Z=0,ee=1,te=2,ne=3;class ie{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=f,this._timers={},this.upDur=null,this.downDur=null;const{host:t,env:n}=e.options;t&&(this._host=(e=>`${C.test(e)?"":"wss://"}${e}`)(t)),n&&(this._host="development"===n?"wss://rtcdev.telnyx.com":f)}get connected(){return this._wsClient&&this._wsClient.readyState===ee}get connecting(){return this._wsClient&&this._wsClient.readyState===Z}get closing(){return this._wsClient&&this._wsClient.readyState===te}get closed(){return this._wsClient&&this._wsClient.readyState===ne}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){const e=new URL(this._host),t=Q();t&&e.searchParams.set("voice_sdk_id",t),this._wsClient=new X(e.toString()),this._wsClient.onopen=e=>j(b.SocketOpen,e,this.session.uuid),this._wsClient.onclose=e=>j(b.SocketClose,e,this.session.uuid),this._wsClient.onerror=e=>j(b.SocketError,{error:e,sessionId:this.session.sessionid},this.session.uuid),this._wsClient.onmessage=e=>{var t,n;const i=w(e.data);var s;if("string"!=typeof i){if(i.voice_sdk_id&&(s=i.voice_sdk_id,sessionStorage.setItem(Y,s)),this._unsetTimer(i.id),h.debug("RECV: \n",JSON.stringify(i,null,2),"\n"),z[`${null===(n=null===(t=null==i?void 0:i.result)||void 0===t?void 0:t.params)||void 0===n?void 0:n.state}`]||!j(i.id,i)){const e=x(i);j(b.SocketMessage,i,this.session.uuid),Boolean(e)&&(this.previousGatewayState=e)}}else this._handleStringResponse(i)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:t}=e,n=new Promise(((e,n)=>{if(t.hasOwnProperty("result"))return e();P(t.id,(t=>{const{result:i,error:s}=E(t);return s?n(s):e(i)}))}));return h.debug("SEND: \n",JSON.stringify(t,null,2),"\n"),this._wsClient.send(JSON.stringify(t)),n}close(){this._wsClient&&(S(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close()),this._wsClient=null}_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)),j(b.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else h.warn("Unknown message from socket",e)}}class se{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:c()},e)}}const oe={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 re extends se{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=t(e.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const e in oe)e&&n.hasOwnProperty(e)&&(n[oe[e]]=n[e],delete n[e]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class ae extends re{constructor(){super(),this.method=B.GatewayState;this.buildRequest({method:this.method,params:{}})}}class ce{constructor(e){this.pendingRequestId=null,this.onSocketMessage=e=>n(this,void 0,void 0,(function*(){e.id===this.pendingRequestId&&this.gatewayStateTask.resolve(x(e))})),this.getIsRegistered=()=>n(this,void 0,void 0,(function*(){const e=new ae;this.pendingRequestId=e.request.id,this.gatewayStateTask=R({}),this.session.execute(e);const t=yield this.gatewayStateTask.promise;return!!t&&[z.REGISTER,z.REGED].includes(t)})),this.session=e,this.gatewayStateTask=R({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class de{constructor(e){if(this.options=e,this.uuid=c(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.connection=null,this._jwtAuth=!1,this._doKeepAlive=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");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 ie(this),this.registerAgent=new ce(this)}get __logger(){return h}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*k(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}),this.connect()}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return T(this.options)}broadcast(e){}disconnect(){return n(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()}))}on(e,t){return O(e,t,this.uuid),this}off(e,t){return U(e,t,this.uuid),this}connect(){return n(this,void 0,void 0,(function*(){this.connection||(this.connection=new ie(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()}))}_handleLoginError(e){j(b.Error,{error:e,sessionId:this.sessionid},this.uuid)}_onSocketOpen(){return n(this,void 0,void 0,(function*(){}))}onNetworkClose(){this.relayProtocol&&$(this.relayProtocol);for(const e in this.subscriptions)$(e);this.subscriptions={},this.contexts=[],this._autoReconnect&&(this._reconnectTimeout=setTimeout((()=>this.connect()),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,t){this._existsSubscription(e,t)&&(t?(delete this.subscriptions[e][t],U(e,null,t)):(delete this.subscriptions[e],$(e)))}_addSubscription(e,t=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},S(t)&&O(e,t,n))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(b.SocketOpen,this._onSocketOpen),this.on(b.SocketClose,this.onNetworkClose),this.on(b.SocketError,this.onNetworkClose),this.on(b.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(b.SocketOpen,this._onSocketOpen),this.off(b.SocketClose,this.onNetworkClose),this.off(b.SocketError,this.onNetworkClose),this.off(b.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()}_keepAlive(){!0===this._doKeepAlive&&(this._pong=!1,this._keepAliveTimeout=setTimeout((()=>this._keepAlive()),3e4))}static on(e,t){O(e,t)}static off(e){U(e)}static uuid(){return c()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}getIsRegistered(){return this.registerAgent.getIsRegistered()}}const le=e=>navigator.mediaDevices.getUserMedia(e),ue=e=>e&&e instanceof MediaStream,he=(e,t)=>{const n=I(e);null!==n&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=t)},pe=(e,t)=>n(void 0,void 0,void 0,(function*(){const n=I(e);if(null===n)return h.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof t)return h.info(`Invalid speaker deviceId: '${t}'`),!1;try{return yield n.setSinkId(t),!0}catch(e){return!1}})),ge=e=>{e&&"live"===e.readyState&&e.stop()},fe=e=>{ue(e)&&e.getTracks().forEach(ge),e=null},ve=e=>n(void 0,void 0,void 0,(function*(){h.info("RTCService.getUserMedia",e);const{audio:t,video:n}=e;if(!t&&!n)return null;try{return yield le(e)}catch(e){throw h.error("getUserMedia error: ",e),e}})),me=(e=null,t=!1)=>n(void 0,void 0,void 0,(function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===J.AudioIn||e===J.AudioOut,video:!e||e===J.Video}))(e)).catch((e=>(console.error(e),null)));if(i){if(fe(i),n=yield navigator.mediaDevices.enumerateDevices(),e&&(n=n.filter((t=>t.kind===e))),!0===t)return n;const s=[];n=n.filter((e=>{if(!e.groupId)return!0;const t=`${e.kind}-${e.groupId}`;return!s.includes(t)&&(s.push(t),!0)}))}return n})),be=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],ye=(e,t,i)=>n(void 0,void 0,void 0,(function*(){const n=yield me(i,!0);for(let i=0;i<n.length;i++){const{deviceId:s,label:o}=n[i];if(e===s||t===o)return s}return null})),_e=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((n=>{t.hasOwnProperty(n)&&null!==e[n]&&void 0!==e[n]||delete e[n]}))},we=(e,t,i,s)=>n(void 0,void 0,void 0,(function*(){const{deviceId:n}=s;if(void 0===n&&(e||t)){const n=yield ye(e,t,i).catch((e=>null));n&&(s.deviceId={exact:n})}return s})),Se=e=>{const t="\r\n",n=e.split(t),i=n.findIndex((e=>/^a=rtpmap/.test(e)&&/opus\/48000/.test(e)));if(i<0)return e;const s=(e=>{const t=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),n=e.match(t);return n&&2==n.length?n[1]:null})(n[i]),o=new RegExp(`a=fmtp:${s}`),r=n.findIndex((e=>o.test(e)));return r>=0?/stereo=1;/.test(n[r])||(n[r]+="; stereo=1; sprop-stereo=1"):n[i]+=`${t}a=fmtp:${s} stereo=1; sprop-stereo=1`,n.join(t)},Ie=e=>/^m=audio/.test(e),Ce=e=>/^m=video/.test(e),Ee=(e,t)=>{const n="\r\n",i=t.split(n);if(i.findIndex(Ie)<i.findIndex(Ce))return e;const s=e.split(n),o=s.findIndex(Ie),r=s.findIndex(Ce),a=s.slice(o,r),c=s.slice(r,s.length-1);return[...s.slice(0,o),...c,...a,""].join(n)},ke=(e,t)=>{if(!e)return!1;const{subscribed:n,alreadySubscribed:i}=Te(e);return n.includes(t)||i.includes(t)},Te=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((n=>{t[n]=e[`${n}Channels`]||[]})),t},xe=(e,t=null,n=null)=>{if(!ue(e))return null;let i=[];switch(t){case"audio":i=e.getAudioTracks();break;case"video":i=e.getVideoTracks();break;default:i=e.getTracks()}i.forEach((e=>{switch(n){case"on":case!0:e.enabled=!0;break;case"off":case!1:e.enabled=!1;break;default:e.enabled=!e.enabled}}))},Re=e=>{xe(e,"audio",!0)},Me=e=>{xe(e,"audio",!1)},De=e=>{xe(e,"audio",null)};function Ae(){try{const{browserInfo:e,name:t,version:n,supportAudio:i,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],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,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],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,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("/"),n=parseInt(t[1],10);return{browserInfo:navigator.userAgent,name:e,version:n,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],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,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:n,supportWebRTC:!!(o&&r&&a&&c&&d),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!ve}}catch(e){return e.message}}var Le;function Ne(e,t){const n=document.getElementById(t);if(n)return n;if(e&&t){const n=document.createElement("audio");return n.id=t,n.loop=!0,n.src=e,n.preload="auto",n.load(),document.body.appendChild(n),n}return null}function Oe(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then((()=>{e._playFulfilled=!0})).catch((t=>{console.error("playAudio",t),e._playFulfilled=!0})))}function Pe(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"}(Le||(Le={}));var Ue="2.22.5",je=Ue;class $e extends re{constructor(e,t,n,i,s={},o){super(),this.method="login";const r={login:e,passwd:t,login_token:n,userVariables:s,reconnection:o,loginParams:{},"User-Agent":{sdkVersion:je,data:navigator.userAgent}};i&&(r.sessid=i),this.buildRequest({method:this.method,params:r})}}class Ve extends re{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Ge extends re{toString(){return B.Invite}}class Be extends re{toString(){return B.Answer}}class Fe extends re{toString(){return B.Attach}}class He extends re{toString(){return B.Bye}}class We extends re{toString(){return B.Modify}}class qe extends re{toString(){return B.Info}}class Ke extends re{toString(){return B.Broadcast}}class Je extends re{toString(){return B.Subscribe}}class ze extends re{toString(){return B.Unsubscribe}}const Ye=(e,t)=>{const{contentType:n,canvasType:i,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&"mcu-personal-canvas"!==i&&delete o.memberID;const a={type:F.conferenceUpdate,call:e.calls[s],canvasInfo:Qe(o),currentLayerIdx:r};switch(n){case"layer-info":{const t=Object.assign({action:K.LayerInfo},a);j(b.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:K.LayoutInfo},a);j(b.Notification,t,e.uuid);break}}},Qe=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return w(t)};var Xe,Ze=l((function(e,t){var n;function i(){}function s(){s.init.call(this)}function o(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function r(e,t,n,s){var r,a,c;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),c=a[t]):(a=e._events=new i,e._eventsCount=0),c){if("function"==typeof c?c=a[t]=s?[n,c]:[c,n]:s?c.unshift(n):c.push(n),!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]=n,++e._eventsCount;return e}function a(e,t,n){function i(){e.removeListener(t,i),s||(s=!0,n.apply(e,arguments))}var s=!1;return i.listener=n,i}function c(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function d(e,t){for(var n=Array(t);t--;)n[t]=e[t];return n}Object.defineProperty(t,"__esModule",{value:!0}),i.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&&n.active&&!(this instanceof n.Domain)&&(this.domain=n.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new i,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,n,i,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(!(n=r[e]))return!1;var u="function"==typeof n;switch(i=arguments.length){case 1:!function(e,t,n){if(t)e.call(n);else for(var i=e.length,s=d(e,i),o=0;o<i;++o)s[o].call(n)}(n,u,this);break;case 2:!function(e,t,n,i){if(t)e.call(n,i);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].call(n,i)}(n,u,this,arguments[1]);break;case 3:!function(e,t,n,i,s){if(t)e.call(n,i,s);else for(var o=e.length,r=d(e,o),a=0;a<o;++a)r[a].call(n,i,s)}(n,u,this,arguments[1],arguments[2]);break;case 4:!function(e,t,n,i,s,o){if(t)e.call(n,i,s,o);else for(var r=e.length,a=d(e,r),c=0;c<r;++c)a[c].call(n,i,s,o)}(n,u,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=Array(i-1),o=1;o<i;o++)s[o-1]=arguments[o];!function(e,t,n,i){if(t)e.apply(n,i);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].apply(n,i)}(n,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 n,s,o,r,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(s=this._events))return this;if(!(n=s[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new i:(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(o=-1,r=n.length;0<r--;)if(n[r]===t||n[r].listener&&n[r].listener===t){a=n[r].listener,o=r;break}if(0>o)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new i,this;delete s[e]}else!function(e,t){for(var n=t,i=n+1,s=e.length;i<s;n+=1,i+=1)e[n]=e[i];e.pop()}(n,o);s.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new i,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new i:delete n[e]),this;if(0===arguments.length){for(var s,o=Object.keys(n),r=0;r<o.length;++r)"removeListener"!==(s=o[r])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if("function"==typeof(t=n[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,n,i=this._events;return i?n=(t=i[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[]:n=[],n},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=[],f=0;256>f;++f)g.push((f+256).toString(16).substr(1));function v(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:0,n=(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)}(n))throw TypeError("Stringified UUID is invalid");return n}function m(e,t,n){var i=(e=e||{}).random||(e.rng||h)();if(i[6]=64|15&i[6],i[8]=128|63&i[8],t){n=n||0;for(var s=0;16>s;++s)t[n+s]=i[s];return t}return v(i)}function b(e,t){if(!e||!t)return{};const n={...e};if(n.localCandidateId){const e=t.get(n.localCandidateId);n.local={...e}}if(n.remoteCandidateId){const e=t.get(n.remoteCandidateId);n.remote={...e}}return n}function y(e,t,n){return 8*function(e,t,n){const i=e[n],s=t?t[n]:null;return null===i||null===s?null:(i-s)/(e.timestamp-t.timestamp)*1e3}(e,t,n)}function _(e){if(!e.entries)return e;const t={};return e.forEach((function(e,n){t[n]=e})),t}function w(e,t,n={}){if(!e)return null;let i={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};n.remote&&(i.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const t of e.values())switch(t.type){case"outbound-rtp":{const n=t.mediaType||t.kind,s={};let o={};if(!["audio","video"].includes(n))continue;if(t.codecId){const n=e.get(t.codecId);n&&(s.clockRate=n.clockRate,s.mimeType=n.mimeType,s.payloadType=n.payloadType)}o=e.get(t.mediaSourceId)||e.get(t.trackId)||{},i[n].outbound.push({...t,...s,track:{...o}});break}case"inbound-rtp":{let n=t.mediaType||t.kind,s={};const o={};if(!["audio","video"].includes(n))if(t.id.includes("Video"))n="video";else{if(!t.id.includes("Audio"))continue;n="audio"}if(t.codecId){const n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}if(!i.connection.id&&t.transportId){const n=e.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=e.get(n.selectedCandidatePairId);i.connection=b(t,e)}}s=e.get(t.mediaSourceId)||e.get(t.trackId)||{},i[n].inbound.push({...t,...o,track:{...s}});break}case"peer-connection":i.connection.dataChannelsClosed=t.dataChannelsClosed,i.connection.dataChannelsOpened=t.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!n.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 n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}if(!i.connection.id&&t.transportId){const n=e.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=e.get(n.selectedCandidatePairId);i.connection=b(t,e)}}i.remote[s].inbound.push({...t,...o});break}case"remote-outbound-rtp":{if(!n.remote)break;const s=t.mediaType||t.kind,o={};if(!["audio","video"].includes(s))continue;if(t.codecId){const n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}i.remote[s].outbound.push({...t,...o});break}}if(!i.connection.id)for(const t of e.values())"candidate-pair"===t.type&&t.nominated&&"succeeded"===t.state&&(i.connection=b(t,e));return i=function(e,t){return t?(e.audio.inbound.map((e=>{let n=t.audio.inbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesReceived"),e.packetRate=y(e,n,"packetsReceived")})),e.audio.outbound.map((e=>{let n=t.audio.outbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesSent"),e.packetRate=y(e,n,"packetsSent")})),e.video.inbound.map((e=>{let n=t.video.inbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesReceived"),e.packetRate=y(e,n,"packetsReceived")})),e.video.outbound.map((e=>{let n=t.video.outbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesSent"),e.packetRate=y(e,n,"packetsSent")})),e):e}(i,t),i}let S,I={},C=[];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:n}=e;let{connectionId:i,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(!n)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[n]){if(i&&i in this.peersToMonitor[n])throw new Error(`We are already monitoring connection with id ${i}.`);for(let e in this.peersToMonitor[n]){const i=this.peersToMonitor[n][e];if(i.pc===t)throw new Error(`We are already monitoring peer with id ${n}.`);"closed"===i.pc.connectionState&&this.removeConnection({pc:i.pc})}}const o=t.getConfiguration();return o.iceServers&&o.iceServers.forEach((function(e){delete e.credential})),i||(i=m()),this.emitEvent({event:"addConnection",tag:"peer",peerId:n,connectionId:i,data:{options:e,peerConfiguration:o}}),this.monitorPeer({peerId:n,connectionId:i,pc:t,remote:s}),{connectionId:i}}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:n,pc:i}=e;if(!i&&!n)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(n){if("string"!=typeof n)throw new Error("connectionId must be a string.");for(let e in this.peersToMonitor)n in this.peersToMonitor[e]&&(i=this.peersToMonitor[e][n].pc,t=e)}else if(i){if(!(i 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===i&&(n=s,t=e)}if(!i||!n)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(n,i),delete this.peersToMonitor[t][n],0===Object.values(this.peersToMonitor[t]).length&&delete this.peersToMonitor[t],{connectionId:n}}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 n=this.peersToMonitor[e][t].pc;this.removePeerConnectionEventListeners(t,n)}delete this.peersToMonitor[e]}}destroy(){this.removeAllPeers(),C.forEach((e=>{this.removeTrackEventListeners(e)})),C=[],this.shouldWrapGetUserMedia&&S&&(navigator.mediaDevices.getUserMedia=S)}monitorPeer(e){let{peerId:t,connectionId:n,pc:i,remote:s}=e;if(!i)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const o={pc:i,connectionId:n,stream:null,stats:{parsed:null,raw:null},options:{remote:s}};if(this.peersToMonitor[t]){if(n in this.peersToMonitor[t])return void this.logger.warn(`Already watching connection with ID ${n}`);this.peersToMonitor[t][n]=o}else this.peersToMonitor[t]={[n]:o};this.addPeerConnectionEventListeners(t,n,i),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 n=[];for(const e in t)for(const i in t[e]){const s=t[e][i],o=s.pc;if(o&&!this.checkIfConnectionIsClosed(e,i,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=w(o,s.stats.parsed,d),u={event:"stats",tag:"stats",peerId:e,connectionId:i,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)),n.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 n}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const e in this.peersToMonitor)for(const t in this.peersToMonitor[e]){const n=this.peersToMonitor[e][t].pc;this.checkIfConnectionIsClosed(e,t,n)}}),this.connectionMonitoringInterval)}checkIfConnectionIsClosed(e,t,n){const i=this.isConnectionClosed(n);if(i){this.removeConnection({pc:n});let i="closed"===n.connectionState?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:i,peerId:e,connectionId:t,tag:"connection",data:"closed"})}return i}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."),S=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const e=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=function(){return e({constraints:arguments[0]}),S.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 n=t[e];this.statsToMonitor.includes(n.type)||delete t[e]}return t}get peerConnectionListeners(){return{icecandidate:(e,t,n,i)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",i),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:e,connectionId:t,data:i.candidate})},track:(e,t,n,i)=>{this.logger.debug(`[pc-event] track | peerId: ${e}`,i);const s=i.track,o=i.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:i.track.kind+":"+i.track.id+" "+i.streams.map((function(e){return"stream:"+e.id}))}})},signalingstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${e}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:e,connectionId:t,data:{signalingState:n.signalingState,localDescription:n.localDescription,remoteDescription:n.remoteDescription}})},iceconnectionstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${e}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:n.iceConnectionState})},icegatheringstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${e}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:e,connectionId:t,data:n.iceGatheringState})},icecandidateerror:(e,t,n,i)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${e}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:e,connectionId:t,error:{errorCode:i.errorCode}})},connectionstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${e}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:n.connectionState})},negotiationneeded:(e,t,n)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${e}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:e,connectionId:t})},datachannel:(e,t,n,i)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${e}`,i),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:e,connectionId:t,data:i.channel})}}}addPeerConnectionEventListeners(e,t,n){this.logger.debug(`Adding event listeners for peer ${e} and connection ${t}.`),I[t]={},Object.keys(this.peerConnectionListeners).forEach((i=>{I[t][i]=this.peerConnectionListeners[i].bind(this,e,t,n),n.addEventListener(i,I[t][i],!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),C.push(e)}))),this.emitEvent(t)}catch(e){}}parseStream(e){const t={audio:[],video:[]};return e.getTracks().forEach((e=>{t[e.kind].push(this.getMediaTrackDetails(e))})),t}getMediaTrackDetails(e){return{enabled:e.enabled,id:e.id,contentHint:e.contentHint,kind:e.kind,label:e.label,muted:e.muted,readyState:e.readyState,constructorName:e.constructor.name,capabilities:e.getCapabilities?e.getCapabilities():{},constraints:e.getConstraints?e.getConstraints():{},settings:e.getSettings?e.getSettings():{},_track:e}}getStreamDetails(e){return{active:e.active,id:e.id,_stream:e}}getTrackEventObject(e){return{mute:t=>{this.emitEvent({event:"mute",tag:"track",connectionId:e,data:{event:t}})},unmute:t=>{this.emitEvent({event:"unmute",tag:"track",connectionId:e,data:{event:t}})},overconstrained:t=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:e,data:{event:t}})},ended:t=>{this.emitEvent({event:"ended",tag:"track",connectionId:e,data:{event:t}}),this.removeTrackEventListeners(t.target)}}}addTrackEventListeners(e,t){I[e.id]={};const n=this.getTrackEventObject(t);Object.keys(n).forEach((t=>{I[e.id][t]=n[t].bind(this),e.addEventListener(t,I[e.id][t])})),I[e.id].readyState=setInterval((()=>{if("ended"===e.readyState){let t=new CustomEvent("ended",{detail:{check:"readyState"}});e.dispatchEvent(t)}}),1e3)}removeTrackEventListeners(e){if(e.id in I){const t=this.getTrackEventObject();Object.keys(t).forEach((t=>{e.removeEventListener(t,I[e.id][t])})),clearInterval(I[e.id].readyState),delete I[e.id]}}addToTimeline(e){this.timeline.push(e),this.emit("timeline",e)}emitEvent(e){const t={...e,timestamp:new Date};this.addToTimeline(t),t.tag&&this.emit(t.tag,t)}set getStatsInterval(e){if(!Number.isInteger(e))throw new Error(`getStatsInterval should be an integer, got: ${e}`);this._getStatsInterval=e,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(e,t){e in I&&(Object.keys(this.peerConnectionListeners).forEach((n=>{t.removeEventListener(n,I[e][n],!1)})),delete I[e]),t.getSenders().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)})),t.getReceivers().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)}))}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const e=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const t=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),n=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=n.bind(navigator.mediaDevices)}}}}));(Xe=Ze)&&Xe.__esModule&&Object.prototype.hasOwnProperty.call(Xe,"default")&&Xe.default;var et=Ze.WebRTCStats;class tt extends se{constructor(e){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1})}}class nt extends se{constructor(e){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1})}}class it extends se{constructor(e,t){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:t})}}class st{constructor(e,t,i){this.type=e,this.options=t,this.onSdpReadyTwice=null,this._negotiating=!1,this.handleConnectionStateChange=e=>n(this,void 0,void 0,(function*(){const{connectionState:e}=this.instance;if(console.log(`[${(new Date).toISOString()}] Connection State`,e),"failed"===e||"disconnected"===e){const e=()=>{this.instance.restartIce(),this._session._closeConnection(),this._session.connect(),window.removeEventListener("online",e)};if(navigator.onLine)return e();window.addEventListener("online",e)}})),this._handleIceConnectionStateChange=e=>{console.log(`[${(new Date).toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=e=>{console.log(`[${(new Date).toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setAudioCodec=e=>{if(this.options.preferred_codecs&&0!==this.options.preferred_codecs.length)return e.setCodecPreferences?e.setCodecPreferences(this.options.preferred_codecs):void 0},this._onDebugReportMessage=e=>n(this,void 0,void 0,(function*(){this.options.debug&&(yield this._session.execute(this._webrtcStatsReporter.reportDataMessage(e)))})),h.info("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},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=i,this._init()}get isOffer(){return this.type===V.Offer}get isAnswer(){return this.type===V.Answer}startNegotiation(){this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}startDebugger(){return n(this,void 0,void 0,(function*(){this.options.debug&&(this._webrtcStatsReporter=function(){const e=c(),t=new et({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,wrapGetUserMedia:!0,debug:!1,logLevel:"warn"});return{reportDataMessage:t=>new it(e,t),start:()=>new tt(e),stop:()=>new nt(e),reportId:e,debuggerInstance:t}}(),yield this._session.execute(this._webrtcStatsReporter.start()),this._webrtcStatsReporter.debuggerInstance.on("timeline",this._onDebugReportMessage),yield new Promise((e=>setTimeout(e,500))),this._webrtcStatsReporter.debuggerInstance.addConnection({pc:this.instance,peerId:this.options.id,connectionId:this.options.telnyxSessionId}))}))}stopDebugger(){this.options.debug&&(this._session.execute(this._webrtcStatsReporter.stop()),this._webrtcStatsReporter.debuggerInstance.destroy())}_logTransceivers(){h.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach(((e,t)=>{h.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),h.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))}handleSignalingStateChangeEvent(e){switch(h.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":this.instance=null;break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){h.info("Negotiation needed event"),"stable"===this.instance.signalingState&&this.startNegotiation()}handleTrackEvent(e){const{streams:[t]}=e,{remoteElement:n,screenShare:i}=this.options;let{remoteStream:s}=this.options;s=t,!1===i&&he(n,s)}createPeerConnection(){return n(this,void 0,void 0,(function*(){var e;this.instance=(e=this._config(),new window.RTCPeerConnection(e)),yield this.startDebugger(),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.options.localStream=yield this._retrieveLocalStream().catch((e=>(j(b.MediaError,e,this.options.id),null)))}))}_init(){return n(this,void 0,void 0,(function*(){yield this.createPeerConnection();const{localElement:e,localStream:t=null,screenShare:n=!1}=this.options;if(ue(t)){const i=t.getAudioTracks();h.info("Local audio tracks: ",i);const s=t.getVideoTracks();if(h.info("Local video tracks: ",s),this.isOffer&&"function"==typeof this.instance.addTransceiver){const e={direction:"sendrecv",streams:[t]};i.forEach((t=>{this.options.userVariables.microphoneLabel=t.label;const n=this.instance.addTransceiver(t,e);this._setAudioCodec(n)})),console.debug("Applying video transceiverParams",e),s.forEach((t=>{this.options.userVariables.cameraLabel=t.label,this.instance.addTransceiver(t,e)}))}else"function"==typeof this.instance.addTrack?(i.forEach((e=>{this.options.userVariables.microphoneLabel=e.label,this.instance.addTrack(e,t)})),this.instance.getTransceivers().forEach((e=>this._setAudioCodec(e))),s.forEach((e=>{this.options.userVariables.cameraLabel=e.label,this.instance.addTrack(e,t)}))):this.instance.addStream(t);!1===n&&((e=>{const t=I(e);t&&(t.muted=!0)})(e),he(e,t))}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this.startNegotiation(),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);h.info("Add transceiver",e,t)}}_createOffer(){this._isOffer()&&(this._constraints.offerToReceiveAudio=Boolean(this.options.audio),this._constraints.offerToReceiveVideo=Boolean(this.options.video),h.info("_createOffer - this._constraints",this._constraints),this.instance.createOffer(this._constraints).then(this._setLocalDescription.bind(this)).then(this._sdpReady).catch((e=>h.error("Peer _createOffer error:",e))))}_setRemoteDescription(e){this.options.useStereo&&(e.sdp=Se(e.sdp)),this.instance.localDescription&&(e.sdp=Ee(e.sdp,this.instance.localDescription.sdp));const t=e;return h.info("REMOTE SDP \n",`Type: ${e.type}`,"\n\n",e.sdp),this.instance.setRemoteDescription(t)}_createAnswer(){return n(this,void 0,void 0,(function*(){if(!this._isAnswer())return;if("stable"!==this.instance.signalingState)return console.log(" - But the signaling state isn't stable, so triggering rollback"),void(yield Promise.all([this.instance.setLocalDescription({type:"rollback"}),this.instance.setRemoteDescription({sdp:this.options.remoteSdp,type:V.Offer})]));yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:V.Offer}),this._logTransceivers();const e=yield this.instance.createAnswer();yield this._setLocalDescription(e)}))}_setLocalDescription(e){const{useStereo:t,googleMaxBitrate:n,googleMinBitrate:i,googleStartBitrate:s,mediaSettings:o}=this.options;return t&&(e.sdp=Se(e.sdp)),n&&i&&s&&(e.sdp=((e,t,n,i)=>{const s=e.split("\r\n");return s.forEach(((e,o)=>{/^a=fmtp:\d*/.test(e)?s[o]+=`;x-google-max-bitrate=${t};x-google-min-bitrate=${n};x-google-start-bitrate=${i}`:/^a=mid:(1|video)/.test(e)&&(s[o]+=`\r\nb=AS:${t}`)})),s.join("\r\n")})(e.sdp,n,i,s)),o&&o.useSdpASBandwidthKbps&&null!==o.sdpASBandwidthKbps&&(e.sdp=((e,t)=>{let n="AS",i=t;!navigator.userAgent.match(/firefox/gim)||navigator.userAgent.match(/OPR\/[0-9]{2}/gi)||navigator.userAgent.match(/edg/gim)||(n="TIAS",i=1e3*(t>>>0));return-1===e.indexOf("b="+n+":")?e.replace(/c=IN (.*)\r\n/,"c=IN $1\r\nb="+n+":"+i+"\r\n"):e.replace(new RegExp("b="+n+":.*\r\n"),"b="+n+":"+i+"\r\n")})(e.sdp,o.sdpASBandwidthKbps)),this.instance.setLocalDescription(e)}_sdpReady(){S(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return n(this,void 0,void 0,(function*(){if(ue(this.options.localStream))return this.options.localStream;const e=yield(t=this.options,n(void 0,void 0,void 0,(function*(){let{audio:e=!0,micId:n}=t;const{micLabel:i=""}=t;n&&(n=yield ye(n,i,J.AudioIn).catch((e=>null)),n&&("boolean"==typeof e&&(e={}),e.deviceId={exact:n}));let{video:s=!1,camId:o}=t;const{camLabel:r=""}=t;return o&&(o=yield ye(o,r,J.Video).catch((e=>null)),o&&("boolean"==typeof s&&(s={}),s.deviceId={exact:o})),{audio:e,video:s}})));var t;return ve(e)}))}_isOffer(){return this.type===V.Offer}_isAnswer(){return this.type===V.Answer}_config(){const{iceServers:e=[],prefetchIceCandidates:t,forceRelayCandidate:n}=this.options,i={bundlePolicy:"max-compat",iceCandidatePoolSize:t?10:0,iceServers:e,iceTransportPolicy:n?"relay":"all"};return h.info("RTC config",i),i}close(){if(this.options.debug){if("file"===this.options.debugOutput){!function(e,t){const n=new Blob([JSON.stringify(e)],{type:"application/json"}),i=URL.createObjectURL(n),s=document.createElement("a");s.href=i,s.download=`${t}.json`,s.click(),URL.revokeObjectURL(i)}(this._webrtcStatsReporter.debuggerInstance.getTimeline(),this.options.telnyxSessionId)}this.stopDebugger()}}}const ot=je;class rt{constructor(e,t){this.session=e,this.id="",this.state=W[W.New],this.prevState="",this.channels=[],this.role=q.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._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(var n in t.constraints)if(t.constraints.hasOwnProperty(n)&&t.constraints[n]!==e[n])return;t.callback(e)}}))}))}))};const{iceServers:n,speaker:i,micId:s,micLabel:o,camId:r,camLabel:a,localElement:c,remoteElement:d,mediaConstraints:{audio:l,video:u},ringtoneFile:h,ringbackFile:p}=e;this.options=Object.assign({},H,{audio:l,video:u,iceServers:n,localElement:c,remoteElement:d,micId:s,micLabel:o,camId:r,camLabel:a,speakerId:i,ringtoneFile:h,ringbackFile:p},t),this._onMediaError=this._onMediaError.bind(this),this._init(),this.options&&(this._ringtone=Ne(this.options.ringtoneFile,"_ringtone"),this._ringback=Ne(this.options.ringbackFile,"_ringback"))}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}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}`}invite(){this.direction=G.Outbound,this.peer=new st(V.Offer,this.options,this.session),this._registerPeerEvents()}answer(e={}){var t,n;this.stopRingtone(),this.direction=G.Inbound,(null===(t=null==e?void 0:e.customHeaders)||void 0===t?void 0:t.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),(null===(n=e.preferred_codecs)||void 0===n?void 0:n.length)>0&&(this.options.preferred_codecs=e.preferred_codecs),this.peer=new st(V.Answer,this.options,this.session),this._registerPeerEvents()}playRingtone(){Oe(this._ringtone)}stopRingtone(){Pe(this._ringtone)}playRingback(){Oe(this._ringback)}stopRingback(){Pe(this._ringback)}hangup(e,t){var n,i,s;let o=e||{},r=!1!==t;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!==(n=this.options.customHeaders)&&void 0!==n?n:[],...null!==(s=null===(i=null==o?void 0:o.dialogParams)||void 0===i?void 0:i.customHeaders)&&void 0!==s?s:[]],this.setState(W.Hangup);const a=()=>{var e;return null===(e=this.peer)||void 0===e||e.close(),this.setState(W.Destroy)};if(this.stopRingtone(),this.stopRingback(),r){const e=new He({sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(e).catch((e=>{h.error("telnyx_rtc.bye failed!",e),j(b.Error,{error:e,sessionId:this.session.sessionid},this.session.uuid)})).then(a.bind(this))}else a()}hold(){const e=new We({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 We({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 We({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 qe({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(t)}message(e,t){const n={from:this.session.options.login,to:e,body:t},i=new qe({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(i)}muteAudio(){Me(this.options.localStream)}unmuteAudio(){Re(this.options.localStream)}toggleAudioMute(){De(this.options.localStream)}setAudioInDevice(e){return n(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 le({audio:{deviceId:{exact:e}}}),i=t.getAudioTracks()[0];n.replaceTrack(i),this.options.micId=e;const{localStream:s}=this.options;s.getAudioTracks().forEach((e=>e.stop())),s.getVideoTracks().forEach((e=>t.addTrack(e))),this.options.localStream=t}}))}muteVideo(){var e;e=this.options.localStream,xe(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,xe(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,xe(e,"video",null)}setVideoDevice(e){return n(this,void 0,void 0,(function*(){const{instance:t}=this.peer,n=t.getSenders().find((({track:{kind:e}})=>"video"===e));if(n){const t=yield le({video:{deviceId:{exact:e}}}),i=t.getVideoTracks()[0];n.replaceTrack(i);const{localElement:s,localStream:o}=this.options;he(s,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t}}))}deaf(){Me(this.options.remoteStream)}undeaf(){Re(this.options.remoteStream)}toggleDeaf(){De(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,t){return n(this,void 0,void 0,(function*(){if(!this||!this.peer)return void h.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:n}=this.peer,i=n.getSenders();if(!i)return void h.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=i.find((({track:{kind:e}})=>e===t));if(s){const n=s.getParameters();n.encodings||(n.encodings=[{rid:"h"}]),h.info("Parameters: ",n),h.info("Setting max ","audio"===t?"audio":"video"," bandwidth to: ",e," [bps]"),n.encodings[0].maxBitrate=e,yield s.setParameters(n).then((()=>{h.info("audio"===t?"New audio":"New video"," bandwidth settings in use: ",s.getParameters())})).catch((e=>console.error(e)))}else h.error("Could not set bandwidth (reason: no "+t+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")}))}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,t){if(!e)return;const n={callback:e,constraints:t};if(this._statsBindings.push(n),!this._statsIntervalId){const e=2e3;this._startStats(e)}}setState(e){switch(this._prevState=this._state,this._state=e,this.state=W[this._state].toLowerCase(),this.prevState=W[this._prevState].toLowerCase(),h.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:F.callUpdate,call:this}),e){case W.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case W.Active:setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&pe(e,t)}),0);break;case W.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:n}=e;switch(t){case B.Answer:if(this.gotAnswer=!0,this._state>=W.Active)return;this._state>=W.Early&&this.setState(W.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case B.Media:if(this._state>=W.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case B.Display:case B.Attach:{const{display_name:e,display_number:i,display_direction:s}=n;this.extension=i;const o=s===G.Inbound?G.Outbound:G.Inbound,r={type:F[t],call:this,displayName:e,displayNumber:i,displayDirection:o};j(b.Notification,r,this.id)||j(b.Notification,r,this.session.uuid);break}case B.Info:case B.Event:{const e=Object.assign(Object.assign({},n),{type:F.generic,call:this});j(b.Notification,e,this.id)||j(b.Notification,e,this.session.uuid);break}case B.Ringing:this.playRingback(),n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id);break;case B.Bye:const e=n.client_state||n.clientState;e&&(this.options.clientState=e),this.stopRingback(),this.stopRingtone(),this.hangup(n,!1)}}handleConferenceUpdate(e,t){return n(this,void 0,void 0,(function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==t.laName)return h.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:n,data:i,hashKey:s=String(this._lastSerno),arrIndex:o}=e;switch(n){case"bootObj":{this._lastSerno=0;const{chatChannel:e,infoChannel:n,modChannel:s,laName:o,conferenceMemberID:r,role:a}=t;this._dispatchConferenceUpdate({action:K.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),n&&(yield this._subscribeConferenceInfo(n)),s&&a===q.Moderator&&(yield this._subscribeConferenceModerator(s));const c=[];for(const e in i)c.push(Object.assign({callId:i[e][0],index:Number(e)},_(i[e][1])));this._dispatchConferenceUpdate({action:K.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:K.Add,callId:s,index:o},_(i)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:K.Modify,callId:s,index:o},_(i)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:K.Delete,callId:s,index:o},_(i)));break;case"clear":this._dispatchConferenceUpdate({action:K.Clear});break;default:this._dispatchConferenceUpdate({action:n,data:i,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 n(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{direction:t,from:n,fromDisplay:i,message:s,type:o}=e.data;this._dispatchConferenceUpdate({action:K.ChatMessage,direction:t,participantNumber:n,participantName:i,messageText:s,messageType:o,messageId:e.eventSerno})}},n=yield this.session.vertoSubscribe(t).catch((e=>{h.error("ConfChat subscription error:",e)}));ke(n,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(t,n)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:t,type:n}})}}}))}))}_subscribeConferenceInfo(e){return n(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,Ye(this.session,t);else h.error("Conference-Info unknown contentType",e)}},n=yield this.session.vertoSubscribe(t).catch((e=>{h.error("ConfInfo subscription error:",e)}));ke(n,e)&&this._addChannel(e)}))}_confControl(e,t={}){const n=Object.assign({application:"conf-control",callID:this.id,value:null},t);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:n})}_subscribeConferenceModerator(e){return n(this,void 0,void 0,(function*(){const t=(t,n=null,i=null)=>{const s=parseInt(n)||null;this._confControl(e,{command:t,id:s,value:i})},n=()=>{const{video:e}=this.options;if("boolean"==typeof e&&!e||"object"==typeof e&&y(e))throw`Conference ${this.id} has no video!`},i={nodeId:this.nodeId,channels:[e],handler:e=>{const{data:t}=e;if("list-videoLayouts"===t["conf-command"]){if(t.responseData){const e=JSON.stringify(t.responseData).replace(/IDS"/g,'Ids"');this._dispatchConferenceUpdate({action:K.LayoutList,layouts:JSON.parse(e)})}}else this._dispatchConferenceUpdate({action:K.ModCmdResponse,command:t["conf-command"],response:t.response})}},s=yield this.session.vertoSubscribe(i).catch((e=>{h.error("ConfMod subscription error:",e)}));ke(s,e)&&(this.role=q.Moderator,this._addChannel(e),Object.defineProperties(this,{listVideoLayouts:{configurable:!0,value:()=>{t("list-videoLayouts")}},playMedia:{configurable:!0,value:e=>{t("play",null,e)}},stopMedia:{configurable:!0,value:()=>{t("stop",null,"all")}},deaf:{configurable:!0,value:e=>{t("deaf",e)}},undeaf:{configurable:!0,value:e=>{t("undeaf",e)}},startRecord:{configurable:!0,value:e=>{t("recording",null,["start",e])}},stopRecord:{configurable:!0,value:()=>{t("recording",null,["stop","all"])}},snapshot:{configurable:!0,value:e=>{n(),t("vid-write-png",null,e)}},setVideoLayout:{configurable:!0,value:(e,i)=>{n();t("vid-layout",null,i?[e,i]:e)}},kick:{configurable:!0,value:e=>{t("kick",e)}},muteMic:{configurable:!0,value:e=>{t("tmute",e)}},muteVideo:{configurable:!0,value:e=>{n(),t("tvmute",e)}},presenter:{configurable:!0,value:e=>{n(),t("vid-res-id",e,"presenter")}},videoFloor:{configurable:!0,value:e=>{n(),t("vid-floor",e,"force")}},banner:{configurable:!0,value:(e,i)=>{n(),t("vid-banner",e,encodeURI(i))}},volumeDown:{configurable:!0,value:e=>{t("volume_out",e,"down")}},volumeUp:{configurable:!0,value:e=>{t("volume_out",e,"up")}},gainDown:{configurable:!0,value:e=>{t("volume_in",e,"down")}},gainUp:{configurable:!0,value:e=>{t("volume_in",e,"up")}},transfer:{configurable:!0,value:(e,n)=>{t("transfer",e,n)}}}))}))}_handleChangeHoldStateSuccess(e){return"active"===e.holdState?this.setState(W.Active):this.setState(W.Held),!0}_handleChangeHoldStateError(e){return h.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){let t=Ee(e,this.peer.instance.localDescription.sdp);this.options.useStereo&&(t=Se(t));const n={sdp:t,type:V.Answer};this.peer.instance.setRemoteDescription(n).then((()=>{this.gotEarly&&this.setState(W.Early),this.gotAnswer&&this.setState(W.Active)})).catch((e=>{h.error("Call setRemoteDescription Error: ",e),this.hangup()}))}_requestAnotherLocalDescription(){S(this.peer.onSdpReadyTwice)?j(b.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,n;this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:i,type:s}=e;if(-1===i.indexOf("candidate"))return h.info("No candidate - retry \n"),void this._requestAnotherLocalDescription();null===(n=null===(t=this.peer)||void 0===t?void 0:t.instance)||void 0===n||n.removeEventListener("icecandidate",this._onIce);let o=null;const r={sessid:this.session.sessionid,sdp:i,dialogParams:this.options,"User-Agent":`Web-${ot}`};switch(s){case V.Offer:this.setState(W.Requesting),o=new Ge(r);break;case V.Answer:this.setState(W.Answering),o=!0===this.options.attach?new Fe(r):new Be(r);break;default:return h.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}this._execute(o).then((e=>{const{node_id:t=null}=e;this._targetNodeId=t,s===V.Offer?this.setState(W.Trying):this.setState(W.Active)})).catch((e=>{h.error(`${this.id} - Sending ${s} error:`,e),this.hangup()})),console.timeEnd(g)}_onIce(e){const{instance:t}=this.peer;null===this._iceTimeout&&(this._iceTimeout=setTimeout((()=>this._onIceSdp(t.localDescription)),1e3)),e.candidate?h.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(t.localDescription)}_registerPeerEvents(){const{instance:e}=this.peer;this._iceDone=!1,e.onicecandidate=e=>{this._iceDone||this._onIce(e)},e.addEventListener("addstream",(e=>{this.options.remoteStream=e.stream})),e.addEventListener("track",(e=>{this.options.remoteStream=e.streams[0];const{remoteElement:t,remoteStream:n,screenShare:i}=this.options;!1===i&&he(t,n)}))}_onMediaError(e){this._dispatchNotification({type:F.userMediaError,error:e}),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:F.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(j(b.Notification,e,this.id,!1)||j(b.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:n,onNotification:i}=this.options;e||(this.options.id=c()),this.id=this.options.id,t&&!y(t)||(this.options.userVariables=this.session.options.userVariables||{}),n||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,O(b.MediaError,this._onMediaError,this.id),S(i)&&O(b.Notification,i.bind(this),this.id),this.setState(W.New),h.info("New Call with Options:",this.options)}_finalize(){this._stopStats(),this.peer&&this.peer.instance&&(this.peer.instance.close(),this.peer=null);const{remoteStream:e,localStream:t}=this.options;fe(e),fe(t),U(b.MediaError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),h.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),h.info("Stats stopped")}}rt.setStateTelnyx=e=>{if(e){switch(e._state){case W.Requesting:case W.Recovering: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 at extends rt{constructor(){super(...arguments),this._statsInterval=null}hangup(e={},t=!0){this.screenShare instanceof at&&this.screenShare.hangup(e,t),super.hangup(e,t)}startScreenShare(e){return n(this,void 0,void 0,(function*(){const t=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;t.getTracks().forEach((e=>{e.addEventListener("ended",(()=>{this.screenShare&&this.screenShare.hangup()}))}));const{remoteCallerName:i,remoteCallerNumber:s,callerName:o,callerNumber:r}=this.options,a=Object.assign({screenShare:!0,localStream:t,destinationNumber:`${this.extension}-screen`,remoteCallerName:i,remoteCallerNumber:`${s}-screen`,callerName:`${o} (Screen)`,callerNumber:`${r} (Screen)`},e);return this.screenShare=new at(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof at&&this.screenShare.hangup()}setAudioOutDevice(e){return n(this,void 0,void 0,(function*(){this.options.speakerId=e;const{remoteElement:t,speakerId:n}=this.options;return!(!t||!n)&&pe(t,n)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);h.setLevel(2),this._statsInterval=window.setInterval((()=>n(this,void 0,void 0,(function*(){const e=yield this.peer.instance.getStats(null);let t="";const n=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],i=["id","type","timestamp"];e.forEach((e=>{n.includes(e.type)||(t+=`\n${e.type}\n`,Object.keys(e).forEach((n=>{i.includes(n)||(t+=`\t${n}: ${e[n]}\n`)})))})),h.info(t)}))),2e3)}}class ct 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._videoConstraints=!1,this._speaker=null,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile}get reconnectDelay(){return 1e3}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return n(this,void 0,void 0,(function*(){e.connect.call(this)}))}checkPermissions(e=!0,t=!0){return n(this,void 0,void 0,(function*(){try{const n=yield ve({audio:e,video:t});return fe(n),!0}catch(e){return!1}}))}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return n(this,void 0,void 0,(function*(){Object.keys(this.calls).forEach((e=>this.calls[e].setState(W.Purge))),this.calls={},yield e.disconnect.call(this)}))}speedTest(e){return new Promise(((t,n)=>{if(P(b.SpeedTest,(n=>{const{upDur:i,downDur:s}=n,o=s?8*e/(s/1e3)/1024:0;t({upDur:i,downDur:s,upKps:(i?8*e/(i/1e3)/1024:0).toFixed(0),downKps:o.toFixed(0)})}),this.uuid),!(e=Number(e)))return n(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let i=e/1024;e%1024&&i++;const s=".".repeat(1024);for(let e=0;e<i;e++)this.executeRaw(`#SPB ${s}`);this.executeRaw("#SPE")}))}getDevices(){return me().catch((e=>(j(b.MediaError,e,this.uuid),[])))}getVideoDevices(){return me(J.Video).catch((e=>(j(b.MediaError,e,this.uuid),[])))}getAudioInDevices(){return me(J.AudioIn).catch((e=>(j(b.MediaError,e,this.uuid),[])))}getAudioOutDevices(){return me(J.AudioOut).catch((e=>(console.error("getAudioOutDevices",e),j(b.MediaError,e,this.uuid),[])))}validateDeviceId(e,t,n){return ye(e,t,n)}getDeviceResolutions(e){return n(this,void 0,void 0,(function*(){try{return yield(e=>n(void 0,void 0,void 0,(function*(){const t=[],n=yield ve({video:{deviceId:{exact:e}}}),i=n.getVideoTracks()[0];for(let e=0;e<be.length;e++){const[n,s]=be[e];(yield i.applyConstraints({width:{exact:n},height:{exact:s}}).then((()=>!0)).catch((()=>!1)))&&t.push({resolution:`${n}x${s}`,width:n,height:s})}return fe(n),t})))(e)}catch(e){throw e}}))}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return n(this,void 0,void 0,(function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=e,s=t(e,["micId","micLabel"]);return _e(s),this._audioConstraints=yield we(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints}))}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}setVideoSettings(e){return n(this,void 0,void 0,(function*(){if(!e)throw new Error("You need to provide the settings object");const{camId:n,camLabel:i}=e,s=t(e,["camId","camLabel"]);return _e(s),this._videoConstraints=yield we(n,i,"videoinput",s),this.camId=n,this.camLabel=i,this._videoConstraints}))}disableWebcam(){this._videoConstraints=!1}enableWebcam(){this._videoConstraints=!0}set iceServers(e){const t={urls:["stun:stun.l.google.com:19302"]};this._iceServers="boolean"==typeof e?e?[t]:[]:e||[m,v,t]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=I(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=I(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:t="",data:n}){if(!t)throw new Error(`Invalid channel for broadcast: ${t}`);const i=new Ke({sessid:this.sessionid,eventChannel:t,data:n});e&&(i.targetNodeId=e),this.execute(i).catch((e=>e))}vertoSubscribe({nodeId:e,channels:t=[],handler:i}){return n(this,void 0,void 0,(function*(){if(!(t=t.filter((e=>e&&!this._existsSubscription(this.relayProtocol,e)))).length)return{};const n=new Je({sessid:this.sessionid,eventChannel:t});e&&(n.targetNodeId=e);const s=yield this.execute(n),{unauthorized:o=[],subscribed:r=[]}=Te(s);return o.length&&o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),r.forEach((e=>this._addSubscription(this.relayProtocol,i,e))),s}))}vertoUnsubscribe({nodeId:e,channels:t=[]}){return n(this,void 0,void 0,(function*(){if(!(t=t.filter((e=>e&&this._existsSubscription(this.relayProtocol,e)))).length)return{};const n=new ze({sessid:this.sessionid,eventChannel:t});e&&(n.targetNodeId=e);const i=yield this.execute(n),{unsubscribed:s=[],notSubscribed:o=[]}=Te(i);return s.forEach((e=>this._removeSubscription(this.relayProtocol,e))),o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),i}))}static telnyxStateCall(e){return at.setStateTelnyx(e)}}class dt{constructor(e,t){this.code=t,this.message=e}}class lt extends re{constructor(){super(),this.method=B.Ping;this.buildRequest({method:this.method,params:{}})}}class ut{constructor(e){this.session=e}_ack(e,t){const n=new Ve(e,t);this.nodeId&&(n.targetNodeId=this.nodeId),this.session.execute(n)}reconnectDelay(){return 1e3*k(2,6)}handleMessage(e){const{session:t}=this,{id:n,method:i,params:s={}}=e,o=null==s?void 0:s.callID,r=null==s?void 0:s.eventChannel,a=null==s?void 0:s.eventType,c=i===B.Attach;if("channelPvtData"===a)return this._handlePvtEvent(s.pvtData);if(o&&t.calls.hasOwnProperty(o)){if(!c)return t.calls[o].handleMessage(e),void this._ack(n,i);t.calls[o].hangup({},!1)}const d=()=>{var e,n,i,r;const a={id:o,remoteSdp:s.sdp,destinationNumber:s.callee_id_number,remoteCallerName:s.caller_id_name,remoteCallerNumber:s.caller_id_number,callerName:s.callee_id_name,callerNumber:s.callee_id_number,attach:c,mediaSettings:s.mediaSettings,debug:null!==(e=t.options.debug)&&void 0!==e&&e,debugOutput:null!==(n=t.options.debugOutput)&&void 0!==n?n:"socket",prefetchIceCandidates:null!==(i=t.options.prefetchIceCandidates)&&void 0!==i&&i,forceRelayCandidate:null!==(r=t.options.forceRelayCandidate)&&void 0!==r&&r};s.telnyx_call_control_id&&(a.telnyxCallControlId=s.telnyx_call_control_id),s.telnyx_session_id&&(a.telnyxSessionId=s.telnyx_session_id),s.telnyx_leg_id&&(a.telnyxLegId=s.telnyx_leg_id),s.client_state&&(a.clientState=s.client_state),s.dialogParams&&s.dialogParams.custom_headers&&s.dialogParams.custom_headers.length&&(a.customHeaders=s.dialogParams.custom_headers);const d=new at(t,a);return d.nodeId=this.nodeId,d},l=new ae,u=new lt;switch(i){case B.Ping:this.session.execute(u);break;case B.Punt:t.disconnect();break;case B.Invite:{const e=d();e.playRingtone(),e.setState(W.Ringing),e.direction=G.Inbound,this._ack(n,i);break}case B.Attach:{const t=d();this.session.autoRecoverCalls?t.answer():t.setState(W.Recovering),t.handleMessage(e);break}case B.Event:case"webrtc.event":if(!r)return void h.error("Verto received an unknown event:",s);const o=t.relayProtocol,a=r.split(".")[0];t._existsSubscription(o,r)?j(o,s,r):r===t.sessionid?this._handleSessionEvent(s.eventData):t._existsSubscription(o,a)?j(o,s,a):t.calls.hasOwnProperty(r)?t.calls[r].handleMessage(e):j(b.Notification,s,t.uuid);break;case B.Info:s.type=F.generic,j(b.Notification,s,t.uuid);break;case B.ClientReady:this.session.execute(l);break;default:{const n=x(e);if(n){switch(n){case z.REGISTER:case z.REGED:t.connection.previousGatewayState!==z.REGED&&t.connection.previousGatewayState!==z.REGISTER&&(ut.retriedRegister=0,s.type=F.vertoClientReady,j(b.Ready,s,t.uuid));break;case z.UNREGED:case z.NOREG:if(ut.retriedRegister+=1,5===ut.retriedRegister){ut.retriedRegister=0,j(b.Error,{error:new dt("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:t.sessionid},t.uuid);break}setTimeout((()=>{this.session.execute(l)}),this.reconnectDelay());break;case z.FAILED:case z.FAIL_WAIT:if(t.connection.previousGatewayState!==z.FAILED&&t.connection.previousGatewayState!==z.FAIL_WAIT){if(!this.session.hasAutoReconnect()){ut.retriedConnect=0,j(b.Error,{error:new dt("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:t.sessionid},t.uuid);break}if(ut.retriedConnect+=1,5===ut.retriedConnect){ut.retriedConnect=0,j(b.Error,{error:new Error("Connection Retry Failed"),sessionId:t.sessionid},t.uuid);break}setTimeout((()=>{this.session.disconnect().then((()=>{this.session.clearConnection(),this.session.connect()}))}),this.reconnectDelay())}break;default:h.warn("GatewayState message unknown method:",e)}break}h.warn("Verto message unknown method:",e);break}}}_retrieveCallId(e,t){const n=Object.keys(this.session.calls);if("bootObj"!==e.action)return n.find((e=>this.session.calls[e].channels.includes(t)));{const t=e.data.find((e=>n.includes(e[0])));if(t instanceof Array)return t[0]}}_handlePvtEvent(e){return n(this,void 0,void 0,(function*(){const{session:t}=this,n=t.relayProtocol,{action:i,laChannel:s,laName:o,chatChannel:r,infoChannel:a,modChannel:c,conferenceMemberID:d,role:l,callID:u}=e;switch(i){case"conference-liveArray-join":{const n=()=>{t.vertoBroadcast({nodeId:this.nodeId,channel:s,data:{liveArray:{command:"bootstrap",context:s,name:o}}})},i={nodeId:this.nodeId,channels:[s],handler:({data:i})=>{const r=u||this._retrieveCallId(i,s);if(r&&t.calls.hasOwnProperty(r)){const a=t.calls[r];a._addChannel(s),a.extension=o,a.handleConferenceUpdate(i,e).then((e=>{"INVALID_PACKET"===e&&n()}))}}},r=yield t.vertoSubscribe(i).catch((e=>{h.error("liveArray subscription error:",e)}));ke(r,s)&&n();break}case"conference-liveArray-part":{let e=null;if(s&&t._existsSubscription(n,s)){const{callId:i=null}=t.subscriptions[n][s];if(e=t.calls[i]||null,null!==i){const n={type:F.conferenceUpdate,action:K.Leave,conferenceName:o,participantId:Number(d),role:l};j(b.Notification,n,i,!1)||j(b.Notification,n,t.uuid),null===e&&U(b.Notification,null,i)}}const i=[s,r,a,c];t.vertoUnsubscribe({nodeId:this.nodeId,channels:i}).then((({unsubscribedChannels:t=[]})=>{e&&(e.channels=e.channels.filter((e=>!t.includes(e))))})).catch((e=>{h.error("liveArray unsubscribe error:",e)}));break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":Ye(this.session,e);break;case"logo-info":{const t={type:F.conferenceUpdate,action:K.LogoInfo,logo:e.logoURL};j(b.Notification,t,this.session.uuid);break}}}}ut.retriedConnect=0,ut.retriedRegister=0;class ht extends ct{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,window.addEventListener("beforeunload",(e=>{this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&this.calls[e].hangup({},!0)}))}))}validateOptions(){return T(this.options)}newCall(e){if(!e||!e.destinationNumber)throw new Error("Verto.newCall() error: destinationNumber is required.");console.time(g);const t=new at(this,e);return t.invite(),t}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}_onSocketOpen(){return n(this,void 0,void 0,(function*(){this._idle=!1;const{login:e,password:t,passwd:n,login_token:i,userVariables:s,autoReconnect:o=!0}=this.options,r=new $e(e,t||n,i,this.sessionid,s,!!Q()),a=yield this.execute(r).catch(this._handleLoginError);a&&(this._autoReconnect=o,this.sessionid=a.sessid)}))}_onSocketMessage(e){new ut(this).handleMessage(e)}}e.TelnyxRTC=class extends ht{constructor(e){super(e),console.log(`SDK version: ${Ue}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Ae()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Le.full},{browserName:"Firefox",features:["audio"],supported:Le.partial},{browserName:"Safari",supported:Le.not_supported},{browserName:"Edge",supported:Le.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Le.not_supported},{browserName:"Firefox",supported:Le.not_supported},{browserName:"Safari",features:["video","audio"],supported:Le.full},{browserName:"Edge",supported:Le.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Le.full},{browserName:"Firefox",features:["audio"],supported:Le.partial},{browserName:"Safari",supported:Le.not_supported},{browserName:"Edge",supported:Le.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Le.full},{browserName:"Firefox",features:["audio"],supported:Le.partial},{browserName:"Safari",features:["video","audio"],supported:Le.full},{browserName:"Edge",features:["audio"],supported:Le.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Le.full},{browserName:"Firefox",features:["audio"],supported:Le.partial},{browserName:"Safari",supported:Le.not_supported},{browserName:"Edge",features:["audio"],supported:Le.partial}]}]}},Object.defineProperty(e,"__esModule",{value:!0})}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).TelnyxWebRTC={})}(this,(function(e){"use strict";function t(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(n[i[s]]=e[i[s]])}return n}function n(e,t,n,i){return new(n||(n=Promise))((function(s,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((i=i.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),s=new Uint8Array(16);function o(){if(!i)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return i(s)}for(var r=[],a=0;a<256;++a)r[a]=(a+256).toString(16).substr(1);function c(e,t,n){var i=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var s=(e=e||{}).random||(e.rng||o)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var a=0;a<16;++a)t[i+a]=s[a];return t||function(e,t){var n=t||0,i=r;return[i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]]].join("")}(s)}var d="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function l(e,t){return e(t={exports:{}},t.exports),t.exports}var u=l((function(e){var t,n;t=d,n=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function s(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[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,n){for(var s=0;s<i.length;s++){var o=i[s];this[o]=s<t?e:this.methodFactory(o,t,n)}this.log=this.debug}function a(e,n,i){return function(){typeof console!==t&&(r.call(this,n,i),this[e].apply(this,arguments))}}function c(i,r,c){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?o:void 0!==console[i]?s(console,i):void 0!==console.log?s(console,"log"):e)}(i)||a.apply(this,arguments)}function d(e,n,s){var o,a=this;n=null==n?"WARN":n;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 n=window.document.cookie,i=n.indexOf(encodeURIComponent(d)+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i))[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(n,s){if("string"==typeof n&&void 0!==a.levels[n.toUpperCase()]&&(n=a.levels[n.toUpperCase()]),!("number"==typeof n&&n>=0&&n<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(o=n,!1!==s&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+n+";"}catch(e){}}}(n),r.call(a,n,e),typeof console===t&&n<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){n=e,l()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(n,!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=n),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=n():t.log=n()}));const h=u.getLogger("telnyx"),p=h.methodFactory;h.methodFactory=(e,t,n)=>{const i=p(e,t,n);return function(){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(let t=0;t<arguments.length;t++)e.push(arguments[t]);i.apply(void 0,e)}},h.setLevel(h.getLevel());const g="Time to call invite",v="wss://rtc.telnyx.com",f={urls:"stun:stun.telnyx.com:3478"},m={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var b;(b=e.SwEvent||(e.SwEvent={})).SocketOpen="telnyx.socket.open",b.SocketClose="telnyx.socket.close",b.SocketError="telnyx.socket.error",b.SocketMessage="telnyx.socket.message",b.SpeedTest="telnyx.internal.speedtest",b.Ready="telnyx.ready",b.Error="telnyx.error",b.Notification="telnyx.notification",b.StatsFrame="telnyx.stats.frame",b.StatsReport="telnyx.stats.report",b.Messages="telnyx.messages",b.Calls="telnyx.calls",b.MediaError="telnyx.rtc.mediaError";const y=e=>0===Object.keys(e).length,w=e=>{const[t,n,i,s,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){h.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},S=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},_=e=>e instanceof Function||"function"==typeof e,I=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,E=/^(ws|wss):\/\//,C=(e,t=null)=>{const{result:n={},error:i}=e;if(i)return{error:i};const{result:s=null}=n;if(null===s)return null!==t&&(n.node_id=t),{result:n};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&"200"!==o?{error:s}:a?C(a,r):{result:s}},k=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),T=({login:e,passwd:t,password:n,login_token:i})=>Boolean(e&&(t||n)||i),R=e=>{var t,n,i,s,o,r;let a="",c="";(null===(n=null===(t=null==e?void 0:e.result)||void 0===t?void 0:t.params)||void 0===n?void 0:n.state)&&(a=null===(s=null===(i=null==e?void 0:e.result)||void 0===i?void 0:i.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 x({debounceTime:e}){let t,n;return{promise:new Promise(((i,s)=>{t=e?M(i,e):i,n=s})),resolve:t,reject:n}}const M=(e,t)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout((()=>{e(...i)}),t)}},L="GLOBAL",A={},D=(e,t)=>`${e}|${t}`,N=(e,t=L)=>D(e,t)in A,O=(e,t,n=L)=>{const i=D(e,n);i in A||(A[i]=[]),A[i].push(t)},P=(e,t,n=L)=>{const i=function(s){U(e,i,n),t(s)};return i.prototype.targetRef=t,O(e,i,n)},U=(e,t,n=L)=>{if(!N(e,n))return!1;const i=D(e,n);if(_(t)){for(let e=A[i].length-1;e>=0;e--){const n=A[i][e];(t===n||n.prototype&&t===n.prototype.targetRef)&&A[i].splice(e,1)}}else A[i]=[];return 0===A[i].length&&delete A[i],!0},j=(e,t,n=L,i=!0)=>{const s=i&&n!==L;if(!N(e,n))return s&&j(e,t),!1;const o=D(e,n),r=A[o].length;if(!r)return s&&j(e,t),!1;for(let e=r-1;e>=0;e--)A[o][e](t);return s&&j(e,t),!0},$=e=>{const t=D(e,"");Object.keys(A).filter((e=>0===e.indexOf(t))).forEach((e=>delete A[e]))};var V,G,B;!function(e){e.Offer="offer",e.Answer="answer"}(V||(V={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(G||(G={})),function(e){e.Invite="telnyx_rtc.invite",e.Attach="telnyx_rtc.attach",e.Answer="telnyx_rtc.answer",e.Info="telnyx_rtc.info",e.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"}(B||(B={}));const F={generic:"event",[B.Display]:"participantData",[B.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError"},H={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,video:!1,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0}};var W,q,K,J,z;!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"}(q||(q={})),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"}(J||(J={})),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"}(z||(z={}));const Y="telnyx-voice-sdk-id";function Q(){return sessionStorage.getItem(Y)}"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{sessionStorage.removeItem(Y)}));let X="undefined"!=typeof WebSocket?WebSocket:null;const Z=0,ee=1,te=2,ne=3;class ie{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=v,this._timers={},this.upDur=null,this.downDur=null;const{host:t,env:n}=e.options;t&&(this._host=(e=>`${E.test(e)?"":"wss://"}${e}`)(t)),n&&(this._host="development"===n?"wss://rtcdev.telnyx.com":v)}get connected(){return this._wsClient&&this._wsClient.readyState===ee}get connecting(){return this._wsClient&&this._wsClient.readyState===Z}get closing(){return this._wsClient&&this._wsClient.readyState===te}get closed(){return this._wsClient&&this._wsClient.readyState===ne}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){const t=new URL(this._host),n=Q();n&&t.searchParams.set("voice_sdk_id",n),this._wsClient=new X(t.toString()),this._wsClient.onopen=t=>j(e.SwEvent.SocketOpen,t,this.session.uuid),this._wsClient.onclose=t=>j(e.SwEvent.SocketClose,t,this.session.uuid),this._wsClient.onerror=t=>j(e.SwEvent.SocketError,{error:t,sessionId:this.session.sessionid},this.session.uuid),this._wsClient.onmessage=t=>{var n,i;const s=S(t.data);var o;if("string"!=typeof s){if(s.voice_sdk_id&&(o=s.voice_sdk_id,sessionStorage.setItem(Y,o)),this._unsetTimer(s.id),h.debug("RECV: \n",JSON.stringify(s,null,2),"\n"),z[`${null===(i=null===(n=null==s?void 0:s.result)||void 0===n?void 0:n.params)||void 0===i?void 0:i.state}`]||!j(s.id,s)){const t=R(s);j(e.SwEvent.SocketMessage,s,this.session.uuid),Boolean(t)&&(this.previousGatewayState=t)}}else this._handleStringResponse(s)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:t}=e,n=new Promise(((e,n)=>{if(t.hasOwnProperty("result"))return e();P(t.id,(t=>{const{result:i,error:s}=C(t);return s?n(s):e(i)}))}));return h.debug("SEND: \n",JSON.stringify(t,null,2),"\n"),this._wsClient.send(JSON.stringify(t)),n}close(){this._wsClient&&(_(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close()),this._wsClient=null}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(t){if(/^#SP/.test(t))switch(t[3]){case"U":this.upDur=parseInt(t.substring(4));break;case"D":this.downDur=parseInt(t.substring(4)),j(e.SwEvent.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else h.warn("Unknown message from socket",t)}}class se{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:c()},e)}}const oe={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 re extends se{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=t(e.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const e in oe)e&&n.hasOwnProperty(e)&&(n[oe[e]]=n[e],delete n[e]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class ae extends re{constructor(){super(),this.method=B.GatewayState;this.buildRequest({method:this.method,params:{}})}}class ce{constructor(e){this.pendingRequestId=null,this.onSocketMessage=e=>n(this,void 0,void 0,(function*(){e.id===this.pendingRequestId&&this.gatewayStateTask.resolve(R(e))})),this.getIsRegistered=()=>n(this,void 0,void 0,(function*(){const e=new ae;this.pendingRequestId=e.request.id,this.gatewayStateTask=x({}),this.session.execute(e);const t=yield this.gatewayStateTask.promise;return!!t&&[z.REGISTER,z.REGED].includes(t)})),this.session=e,this.gatewayStateTask=x({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class de{constructor(e){if(this.options=e,this.uuid=c(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.connection=null,this._jwtAuth=!1,this._doKeepAlive=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");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 ie(this),this.registerAgent=new ce(this)}get __logger(){return h}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*k(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}),this.connect()}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return T(this.options)}broadcast(e){}disconnect(){return n(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()}))}on(e,t){return O(e,t,this.uuid),this}off(e,t){return U(e,t,this.uuid),this}connect(){return n(this,void 0,void 0,(function*(){this.connection||(this.connection=new ie(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()}))}_handleLoginError(t){j(e.SwEvent.Error,{error:t,sessionId:this.sessionid},this.uuid)}_onSocketOpen(){return n(this,void 0,void 0,(function*(){}))}onNetworkClose(){this.relayProtocol&&$(this.relayProtocol);for(const e in this.subscriptions)$(e);this.subscriptions={},this.contexts=[],this._autoReconnect&&(this._reconnectTimeout=setTimeout((()=>this.connect()),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,t){this._existsSubscription(e,t)&&(t?(delete this.subscriptions[e][t],U(e,null,t)):(delete this.subscriptions[e],$(e)))}_addSubscription(e,t=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},_(t)&&O(e,t,n))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(e.SwEvent.SocketOpen,this._onSocketOpen),this.on(e.SwEvent.SocketClose,this.onNetworkClose),this.on(e.SwEvent.SocketError,this.onNetworkClose),this.on(e.SwEvent.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(e.SwEvent.SocketOpen,this._onSocketOpen),this.off(e.SwEvent.SocketClose,this.onNetworkClose),this.off(e.SwEvent.SocketError,this.onNetworkClose),this.off(e.SwEvent.SocketMessage,this._onSocketMessage)}_emptyExecuteQueues(){this._executeQueue.forEach((({resolve:e,msg:t})=>{"string"==typeof t?this.executeRaw(t):e(this.execute(t))}))}_closeConnection(){this._idle=!0,clearTimeout(this._keepAliveTimeout),this.connection&&this.connection.close()}_keepAlive(){!0===this._doKeepAlive&&(this._pong=!1,this._keepAliveTimeout=setTimeout((()=>this._keepAlive()),3e4))}static on(e,t){O(e,t)}static off(e){U(e)}static uuid(){return c()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}getIsRegistered(){return this.registerAgent.getIsRegistered()}}const le=e=>navigator.mediaDevices.getUserMedia(e),ue=e=>e&&e instanceof MediaStream,he=(e,t)=>{const n=I(e);null!==n&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=t)},pe=(e,t)=>n(void 0,void 0,void 0,(function*(){const n=I(e);if(null===n)return h.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof t)return h.info(`Invalid speaker deviceId: '${t}'`),!1;try{return yield n.setSinkId(t),!0}catch(e){return!1}})),ge=e=>{e&&"live"===e.readyState&&e.stop()},ve=e=>{ue(e)&&e.getTracks().forEach(ge),e=null},fe=e=>n(void 0,void 0,void 0,(function*(){h.info("RTCService.getUserMedia",e);const{audio:t,video:n}=e;if(!t&&!n)return null;try{return yield le(e)}catch(e){throw h.error("getUserMedia error: ",e),e}})),me=(e=null,t=!1)=>n(void 0,void 0,void 0,(function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===J.AudioIn||e===J.AudioOut,video:!e||e===J.Video}))(e)).catch((e=>(console.error(e),null)));if(i){if(ve(i),n=yield navigator.mediaDevices.enumerateDevices(),e&&(n=n.filter((t=>t.kind===e))),!0===t)return n;const s=[];n=n.filter((e=>{if(!e.groupId)return!0;const t=`${e.kind}-${e.groupId}`;return!s.includes(t)&&(s.push(t),!0)}))}return n})),be=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],ye=(e,t,i)=>n(void 0,void 0,void 0,(function*(){const n=yield me(i,!0);for(let i=0;i<n.length;i++){const{deviceId:s,label:o}=n[i];if(e===s||t===o)return s}return null})),we=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((n=>{t.hasOwnProperty(n)&&null!==e[n]&&void 0!==e[n]||delete e[n]}))},Se=(e,t,i,s)=>n(void 0,void 0,void 0,(function*(){const{deviceId:n}=s;if(void 0===n&&(e||t)){const n=yield ye(e,t,i).catch((e=>null));n&&(s.deviceId={exact:n})}return s})),_e=e=>{const t="\r\n",n=e.split(t),i=n.findIndex((e=>/^a=rtpmap/.test(e)&&/opus\/48000/.test(e)));if(i<0)return e;const s=(e=>{const t=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),n=e.match(t);return n&&2==n.length?n[1]:null})(n[i]),o=new RegExp(`a=fmtp:${s}`),r=n.findIndex((e=>o.test(e)));return r>=0?/stereo=1;/.test(n[r])||(n[r]+="; stereo=1; sprop-stereo=1"):n[i]+=`${t}a=fmtp:${s} stereo=1; sprop-stereo=1`,n.join(t)},Ie=e=>/^m=audio/.test(e),Ee=e=>/^m=video/.test(e),Ce=(e,t)=>{const n="\r\n",i=t.split(n);if(i.findIndex(Ie)<i.findIndex(Ee))return e;const s=e.split(n),o=s.findIndex(Ie),r=s.findIndex(Ee),a=s.slice(o,r),c=s.slice(r,s.length-1);return[...s.slice(0,o),...c,...a,""].join(n)},ke=(e,t)=>{if(!e)return!1;const{subscribed:n,alreadySubscribed:i}=Te(e);return n.includes(t)||i.includes(t)},Te=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((n=>{t[n]=e[`${n}Channels`]||[]})),t},Re=(e,t=null,n=null)=>{if(!ue(e))return null;let i=[];switch(t){case"audio":i=e.getAudioTracks();break;case"video":i=e.getVideoTracks();break;default:i=e.getTracks()}i.forEach((e=>{switch(n){case"on":case!0:e.enabled=!0;break;case"off":case!1:e.enabled=!1;break;default:e.enabled=!e.enabled}}))},xe=e=>{Re(e,"audio",!0)},Me=e=>{Re(e,"audio",!1)},Le=e=>{Re(e,"audio",null)};function Ae(){try{const{browserInfo:e,name:t,version:n,supportAudio:i,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],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,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],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,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("/"),n=parseInt(t[1],10);return{browserInfo:navigator.userAgent,name:e,version:n,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],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,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:n,supportWebRTC:!!(o&&r&&a&&c&&d),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!fe}}catch(e){return e.message}}var De;function Ne(e,t){const n=document.getElementById(t);if(n)return n;if(e&&t){const n=document.createElement("audio");return n.id=t,n.loop=!0,n.src=e,n.preload="auto",n.load(),document.body.appendChild(n),n}return null}function Oe(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then((()=>{e._playFulfilled=!0})).catch((t=>{console.error("playAudio",t),e._playFulfilled=!0})))}function Pe(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"}(De||(De={}));var Ue="2.22.7",je=Ue;class $e extends re{constructor(e,t,n,i,s={},o){super(),this.method="login";const r={login:e,passwd:t,login_token:n,userVariables:s,reconnection:o,loginParams:{},"User-Agent":{sdkVersion:je,data:navigator.userAgent}};i&&(r.sessid=i),this.buildRequest({method:this.method,params:r})}}class Ve extends re{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Ge extends re{toString(){return B.Invite}}class Be extends re{toString(){return B.Answer}}class Fe extends re{toString(){return B.Attach}}class He extends re{toString(){return B.Bye}}class We extends re{toString(){return B.Modify}}class qe extends re{toString(){return B.Info}}class Ke extends re{toString(){return B.Broadcast}}class Je extends re{toString(){return B.Subscribe}}class ze extends re{toString(){return B.Unsubscribe}}const Ye=(t,n)=>{const{contentType:i,canvasType:s,callID:o,canvasInfo:r=null,currentLayerIdx:a=-1}=n;r&&"mcu-personal-canvas"!==s&&delete r.memberID;const c={type:F.conferenceUpdate,call:t.calls[o],canvasInfo:Qe(r),currentLayerIdx:a};switch(i){case"layer-info":{const n=Object.assign({action:K.LayerInfo},c);j(e.SwEvent.Notification,n,t.uuid);break}case"layout-info":{const n=Object.assign({action:K.LayoutInfo},c);j(e.SwEvent.Notification,n,t.uuid);break}}},Qe=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return S(t)};function Xe(e){const{packetsLost:t,packetsReceived:n,jitter:i,rtt:s}=e,o=function(e){const{jitter:t,rtt:n}=e,i=t+n/2;return.024*i+.11*(i-177.3)*(i>177.3?1:0)}({rtt:s,jitter:i}),r=function(e){const{packetsLost:t,packetsReceived:n}=e,i=t/(n+t)*100;return 20*Math.log(1+i)}({packetsLost:t,packetsReceived:n}),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 Ze(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"}var et,tt=l((function(e,t){var n;function i(){}function s(){s.init.call(this)}function o(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function r(e,t,n,s){var r,a,c;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),c=a[t]):(a=e._events=new i,e._eventsCount=0),c){if("function"==typeof c?c=a[t]=s?[n,c]:[c,n]:s?c.unshift(n):c.push(n),!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]=n,++e._eventsCount;return e}function a(e,t,n){function i(){e.removeListener(t,i),s||(s=!0,n.apply(e,arguments))}var s=!1;return i.listener=n,i}function c(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function d(e,t){for(var n=Array(t);t--;)n[t]=e[t];return n}Object.defineProperty(t,"__esModule",{value:!0}),i.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&&n.active&&!(this instanceof n.Domain)&&(this.domain=n.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new i,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,n,i,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(!(n=r[e]))return!1;var u="function"==typeof n;switch(i=arguments.length){case 1:!function(e,t,n){if(t)e.call(n);else for(var i=e.length,s=d(e,i),o=0;o<i;++o)s[o].call(n)}(n,u,this);break;case 2:!function(e,t,n,i){if(t)e.call(n,i);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].call(n,i)}(n,u,this,arguments[1]);break;case 3:!function(e,t,n,i,s){if(t)e.call(n,i,s);else for(var o=e.length,r=d(e,o),a=0;a<o;++a)r[a].call(n,i,s)}(n,u,this,arguments[1],arguments[2]);break;case 4:!function(e,t,n,i,s,o){if(t)e.call(n,i,s,o);else for(var r=e.length,a=d(e,r),c=0;c<r;++c)a[c].call(n,i,s,o)}(n,u,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=Array(i-1),o=1;o<i;o++)s[o-1]=arguments[o];!function(e,t,n,i){if(t)e.apply(n,i);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].apply(n,i)}(n,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 n,s,o,r,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(s=this._events))return this;if(!(n=s[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new i:(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(o=-1,r=n.length;0<r--;)if(n[r]===t||n[r].listener&&n[r].listener===t){a=n[r].listener,o=r;break}if(0>o)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new i,this;delete s[e]}else!function(e,t){for(var n=t,i=n+1,s=e.length;i<s;n+=1,i+=1)e[n]=e[i];e.pop()}(n,o);s.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new i,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new i:delete n[e]),this;if(0===arguments.length){for(var s,o=Object.keys(n),r=0;r<o.length;++r)"removeListener"!==(s=o[r])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if("function"==typeof(t=n[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,n,i=this._events;return i?n=(t=i[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[]:n=[],n},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,n=(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)}(n))throw TypeError("Stringified UUID is invalid");return n}function m(e,t,n){var i=(e=e||{}).random||(e.rng||h)();if(i[6]=64|15&i[6],i[8]=128|63&i[8],t){n=n||0;for(var s=0;16>s;++s)t[n+s]=i[s];return t}return f(i)}function b(e,t){if(!e||!t)return{};const n={...e};if(n.localCandidateId){const e=t.get(n.localCandidateId);n.local={...e}}if(n.remoteCandidateId){const e=t.get(n.remoteCandidateId);n.remote={...e}}return n}function y(e,t,n){return 8*function(e,t,n){const i=e[n],s=t?t[n]:null;return null===i||null===s?null:(i-s)/(e.timestamp-t.timestamp)*1e3}(e,t,n)}function w(e){if(!e.entries)return e;const t={};return e.forEach((function(e,n){t[n]=e})),t}function S(e,t,n={}){if(!e)return null;let i={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};n.remote&&(i.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const t of e.values())switch(t.type){case"outbound-rtp":{const n=t.mediaType||t.kind,s={};let o={};if(!["audio","video"].includes(n))continue;if(t.codecId){const n=e.get(t.codecId);n&&(s.clockRate=n.clockRate,s.mimeType=n.mimeType,s.payloadType=n.payloadType)}o=e.get(t.mediaSourceId)||e.get(t.trackId)||{},i[n].outbound.push({...t,...s,track:{...o}});break}case"inbound-rtp":{let n=t.mediaType||t.kind,s={};const o={};if(!["audio","video"].includes(n))if(t.id.includes("Video"))n="video";else{if(!t.id.includes("Audio"))continue;n="audio"}if(t.codecId){const n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}if(!i.connection.id&&t.transportId){const n=e.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=e.get(n.selectedCandidatePairId);i.connection=b(t,e)}}s=e.get(t.mediaSourceId)||e.get(t.trackId)||{},i[n].inbound.push({...t,...o,track:{...s}});break}case"peer-connection":i.connection.dataChannelsClosed=t.dataChannelsClosed,i.connection.dataChannelsOpened=t.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!n.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 n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}if(!i.connection.id&&t.transportId){const n=e.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=e.get(n.selectedCandidatePairId);i.connection=b(t,e)}}i.remote[s].inbound.push({...t,...o});break}case"remote-outbound-rtp":{if(!n.remote)break;const s=t.mediaType||t.kind,o={};if(!["audio","video"].includes(s))continue;if(t.codecId){const n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}i.remote[s].outbound.push({...t,...o});break}}if(!i.connection.id)for(const t of e.values())"candidate-pair"===t.type&&t.nominated&&"succeeded"===t.state&&(i.connection=b(t,e));return i=function(e,t){return t?(e.audio.inbound.map((e=>{let n=t.audio.inbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesReceived"),e.packetRate=y(e,n,"packetsReceived")})),e.audio.outbound.map((e=>{let n=t.audio.outbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesSent"),e.packetRate=y(e,n,"packetsSent")})),e.video.inbound.map((e=>{let n=t.video.inbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesReceived"),e.packetRate=y(e,n,"packetsReceived")})),e.video.outbound.map((e=>{let n=t.video.outbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesSent"),e.packetRate=y(e,n,"packetsSent")})),e):e}(i,t),i}let _,I={},E=[];t.WebRTCStats=class extends s{constructor(e){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],"undefined"==typeof window)throw new Error("WebRTCStats only works in browser");const t={...e};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=t.getStatsInterval||1e3,this.rawStats=!!t.rawStats,this.statsObject=!!t.statsObject,this.filteredStats=!!t.filteredStats,this.shouldWrapGetUserMedia=!!t.wrapGetUserMedia,"boolean"==typeof t.remote&&(this.remote=t.remote),this.debug=!!t.debug,this.logLevel=t.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(e,t){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:e,pc:t})}async addConnection(e){const{pc:t,peerId:n}=e;let{connectionId:i,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(!n)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[n]){if(i&&i in this.peersToMonitor[n])throw new Error(`We are already monitoring connection with id ${i}.`);for(let e in this.peersToMonitor[n]){const i=this.peersToMonitor[n][e];if(i.pc===t)throw new Error(`We are already monitoring peer with id ${n}.`);"closed"===i.pc.connectionState&&this.removeConnection({pc:i.pc})}}const o=t.getConfiguration();return o.iceServers&&o.iceServers.forEach((function(e){delete e.credential})),i||(i=m()),this.emitEvent({event:"addConnection",tag:"peer",peerId:n,connectionId:i,data:{options:e,peerConfiguration:o}}),this.monitorPeer({peerId:n,connectionId:i,pc:t,remote:s}),{connectionId:i}}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:n,pc:i}=e;if(!i&&!n)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(n){if("string"!=typeof n)throw new Error("connectionId must be a string.");for(let e in this.peersToMonitor)n in this.peersToMonitor[e]&&(i=this.peersToMonitor[e][n].pc,t=e)}else if(i){if(!(i 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===i&&(n=s,t=e)}if(!i||!n)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(n,i),delete this.peersToMonitor[t][n],0===Object.values(this.peersToMonitor[t]).length&&delete this.peersToMonitor[t],{connectionId:n}}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 n=this.peersToMonitor[e][t].pc;this.removePeerConnectionEventListeners(t,n)}delete this.peersToMonitor[e]}}destroy(){this.removeAllPeers(),E.forEach((e=>{this.removeTrackEventListeners(e)})),E=[],this.shouldWrapGetUserMedia&&_&&(navigator.mediaDevices.getUserMedia=_)}monitorPeer(e){let{peerId:t,connectionId:n,pc:i,remote:s}=e;if(!i)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const o={pc:i,connectionId:n,stream:null,stats:{parsed:null,raw:null},options:{remote:s}};if(this.peersToMonitor[t]){if(n in this.peersToMonitor[t])return void this.logger.warn(`Already watching connection with ID ${n}`);this.peersToMonitor[t][n]=o}else this.peersToMonitor[t]={[n]:o};this.addPeerConnectionEventListeners(t,n,i),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 n=[];for(const e in t)for(const i in t[e]){const s=t[e][i],o=s.pc;if(o&&!this.checkIfConnectionIsClosed(e,i,o))try{const t=this.getTimestamp(),r=o.getStats(null);if(r){const o=await r,a=this.getTimestamp(),c=w(o),d={remote:s.options.remote},l=S(o,s.stats.parsed,d),u={event:"stats",tag:"stats",peerId:e,connectionId:i,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)),n.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 n}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const e in this.peersToMonitor)for(const t in this.peersToMonitor[e]){const n=this.peersToMonitor[e][t].pc;this.checkIfConnectionIsClosed(e,t,n)}}),this.connectionMonitoringInterval)}checkIfConnectionIsClosed(e,t,n){const i=this.isConnectionClosed(n);if(i){this.removeConnection({pc:n});let i="closed"===n.connectionState?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:i,peerId:e,connectionId:t,tag:"connection",data:"closed"})}return i}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."),_=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const e=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=function(){return e({constraints:arguments[0]}),_.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 n=t[e];this.statsToMonitor.includes(n.type)||delete t[e]}return t}get peerConnectionListeners(){return{icecandidate:(e,t,n,i)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",i),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:e,connectionId:t,data:i.candidate})},track:(e,t,n,i)=>{this.logger.debug(`[pc-event] track | peerId: ${e}`,i);const s=i.track,o=i.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:i.track.kind+":"+i.track.id+" "+i.streams.map((function(e){return"stream:"+e.id}))}})},signalingstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${e}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:e,connectionId:t,data:{signalingState:n.signalingState,localDescription:n.localDescription,remoteDescription:n.remoteDescription}})},iceconnectionstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${e}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:n.iceConnectionState})},icegatheringstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${e}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:e,connectionId:t,data:n.iceGatheringState})},icecandidateerror:(e,t,n,i)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${e}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:e,connectionId:t,error:{errorCode:i.errorCode}})},connectionstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${e}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:n.connectionState})},negotiationneeded:(e,t,n)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${e}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:e,connectionId:t})},datachannel:(e,t,n,i)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${e}`,i),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:e,connectionId:t,data:i.channel})}}}addPeerConnectionEventListeners(e,t,n){this.logger.debug(`Adding event listeners for peer ${e} and connection ${t}.`),I[t]={},Object.keys(this.peerConnectionListeners).forEach((i=>{I[t][i]=this.peerConnectionListeners[i].bind(this,e,t,n),n.addEventListener(i,I[t][i],!1)}))}parseGetUserMedia(e){try{const t={event:"getUserMedia",tag:"getUserMedia",data:{...e}};e.stream&&(t.data.details=this.parseStream(e.stream),e.stream.getTracks().map((e=>{this.addTrackEventListeners(e),E.push(e)}))),this.emitEvent(t)}catch(e){}}parseStream(e){const t={audio:[],video:[]};return e.getTracks().forEach((e=>{t[e.kind].push(this.getMediaTrackDetails(e))})),t}getMediaTrackDetails(e){return{enabled:e.enabled,id:e.id,contentHint:e.contentHint,kind:e.kind,label:e.label,muted:e.muted,readyState:e.readyState,constructorName:e.constructor.name,capabilities:e.getCapabilities?e.getCapabilities():{},constraints:e.getConstraints?e.getConstraints():{},settings:e.getSettings?e.getSettings():{},_track:e}}getStreamDetails(e){return{active:e.active,id:e.id,_stream:e}}getTrackEventObject(e){return{mute:t=>{this.emitEvent({event:"mute",tag:"track",connectionId:e,data:{event:t}})},unmute:t=>{this.emitEvent({event:"unmute",tag:"track",connectionId:e,data:{event:t}})},overconstrained:t=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:e,data:{event:t}})},ended:t=>{this.emitEvent({event:"ended",tag:"track",connectionId:e,data:{event:t}}),this.removeTrackEventListeners(t.target)}}}addTrackEventListeners(e,t){I[e.id]={};const n=this.getTrackEventObject(t);Object.keys(n).forEach((t=>{I[e.id][t]=n[t].bind(this),e.addEventListener(t,I[e.id][t])})),I[e.id].readyState=setInterval((()=>{if("ended"===e.readyState){let t=new CustomEvent("ended",{detail:{check:"readyState"}});e.dispatchEvent(t)}}),1e3)}removeTrackEventListeners(e){if(e.id in I){const t=this.getTrackEventObject();Object.keys(t).forEach((t=>{e.removeEventListener(t,I[e.id][t])})),clearInterval(I[e.id].readyState),delete I[e.id]}}addToTimeline(e){this.timeline.push(e),this.emit("timeline",e)}emitEvent(e){const t={...e,timestamp:new Date};this.addToTimeline(t),t.tag&&this.emit(t.tag,t)}set getStatsInterval(e){if(!Number.isInteger(e))throw new Error(`getStatsInterval should be an integer, got: ${e}`);this._getStatsInterval=e,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(e,t){e in I&&(Object.keys(this.peerConnectionListeners).forEach((n=>{t.removeEventListener(n,I[e][n],!1)})),delete I[e]),t.getSenders().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)})),t.getReceivers().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)}))}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const e=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const t=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),n=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=n.bind(navigator.mediaDevices)}}}}));(et=tt)&&et.__esModule&&Object.prototype.hasOwnProperty.call(et,"default")&&et.default;var nt=tt.WebRTCStats;class it extends se{constructor(e){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1})}}class st extends se{constructor(e){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1})}}class ot extends se{constructor(e,t){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:t})}}class rt{constructor(t,i,s){this.type=t,this.options=i,this.onSdpReadyTwice=null,this._negotiating=!1,this.handleConnectionStateChange=e=>n(this,void 0,void 0,(function*(){const{connectionState:e}=this.instance;if(console.log(`[${(new Date).toISOString()}] Connection State`,e),"failed"===e||"disconnected"===e){const e=()=>{this.instance.restartIce(),this._session._closeConnection(),this._session.connect(),window.removeEventListener("online",e)};if(navigator.onLine)return e();window.addEventListener("online",e)}})),this._handleIceConnectionStateChange=e=>{console.log(`[${(new Date).toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=e=>{console.log(`[${(new Date).toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setAudioCodec=e=>{if(this.options.preferred_codecs&&0!==this.options.preferred_codecs.length)return e.setCodecPreferences?e.setCodecPreferences(this.options.preferred_codecs):void 0},this._onDebugReportMessage=t=>n(this,void 0,void 0,(function*(){this.options.debug&&("stats"===t.event&&j(e.SwEvent.StatsFrame,function({data:e}){var t,n,i,s,o,r,a,c;const{audio:d,remote:l}=e,{audio:u}=l,h=null!==(n=null===(t=u.inbound[0])||void 0===t?void 0:t.jitter)&&void 0!==n?n:1/0,p=null!==(s=null===(i=u.inbound[0])||void 0===i?void 0:i.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=Xe({jitter:1e3*h,rtt:1e3*p,packetsLost:v,packetsReceived:g});return{jitter:h,rtt:p,mos:f,quality:Ze(f),inboundAudio:d.inbound[0],outboundAudio:d.outbound[0],remoteInboundAudio:u.inbound[0],remoteOutboundAudio:u.outbound[0]}}(t),this._session.uuid),yield this._session.execute(this._webrtcStatsReporter.reportDataMessage(t)))})),h.info("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._sdpReady=this._sdpReady.bind(this),this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this._session=s,this._init()}get isOffer(){return this.type===V.Offer}get isAnswer(){return this.type===V.Answer}startNegotiation(){this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}startDebugger(){return n(this,void 0,void 0,(function*(){this.options.debug&&(this._webrtcStatsReporter=function(){const e=c(),t=new nt({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,wrapGetUserMedia:!0,debug:!1,logLevel:"warn"});return{reportDataMessage:t=>new ot(e,t),start:()=>new it(e),stop:()=>new st(e),reportId:e,debuggerInstance:t}}(),yield this._session.execute(this._webrtcStatsReporter.start()),this._webrtcStatsReporter.debuggerInstance.on("timeline",this._onDebugReportMessage),yield new Promise((e=>setTimeout(e,500))),this._webrtcStatsReporter.debuggerInstance.addConnection({pc:this.instance,peerId:this.options.id,connectionId:this.options.telnyxSessionId}))}))}stopDebugger(){this.options.debug&&(j(e.SwEvent.StatsReport,this._webrtcStatsReporter.debuggerInstance.getTimeline()),this._session.execute(this._webrtcStatsReporter.stop()),this._webrtcStatsReporter.debuggerInstance.destroy())}_logTransceivers(){h.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach(((e,t)=>{h.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),h.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))}handleSignalingStateChangeEvent(e){switch(h.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":this.instance=null;break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){h.info("Negotiation needed event"),"stable"===this.instance.signalingState&&this.startNegotiation()}handleTrackEvent(e){const{streams:[t]}=e,{remoteElement:n,screenShare:i}=this.options;let{remoteStream:s}=this.options;s=t,!1===i&&he(n,s)}createPeerConnection(){return n(this,void 0,void 0,(function*(){var t;this.instance=(t=this._config(),new window.RTCPeerConnection(t)),yield this.startDebugger(),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.options.localStream=yield this._retrieveLocalStream().catch((t=>(j(e.SwEvent.MediaError,t,this.options.id),null)))}))}_init(){return n(this,void 0,void 0,(function*(){yield this.createPeerConnection();const{localElement:e,localStream:t=null,screenShare:n=!1}=this.options;if(ue(t)){const i=t.getAudioTracks();h.info("Local audio tracks: ",i);const s=t.getVideoTracks();if(h.info("Local video tracks: ",s),this.isOffer&&"function"==typeof this.instance.addTransceiver){const e={direction:"sendrecv",streams:[t]};i.forEach((t=>{this.options.userVariables.microphoneLabel=t.label;const n=this.instance.addTransceiver(t,e);this._setAudioCodec(n)})),console.debug("Applying video transceiverParams",e),s.forEach((t=>{this.options.userVariables.cameraLabel=t.label,this.instance.addTransceiver(t,e)}))}else"function"==typeof this.instance.addTrack?(i.forEach((e=>{this.options.userVariables.microphoneLabel=e.label,this.instance.addTrack(e,t)})),this.instance.getTransceivers().forEach((e=>this._setAudioCodec(e))),s.forEach((e=>{this.options.userVariables.cameraLabel=e.label,this.instance.addTrack(e,t)}))):this.instance.addStream(t);!1===n&&((e=>{const t=I(e);t&&(t.muted=!0)})(e),he(e,t))}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this.startNegotiation(),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);h.info("Add transceiver",e,t)}}_createOffer(){this._isOffer()&&(this._constraints.offerToReceiveAudio=Boolean(this.options.audio),this._constraints.offerToReceiveVideo=Boolean(this.options.video),h.info("_createOffer - this._constraints",this._constraints),this.instance.createOffer(this._constraints).then(this._setLocalDescription.bind(this)).then(this._sdpReady).catch((e=>h.error("Peer _createOffer error:",e))))}_setRemoteDescription(e){this.options.useStereo&&(e.sdp=_e(e.sdp)),this.instance.localDescription&&(e.sdp=Ce(e.sdp,this.instance.localDescription.sdp));const t=e;return h.info("REMOTE SDP \n",`Type: ${e.type}`,"\n\n",e.sdp),this.instance.setRemoteDescription(t)}_createAnswer(){return n(this,void 0,void 0,(function*(){if(!this._isAnswer())return;if("stable"!==this.instance.signalingState)return console.log(" - But the signaling state isn't stable, so triggering rollback"),void(yield Promise.all([this.instance.setLocalDescription({type:"rollback"}),this.instance.setRemoteDescription({sdp:this.options.remoteSdp,type:V.Offer})]));yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:V.Offer}),this._logTransceivers();const e=yield this.instance.createAnswer();yield this._setLocalDescription(e)}))}_setLocalDescription(e){const{useStereo:t,googleMaxBitrate:n,googleMinBitrate:i,googleStartBitrate:s,mediaSettings:o}=this.options;return t&&(e.sdp=_e(e.sdp)),n&&i&&s&&(e.sdp=((e,t,n,i)=>{const s=e.split("\r\n");return s.forEach(((e,o)=>{/^a=fmtp:\d*/.test(e)?s[o]+=`;x-google-max-bitrate=${t};x-google-min-bitrate=${n};x-google-start-bitrate=${i}`:/^a=mid:(1|video)/.test(e)&&(s[o]+=`\r\nb=AS:${t}`)})),s.join("\r\n")})(e.sdp,n,i,s)),o&&o.useSdpASBandwidthKbps&&null!==o.sdpASBandwidthKbps&&(e.sdp=((e,t)=>{let n="AS",i=t;!navigator.userAgent.match(/firefox/gim)||navigator.userAgent.match(/OPR\/[0-9]{2}/gi)||navigator.userAgent.match(/edg/gim)||(n="TIAS",i=1e3*(t>>>0));return-1===e.indexOf("b="+n+":")?e.replace(/c=IN (.*)\r\n/,"c=IN $1\r\nb="+n+":"+i+"\r\n"):e.replace(new RegExp("b="+n+":.*\r\n"),"b="+n+":"+i+"\r\n")})(e.sdp,o.sdpASBandwidthKbps)),this.instance.setLocalDescription(e)}_sdpReady(){_(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return n(this,void 0,void 0,(function*(){if(ue(this.options.localStream))return this.options.localStream;const e=yield(t=this.options,n(void 0,void 0,void 0,(function*(){let{audio:e=!0,micId:n}=t;const{micLabel:i=""}=t;n&&(n=yield ye(n,i,J.AudioIn).catch((e=>null)),n&&("boolean"==typeof e&&(e={}),e.deviceId={exact:n}));let{camId:s}=t,o=t.video;const{camLabel:r=""}=t;return s&&(s=yield ye(s,r,J.Video).catch((e=>null)),s&&("boolean"==typeof o&&(o={}),o.deviceId={exact:s})),{audio:e,video:o}})));var t;return fe(e)}))}_isOffer(){return this.type===V.Offer}_isAnswer(){return this.type===V.Answer}_config(){const{iceServers:e=[],prefetchIceCandidates:t,forceRelayCandidate:n}=this.options,i={bundlePolicy:"max-compat",iceCandidatePoolSize:t?10:0,iceServers:e,iceTransportPolicy:n?"relay":"all"};return h.info("RTC config",i),i}close(){if(this.options.debug){if("file"===this.options.debugOutput){!function(e,t){const n=new Blob([JSON.stringify(e)],{type:"application/json"}),i=URL.createObjectURL(n),s=document.createElement("a");s.href=i,s.download=`${t}.json`,s.click(),URL.revokeObjectURL(i)}(this._webrtcStatsReporter.debuggerInstance.getTimeline(),this.options.telnyxSessionId)}this.stopDebugger()}}}const at=je;class ct{constructor(e,t){this.session=e,this.id="",this.state=W[W.New],this.prevState="",this.channels=[],this.role=q.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._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(var n in t.constraints)if(t.constraints.hasOwnProperty(n)&&t.constraints[n]!==e[n])return;t.callback(e)}}))}))}))};const{iceServers:n,speaker:i,micId:s,micLabel:o,camId:r,camLabel:a,localElement:c,remoteElement:d,mediaConstraints:{audio:l,video:u},ringtoneFile:h,ringbackFile:p}=e;this.options=Object.assign({},H,{audio:l,video:u,iceServers:n,localElement:c,remoteElement:d,micId:s,micLabel:o,camId:r,camLabel:a,speakerId:i,ringtoneFile:h,ringbackFile:p},t),this._onMediaError=this._onMediaError.bind(this),this._init(),this.options&&(this._ringtone=Ne(this.options.ringtoneFile,"_ringtone"),this._ringback=Ne(this.options.ringbackFile,"_ringback"))}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}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}`}invite(){this.direction=G.Outbound,this.peer=new rt(V.Offer,this.options,this.session),this._registerPeerEvents()}answer(e={}){var t,n,i,s;this.stopRingtone(),this.options.video=null!==(n=null!==(t=e.video)&&void 0!==t?t:this.options.video)&&void 0!==n&&n,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})),(null===(s=e.preferred_codecs)||void 0===s?void 0:s.length)>0&&(this.options.preferred_codecs=e.preferred_codecs),this.peer=new rt(V.Answer,this.options,this.session),this._registerPeerEvents()}playRingtone(){Oe(this._ringtone)}stopRingtone(){Pe(this._ringtone)}playRingback(){Oe(this._ringback)}stopRingback(){Pe(this._ringback)}hangup(t,n){var i,s,o;let r=t||{},a=!1!==n;this.cause=r.cause||"NORMAL_CLEARING",this.causeCode=r.causeCode||16,this.sipCode=r.sipCode||null,this.sipReason=r.sipReason||null,this.sipCallId=r.sip_call_id||null,this.options.customHeaders=[...null!==(i=this.options.customHeaders)&&void 0!==i?i:[],...null!==(o=null===(s=null==r?void 0:r.dialogParams)||void 0===s?void 0:s.customHeaders)&&void 0!==o?o:[]],this.setState(W.Hangup);const c=()=>{var e;return null===(e=this.peer)||void 0===e||e.close(),this.setState(W.Destroy)};if(this.stopRingtone(),this.stopRingback(),a){const t=new He({sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(t).catch((t=>{h.error("telnyx_rtc.bye failed!",t),j(e.SwEvent.Error,{error:t,sessionId:this.session.sessionid},this.session.uuid)})).then(c.bind(this))}else c()}hold(){const e=new We({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 We({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 We({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 qe({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(t)}message(e,t){const n={from:this.session.options.login,to:e,body:t},i=new qe({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(i)}muteAudio(){Me(this.options.localStream)}unmuteAudio(){xe(this.options.localStream)}toggleAudioMute(){Le(this.options.localStream)}setAudioInDevice(e){return n(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 le({audio:{deviceId:{exact:e}}}),i=t.getAudioTracks()[0];n.replaceTrack(i),this.options.micId=e;const{localStream:s}=this.options;s.getAudioTracks().forEach((e=>e.stop())),s.getVideoTracks().forEach((e=>t.addTrack(e))),this.options.localStream=t}}))}muteVideo(){var e;e=this.options.localStream,Re(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Re(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Re(e,"video",null)}setVideoDevice(e){return n(this,void 0,void 0,(function*(){const{instance:t}=this.peer,n=t.getSenders().find((({track:{kind:e}})=>"video"===e));if(n){const t=yield le({video:{deviceId:{exact:e}}}),i=t.getVideoTracks()[0];n.replaceTrack(i);const{localElement:s,localStream:o}=this.options;he(s,t),this.options.camId=e,o.getAudioTracks().forEach((e=>t.addTrack(e))),o.getVideoTracks().forEach((e=>e.stop())),this.options.localStream=t}}))}deaf(){Me(this.options.remoteStream)}undeaf(){xe(this.options.remoteStream)}toggleDeaf(){Le(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,t){return n(this,void 0,void 0,(function*(){if(!this||!this.peer)return void h.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:n}=this.peer,i=n.getSenders();if(!i)return void h.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=i.find((({track:{kind:e}})=>e===t));if(s){const n=s.getParameters();n.encodings||(n.encodings=[{rid:"h"}]),h.info("Parameters: ",n),h.info("Setting max ","audio"===t?"audio":"video"," bandwidth to: ",e," [bps]"),n.encodings[0].maxBitrate=e,yield s.setParameters(n).then((()=>{h.info("audio"===t?"New audio":"New video"," bandwidth settings in use: ",s.getParameters())})).catch((e=>console.error(e)))}else h.error("Could not set bandwidth (reason: no "+t+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")}))}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,t){if(!e)return;const n={callback:e,constraints:t};if(this._statsBindings.push(n),!this._statsIntervalId){const e=2e3;this._startStats(e)}}setState(e){switch(this._prevState=this._state,this._state=e,this.state=W[this._state].toLowerCase(),this.prevState=W[this._prevState].toLowerCase(),h.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:F.callUpdate,call:this}),e){case W.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case W.Active:setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&pe(e,t)}),0);break;case W.Destroy:this._finalize()}}handleMessage(t){const{method:n,params:i}=t;switch(n){case B.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 B.Media:if(this._state>=W.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case B.Display:case B.Attach:{const{display_name:t,display_number:s,display_direction:o}=i;this.extension=s;const r=o===G.Inbound?G.Outbound:G.Inbound,a={type:F[n],call:this,displayName:t,displayNumber:s,displayDirection:r};j(e.SwEvent.Notification,a,this.id)||j(e.SwEvent.Notification,a,this.session.uuid);break}case B.Info:case B.Event:{const t=Object.assign(Object.assign({},i),{type:F.generic,call:this});j(e.SwEvent.Notification,t,this.id)||j(e.SwEvent.Notification,t,this.session.uuid);break}case B.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 B.Bye:const t=i.client_state||i.clientState;t&&(this.options.clientState=t),this.stopRingback(),this.stopRingtone(),this.hangup(i,!1)}}handleConferenceUpdate(e,t){return n(this,void 0,void 0,(function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==t.laName)return h.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:n,data:i,hashKey:s=String(this._lastSerno),arrIndex:o}=e;switch(n){case"bootObj":{this._lastSerno=0;const{chatChannel:e,infoChannel:n,modChannel:s,laName:o,conferenceMemberID:r,role:a}=t;this._dispatchConferenceUpdate({action:K.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),n&&(yield this._subscribeConferenceInfo(n)),s&&a===q.Moderator&&(yield this._subscribeConferenceModerator(s));const c=[];for(const e in i)c.push(Object.assign({callId:i[e][0],index:Number(e)},w(i[e][1])));this._dispatchConferenceUpdate({action:K.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:K.Add,callId:s,index:o},w(i)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:K.Modify,callId:s,index:o},w(i)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:K.Delete,callId:s,index:o},w(i)));break;case"clear":this._dispatchConferenceUpdate({action:K.Clear});break;default:this._dispatchConferenceUpdate({action:n,data:i,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 n(this,void 0,void 0,(function*(){const t={nodeId:this.nodeId,channels:[e],handler:e=>{const{direction:t,from:n,fromDisplay:i,message:s,type:o}=e.data;this._dispatchConferenceUpdate({action:K.ChatMessage,direction:t,participantNumber:n,participantName:i,messageText:s,messageType:o,messageId:e.eventSerno})}},n=yield this.session.vertoSubscribe(t).catch((e=>{h.error("ConfChat subscription error:",e)}));ke(n,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(t,n)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:t,type:n}})}}}))}))}_subscribeConferenceInfo(e){return n(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,Ye(this.session,t);else h.error("Conference-Info unknown contentType",e)}},n=yield this.session.vertoSubscribe(t).catch((e=>{h.error("ConfInfo subscription error:",e)}));ke(n,e)&&this._addChannel(e)}))}_confControl(e,t={}){const n=Object.assign({application:"conf-control",callID:this.id,value:null},t);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:n})}_subscribeConferenceModerator(e){return n(this,void 0,void 0,(function*(){const t=(t,n=null,i=null)=>{const s=parseInt(n)||null;this._confControl(e,{command:t,id:s,value:i})},n=()=>{const{video:e}=this.options;if("boolean"==typeof e&&!e||"object"==typeof e&&y(e))throw`Conference ${this.id} has no video!`},i={nodeId:this.nodeId,channels:[e],handler:e=>{const{data:t}=e;if("list-videoLayouts"===t["conf-command"]){if(t.responseData){const e=JSON.stringify(t.responseData).replace(/IDS"/g,'Ids"');this._dispatchConferenceUpdate({action:K.LayoutList,layouts:JSON.parse(e)})}}else this._dispatchConferenceUpdate({action:K.ModCmdResponse,command:t["conf-command"],response:t.response})}},s=yield this.session.vertoSubscribe(i).catch((e=>{h.error("ConfMod subscription error:",e)}));ke(s,e)&&(this.role=q.Moderator,this._addChannel(e),Object.defineProperties(this,{listVideoLayouts:{configurable:!0,value:()=>{t("list-videoLayouts")}},playMedia:{configurable:!0,value:e=>{t("play",null,e)}},stopMedia:{configurable:!0,value:()=>{t("stop",null,"all")}},deaf:{configurable:!0,value:e=>{t("deaf",e)}},undeaf:{configurable:!0,value:e=>{t("undeaf",e)}},startRecord:{configurable:!0,value:e=>{t("recording",null,["start",e])}},stopRecord:{configurable:!0,value:()=>{t("recording",null,["stop","all"])}},snapshot:{configurable:!0,value:e=>{n(),t("vid-write-png",null,e)}},setVideoLayout:{configurable:!0,value:(e,i)=>{n();t("vid-layout",null,i?[e,i]:e)}},kick:{configurable:!0,value:e=>{t("kick",e)}},muteMic:{configurable:!0,value:e=>{t("tmute",e)}},muteVideo:{configurable:!0,value:e=>{n(),t("tvmute",e)}},presenter:{configurable:!0,value:e=>{n(),t("vid-res-id",e,"presenter")}},videoFloor:{configurable:!0,value:e=>{n(),t("vid-floor",e,"force")}},banner:{configurable:!0,value:(e,i)=>{n(),t("vid-banner",e,encodeURI(i))}},volumeDown:{configurable:!0,value:e=>{t("volume_out",e,"down")}},volumeUp:{configurable:!0,value:e=>{t("volume_out",e,"up")}},gainDown:{configurable:!0,value:e=>{t("volume_in",e,"down")}},gainUp:{configurable:!0,value:e=>{t("volume_in",e,"up")}},transfer:{configurable:!0,value:(e,n)=>{t("transfer",e,n)}}}))}))}_handleChangeHoldStateSuccess(e){return"active"===e.holdState?this.setState(W.Active):this.setState(W.Held),!0}_handleChangeHoldStateError(e){return h.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){let t=Ce(e,this.peer.instance.localDescription.sdp);this.options.useStereo&&(t=_e(t));const n={sdp:t,type:V.Answer};this.peer.instance.setRemoteDescription(n).then((()=>{this.gotEarly&&this.setState(W.Early),this.gotAnswer&&this.setState(W.Active)})).catch((e=>{h.error("Call setRemoteDescription Error: ",e),this.hangup()}))}_requestAnotherLocalDescription(){_(this.peer.onSdpReadyTwice)?j(e.SwEvent.Error,{error:new Error("SDP without candidates for the second time!"),sessionId:this.session.sessionid},this.session.uuid):(Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this._iceDone=!1,this.peer.startNegotiation())}_onIceSdp(e){var t,n;this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:i,type:s}=e;if(-1===i.indexOf("candidate"))return h.info("No candidate - retry \n"),void this._requestAnotherLocalDescription();null===(n=null===(t=this.peer)||void 0===t?void 0:t.instance)||void 0===n||n.removeEventListener("icecandidate",this._onIce);let o=null;const r={sessid:this.session.sessionid,sdp:i,dialogParams:this.options,"User-Agent":`Web-${at}`};switch(s){case V.Offer:this.setState(W.Requesting),o=new Ge(r);break;case V.Answer:this.setState(W.Answering),o=!0===this.options.attach?new Fe(r):new Be(r);break;default:return h.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}this._execute(o).then((e=>{const{node_id:t=null}=e;this._targetNodeId=t,s===V.Offer?this.setState(W.Trying):this.setState(W.Active)})).catch((e=>{h.error(`${this.id} - Sending ${s} error:`,e),this.hangup()})),console.timeEnd(g)}_onIce(e){const{instance:t}=this.peer;null===this._iceTimeout&&(this._iceTimeout=setTimeout((()=>this._onIceSdp(t.localDescription)),1e3)),e.candidate?h.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(t.localDescription)}_registerPeerEvents(){const{instance:e}=this.peer;this._iceDone=!1,e.onicecandidate=e=>{this._iceDone||this._onIce(e)},e.addEventListener("addstream",(e=>{this.options.remoteStream=e.stream})),e.addEventListener("track",(e=>{this.options.remoteStream=e.streams[0];const{remoteElement:t,remoteStream:n,screenShare:i}=this.options;!1===i&&he(t,n)}))}_onMediaError(e){this._dispatchNotification({type:F.userMediaError,error:e}),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:F.conferenceUpdate,call:this},e))}_dispatchNotification(t){!0!==this.options.screenShare&&(j(e.SwEvent.Notification,t,this.id,!1)||j(e.SwEvent.Notification,t,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){const{id:t,userVariables:n,remoteCallerNumber:i,onNotification:s}=this.options;t||(this.options.id=c()),this.id=this.options.id,n&&!y(n)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,O(e.SwEvent.MediaError,this._onMediaError,this.id),_(s)&&O(e.SwEvent.Notification,s.bind(this),this.id),this.setState(W.New),h.info("New Call with Options:",this.options)}_finalize(){this._stopStats(),this.peer&&this.peer.instance&&(this.peer.instance.close(),this.peer=null);const{remoteStream:t,localStream:n}=this.options;ve(t),ve(n),U(e.SwEvent.MediaError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),h.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),h.info("Stats stopped")}}ct.setStateTelnyx=e=>{if(e){switch(e._state){case W.Requesting:case W.Recovering: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 dt extends ct{constructor(){super(...arguments),this._statsInterval=null}hangup(e={},t=!0){this.screenShare instanceof dt&&this.screenShare.hangup(e,t),super.hangup(e,t)}startScreenShare(e){return n(this,void 0,void 0,(function*(){const t=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;t.getTracks().forEach((e=>{e.addEventListener("ended",(()=>{this.screenShare&&this.screenShare.hangup()}))}));const{remoteCallerName:i,remoteCallerNumber:s,callerName:o,callerNumber:r}=this.options,a=Object.assign({screenShare:!0,localStream:t,destinationNumber:`${this.extension}-screen`,remoteCallerName:i,remoteCallerNumber:`${s}-screen`,callerName:`${o} (Screen)`,callerNumber:`${r} (Screen)`},e);return this.screenShare=new dt(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof dt&&this.screenShare.hangup()}setAudioOutDevice(e){return n(this,void 0,void 0,(function*(){this.options.speakerId=e;const{remoteElement:t,speakerId:n}=this.options;return!(!t||!n)&&pe(t,n)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);h.setLevel(2),this._statsInterval=window.setInterval((()=>n(this,void 0,void 0,(function*(){const e=yield this.peer.instance.getStats(null);let t="";const n=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],i=["id","type","timestamp"];e.forEach((e=>{n.includes(e.type)||(t+=`\n${e.type}\n`,Object.keys(e).forEach((n=>{i.includes(n)||(t+=`\t${n}: ${e[n]}\n`)})))})),h.info(t)}))),2e3)}}class lt 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._videoConstraints=!1,this._speaker=null,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile}get reconnectDelay(){return 1e3}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return n(this,void 0,void 0,(function*(){e.connect.call(this)}))}checkPermissions(e=!0,t=!0){return n(this,void 0,void 0,(function*(){try{const n=yield fe({audio:e,video:t});return ve(n),!0}catch(e){return!1}}))}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return n(this,void 0,void 0,(function*(){Object.keys(this.calls).forEach((e=>this.calls[e].setState(W.Purge))),this.calls={},yield e.disconnect.call(this)}))}speedTest(t){return new Promise(((n,i)=>{if(P(e.SwEvent.SpeedTest,(e=>{const{upDur:i,downDur:s}=e,o=s?8*t/(s/1e3)/1024:0;n({upDur:i,downDur:s,upKps:(i?8*t/(i/1e3)/1024:0).toFixed(0),downKps:o.toFixed(0)})}),this.uuid),!(t=Number(t)))return i(`Invalid parameter 'bytes': ${t}`);this.executeRaw(`#SPU ${t}`);let s=t/1024;t%1024&&s++;const o=".".repeat(1024);for(let e=0;e<s;e++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")}))}getDevices(){return me().catch((t=>(j(e.SwEvent.MediaError,t,this.uuid),[])))}getVideoDevices(){return me(J.Video).catch((t=>(j(e.SwEvent.MediaError,t,this.uuid),[])))}getAudioInDevices(){return me(J.AudioIn).catch((t=>(j(e.SwEvent.MediaError,t,this.uuid),[])))}getAudioOutDevices(){return me(J.AudioOut).catch((t=>(console.error("getAudioOutDevices",t),j(e.SwEvent.MediaError,t,this.uuid),[])))}validateDeviceId(e,t,n){return ye(e,t,n)}getDeviceResolutions(e){return n(this,void 0,void 0,(function*(){try{return yield(e=>n(void 0,void 0,void 0,(function*(){const t=[],n=yield fe({video:{deviceId:{exact:e}}}),i=n.getVideoTracks()[0];for(let e=0;e<be.length;e++){const[n,s]=be[e];(yield i.applyConstraints({width:{exact:n},height:{exact:s}}).then((()=>!0)).catch((()=>!1)))&&t.push({resolution:`${n}x${s}`,width:n,height:s})}return ve(n),t})))(e)}catch(e){throw e}}))}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return n(this,void 0,void 0,(function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=e,s=t(e,["micId","micLabel"]);return we(s),this._audioConstraints=yield Se(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints}))}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}setVideoSettings(e){return n(this,void 0,void 0,(function*(){if(!e)throw new Error("You need to provide the settings object");const{camId:n,camLabel:i}=e,s=t(e,["camId","camLabel"]);return we(s),this._videoConstraints=yield Se(n,i,"videoinput",s),this.camId=n,this.camLabel=i,this._videoConstraints}))}disableWebcam(){this._videoConstraints=!1}enableWebcam(){this._videoConstraints=!0}set iceServers(e){const t={urls:["stun:stun.l.google.com:19302"]};this._iceServers="boolean"==typeof e?e?[t]:[]:e||[m,f,t]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=I(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=I(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:t="",data:n}){if(!t)throw new Error(`Invalid channel for broadcast: ${t}`);const i=new Ke({sessid:this.sessionid,eventChannel:t,data:n});e&&(i.targetNodeId=e),this.execute(i).catch((e=>e))}vertoSubscribe({nodeId:e,channels:t=[],handler:i}){return n(this,void 0,void 0,(function*(){if(!(t=t.filter((e=>e&&!this._existsSubscription(this.relayProtocol,e)))).length)return{};const n=new Je({sessid:this.sessionid,eventChannel:t});e&&(n.targetNodeId=e);const s=yield this.execute(n),{unauthorized:o=[],subscribed:r=[]}=Te(s);return o.length&&o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),r.forEach((e=>this._addSubscription(this.relayProtocol,i,e))),s}))}vertoUnsubscribe({nodeId:e,channels:t=[]}){return n(this,void 0,void 0,(function*(){if(!(t=t.filter((e=>e&&this._existsSubscription(this.relayProtocol,e)))).length)return{};const n=new ze({sessid:this.sessionid,eventChannel:t});e&&(n.targetNodeId=e);const i=yield this.execute(n),{unsubscribed:s=[],notSubscribed:o=[]}=Te(i);return s.forEach((e=>this._removeSubscription(this.relayProtocol,e))),o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),i}))}static telnyxStateCall(e){return dt.setStateTelnyx(e)}}class ut{constructor(e,t){this.code=t,this.message=e}}class ht extends re{constructor(){super(),this.method=B.Ping;this.buildRequest({method:this.method,params:{}})}}class pt{constructor(e){this.session=e}_ack(e,t){const n=new Ve(e,t);this.nodeId&&(n.targetNodeId=this.nodeId),this.session.execute(n)}reconnectDelay(){return 1e3*k(2,6)}handleMessage(t){const{session:n}=this,{id:i,method:s,params:o={}}=t,r=null==o?void 0:o.callID,a=null==o?void 0:o.eventChannel,c=null==o?void 0:o.eventType,d=s===B.Attach;if("channelPvtData"===c)return this._handlePvtEvent(o.pvtData);if(r&&n.calls.hasOwnProperty(r)){if(!d)return n.calls[r].handleMessage(t),void this._ack(i,s);n.calls[r].hangup({},!1)}const l=()=>{var e,t,i,s;const a={id:r,remoteSdp:o.sdp,destinationNumber:o.callee_id_number,remoteCallerName:o.caller_id_name,remoteCallerNumber:o.caller_id_number,callerName:o.callee_id_name,callerNumber:o.callee_id_number,attach:d,mediaSettings:o.mediaSettings,debug:null!==(e=n.options.debug)&&void 0!==e&&e,debugOutput:null!==(t=n.options.debugOutput)&&void 0!==t?t:"socket",prefetchIceCandidates:null!==(i=n.options.prefetchIceCandidates)&&void 0!==i&&i,forceRelayCandidate:null!==(s=n.options.forceRelayCandidate)&&void 0!==s&&s};o.telnyx_call_control_id&&(a.telnyxCallControlId=o.telnyx_call_control_id),o.telnyx_session_id&&(a.telnyxSessionId=o.telnyx_session_id),o.telnyx_leg_id&&(a.telnyxLegId=o.telnyx_leg_id),o.client_state&&(a.clientState=o.client_state),o.dialogParams&&o.dialogParams.custom_headers&&o.dialogParams.custom_headers.length&&(a.customHeaders=o.dialogParams.custom_headers);const c=new dt(n,a);return c.nodeId=this.nodeId,c},u=new ae,p=new ht;switch(s){case B.Ping:this.session.execute(p);break;case B.Punt:n.disconnect();break;case B.Invite:{const e=l();e.playRingtone(),e.setState(W.Ringing),e.direction=G.Inbound,this._ack(i,s);break}case B.Attach:{const e=l();this.session.autoRecoverCalls?e.answer():e.setState(W.Recovering),e.handleMessage(t);break}case B.Event:case"webrtc.event":if(!a)return void h.error("Verto received an unknown event:",o);const r=n.relayProtocol,c=a.split(".")[0];n._existsSubscription(r,a)?j(r,o,a):a===n.sessionid?this._handleSessionEvent(o.eventData):n._existsSubscription(r,c)?j(r,o,c):n.calls.hasOwnProperty(a)?n.calls[a].handleMessage(t):j(e.SwEvent.Notification,o,n.uuid);break;case B.Info:o.type=F.generic,j(e.SwEvent.Notification,o,n.uuid);break;case B.ClientReady:this.session.execute(u);break;default:{const i=R(t);if(i){switch(i){case z.REGISTER:case z.REGED:n.connection.previousGatewayState!==z.REGED&&n.connection.previousGatewayState!==z.REGISTER&&(pt.retriedRegister=0,o.type=F.vertoClientReady,j(e.SwEvent.Ready,o,n.uuid));break;case z.UNREGED:case z.NOREG:if(pt.retriedRegister+=1,5===pt.retriedRegister){pt.retriedRegister=0,j(e.SwEvent.Error,{error:new ut("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:n.sessionid},n.uuid);break}setTimeout((()=>{this.session.execute(u)}),this.reconnectDelay());break;case z.FAILED:case z.FAIL_WAIT:if(n.connection.previousGatewayState!==z.FAILED&&n.connection.previousGatewayState!==z.FAIL_WAIT){if(!this.session.hasAutoReconnect()){pt.retriedConnect=0,j(e.SwEvent.Error,{error:new ut("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:n.sessionid},n.uuid);break}if(pt.retriedConnect+=1,5===pt.retriedConnect){pt.retriedConnect=0,j(e.SwEvent.Error,{error:new Error("Connection Retry Failed"),sessionId:n.sessionid},n.uuid);break}setTimeout((()=>{this.session.disconnect().then((()=>{this.session.clearConnection(),this.session.connect()}))}),this.reconnectDelay())}break;default:h.warn("GatewayState message unknown method:",t)}break}h.warn("Verto message unknown method:",t);break}}}_retrieveCallId(e,t){const n=Object.keys(this.session.calls);if("bootObj"!==e.action)return n.find((e=>this.session.calls[e].channels.includes(t)));{const t=e.data.find((e=>n.includes(e[0])));if(t instanceof Array)return t[0]}}_handlePvtEvent(t){return n(this,void 0,void 0,(function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:c,modChannel:d,conferenceMemberID:l,role:u,callID:p}=t;switch(s){case"conference-liveArray-join":{const e=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},i={nodeId:this.nodeId,channels:[o],handler:({data:i})=>{const s=p||this._retrieveCallId(i,o);if(s&&n.calls.hasOwnProperty(s)){const a=n.calls[s];a._addChannel(o),a.extension=r,a.handleConferenceUpdate(i,t).then((t=>{"INVALID_PACKET"===t&&e()}))}}},s=yield n.vertoSubscribe(i).catch((e=>{h.error("liveArray subscription error:",e)}));ke(s,o)&&e();break}case"conference-liveArray-part":{let t=null;if(o&&n._existsSubscription(i,o)){const{callId:s=null}=n.subscriptions[i][o];if(t=n.calls[s]||null,null!==s){const i={type:F.conferenceUpdate,action:K.Leave,conferenceName:r,participantId:Number(l),role:u};j(e.SwEvent.Notification,i,s,!1)||j(e.SwEvent.Notification,i,n.uuid),null===t&&U(e.SwEvent.Notification,null,s)}}const s=[o,a,c,d];n.vertoUnsubscribe({nodeId:this.nodeId,channels:s}).then((({unsubscribedChannels:e=[]})=>{t&&(t.channels=t.channels.filter((t=>!e.includes(t))))})).catch((e=>{h.error("liveArray unsubscribe error:",e)}));break}}}))}_handleSessionEvent(t){switch(t.contentType){case"layout-info":case"layer-info":Ye(this.session,t);break;case"logo-info":{const n={type:F.conferenceUpdate,action:K.LogoInfo,logo:t.logoURL};j(e.SwEvent.Notification,n,this.session.uuid);break}}}}pt.retriedConnect=0,pt.retriedRegister=0;class gt extends lt{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,window.addEventListener("beforeunload",(e=>{this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&this.calls[e].hangup({},!0)}))}))}validateOptions(){return T(this.options)}newCall(e){if(!e||!e.destinationNumber)throw new Error("Verto.newCall() error: destinationNumber is required.");console.time(g);const t=new dt(this,e);return t.invite(),t}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}_onSocketOpen(){return n(this,void 0,void 0,(function*(){this._idle=!1;const{login:e,password:t,passwd:n,login_token:i,userVariables:s,autoReconnect:o=!0}=this.options,r=new $e(e,t||n,i,this.sessionid,s,!!Q()),a=yield this.execute(r).catch(this._handleLoginError);a&&(this._autoReconnect=o,this.sessionid=a.sessid)}))}_onSocketMessage(e){new pt(this).handleMessage(e)}}class vt extends gt{constructor(e){super(e),console.log(`SDK version: ${Ue}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Ae()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:De.full},{browserName:"Firefox",features:["audio"],supported:De.partial},{browserName:"Safari",supported:De.not_supported},{browserName:"Edge",supported:De.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:De.not_supported},{browserName:"Firefox",supported:De.not_supported},{browserName:"Safari",features:["video","audio"],supported:De.full},{browserName:"Edge",supported:De.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:De.full},{browserName:"Firefox",features:["audio"],supported:De.partial},{browserName:"Safari",supported:De.not_supported},{browserName:"Edge",supported:De.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:De.full},{browserName:"Firefox",features:["audio"],supported:De.partial},{browserName:"Safari",features:["video","audio"],supported:De.full},{browserName:"Edge",features:["audio"],supported:De.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:De.full},{browserName:"Firefox",features:["audio"],supported:De.partial},{browserName:"Safari",supported:De.not_supported},{browserName:"Edge",features:["audio"],supported:De.partial}]}]}}class ft{static run(t){return n(this,void 0,void 0,(function*(){const n=x({}),i=x({}),s=new vt(t.credentials);yield s.connect(),s.on(e.SwEvent.Ready,n.resolve),s.on(e.SwEvent.Error,n.reject),s.on(e.SwEvent.MediaError,n.reject),s.on(e.SwEvent.MediaError,n.reject),s.on(e.SwEvent.Notification,(e=>{e.call&&e.call.sipCode>=400&&i.reject(new Error(e.call.sipReason))})),O(e.SwEvent.StatsReport,(e=>{i.resolve(ft.mapReport(e))})),yield n.promise,yield s.newCall({destinationNumber:t.texMLApplicationNumber,debug:!0});const o=yield i.promise;return yield s.disconnect(),o}))}static mapReport(e){var t,n,i,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,w=1/0,S=-1/0,_=0;v.forEach((e=>{var t,n,i;if(!(null===(t=e.remote.audio.inbound)||void 0===t?void 0:t[0]))return;f+=1;const s=null!==(n=e.remote.audio.inbound[0].jitter)&&void 0!==n?n:0,o=null!==(i=e.remote.audio.inbound[0].roundTripTime)&&void 0!==i?i:0;y+=s,_+=o,b=Math.max(b,s),m=Math.min(m,s),S=Math.max(S,o),w=Math.min(w,o)}));const I=_/f,E=y/f,C=v[v.length-1],k=Xe({jitter:1e3*E,rtt:1e3*I,packetsReceived:null!==(i=null===(n=null===(t=C.audio.inbound)||void 0===t?void 0:t[0])||void 0===n?void 0:n.packetsReceived)&&void 0!==i?i:0,packetsLost:null!==(r=null===(o=null===(s=C.audio.inbound)||void 0===s?void 0:s[0])||void 0===o?void 0:o.packetsLost)&&void 0!==r?r:0});return{iceCandidatePairStats:v[v.length-1].connection,summaryStats:{mos:k,jitter:{average:E,max:b,min:m},rtt:{average:I,max:S,min:w},quality:Ze(k)},sessionStats:{packetsSent:null!==(a=C.connection.packetsSent)&&void 0!==a?a:0,bytesSent:null!==(c=C.connection.bytesSent)&&void 0!==c?c:0,bytesReceived:null!==(d=C.connection.bytesReceived)&&void 0!==d?d:0,packetsLost:null!==(h=null===(u=null===(l=C.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=C.connection.packetsReceived)&&void 0!==p?p:0},iceCandidateStats:g}}getTelnyxIds(){return{telnyxCallControlId:"",telnyxSessionId:"",telnyxLegId:""}}}e.PreCallDiagnosis=ft,e.TelnyxRTC=vt,Object.defineProperty(e,"__esModule",{value:!0})}));
package/lib/bundle.mjs CHANGED
@@ -1 +1 @@
1
- function e(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(n[i[s]]=e[i[s]])}return n}function t(e,t,n,i){return new(n||(n=Promise))((function(s,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),i=new Uint8Array(16);function s(){if(!n)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return n(i)}for(var o=[],r=0;r<256;++r)o[r]=(r+256).toString(16).substr(1);function a(e,t,n){var i=t&&n||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[i+a]=r[a];return t||function(e,t){var n=t||0,i=o;return[i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]]].join("")}(r)}var c="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function d(e,t){return e(t={exports:{}},t.exports),t.exports}var l=d((function(e){var t,n;t=c,n=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function s(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[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,n){for(var s=0;s<i.length;s++){var o=i[s];this[o]=s<t?e:this.methodFactory(o,t,n)}this.log=this.debug}function a(e,n,i){return function(){typeof console!==t&&(r.call(this,n,i),this[e].apply(this,arguments))}}function c(i,r,c){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?o:void 0!==console[i]?s(console,i):void 0!==console.log?s(console,"log"):e)}(i)||a.apply(this,arguments)}function d(e,n,s){var o,a=this;n=null==n?"WARN":n;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 n=window.document.cookie,i=n.indexOf(encodeURIComponent(d)+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i))[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(n,s){if("string"==typeof n&&void 0!==a.levels[n.toUpperCase()]&&(n=a.levels[n.toUpperCase()]),!("number"==typeof n&&n>=0&&n<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(o=n,!1!==s&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+n+";"}catch(e){}}}(n),r.call(a,n,e),typeof console===t&&n<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){n=e,l()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(n,!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=n),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=n():t.log=n()}));const u=l.getLogger("telnyx"),h=u.methodFactory;u.methodFactory=(e,t,n)=>{const i=h(e,t,n);return function(){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(let t=0;t<arguments.length;t++)e.push(arguments[t]);i.apply(void 0,e)}},u.setLevel(u.getLevel());const p="Time to call invite",g="wss://rtc.telnyx.com",f={urls:"stun:stun.telnyx.com:3478"},v={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var m;!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.Messages="telnyx.messages",e.Calls="telnyx.calls",e.MediaError="telnyx.rtc.mediaError"}(m||(m={}));const b=e=>0===Object.keys(e).length,y=e=>{const[t,n,i,s,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){u.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},_=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},w=e=>e instanceof Function||"function"==typeof e,S=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,I=/^(ws|wss):\/\//,C=(e,t=null)=>{const{result:n={},error:i}=e;if(i)return{error:i};const{result:s=null}=n;if(null===s)return null!==t&&(n.node_id=t),{result:n};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&"200"!==o?{error:s}:a?C(a,r):{result:s}},E=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),k=({login:e,passwd:t,password:n,login_token:i})=>Boolean(e&&(t||n)||i),T=e=>{var t,n,i,s,o,r;let a="",c="";(null===(n=null===(t=null==e?void 0:e.result)||void 0===t?void 0:t.params)||void 0===n?void 0:n.state)&&(a=null===(s=null===(i=null==e?void 0:e.result)||void 0===i?void 0:i.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 R({debounceTime:e}){let t,n;return{promise:new Promise(((i,s)=>{t=e?x(i,e):i,n=s})),resolve:t,reject:n}}const x=(e,t)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout((()=>{e(...i)}),t)}},M="GLOBAL",D={},A=(e,t)=>`${e}|${t}`,L=(e,t=M)=>A(e,t)in D,N=(e,t,n=M)=>{const i=A(e,n);i in D||(D[i]=[]),D[i].push(t)},O=(e,t,n=M)=>{const i=function(s){P(e,i,n),t(s)};return i.prototype.targetRef=t,N(e,i,n)},P=(e,t,n=M)=>{if(!L(e,n))return!1;const i=A(e,n);if(w(t)){for(let e=D[i].length-1;e>=0;e--){const n=D[i][e];(t===n||n.prototype&&t===n.prototype.targetRef)&&D[i].splice(e,1)}}else D[i]=[];return 0===D[i].length&&delete D[i],!0},U=(e,t,n=M,i=!0)=>{const s=i&&n!==M;if(!L(e,n))return s&&U(e,t),!1;const o=A(e,n),r=D[o].length;if(!r)return s&&U(e,t),!1;for(let e=r-1;e>=0;e--)D[o][e](t);return s&&U(e,t),!0},j=e=>{const t=A(e,"");Object.keys(D).filter((e=>0===e.indexOf(t))).forEach((e=>delete D[e]))};var $,V,G;!function(e){e.Offer="offer",e.Answer="answer"}($||($={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(V||(V={})),function(e){e.Invite="telnyx_rtc.invite",e.Attach="telnyx_rtc.attach",e.Answer="telnyx_rtc.answer",e.Info="telnyx_rtc.info",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 B={generic:"event",[G.Display]:"participantData",[G.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError"},F={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,video:!1,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0}};var H,W,q,K,J;!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"}(H||(H={})),function(e){e.Participant="participant",e.Moderator="moderator"}(W||(W={})),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"}(q||(q={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(K||(K={})),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"}(J||(J={}));const z="telnyx-voice-sdk-id";function Y(){return sessionStorage.getItem(z)}"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{sessionStorage.removeItem(z)}));let Q="undefined"!=typeof WebSocket?WebSocket:null;const X=0,Z=1,ee=2,te=3;class ne{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=g,this._timers={},this.upDur=null,this.downDur=null;const{host:t,env:n}=e.options;t&&(this._host=(e=>`${I.test(e)?"":"wss://"}${e}`)(t)),n&&(this._host="development"===n?"wss://rtcdev.telnyx.com":g)}get connected(){return this._wsClient&&this._wsClient.readyState===Z}get connecting(){return this._wsClient&&this._wsClient.readyState===X}get closing(){return this._wsClient&&this._wsClient.readyState===ee}get closed(){return this._wsClient&&this._wsClient.readyState===te}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){const e=new URL(this._host),t=Y();t&&e.searchParams.set("voice_sdk_id",t),this._wsClient=new Q(e.toString()),this._wsClient.onopen=e=>U(m.SocketOpen,e,this.session.uuid),this._wsClient.onclose=e=>U(m.SocketClose,e,this.session.uuid),this._wsClient.onerror=e=>U(m.SocketError,{error:e,sessionId:this.session.sessionid},this.session.uuid),this._wsClient.onmessage=e=>{var t,n;const i=_(e.data);var s;if("string"!=typeof i){if(i.voice_sdk_id&&(s=i.voice_sdk_id,sessionStorage.setItem(z,s)),this._unsetTimer(i.id),u.debug("RECV: \n",JSON.stringify(i,null,2),"\n"),J[`${null===(n=null===(t=null==i?void 0:i.result)||void 0===t?void 0:t.params)||void 0===n?void 0:n.state}`]||!U(i.id,i)){const e=T(i);U(m.SocketMessage,i,this.session.uuid),Boolean(e)&&(this.previousGatewayState=e)}}else this._handleStringResponse(i)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:t}=e,n=new Promise(((e,n)=>{if(t.hasOwnProperty("result"))return e();O(t.id,(t=>{const{result:i,error:s}=C(t);return s?n(s):e(i)}))}));return u.debug("SEND: \n",JSON.stringify(t,null,2),"\n"),this._wsClient.send(JSON.stringify(t)),n}close(){this._wsClient&&(w(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close()),this._wsClient=null}_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)),U(m.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else u.warn("Unknown message from socket",e)}}class ie{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:a()},e)}}const se={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 oe extends ie{constructor(t={}){if(super(),t.hasOwnProperty("dialogParams")){const n=e(t.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const e in se)e&&n.hasOwnProperty(e)&&(n[se[e]]=n[e],delete n[e]);t.dialogParams=n}this.buildRequest({method:this.toString(),params:t})}}class re extends oe{constructor(){super(),this.method=G.GatewayState;this.buildRequest({method:this.method,params:{}})}}class ae{constructor(e){this.pendingRequestId=null,this.onSocketMessage=e=>t(this,void 0,void 0,(function*(){e.id===this.pendingRequestId&&this.gatewayStateTask.resolve(T(e))})),this.getIsRegistered=()=>t(this,void 0,void 0,(function*(){const e=new re;this.pendingRequestId=e.request.id,this.gatewayStateTask=R({}),this.session.execute(e);const t=yield this.gatewayStateTask.promise;return!!t&&[J.REGISTER,J.REGED].includes(t)})),this.session=e,this.gatewayStateTask=R({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class ce{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.connection=null,this._jwtAuth=!1,this._doKeepAlive=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");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 ne(this),this.registerAgent=new ae(this)}get __logger(){return u}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*E(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}),this.connect()}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return k(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()}))}on(e,t){return N(e,t,this.uuid),this}off(e,t){return P(e,t,this.uuid),this}connect(){return t(this,void 0,void 0,(function*(){this.connection||(this.connection=new ne(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()}))}_handleLoginError(e){U(m.Error,{error:e,sessionId:this.sessionid},this.uuid)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){}))}onNetworkClose(){this.relayProtocol&&j(this.relayProtocol);for(const e in this.subscriptions)j(e);this.subscriptions={},this.contexts=[],this._autoReconnect&&(this._reconnectTimeout=setTimeout((()=>this.connect()),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,t){this._existsSubscription(e,t)&&(t?(delete this.subscriptions[e][t],P(e,null,t)):(delete this.subscriptions[e],j(e)))}_addSubscription(e,t=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},w(t)&&N(e,t,n))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(m.SocketOpen,this._onSocketOpen),this.on(m.SocketClose,this.onNetworkClose),this.on(m.SocketError,this.onNetworkClose),this.on(m.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(m.SocketOpen,this._onSocketOpen),this.off(m.SocketClose,this.onNetworkClose),this.off(m.SocketError,this.onNetworkClose),this.off(m.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()}_keepAlive(){!0===this._doKeepAlive&&(this._pong=!1,this._keepAliveTimeout=setTimeout((()=>this._keepAlive()),3e4))}static on(e,t){N(e,t)}static off(e){P(e)}static uuid(){return a()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}getIsRegistered(){return this.registerAgent.getIsRegistered()}}const de=e=>navigator.mediaDevices.getUserMedia(e),le=e=>e&&e instanceof MediaStream,ue=(e,t)=>{const n=S(e);null!==n&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=t)},he=(e,n)=>t(void 0,void 0,void 0,(function*(){const t=S(e);if(null===t)return u.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof n)return u.info(`Invalid speaker deviceId: '${n}'`),!1;try{return yield t.setSinkId(n),!0}catch(e){return!1}})),pe=e=>{e&&"live"===e.readyState&&e.stop()},ge=e=>{le(e)&&e.getTracks().forEach(pe),e=null},fe=e=>t(void 0,void 0,void 0,(function*(){u.info("RTCService.getUserMedia",e);const{audio:t,video:n}=e;if(!t&&!n)return null;try{return yield de(e)}catch(e){throw u.error("getUserMedia error: ",e),e}})),ve=(e=null,n=!1)=>t(void 0,void 0,void 0,(function*(){let t=[];const i=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===K.AudioIn||e===K.AudioOut,video:!e||e===K.Video}))(e)).catch((e=>(console.error(e),null)));if(i){if(ge(i),t=yield navigator.mediaDevices.enumerateDevices(),e&&(t=t.filter((t=>t.kind===e))),!0===n)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})),me=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],be=(e,n,i)=>t(void 0,void 0,void 0,(function*(){const t=yield ve(i,!0);for(let i=0;i<t.length;i++){const{deviceId:s,label:o}=t[i];if(e===s||n===o)return s}return null})),ye=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((n=>{t.hasOwnProperty(n)&&null!==e[n]&&void 0!==e[n]||delete e[n]}))},_e=(e,n,i,s)=>t(void 0,void 0,void 0,(function*(){const{deviceId:t}=s;if(void 0===t&&(e||n)){const t=yield be(e,n,i).catch((e=>null));t&&(s.deviceId={exact:t})}return s})),we=e=>{const t="\r\n",n=e.split(t),i=n.findIndex((e=>/^a=rtpmap/.test(e)&&/opus\/48000/.test(e)));if(i<0)return e;const s=(e=>{const t=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),n=e.match(t);return n&&2==n.length?n[1]:null})(n[i]),o=new RegExp(`a=fmtp:${s}`),r=n.findIndex((e=>o.test(e)));return r>=0?/stereo=1;/.test(n[r])||(n[r]+="; stereo=1; sprop-stereo=1"):n[i]+=`${t}a=fmtp:${s} stereo=1; sprop-stereo=1`,n.join(t)},Se=e=>/^m=audio/.test(e),Ie=e=>/^m=video/.test(e),Ce=(e,t)=>{const n="\r\n",i=t.split(n);if(i.findIndex(Se)<i.findIndex(Ie))return e;const s=e.split(n),o=s.findIndex(Se),r=s.findIndex(Ie),a=s.slice(o,r),c=s.slice(r,s.length-1);return[...s.slice(0,o),...c,...a,""].join(n)},Ee=(e,t)=>{if(!e)return!1;const{subscribed:n,alreadySubscribed:i}=ke(e);return n.includes(t)||i.includes(t)},ke=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((n=>{t[n]=e[`${n}Channels`]||[]})),t},Te=(e,t=null,n=null)=>{if(!le(e))return null;let i=[];switch(t){case"audio":i=e.getAudioTracks();break;case"video":i=e.getVideoTracks();break;default:i=e.getTracks()}i.forEach((e=>{switch(n){case"on":case!0:e.enabled=!0;break;case"off":case!1:e.enabled=!1;break;default:e.enabled=!e.enabled}}))},Re=e=>{Te(e,"audio",!0)},xe=e=>{Te(e,"audio",!1)},Me=e=>{Te(e,"audio",null)};function De(){try{const{browserInfo:e,name:t,version:n,supportAudio:i,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],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,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],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,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("/"),n=parseInt(t[1],10);return{browserInfo:navigator.userAgent,name:e,version:n,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],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,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:n,supportWebRTC:!!(o&&r&&a&&c&&d),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!fe}}catch(e){return e.message}}var Ae;function Le(e,t){const n=document.getElementById(t);if(n)return n;if(e&&t){const n=document.createElement("audio");return n.id=t,n.loop=!0,n.src=e,n.preload="auto",n.load(),document.body.appendChild(n),n}return null}function Ne(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then((()=>{e._playFulfilled=!0})).catch((t=>{console.error("playAudio",t),e._playFulfilled=!0})))}function Oe(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"}(Ae||(Ae={}));var Pe="2.22.5",Ue=Pe;class je extends oe{constructor(e,t,n,i,s={},o){super(),this.method="login";const r={login:e,passwd:t,login_token:n,userVariables:s,reconnection:o,loginParams:{},"User-Agent":{sdkVersion:Ue,data:navigator.userAgent}};i&&(r.sessid=i),this.buildRequest({method:this.method,params:r})}}class $e extends oe{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Ve extends oe{toString(){return G.Invite}}class Ge extends oe{toString(){return G.Answer}}class Be extends oe{toString(){return G.Attach}}class Fe extends oe{toString(){return G.Bye}}class He extends oe{toString(){return G.Modify}}class We extends oe{toString(){return G.Info}}class qe extends oe{toString(){return G.Broadcast}}class Ke extends oe{toString(){return G.Subscribe}}class Je extends oe{toString(){return G.Unsubscribe}}const ze=(e,t)=>{const{contentType:n,canvasType:i,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&"mcu-personal-canvas"!==i&&delete o.memberID;const a={type:B.conferenceUpdate,call:e.calls[s],canvasInfo:Ye(o),currentLayerIdx:r};switch(n){case"layer-info":{const t=Object.assign({action:q.LayerInfo},a);U(m.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:q.LayoutInfo},a);U(m.Notification,t,e.uuid);break}}},Ye=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return _(t)};var Qe,Xe=d((function(e,t){var n;function i(){}function s(){s.init.call(this)}function o(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function r(e,t,n,s){var r,a,c;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),c=a[t]):(a=e._events=new i,e._eventsCount=0),c){if("function"==typeof c?c=a[t]=s?[n,c]:[c,n]:s?c.unshift(n):c.push(n),!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]=n,++e._eventsCount;return e}function a(e,t,n){function i(){e.removeListener(t,i),s||(s=!0,n.apply(e,arguments))}var s=!1;return i.listener=n,i}function c(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function d(e,t){for(var n=Array(t);t--;)n[t]=e[t];return n}Object.defineProperty(t,"__esModule",{value:!0}),i.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&&n.active&&!(this instanceof n.Domain)&&(this.domain=n.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new i,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,n,i,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(!(n=r[e]))return!1;var u="function"==typeof n;switch(i=arguments.length){case 1:!function(e,t,n){if(t)e.call(n);else for(var i=e.length,s=d(e,i),o=0;o<i;++o)s[o].call(n)}(n,u,this);break;case 2:!function(e,t,n,i){if(t)e.call(n,i);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].call(n,i)}(n,u,this,arguments[1]);break;case 3:!function(e,t,n,i,s){if(t)e.call(n,i,s);else for(var o=e.length,r=d(e,o),a=0;a<o;++a)r[a].call(n,i,s)}(n,u,this,arguments[1],arguments[2]);break;case 4:!function(e,t,n,i,s,o){if(t)e.call(n,i,s,o);else for(var r=e.length,a=d(e,r),c=0;c<r;++c)a[c].call(n,i,s,o)}(n,u,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=Array(i-1),o=1;o<i;o++)s[o-1]=arguments[o];!function(e,t,n,i){if(t)e.apply(n,i);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].apply(n,i)}(n,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 n,s,o,r,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(s=this._events))return this;if(!(n=s[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new i:(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(o=-1,r=n.length;0<r--;)if(n[r]===t||n[r].listener&&n[r].listener===t){a=n[r].listener,o=r;break}if(0>o)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new i,this;delete s[e]}else!function(e,t){for(var n=t,i=n+1,s=e.length;i<s;n+=1,i+=1)e[n]=e[i];e.pop()}(n,o);s.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new i,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new i:delete n[e]),this;if(0===arguments.length){for(var s,o=Object.keys(n),r=0;r<o.length;++r)"removeListener"!==(s=o[r])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if("function"==typeof(t=n[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,n,i=this._events;return i?n=(t=i[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[]:n=[],n},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=[],f=0;256>f;++f)g.push((f+256).toString(16).substr(1));function v(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:0,n=(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)}(n))throw TypeError("Stringified UUID is invalid");return n}function m(e,t,n){var i=(e=e||{}).random||(e.rng||h)();if(i[6]=64|15&i[6],i[8]=128|63&i[8],t){n=n||0;for(var s=0;16>s;++s)t[n+s]=i[s];return t}return v(i)}function b(e,t){if(!e||!t)return{};const n={...e};if(n.localCandidateId){const e=t.get(n.localCandidateId);n.local={...e}}if(n.remoteCandidateId){const e=t.get(n.remoteCandidateId);n.remote={...e}}return n}function y(e,t,n){return 8*function(e,t,n){const i=e[n],s=t?t[n]:null;return null===i||null===s?null:(i-s)/(e.timestamp-t.timestamp)*1e3}(e,t,n)}function _(e){if(!e.entries)return e;const t={};return e.forEach((function(e,n){t[n]=e})),t}function w(e,t,n={}){if(!e)return null;let i={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};n.remote&&(i.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const t of e.values())switch(t.type){case"outbound-rtp":{const n=t.mediaType||t.kind,s={};let o={};if(!["audio","video"].includes(n))continue;if(t.codecId){const n=e.get(t.codecId);n&&(s.clockRate=n.clockRate,s.mimeType=n.mimeType,s.payloadType=n.payloadType)}o=e.get(t.mediaSourceId)||e.get(t.trackId)||{},i[n].outbound.push({...t,...s,track:{...o}});break}case"inbound-rtp":{let n=t.mediaType||t.kind,s={};const o={};if(!["audio","video"].includes(n))if(t.id.includes("Video"))n="video";else{if(!t.id.includes("Audio"))continue;n="audio"}if(t.codecId){const n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}if(!i.connection.id&&t.transportId){const n=e.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=e.get(n.selectedCandidatePairId);i.connection=b(t,e)}}s=e.get(t.mediaSourceId)||e.get(t.trackId)||{},i[n].inbound.push({...t,...o,track:{...s}});break}case"peer-connection":i.connection.dataChannelsClosed=t.dataChannelsClosed,i.connection.dataChannelsOpened=t.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!n.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 n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}if(!i.connection.id&&t.transportId){const n=e.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=e.get(n.selectedCandidatePairId);i.connection=b(t,e)}}i.remote[s].inbound.push({...t,...o});break}case"remote-outbound-rtp":{if(!n.remote)break;const s=t.mediaType||t.kind,o={};if(!["audio","video"].includes(s))continue;if(t.codecId){const n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}i.remote[s].outbound.push({...t,...o});break}}if(!i.connection.id)for(const t of e.values())"candidate-pair"===t.type&&t.nominated&&"succeeded"===t.state&&(i.connection=b(t,e));return i=function(e,t){return t?(e.audio.inbound.map((e=>{let n=t.audio.inbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesReceived"),e.packetRate=y(e,n,"packetsReceived")})),e.audio.outbound.map((e=>{let n=t.audio.outbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesSent"),e.packetRate=y(e,n,"packetsSent")})),e.video.inbound.map((e=>{let n=t.video.inbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesReceived"),e.packetRate=y(e,n,"packetsReceived")})),e.video.outbound.map((e=>{let n=t.video.outbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesSent"),e.packetRate=y(e,n,"packetsSent")})),e):e}(i,t),i}let S,I={},C=[];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:n}=e;let{connectionId:i,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(!n)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[n]){if(i&&i in this.peersToMonitor[n])throw new Error(`We are already monitoring connection with id ${i}.`);for(let e in this.peersToMonitor[n]){const i=this.peersToMonitor[n][e];if(i.pc===t)throw new Error(`We are already monitoring peer with id ${n}.`);"closed"===i.pc.connectionState&&this.removeConnection({pc:i.pc})}}const o=t.getConfiguration();return o.iceServers&&o.iceServers.forEach((function(e){delete e.credential})),i||(i=m()),this.emitEvent({event:"addConnection",tag:"peer",peerId:n,connectionId:i,data:{options:e,peerConfiguration:o}}),this.monitorPeer({peerId:n,connectionId:i,pc:t,remote:s}),{connectionId:i}}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:n,pc:i}=e;if(!i&&!n)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(n){if("string"!=typeof n)throw new Error("connectionId must be a string.");for(let e in this.peersToMonitor)n in this.peersToMonitor[e]&&(i=this.peersToMonitor[e][n].pc,t=e)}else if(i){if(!(i 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===i&&(n=s,t=e)}if(!i||!n)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(n,i),delete this.peersToMonitor[t][n],0===Object.values(this.peersToMonitor[t]).length&&delete this.peersToMonitor[t],{connectionId:n}}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 n=this.peersToMonitor[e][t].pc;this.removePeerConnectionEventListeners(t,n)}delete this.peersToMonitor[e]}}destroy(){this.removeAllPeers(),C.forEach((e=>{this.removeTrackEventListeners(e)})),C=[],this.shouldWrapGetUserMedia&&S&&(navigator.mediaDevices.getUserMedia=S)}monitorPeer(e){let{peerId:t,connectionId:n,pc:i,remote:s}=e;if(!i)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const o={pc:i,connectionId:n,stream:null,stats:{parsed:null,raw:null},options:{remote:s}};if(this.peersToMonitor[t]){if(n in this.peersToMonitor[t])return void this.logger.warn(`Already watching connection with ID ${n}`);this.peersToMonitor[t][n]=o}else this.peersToMonitor[t]={[n]:o};this.addPeerConnectionEventListeners(t,n,i),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 n=[];for(const e in t)for(const i in t[e]){const s=t[e][i],o=s.pc;if(o&&!this.checkIfConnectionIsClosed(e,i,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=w(o,s.stats.parsed,d),u={event:"stats",tag:"stats",peerId:e,connectionId:i,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)),n.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 n}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const e in this.peersToMonitor)for(const t in this.peersToMonitor[e]){const n=this.peersToMonitor[e][t].pc;this.checkIfConnectionIsClosed(e,t,n)}}),this.connectionMonitoringInterval)}checkIfConnectionIsClosed(e,t,n){const i=this.isConnectionClosed(n);if(i){this.removeConnection({pc:n});let i="closed"===n.connectionState?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:i,peerId:e,connectionId:t,tag:"connection",data:"closed"})}return i}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."),S=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const e=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=function(){return e({constraints:arguments[0]}),S.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 n=t[e];this.statsToMonitor.includes(n.type)||delete t[e]}return t}get peerConnectionListeners(){return{icecandidate:(e,t,n,i)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",i),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:e,connectionId:t,data:i.candidate})},track:(e,t,n,i)=>{this.logger.debug(`[pc-event] track | peerId: ${e}`,i);const s=i.track,o=i.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:i.track.kind+":"+i.track.id+" "+i.streams.map((function(e){return"stream:"+e.id}))}})},signalingstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${e}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:e,connectionId:t,data:{signalingState:n.signalingState,localDescription:n.localDescription,remoteDescription:n.remoteDescription}})},iceconnectionstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${e}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:n.iceConnectionState})},icegatheringstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${e}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:e,connectionId:t,data:n.iceGatheringState})},icecandidateerror:(e,t,n,i)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${e}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:e,connectionId:t,error:{errorCode:i.errorCode}})},connectionstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${e}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:n.connectionState})},negotiationneeded:(e,t,n)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${e}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:e,connectionId:t})},datachannel:(e,t,n,i)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${e}`,i),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:e,connectionId:t,data:i.channel})}}}addPeerConnectionEventListeners(e,t,n){this.logger.debug(`Adding event listeners for peer ${e} and connection ${t}.`),I[t]={},Object.keys(this.peerConnectionListeners).forEach((i=>{I[t][i]=this.peerConnectionListeners[i].bind(this,e,t,n),n.addEventListener(i,I[t][i],!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),C.push(e)}))),this.emitEvent(t)}catch(e){}}parseStream(e){const t={audio:[],video:[]};return e.getTracks().forEach((e=>{t[e.kind].push(this.getMediaTrackDetails(e))})),t}getMediaTrackDetails(e){return{enabled:e.enabled,id:e.id,contentHint:e.contentHint,kind:e.kind,label:e.label,muted:e.muted,readyState:e.readyState,constructorName:e.constructor.name,capabilities:e.getCapabilities?e.getCapabilities():{},constraints:e.getConstraints?e.getConstraints():{},settings:e.getSettings?e.getSettings():{},_track:e}}getStreamDetails(e){return{active:e.active,id:e.id,_stream:e}}getTrackEventObject(e){return{mute:t=>{this.emitEvent({event:"mute",tag:"track",connectionId:e,data:{event:t}})},unmute:t=>{this.emitEvent({event:"unmute",tag:"track",connectionId:e,data:{event:t}})},overconstrained:t=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:e,data:{event:t}})},ended:t=>{this.emitEvent({event:"ended",tag:"track",connectionId:e,data:{event:t}}),this.removeTrackEventListeners(t.target)}}}addTrackEventListeners(e,t){I[e.id]={};const n=this.getTrackEventObject(t);Object.keys(n).forEach((t=>{I[e.id][t]=n[t].bind(this),e.addEventListener(t,I[e.id][t])})),I[e.id].readyState=setInterval((()=>{if("ended"===e.readyState){let t=new CustomEvent("ended",{detail:{check:"readyState"}});e.dispatchEvent(t)}}),1e3)}removeTrackEventListeners(e){if(e.id in I){const t=this.getTrackEventObject();Object.keys(t).forEach((t=>{e.removeEventListener(t,I[e.id][t])})),clearInterval(I[e.id].readyState),delete I[e.id]}}addToTimeline(e){this.timeline.push(e),this.emit("timeline",e)}emitEvent(e){const t={...e,timestamp:new Date};this.addToTimeline(t),t.tag&&this.emit(t.tag,t)}set getStatsInterval(e){if(!Number.isInteger(e))throw new Error(`getStatsInterval should be an integer, got: ${e}`);this._getStatsInterval=e,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(e,t){e in I&&(Object.keys(this.peerConnectionListeners).forEach((n=>{t.removeEventListener(n,I[e][n],!1)})),delete I[e]),t.getSenders().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)})),t.getReceivers().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)}))}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const e=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const t=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),n=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=n.bind(navigator.mediaDevices)}}}}));(Qe=Xe)&&Qe.__esModule&&Object.prototype.hasOwnProperty.call(Qe,"default")&&Qe.default;var Ze=Xe.WebRTCStats;class et extends ie{constructor(e){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1})}}class tt extends ie{constructor(e){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1})}}class nt extends ie{constructor(e,t){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:t})}}class it{constructor(e,n,i){this.type=e,this.options=n,this.onSdpReadyTwice=null,this._negotiating=!1,this.handleConnectionStateChange=e=>t(this,void 0,void 0,(function*(){const{connectionState:e}=this.instance;if(console.log(`[${(new Date).toISOString()}] Connection State`,e),"failed"===e||"disconnected"===e){const e=()=>{this.instance.restartIce(),this._session._closeConnection(),this._session.connect(),window.removeEventListener("online",e)};if(navigator.onLine)return e();window.addEventListener("online",e)}})),this._handleIceConnectionStateChange=e=>{console.log(`[${(new Date).toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=e=>{console.log(`[${(new Date).toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setAudioCodec=e=>{if(this.options.preferred_codecs&&0!==this.options.preferred_codecs.length)return e.setCodecPreferences?e.setCodecPreferences(this.options.preferred_codecs):void 0},this._onDebugReportMessage=e=>t(this,void 0,void 0,(function*(){this.options.debug&&(yield this._session.execute(this._webrtcStatsReporter.reportDataMessage(e)))})),u.info("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},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=i,this._init()}get isOffer(){return this.type===$.Offer}get isAnswer(){return this.type===$.Answer}startNegotiation(){this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}startDebugger(){return t(this,void 0,void 0,(function*(){this.options.debug&&(this._webrtcStatsReporter=function(){const e=a(),t=new Ze({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,wrapGetUserMedia:!0,debug:!1,logLevel:"warn"});return{reportDataMessage:t=>new nt(e,t),start:()=>new et(e),stop:()=>new tt(e),reportId:e,debuggerInstance:t}}(),yield this._session.execute(this._webrtcStatsReporter.start()),this._webrtcStatsReporter.debuggerInstance.on("timeline",this._onDebugReportMessage),yield new Promise((e=>setTimeout(e,500))),this._webrtcStatsReporter.debuggerInstance.addConnection({pc:this.instance,peerId:this.options.id,connectionId:this.options.telnyxSessionId}))}))}stopDebugger(){this.options.debug&&(this._session.execute(this._webrtcStatsReporter.stop()),this._webrtcStatsReporter.debuggerInstance.destroy())}_logTransceivers(){u.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach(((e,t)=>{u.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),u.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))}handleSignalingStateChangeEvent(e){switch(u.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":this.instance=null;break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){u.info("Negotiation needed event"),"stable"===this.instance.signalingState&&this.startNegotiation()}handleTrackEvent(e){const{streams:[t]}=e,{remoteElement:n,screenShare:i}=this.options;let{remoteStream:s}=this.options;s=t,!1===i&&ue(n,s)}createPeerConnection(){return t(this,void 0,void 0,(function*(){var e;this.instance=(e=this._config(),new window.RTCPeerConnection(e)),yield this.startDebugger(),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.options.localStream=yield this._retrieveLocalStream().catch((e=>(U(m.MediaError,e,this.options.id),null)))}))}_init(){return t(this,void 0,void 0,(function*(){yield this.createPeerConnection();const{localElement:e,localStream:t=null,screenShare:n=!1}=this.options;if(le(t)){const i=t.getAudioTracks();u.info("Local audio tracks: ",i);const s=t.getVideoTracks();if(u.info("Local video tracks: ",s),this.isOffer&&"function"==typeof this.instance.addTransceiver){const e={direction:"sendrecv",streams:[t]};i.forEach((t=>{this.options.userVariables.microphoneLabel=t.label;const n=this.instance.addTransceiver(t,e);this._setAudioCodec(n)})),console.debug("Applying video transceiverParams",e),s.forEach((t=>{this.options.userVariables.cameraLabel=t.label,this.instance.addTransceiver(t,e)}))}else"function"==typeof this.instance.addTrack?(i.forEach((e=>{this.options.userVariables.microphoneLabel=e.label,this.instance.addTrack(e,t)})),this.instance.getTransceivers().forEach((e=>this._setAudioCodec(e))),s.forEach((e=>{this.options.userVariables.cameraLabel=e.label,this.instance.addTrack(e,t)}))):this.instance.addStream(t);!1===n&&((e=>{const t=S(e);t&&(t.muted=!0)})(e),ue(e,t))}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this.startNegotiation(),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);u.info("Add transceiver",e,t)}}_createOffer(){this._isOffer()&&(this._constraints.offerToReceiveAudio=Boolean(this.options.audio),this._constraints.offerToReceiveVideo=Boolean(this.options.video),u.info("_createOffer - this._constraints",this._constraints),this.instance.createOffer(this._constraints).then(this._setLocalDescription.bind(this)).then(this._sdpReady).catch((e=>u.error("Peer _createOffer error:",e))))}_setRemoteDescription(e){this.options.useStereo&&(e.sdp=we(e.sdp)),this.instance.localDescription&&(e.sdp=Ce(e.sdp,this.instance.localDescription.sdp));const t=e;return u.info("REMOTE SDP \n",`Type: ${e.type}`,"\n\n",e.sdp),this.instance.setRemoteDescription(t)}_createAnswer(){return t(this,void 0,void 0,(function*(){if(!this._isAnswer())return;if("stable"!==this.instance.signalingState)return console.log(" - 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:$.Offer})]));yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:$.Offer}),this._logTransceivers();const e=yield this.instance.createAnswer();yield this._setLocalDescription(e)}))}_setLocalDescription(e){const{useStereo:t,googleMaxBitrate:n,googleMinBitrate:i,googleStartBitrate:s,mediaSettings:o}=this.options;return t&&(e.sdp=we(e.sdp)),n&&i&&s&&(e.sdp=((e,t,n,i)=>{const s=e.split("\r\n");return s.forEach(((e,o)=>{/^a=fmtp:\d*/.test(e)?s[o]+=`;x-google-max-bitrate=${t};x-google-min-bitrate=${n};x-google-start-bitrate=${i}`:/^a=mid:(1|video)/.test(e)&&(s[o]+=`\r\nb=AS:${t}`)})),s.join("\r\n")})(e.sdp,n,i,s)),o&&o.useSdpASBandwidthKbps&&null!==o.sdpASBandwidthKbps&&(e.sdp=((e,t)=>{let n="AS",i=t;!navigator.userAgent.match(/firefox/gim)||navigator.userAgent.match(/OPR\/[0-9]{2}/gi)||navigator.userAgent.match(/edg/gim)||(n="TIAS",i=1e3*(t>>>0));return-1===e.indexOf("b="+n+":")?e.replace(/c=IN (.*)\r\n/,"c=IN $1\r\nb="+n+":"+i+"\r\n"):e.replace(new RegExp("b="+n+":.*\r\n"),"b="+n+":"+i+"\r\n")})(e.sdp,o.sdpASBandwidthKbps)),this.instance.setLocalDescription(e)}_sdpReady(){w(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return t(this,void 0,void 0,(function*(){if(le(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,t(void 0,void 0,void 0,(function*(){let{audio:e=!0,micId:t}=n;const{micLabel:i=""}=n;t&&(t=yield be(t,i,K.AudioIn).catch((e=>null)),t&&("boolean"==typeof e&&(e={}),e.deviceId={exact:t}));let{video:s=!1,camId:o}=n;const{camLabel:r=""}=n;return o&&(o=yield be(o,r,K.Video).catch((e=>null)),o&&("boolean"==typeof s&&(s={}),s.deviceId={exact:o})),{audio:e,video:s}})));var n;return fe(e)}))}_isOffer(){return this.type===$.Offer}_isAnswer(){return this.type===$.Answer}_config(){const{iceServers:e=[],prefetchIceCandidates:t,forceRelayCandidate:n}=this.options,i={bundlePolicy:"max-compat",iceCandidatePoolSize:t?10:0,iceServers:e,iceTransportPolicy:n?"relay":"all"};return u.info("RTC config",i),i}close(){if(this.options.debug){if("file"===this.options.debugOutput){!function(e,t){const n=new Blob([JSON.stringify(e)],{type:"application/json"}),i=URL.createObjectURL(n),s=document.createElement("a");s.href=i,s.download=`${t}.json`,s.click(),URL.revokeObjectURL(i)}(this._webrtcStatsReporter.debuggerInstance.getTimeline(),this.options.telnyxSessionId)}this.stopDebugger()}}}const st=Ue;class ot{constructor(e,t){this.session=e,this.id="",this.state=H[H.New],this.prevState="",this.channels=[],this.role=W.Participant,this.extension=null,this._state=H.New,this._prevState=H.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._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(var n in t.constraints)if(t.constraints.hasOwnProperty(n)&&t.constraints[n]!==e[n])return;t.callback(e)}}))}))}))};const{iceServers:n,speaker:i,micId:s,micLabel:o,camId:r,camLabel:a,localElement:c,remoteElement:d,mediaConstraints:{audio:l,video:u},ringtoneFile:h,ringbackFile:p}=e;this.options=Object.assign({},F,{audio:l,video:u,iceServers:n,localElement:c,remoteElement:d,micId:s,micLabel:o,camId:r,camLabel:a,speakerId:i,ringtoneFile:h,ringbackFile:p},t),this._onMediaError=this._onMediaError.bind(this),this._init(),this.options&&(this._ringtone=Le(this.options.ringtoneFile,"_ringtone"),this._ringback=Le(this.options.ringbackFile,"_ringback"))}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}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}`}invite(){this.direction=V.Outbound,this.peer=new it($.Offer,this.options,this.session),this._registerPeerEvents()}answer(e={}){var t,n;this.stopRingtone(),this.direction=V.Inbound,(null===(t=null==e?void 0:e.customHeaders)||void 0===t?void 0:t.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),(null===(n=e.preferred_codecs)||void 0===n?void 0:n.length)>0&&(this.options.preferred_codecs=e.preferred_codecs),this.peer=new it($.Answer,this.options,this.session),this._registerPeerEvents()}playRingtone(){Ne(this._ringtone)}stopRingtone(){Oe(this._ringtone)}playRingback(){Ne(this._ringback)}stopRingback(){Oe(this._ringback)}hangup(e,t){var n,i,s;let o=e||{},r=!1!==t;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!==(n=this.options.customHeaders)&&void 0!==n?n:[],...null!==(s=null===(i=null==o?void 0:o.dialogParams)||void 0===i?void 0:i.customHeaders)&&void 0!==s?s:[]],this.setState(H.Hangup);const a=()=>{var e;return null===(e=this.peer)||void 0===e||e.close(),this.setState(H.Destroy)};if(this.stopRingtone(),this.stopRingback(),r){const e=new Fe({sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(e).catch((e=>{u.error("telnyx_rtc.bye failed!",e),U(m.Error,{error:e,sessionId:this.session.sessionid},this.session.uuid)})).then(a.bind(this))}else a()}hold(){const e=new He({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 He({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 He({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 We({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(t)}message(e,t){const n={from:this.session.options.login,to:e,body:t},i=new We({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(i)}muteAudio(){xe(this.options.localStream)}unmuteAudio(){Re(this.options.localStream)}toggleAudioMute(){Me(this.options.localStream)}setAudioInDevice(e){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}}}),i=t.getAudioTracks()[0];n.replaceTrack(i),this.options.micId=e;const{localStream:s}=this.options;s.getAudioTracks().forEach((e=>e.stop())),s.getVideoTracks().forEach((e=>t.addTrack(e))),this.options.localStream=t}}))}muteVideo(){var e;e=this.options.localStream,Te(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Te(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Te(e,"video",null)}setVideoDevice(e){return t(this,void 0,void 0,(function*(){const{instance:t}=this.peer,n=t.getSenders().find((({track:{kind:e}})=>"video"===e));if(n){const t=yield de({video:{deviceId:{exact:e}}}),i=t.getVideoTracks()[0];n.replaceTrack(i);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(){xe(this.options.remoteStream)}undeaf(){Re(this.options.remoteStream)}toggleDeaf(){Me(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return t(this,void 0,void 0,(function*(){if(!this||!this.peer)return void u.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,i=t.getSenders();if(!i)return void u.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=i.find((({track:{kind:e}})=>e===n));if(s){const t=s.getParameters();t.encodings||(t.encodings=[{rid:"h"}]),u.info("Parameters: ",t),u.info("Setting max ","audio"===n?"audio":"video"," bandwidth to: ",e," [bps]"),t.encodings[0].maxBitrate=e,yield s.setParameters(t).then((()=>{u.info("audio"===n?"New audio":"New video"," bandwidth settings in use: ",s.getParameters())})).catch((e=>console.error(e)))}else u.error("Could not set bandwidth (reason: no "+n+" 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 n={callback:e,constraints:t};if(this._statsBindings.push(n),!this._statsIntervalId){const e=2e3;this._startStats(e)}}setState(e){switch(this._prevState=this._state,this._state=e,this.state=H[this._state].toLowerCase(),this.prevState=H[this._prevState].toLowerCase(),u.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:B.callUpdate,call:this}),e){case H.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case H.Active:setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&he(e,t)}),0);break;case H.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:n}=e;switch(t){case G.Answer:if(this.gotAnswer=!0,this._state>=H.Active)return;this._state>=H.Early&&this.setState(H.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case G.Media:if(this._state>=H.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case G.Display:case G.Attach:{const{display_name:e,display_number:i,display_direction:s}=n;this.extension=i;const o=s===V.Inbound?V.Outbound:V.Inbound,r={type:B[t],call:this,displayName:e,displayNumber:i,displayDirection:o};U(m.Notification,r,this.id)||U(m.Notification,r,this.session.uuid);break}case G.Info:case G.Event:{const e=Object.assign(Object.assign({},n),{type:B.generic,call:this});U(m.Notification,e,this.id)||U(m.Notification,e,this.session.uuid);break}case G.Ringing:this.playRingback(),n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id);break;case G.Bye:const e=n.client_state||n.clientState;e&&(this.options.clientState=e),this.stopRingback(),this.stopRingtone(),this.hangup(n,!1)}}handleConferenceUpdate(e,n){return t(this,void 0,void 0,(function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return u.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:t,data:i,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}=n;this._dispatchConferenceUpdate({action:q.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),t&&(yield this._subscribeConferenceInfo(t)),s&&a===W.Moderator&&(yield this._subscribeConferenceModerator(s));const c=[];for(const e in i)c.push(Object.assign({callId:i[e][0],index:Number(e)},y(i[e][1])));this._dispatchConferenceUpdate({action:q.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:q.Add,callId:s,index:o},y(i)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:q.Modify,callId:s,index:o},y(i)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:q.Delete,callId:s,index:o},y(i)));break;case"clear":this._dispatchConferenceUpdate({action:q.Clear});break;default:this._dispatchConferenceUpdate({action:t,data:i,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:n,fromDisplay:i,message:s,type:o}=e.data;this._dispatchConferenceUpdate({action:q.ChatMessage,direction:t,participantNumber:n,participantName:i,messageText:s,messageType:o,messageId:e.eventSerno})}},n=yield this.session.vertoSubscribe(t).catch((e=>{u.error("ConfChat subscription error:",e)}));Ee(n,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(t,n)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:t,type:n}})}}}))}))}_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,ze(this.session,t);else u.error("Conference-Info unknown contentType",e)}},n=yield this.session.vertoSubscribe(t).catch((e=>{u.error("ConfInfo subscription error:",e)}));Ee(n,e)&&this._addChannel(e)}))}_confControl(e,t={}){const n=Object.assign({application:"conf-control",callID:this.id,value:null},t);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:n})}_subscribeConferenceModerator(e){return t(this,void 0,void 0,(function*(){const t=(t,n=null,i=null)=>{const s=parseInt(n)||null;this._confControl(e,{command:t,id:s,value:i})},n=()=>{const{video:e}=this.options;if("boolean"==typeof e&&!e||"object"==typeof e&&b(e))throw`Conference ${this.id} has no video!`},i={nodeId:this.nodeId,channels:[e],handler:e=>{const{data:t}=e;if("list-videoLayouts"===t["conf-command"]){if(t.responseData){const e=JSON.stringify(t.responseData).replace(/IDS"/g,'Ids"');this._dispatchConferenceUpdate({action:q.LayoutList,layouts:JSON.parse(e)})}}else this._dispatchConferenceUpdate({action:q.ModCmdResponse,command:t["conf-command"],response:t.response})}},s=yield this.session.vertoSubscribe(i).catch((e=>{u.error("ConfMod subscription error:",e)}));Ee(s,e)&&(this.role=W.Moderator,this._addChannel(e),Object.defineProperties(this,{listVideoLayouts:{configurable:!0,value:()=>{t("list-videoLayouts")}},playMedia:{configurable:!0,value:e=>{t("play",null,e)}},stopMedia:{configurable:!0,value:()=>{t("stop",null,"all")}},deaf:{configurable:!0,value:e=>{t("deaf",e)}},undeaf:{configurable:!0,value:e=>{t("undeaf",e)}},startRecord:{configurable:!0,value:e=>{t("recording",null,["start",e])}},stopRecord:{configurable:!0,value:()=>{t("recording",null,["stop","all"])}},snapshot:{configurable:!0,value:e=>{n(),t("vid-write-png",null,e)}},setVideoLayout:{configurable:!0,value:(e,i)=>{n();t("vid-layout",null,i?[e,i]:e)}},kick:{configurable:!0,value:e=>{t("kick",e)}},muteMic:{configurable:!0,value:e=>{t("tmute",e)}},muteVideo:{configurable:!0,value:e=>{n(),t("tvmute",e)}},presenter:{configurable:!0,value:e=>{n(),t("vid-res-id",e,"presenter")}},videoFloor:{configurable:!0,value:e=>{n(),t("vid-floor",e,"force")}},banner:{configurable:!0,value:(e,i)=>{n(),t("vid-banner",e,encodeURI(i))}},volumeDown:{configurable:!0,value:e=>{t("volume_out",e,"down")}},volumeUp:{configurable:!0,value:e=>{t("volume_out",e,"up")}},gainDown:{configurable:!0,value:e=>{t("volume_in",e,"down")}},gainUp:{configurable:!0,value:e=>{t("volume_in",e,"up")}},transfer:{configurable:!0,value:(e,n)=>{t("transfer",e,n)}}}))}))}_handleChangeHoldStateSuccess(e){return"active"===e.holdState?this.setState(H.Active):this.setState(H.Held),!0}_handleChangeHoldStateError(e){return u.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){let t=Ce(e,this.peer.instance.localDescription.sdp);this.options.useStereo&&(t=we(t));const n={sdp:t,type:$.Answer};this.peer.instance.setRemoteDescription(n).then((()=>{this.gotEarly&&this.setState(H.Early),this.gotAnswer&&this.setState(H.Active)})).catch((e=>{u.error("Call setRemoteDescription Error: ",e),this.hangup()}))}_requestAnotherLocalDescription(){w(this.peer.onSdpReadyTwice)?U(m.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,n;this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:i,type:s}=e;if(-1===i.indexOf("candidate"))return u.info("No candidate - retry \n"),void this._requestAnotherLocalDescription();null===(n=null===(t=this.peer)||void 0===t?void 0:t.instance)||void 0===n||n.removeEventListener("icecandidate",this._onIce);let o=null;const r={sessid:this.session.sessionid,sdp:i,dialogParams:this.options,"User-Agent":`Web-${st}`};switch(s){case $.Offer:this.setState(H.Requesting),o=new Ve(r);break;case $.Answer:this.setState(H.Answering),o=!0===this.options.attach?new Be(r):new Ge(r);break;default:return u.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}this._execute(o).then((e=>{const{node_id:t=null}=e;this._targetNodeId=t,s===$.Offer?this.setState(H.Trying):this.setState(H.Active)})).catch((e=>{u.error(`${this.id} - Sending ${s} error:`,e),this.hangup()})),console.timeEnd(p)}_onIce(e){const{instance:t}=this.peer;null===this._iceTimeout&&(this._iceTimeout=setTimeout((()=>this._onIceSdp(t.localDescription)),1e3)),e.candidate?u.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(t.localDescription)}_registerPeerEvents(){const{instance:e}=this.peer;this._iceDone=!1,e.onicecandidate=e=>{this._iceDone||this._onIce(e)},e.addEventListener("addstream",(e=>{this.options.remoteStream=e.stream})),e.addEventListener("track",(e=>{this.options.remoteStream=e.streams[0];const{remoteElement:t,remoteStream:n,screenShare:i}=this.options;!1===i&&ue(t,n)}))}_onMediaError(e){this._dispatchNotification({type:B.userMediaError,error:e}),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:B.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(U(m.Notification,e,this.id,!1)||U(m.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:n,onNotification:i}=this.options;e||(this.options.id=a()),this.id=this.options.id,t&&!b(t)||(this.options.userVariables=this.session.options.userVariables||{}),n||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,N(m.MediaError,this._onMediaError,this.id),w(i)&&N(m.Notification,i.bind(this),this.id),this.setState(H.New),u.info("New Call with Options:",this.options)}_finalize(){this._stopStats(),this.peer&&this.peer.instance&&(this.peer.instance.close(),this.peer=null);const{remoteStream:e,localStream:t}=this.options;ge(e),ge(t),P(m.MediaError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),u.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),u.info("Stats stopped")}}ot.setStateTelnyx=e=>{if(e){switch(e._state){case H.Requesting:case H.Recovering:case H.Trying:case H.Early:e.state="connecting";break;case H.Active:e.state="active";break;case H.Held:e.state="held";break;case H.Hangup:case H.Destroy:e.state="done";break;case H.Answering:e.state="ringing";break;case H.New:e.state="new"}return e}};class rt extends ot{constructor(){super(...arguments),this._statsInterval=null}hangup(e={},t=!0){this.screenShare instanceof rt&&this.screenShare.hangup(e,t),super.hangup(e,t)}startScreenShare(e){return t(this,void 0,void 0,(function*(){const t=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;t.getTracks().forEach((e=>{e.addEventListener("ended",(()=>{this.screenShare&&this.screenShare.hangup()}))}));const{remoteCallerName:i,remoteCallerNumber:s,callerName:o,callerNumber:r}=this.options,a=Object.assign({screenShare:!0,localStream:t,destinationNumber:`${this.extension}-screen`,remoteCallerName:i,remoteCallerNumber:`${s}-screen`,callerName:`${o} (Screen)`,callerNumber:`${r} (Screen)`},e);return this.screenShare=new rt(this.session,a),this.screenShare.invite(),this.screenShare}))}stopScreenShare(){this.screenShare instanceof rt&&this.screenShare.hangup()}setAudioOutDevice(e){return t(this,void 0,void 0,(function*(){this.options.speakerId=e;const{remoteElement:t,speakerId:n}=this.options;return!(!t||!n)&&he(t,n)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);u.setLevel(2),this._statsInterval=window.setInterval((()=>t(this,void 0,void 0,(function*(){const e=yield this.peer.instance.getStats(null);let t="";const n=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],i=["id","type","timestamp"];e.forEach((e=>{n.includes(e.type)||(t+=`\n${e.type}\n`,Object.keys(e).forEach((n=>{i.includes(n)||(t+=`\t${n}: ${e[n]}\n`)})))})),u.info(t)}))),2e3)}}class at extends ce{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile}get reconnectDelay(){return 1e3}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,n=!0){return t(this,void 0,void 0,(function*(){try{const t=yield fe({audio:e,video:n});return ge(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(H.Purge))),this.calls={},yield e.disconnect.call(this)}))}speedTest(e){return new Promise(((t,n)=>{if(O(m.SpeedTest,(n=>{const{upDur:i,downDur:s}=n,o=s?8*e/(s/1e3)/1024:0;t({upDur:i,downDur:s,upKps:(i?8*e/(i/1e3)/1024:0).toFixed(0),downKps:o.toFixed(0)})}),this.uuid),!(e=Number(e)))return n(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let i=e/1024;e%1024&&i++;const s=".".repeat(1024);for(let e=0;e<i;e++)this.executeRaw(`#SPB ${s}`);this.executeRaw("#SPE")}))}getDevices(){return ve().catch((e=>(U(m.MediaError,e,this.uuid),[])))}getVideoDevices(){return ve(K.Video).catch((e=>(U(m.MediaError,e,this.uuid),[])))}getAudioInDevices(){return ve(K.AudioIn).catch((e=>(U(m.MediaError,e,this.uuid),[])))}getAudioOutDevices(){return ve(K.AudioOut).catch((e=>(console.error("getAudioOutDevices",e),U(m.MediaError,e,this.uuid),[])))}validateDeviceId(e,t,n){return be(e,t,n)}getDeviceResolutions(e){return t(this,void 0,void 0,(function*(){try{return yield(e=>t(void 0,void 0,void 0,(function*(){const t=[],n=yield fe({video:{deviceId:{exact:e}}}),i=n.getVideoTracks()[0];for(let e=0;e<me.length;e++){const[n,s]=me[e];(yield i.applyConstraints({width:{exact:n},height:{exact:s}}).then((()=>!0)).catch((()=>!1)))&&t.push({resolution:`${n}x${s}`,width:n,height:s})}return ge(n),t})))(e)}catch(e){throw e}}))}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(n){return t(this,void 0,void 0,(function*(){if(!n)throw new Error("You need to provide the settings object");const{micId:t,micLabel:i}=n,s=e(n,["micId","micLabel"]);return ye(s),this._audioConstraints=yield _e(t,i,"audioinput",s),this.micId=t,this.micLabel=i,this._audioConstraints}))}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}setVideoSettings(n){return t(this,void 0,void 0,(function*(){if(!n)throw new Error("You need to provide the settings object");const{camId:t,camLabel:i}=n,s=e(n,["camId","camLabel"]);return ye(s),this._videoConstraints=yield _e(t,i,"videoinput",s),this.camId=t,this.camLabel=i,this._videoConstraints}))}disableWebcam(){this._videoConstraints=!1}enableWebcam(){this._videoConstraints=!0}set iceServers(e){const t={urls:["stun:stun.l.google.com:19302"]};this._iceServers="boolean"==typeof e?e?[t]:[]:e||[v,f,t]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=S(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=S(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:t="",data:n}){if(!t)throw new Error(`Invalid channel for broadcast: ${t}`);const i=new qe({sessid:this.sessionid,eventChannel:t,data:n});e&&(i.targetNodeId=e),this.execute(i).catch((e=>e))}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return t(this,void 0,void 0,(function*(){if(!(n=n.filter((e=>e&&!this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new Ke({sessid:this.sessionid,eventChannel:n});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,i,e))),s}))}vertoUnsubscribe({nodeId:e,channels:n=[]}){return t(this,void 0,void 0,(function*(){if(!(n=n.filter((e=>e&&this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new Je({sessid:this.sessionid,eventChannel:n});e&&(t.targetNodeId=e);const i=yield this.execute(t),{unsubscribed:s=[],notSubscribed:o=[]}=ke(i);return s.forEach((e=>this._removeSubscription(this.relayProtocol,e))),o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),i}))}static telnyxStateCall(e){return rt.setStateTelnyx(e)}}class ct{constructor(e,t){this.code=t,this.message=e}}class dt extends oe{constructor(){super(),this.method=G.Ping;this.buildRequest({method:this.method,params:{}})}}class lt{constructor(e){this.session=e}_ack(e,t){const n=new $e(e,t);this.nodeId&&(n.targetNodeId=this.nodeId),this.session.execute(n)}reconnectDelay(){return 1e3*E(2,6)}handleMessage(e){const{session:t}=this,{id:n,method:i,params:s={}}=e,o=null==s?void 0:s.callID,r=null==s?void 0:s.eventChannel,a=null==s?void 0:s.eventType,c=i===G.Attach;if("channelPvtData"===a)return this._handlePvtEvent(s.pvtData);if(o&&t.calls.hasOwnProperty(o)){if(!c)return t.calls[o].handleMessage(e),void this._ack(n,i);t.calls[o].hangup({},!1)}const d=()=>{var e,n,i,r;const a={id:o,remoteSdp:s.sdp,destinationNumber:s.callee_id_number,remoteCallerName:s.caller_id_name,remoteCallerNumber:s.caller_id_number,callerName:s.callee_id_name,callerNumber:s.callee_id_number,attach:c,mediaSettings:s.mediaSettings,debug:null!==(e=t.options.debug)&&void 0!==e&&e,debugOutput:null!==(n=t.options.debugOutput)&&void 0!==n?n:"socket",prefetchIceCandidates:null!==(i=t.options.prefetchIceCandidates)&&void 0!==i&&i,forceRelayCandidate:null!==(r=t.options.forceRelayCandidate)&&void 0!==r&&r};s.telnyx_call_control_id&&(a.telnyxCallControlId=s.telnyx_call_control_id),s.telnyx_session_id&&(a.telnyxSessionId=s.telnyx_session_id),s.telnyx_leg_id&&(a.telnyxLegId=s.telnyx_leg_id),s.client_state&&(a.clientState=s.client_state),s.dialogParams&&s.dialogParams.custom_headers&&s.dialogParams.custom_headers.length&&(a.customHeaders=s.dialogParams.custom_headers);const d=new rt(t,a);return d.nodeId=this.nodeId,d},l=new re,h=new dt;switch(i){case G.Ping:this.session.execute(h);break;case G.Punt:t.disconnect();break;case G.Invite:{const e=d();e.playRingtone(),e.setState(H.Ringing),e.direction=V.Inbound,this._ack(n,i);break}case G.Attach:{const t=d();this.session.autoRecoverCalls?t.answer():t.setState(H.Recovering),t.handleMessage(e);break}case G.Event:case"webrtc.event":if(!r)return void u.error("Verto received an unknown event:",s);const o=t.relayProtocol,a=r.split(".")[0];t._existsSubscription(o,r)?U(o,s,r):r===t.sessionid?this._handleSessionEvent(s.eventData):t._existsSubscription(o,a)?U(o,s,a):t.calls.hasOwnProperty(r)?t.calls[r].handleMessage(e):U(m.Notification,s,t.uuid);break;case G.Info:s.type=B.generic,U(m.Notification,s,t.uuid);break;case G.ClientReady:this.session.execute(l);break;default:{const n=T(e);if(n){switch(n){case J.REGISTER:case J.REGED:t.connection.previousGatewayState!==J.REGED&&t.connection.previousGatewayState!==J.REGISTER&&(lt.retriedRegister=0,s.type=B.vertoClientReady,U(m.Ready,s,t.uuid));break;case J.UNREGED:case J.NOREG:if(lt.retriedRegister+=1,5===lt.retriedRegister){lt.retriedRegister=0,U(m.Error,{error:new ct("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:t.sessionid},t.uuid);break}setTimeout((()=>{this.session.execute(l)}),this.reconnectDelay());break;case J.FAILED:case J.FAIL_WAIT:if(t.connection.previousGatewayState!==J.FAILED&&t.connection.previousGatewayState!==J.FAIL_WAIT){if(!this.session.hasAutoReconnect()){lt.retriedConnect=0,U(m.Error,{error:new ct("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:t.sessionid},t.uuid);break}if(lt.retriedConnect+=1,5===lt.retriedConnect){lt.retriedConnect=0,U(m.Error,{error:new Error("Connection Retry Failed"),sessionId:t.sessionid},t.uuid);break}setTimeout((()=>{this.session.disconnect().then((()=>{this.session.clearConnection(),this.session.connect()}))}),this.reconnectDelay())}break;default:u.warn("GatewayState message unknown method:",e)}break}u.warn("Verto message unknown method:",e);break}}}_retrieveCallId(e,t){const n=Object.keys(this.session.calls);if("bootObj"!==e.action)return n.find((e=>this.session.calls[e].channels.includes(t)));{const t=e.data.find((e=>n.includes(e[0])));if(t instanceof Array)return t[0]}}_handlePvtEvent(e){return t(this,void 0,void 0,(function*(){const{session:t}=this,n=t.relayProtocol,{action:i,laChannel:s,laName:o,chatChannel:r,infoChannel:a,modChannel:c,conferenceMemberID:d,role:l,callID:h}=e;switch(i){case"conference-liveArray-join":{const n=()=>{t.vertoBroadcast({nodeId:this.nodeId,channel:s,data:{liveArray:{command:"bootstrap",context:s,name:o}}})},i={nodeId:this.nodeId,channels:[s],handler:({data:i})=>{const r=h||this._retrieveCallId(i,s);if(r&&t.calls.hasOwnProperty(r)){const a=t.calls[r];a._addChannel(s),a.extension=o,a.handleConferenceUpdate(i,e).then((e=>{"INVALID_PACKET"===e&&n()}))}}},r=yield t.vertoSubscribe(i).catch((e=>{u.error("liveArray subscription error:",e)}));Ee(r,s)&&n();break}case"conference-liveArray-part":{let e=null;if(s&&t._existsSubscription(n,s)){const{callId:i=null}=t.subscriptions[n][s];if(e=t.calls[i]||null,null!==i){const n={type:B.conferenceUpdate,action:q.Leave,conferenceName:o,participantId:Number(d),role:l};U(m.Notification,n,i,!1)||U(m.Notification,n,t.uuid),null===e&&P(m.Notification,null,i)}}const i=[s,r,a,c];t.vertoUnsubscribe({nodeId:this.nodeId,channels:i}).then((({unsubscribedChannels:t=[]})=>{e&&(e.channels=e.channels.filter((e=>!t.includes(e))))})).catch((e=>{u.error("liveArray unsubscribe error:",e)}));break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":ze(this.session,e);break;case"logo-info":{const t={type:B.conferenceUpdate,action:q.LogoInfo,logo:e.logoURL};U(m.Notification,t,this.session.uuid);break}}}}lt.retriedConnect=0,lt.retriedRegister=0;class ut extends at{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,window.addEventListener("beforeunload",(e=>{this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&this.calls[e].hangup({},!0)}))}))}validateOptions(){return k(this.options)}newCall(e){if(!e||!e.destinationNumber)throw new Error("Verto.newCall() error: destinationNumber is required.");console.time(p);const t=new rt(this,e);return t.invite(),t}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){this._idle=!1;const{login:e,password:t,passwd:n,login_token:i,userVariables:s,autoReconnect:o=!0}=this.options,r=new je(e,t||n,i,this.sessionid,s,!!Y()),a=yield this.execute(r).catch(this._handleLoginError);a&&(this._autoReconnect=o,this.sessionid=a.sessid)}))}_onSocketMessage(e){new lt(this).handleMessage(e)}}class ht extends ut{constructor(e){super(e),console.log(`SDK version: ${Pe}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return De()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",supported:Ae.not_supported},{browserName:"Edge",supported:Ae.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Ae.not_supported},{browserName:"Firefox",supported:Ae.not_supported},{browserName:"Safari",features:["video","audio"],supported:Ae.full},{browserName:"Edge",supported:Ae.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",supported:Ae.not_supported},{browserName:"Edge",supported:Ae.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",features:["video","audio"],supported:Ae.full},{browserName:"Edge",features:["audio"],supported:Ae.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",supported:Ae.not_supported},{browserName:"Edge",features:["audio"],supported:Ae.partial}]}]}}export{ht as TelnyxRTC};
1
+ function e(e,t){var n={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(i=Object.getOwnPropertySymbols(e);s<i.length;s++)t.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(e,i[s])&&(n[i[s]]=e[i[s]])}return n}function t(e,t,n,i){return new(n||(n=Promise))((function(s,o){function r(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var n="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto),i=new Uint8Array(16);function s(){if(!n)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return n(i)}for(var o=[],r=0;r<256;++r)o[r]=(r+256).toString(16).substr(1);function a(e,t,n){var i=t&&n||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[i+a]=r[a];return t||function(e,t){var n=t||0,i=o;return[i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],"-",i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]],i[e[n++]]].join("")}(r)}var c="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function d(e,t){return e(t={exports:{}},t.exports),t.exports}var l=d((function(e){var t,n;t=c,n=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function s(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[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,n){for(var s=0;s<i.length;s++){var o=i[s];this[o]=s<t?e:this.methodFactory(o,t,n)}this.log=this.debug}function a(e,n,i){return function(){typeof console!==t&&(r.call(this,n,i),this[e].apply(this,arguments))}}function c(i,r,c){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?o:void 0!==console[i]?s(console,i):void 0!==console.log?s(console,"log"):e)}(i)||a.apply(this,arguments)}function d(e,n,s){var o,a=this;n=null==n?"WARN":n;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 n=window.document.cookie,i=n.indexOf(encodeURIComponent(d)+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i))[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(n,s){if("string"==typeof n&&void 0!==a.levels[n.toUpperCase()]&&(n=a.levels[n.toUpperCase()]),!("number"==typeof n&&n>=0&&n<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(o=n,!1!==s&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&d){try{return void(window.localStorage[d]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(d)+"="+n+";"}catch(e){}}}(n),r.call(a,n,e),typeof console===t&&n<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){n=e,l()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(n,!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=n),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=n():t.log=n()}));const u=l.getLogger("telnyx"),h=u.methodFactory;u.methodFactory=(e,t,n)=>{const i=h(e,t,n);return function(){const e=[(new Date).toISOString().replace("T"," ").replace("Z",""),"-"];for(let t=0;t<arguments.length;t++)e.push(arguments[t]);i.apply(void 0,e)}},u.setLevel(u.getLevel());const p="Time to call invite",g="wss://rtc.telnyx.com",f={urls:"stun:stun.telnyx.com:3478"},v={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var m;!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"}(m||(m={}));const b=e=>0===Object.keys(e).length,y=e=>{const[t,n,i,s,o,r]=e;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch(e){u.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(t),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},_=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}},w=e=>e instanceof Function||"function"==typeof e,S=e=>"object"==typeof document&&"getElementById"in document?"string"==typeof e?document.getElementById(e)||null:"function"==typeof e?e():e instanceof HTMLMediaElement?e:null:null,I=/^(ws|wss):\/\//,C=(e,t=null)=>{const{result:n={},error:i}=e;if(i)return{error:i};const{result:s=null}=n;if(null===s)return null!==t&&(n.node_id=t),{result:n};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&"200"!==o?{error:s}:a?C(a,r):{result:s}},k=(e,t)=>Math.floor(Math.random()*(t-e+1)+e),E=({login:e,passwd:t,password:n,login_token:i})=>Boolean(e&&(t||n)||i),T=e=>{var t,n,i,s,o,r;let a="",c="";(null===(n=null===(t=null==e?void 0:e.result)||void 0===t?void 0:t.params)||void 0===n?void 0:n.state)&&(a=null===(s=null===(i=null==e?void 0:e.result)||void 0===i?void 0:i.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 R({debounceTime:e}){let t,n;return{promise:new Promise(((i,s)=>{t=e?x(i,e):i,n=s})),resolve:t,reject:n}}const x=(e,t)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout((()=>{e(...i)}),t)}},M="GLOBAL",L={},A=(e,t)=>`${e}|${t}`,D=(e,t=M)=>A(e,t)in L,N=(e,t,n=M)=>{const i=A(e,n);i in L||(L[i]=[]),L[i].push(t)},O=(e,t,n=M)=>{const i=function(s){P(e,i,n),t(s)};return i.prototype.targetRef=t,N(e,i,n)},P=(e,t,n=M)=>{if(!D(e,n))return!1;const i=A(e,n);if(w(t)){for(let e=L[i].length-1;e>=0;e--){const n=L[i][e];(t===n||n.prototype&&t===n.prototype.targetRef)&&L[i].splice(e,1)}}else L[i]=[];return 0===L[i].length&&delete L[i],!0},U=(e,t,n=M,i=!0)=>{const s=i&&n!==M;if(!D(e,n))return s&&U(e,t),!1;const o=A(e,n),r=L[o].length;if(!r)return s&&U(e,t),!1;for(let e=r-1;e>=0;e--)L[o][e](t);return s&&U(e,t),!0},j=e=>{const t=A(e,"");Object.keys(L).filter((e=>0===e.indexOf(t))).forEach((e=>delete L[e]))};var $,V,G;!function(e){e.Offer="offer",e.Answer="answer"}($||($={})),function(e){e.Inbound="inbound",e.Outbound="outbound"}(V||(V={})),function(e){e.Invite="telnyx_rtc.invite",e.Attach="telnyx_rtc.attach",e.Answer="telnyx_rtc.answer",e.Info="telnyx_rtc.info",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 B={generic:"event",[G.Display]:"participantData",[G.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError"},F={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,video:!1,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0}};var H,W,q,K,J;!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"}(H||(H={})),function(e){e.Participant="participant",e.Moderator="moderator"}(W||(W={})),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"}(q||(q={})),function(e){e.Video="videoinput",e.AudioIn="audioinput",e.AudioOut="audiooutput"}(K||(K={})),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"}(J||(J={}));const z="telnyx-voice-sdk-id";function Y(){return sessionStorage.getItem(z)}"undefined"!=typeof window&&window.addEventListener("beforeunload",(()=>{sessionStorage.removeItem(z)}));let Q="undefined"!=typeof WebSocket?WebSocket:null;const X=0,Z=1,ee=2,te=3;class ne{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=g,this._timers={},this.upDur=null,this.downDur=null;const{host:t,env:n}=e.options;t&&(this._host=(e=>`${I.test(e)?"":"wss://"}${e}`)(t)),n&&(this._host="development"===n?"wss://rtcdev.telnyx.com":g)}get connected(){return this._wsClient&&this._wsClient.readyState===Z}get connecting(){return this._wsClient&&this._wsClient.readyState===X}get closing(){return this._wsClient&&this._wsClient.readyState===ee}get closed(){return this._wsClient&&this._wsClient.readyState===te}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){const e=new URL(this._host),t=Y();t&&e.searchParams.set("voice_sdk_id",t),this._wsClient=new Q(e.toString()),this._wsClient.onopen=e=>U(m.SocketOpen,e,this.session.uuid),this._wsClient.onclose=e=>U(m.SocketClose,e,this.session.uuid),this._wsClient.onerror=e=>U(m.SocketError,{error:e,sessionId:this.session.sessionid},this.session.uuid),this._wsClient.onmessage=e=>{var t,n;const i=_(e.data);var s;if("string"!=typeof i){if(i.voice_sdk_id&&(s=i.voice_sdk_id,sessionStorage.setItem(z,s)),this._unsetTimer(i.id),u.debug("RECV: \n",JSON.stringify(i,null,2),"\n"),J[`${null===(n=null===(t=null==i?void 0:i.result)||void 0===t?void 0:t.params)||void 0===n?void 0:n.state}`]||!U(i.id,i)){const e=T(i);U(m.SocketMessage,i,this.session.uuid),Boolean(e)&&(this.previousGatewayState=e)}}else this._handleStringResponse(i)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:t}=e,n=new Promise(((e,n)=>{if(t.hasOwnProperty("result"))return e();O(t.id,(t=>{const{result:i,error:s}=C(t);return s?n(s):e(i)}))}));return u.debug("SEND: \n",JSON.stringify(t,null,2),"\n"),this._wsClient.send(JSON.stringify(t)),n}close(){this._wsClient&&(w(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close()),this._wsClient=null}_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)),U(m.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else u.warn("Unknown message from socket",e)}}class ie{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:a()},e)}}const se={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 oe extends ie{constructor(t={}){if(super(),t.hasOwnProperty("dialogParams")){const n=e(t.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const e in se)e&&n.hasOwnProperty(e)&&(n[se[e]]=n[e],delete n[e]);t.dialogParams=n}this.buildRequest({method:this.toString(),params:t})}}class re extends oe{constructor(){super(),this.method=G.GatewayState;this.buildRequest({method:this.method,params:{}})}}class ae{constructor(e){this.pendingRequestId=null,this.onSocketMessage=e=>t(this,void 0,void 0,(function*(){e.id===this.pendingRequestId&&this.gatewayStateTask.resolve(T(e))})),this.getIsRegistered=()=>t(this,void 0,void 0,(function*(){const e=new re;this.pendingRequestId=e.request.id,this.gatewayStateTask=R({}),this.session.execute(e);const t=yield this.gatewayStateTask.promise;return!!t&&[J.REGISTER,J.REGED].includes(t)})),this.session=e,this.gatewayStateTask=R({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class ce{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.connection=null,this._jwtAuth=!1,this._doKeepAlive=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");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 ne(this),this.registerAgent=new ae(this)}get __logger(){return u}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*k(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}),this.connect()}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return E(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()}))}on(e,t){return N(e,t,this.uuid),this}off(e,t){return P(e,t,this.uuid),this}connect(){return t(this,void 0,void 0,(function*(){this.connection||(this.connection=new ne(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()}))}_handleLoginError(e){U(m.Error,{error:e,sessionId:this.sessionid},this.uuid)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){}))}onNetworkClose(){this.relayProtocol&&j(this.relayProtocol);for(const e in this.subscriptions)j(e);this.subscriptions={},this.contexts=[],this._autoReconnect&&(this._reconnectTimeout=setTimeout((()=>this.connect()),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,t){this._existsSubscription(e,t)&&(t?(delete this.subscriptions[e][t],P(e,null,t)):(delete this.subscriptions[e],j(e)))}_addSubscription(e,t=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},w(t)&&N(e,t,n))}_existsSubscription(e,t){return!(!this.subscriptions.hasOwnProperty(e)||!(!t||t&&this.subscriptions[e].hasOwnProperty(t)))}_attachListeners(){this._detachListeners(),this.on(m.SocketOpen,this._onSocketOpen),this.on(m.SocketClose,this.onNetworkClose),this.on(m.SocketError,this.onNetworkClose),this.on(m.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(m.SocketOpen,this._onSocketOpen),this.off(m.SocketClose,this.onNetworkClose),this.off(m.SocketError,this.onNetworkClose),this.off(m.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()}_keepAlive(){!0===this._doKeepAlive&&(this._pong=!1,this._keepAliveTimeout=setTimeout((()=>this._keepAlive()),3e4))}static on(e,t){N(e,t)}static off(e){P(e)}static uuid(){return a()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}getIsRegistered(){return this.registerAgent.getIsRegistered()}}const de=e=>navigator.mediaDevices.getUserMedia(e),le=e=>e&&e instanceof MediaStream,ue=(e,t)=>{const n=S(e);null!==n&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=t)},he=(e,n)=>t(void 0,void 0,void 0,(function*(){const t=S(e);if(null===t)return u.info("No HTMLMediaElement to attach the speakerId"),!1;if("string"!=typeof n)return u.info(`Invalid speaker deviceId: '${n}'`),!1;try{return yield t.setSinkId(n),!0}catch(e){return!1}})),pe=e=>{e&&"live"===e.readyState&&e.stop()},ge=e=>{le(e)&&e.getTracks().forEach(pe),e=null},fe=e=>t(void 0,void 0,void 0,(function*(){u.info("RTCService.getUserMedia",e);const{audio:t,video:n}=e;if(!t&&!n)return null;try{return yield de(e)}catch(e){throw u.error("getUserMedia error: ",e),e}})),ve=(e=null,n=!1)=>t(void 0,void 0,void 0,(function*(){let t=[];const i=yield navigator.mediaDevices.getUserMedia(((e=null)=>({audio:!e||e===K.AudioIn||e===K.AudioOut,video:!e||e===K.Video}))(e)).catch((e=>(console.error(e),null)));if(i){if(ge(i),t=yield navigator.mediaDevices.enumerateDevices(),e&&(t=t.filter((t=>t.kind===e))),!0===n)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})),me=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],be=(e,n,i)=>t(void 0,void 0,void 0,(function*(){const t=yield ve(i,!0);for(let i=0;i<t.length;i++){const{deviceId:s,label:o}=t[i];if(e===s||n===o)return s}return null})),ye=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map((n=>{t.hasOwnProperty(n)&&null!==e[n]&&void 0!==e[n]||delete e[n]}))},_e=(e,n,i,s)=>t(void 0,void 0,void 0,(function*(){const{deviceId:t}=s;if(void 0===t&&(e||n)){const t=yield be(e,n,i).catch((e=>null));t&&(s.deviceId={exact:t})}return s})),we=e=>{const t="\r\n",n=e.split(t),i=n.findIndex((e=>/^a=rtpmap/.test(e)&&/opus\/48000/.test(e)));if(i<0)return e;const s=(e=>{const t=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),n=e.match(t);return n&&2==n.length?n[1]:null})(n[i]),o=new RegExp(`a=fmtp:${s}`),r=n.findIndex((e=>o.test(e)));return r>=0?/stereo=1;/.test(n[r])||(n[r]+="; stereo=1; sprop-stereo=1"):n[i]+=`${t}a=fmtp:${s} stereo=1; sprop-stereo=1`,n.join(t)},Se=e=>/^m=audio/.test(e),Ie=e=>/^m=video/.test(e),Ce=(e,t)=>{const n="\r\n",i=t.split(n);if(i.findIndex(Se)<i.findIndex(Ie))return e;const s=e.split(n),o=s.findIndex(Se),r=s.findIndex(Ie),a=s.slice(o,r),c=s.slice(r,s.length-1);return[...s.slice(0,o),...c,...a,""].join(n)},ke=(e,t)=>{if(!e)return!1;const{subscribed:n,alreadySubscribed:i}=Ee(e);return n.includes(t)||i.includes(t)},Ee=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach((n=>{t[n]=e[`${n}Channels`]||[]})),t},Te=(e,t=null,n=null)=>{if(!le(e))return null;let i=[];switch(t){case"audio":i=e.getAudioTracks();break;case"video":i=e.getVideoTracks();break;default:i=e.getTracks()}i.forEach((e=>{switch(n){case"on":case!0:e.enabled=!0;break;case"off":case!1:e.enabled=!1;break;default:e.enabled=!e.enabled}}))},Re=e=>{Te(e,"audio",!0)},xe=e=>{Te(e,"audio",!1)},Me=e=>{Te(e,"audio",null)};function Le(){try{const{browserInfo:e,name:t,version:n,supportAudio:i,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],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,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],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,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("/"),n=parseInt(t[1],10);return{browserInfo:navigator.userAgent,name:e,version:n,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],n=parseInt(e[1],10);return{browserInfo:navigator.userAgent,name:t,version:n,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:n,supportWebRTC:!!(o&&r&&a&&c&&d),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!fe}}catch(e){return e.message}}var Ae;function De(e,t){const n=document.getElementById(t);if(n)return n;if(e&&t){const n=document.createElement("audio");return n.id=t,n.loop=!0,n.src=e,n.preload="auto",n.load(),document.body.appendChild(n),n}return null}function Ne(e){e&&(e._playFulfilled=!1,e._promise=e.play(),e._promise.then((()=>{e._playFulfilled=!0})).catch((t=>{console.error("playAudio",t),e._playFulfilled=!0})))}function Oe(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"}(Ae||(Ae={}));var Pe="2.22.7",Ue=Pe;class je extends oe{constructor(e,t,n,i,s={},o){super(),this.method="login";const r={login:e,passwd:t,login_token:n,userVariables:s,reconnection:o,loginParams:{},"User-Agent":{sdkVersion:Ue,data:navigator.userAgent}};i&&(r.sessid=i),this.buildRequest({method:this.method,params:r})}}class $e extends oe{constructor(e,t){super(),this.buildRequest({id:e,result:{method:t}})}}class Ve extends oe{toString(){return G.Invite}}class Ge extends oe{toString(){return G.Answer}}class Be extends oe{toString(){return G.Attach}}class Fe extends oe{toString(){return G.Bye}}class He extends oe{toString(){return G.Modify}}class We extends oe{toString(){return G.Info}}class qe extends oe{toString(){return G.Broadcast}}class Ke extends oe{toString(){return G.Subscribe}}class Je extends oe{toString(){return G.Unsubscribe}}const ze=(e,t)=>{const{contentType:n,canvasType:i,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&"mcu-personal-canvas"!==i&&delete o.memberID;const a={type:B.conferenceUpdate,call:e.calls[s],canvasInfo:Ye(o),currentLayerIdx:r};switch(n){case"layer-info":{const t=Object.assign({action:q.LayerInfo},a);U(m.Notification,t,e.uuid);break}case"layout-info":{const t=Object.assign({action:q.LayoutInfo},a);U(m.Notification,t,e.uuid);break}}},Ye=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return _(t)};function Qe(e){const{packetsLost:t,packetsReceived:n,jitter:i,rtt:s}=e,o=function(e){const{jitter:t,rtt:n}=e,i=t+n/2;return.024*i+.11*(i-177.3)*(i>177.3?1:0)}({rtt:s,jitter:i}),r=function(e){const{packetsLost:t,packetsReceived:n}=e,i=t/(n+t)*100;return 20*Math.log(1+i)}({packetsLost:t,packetsReceived:n}),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 Xe(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"}var Ze,et=d((function(e,t){var n;function i(){}function s(){s.init.call(this)}function o(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function r(e,t,n,s){var r,a,c;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),c=a[t]):(a=e._events=new i,e._eventsCount=0),c){if("function"==typeof c?c=a[t]=s?[n,c]:[c,n]:s?c.unshift(n):c.push(n),!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]=n,++e._eventsCount;return e}function a(e,t,n){function i(){e.removeListener(t,i),s||(s=!0,n.apply(e,arguments))}var s=!1;return i.listener=n,i}function c(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function d(e,t){for(var n=Array(t);t--;)n[t]=e[t];return n}Object.defineProperty(t,"__esModule",{value:!0}),i.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&&n.active&&!(this instanceof n.Domain)&&(this.domain=n.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new i,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,n,i,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(!(n=r[e]))return!1;var u="function"==typeof n;switch(i=arguments.length){case 1:!function(e,t,n){if(t)e.call(n);else for(var i=e.length,s=d(e,i),o=0;o<i;++o)s[o].call(n)}(n,u,this);break;case 2:!function(e,t,n,i){if(t)e.call(n,i);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].call(n,i)}(n,u,this,arguments[1]);break;case 3:!function(e,t,n,i,s){if(t)e.call(n,i,s);else for(var o=e.length,r=d(e,o),a=0;a<o;++a)r[a].call(n,i,s)}(n,u,this,arguments[1],arguments[2]);break;case 4:!function(e,t,n,i,s,o){if(t)e.call(n,i,s,o);else for(var r=e.length,a=d(e,r),c=0;c<r;++c)a[c].call(n,i,s,o)}(n,u,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=Array(i-1),o=1;o<i;o++)s[o-1]=arguments[o];!function(e,t,n,i){if(t)e.apply(n,i);else for(var s=e.length,o=d(e,s),r=0;r<s;++r)o[r].apply(n,i)}(n,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 n,s,o,r,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(s=this._events))return this;if(!(n=s[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new i:(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(o=-1,r=n.length;0<r--;)if(n[r]===t||n[r].listener&&n[r].listener===t){a=n[r].listener,o=r;break}if(0>o)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new i,this;delete s[e]}else!function(e,t){for(var n=t,i=n+1,s=e.length;i<s;n+=1,i+=1)e[n]=e[i];e.pop()}(n,o);s.removeListener&&this.emit("removeListener",e,a||t)}return this},s.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new i,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new i:delete n[e]),this;if(0===arguments.length){for(var s,o=Object.keys(n),r=0;r<o.length;++r)"removeListener"!==(s=o[r])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if("function"==typeof(t=n[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,n,i=this._events;return i?n=(t=i[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[]:n=[],n},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=[],f=0;256>f;++f)g.push((f+256).toString(16).substr(1));function v(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:0,n=(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)}(n))throw TypeError("Stringified UUID is invalid");return n}function m(e,t,n){var i=(e=e||{}).random||(e.rng||h)();if(i[6]=64|15&i[6],i[8]=128|63&i[8],t){n=n||0;for(var s=0;16>s;++s)t[n+s]=i[s];return t}return v(i)}function b(e,t){if(!e||!t)return{};const n={...e};if(n.localCandidateId){const e=t.get(n.localCandidateId);n.local={...e}}if(n.remoteCandidateId){const e=t.get(n.remoteCandidateId);n.remote={...e}}return n}function y(e,t,n){return 8*function(e,t,n){const i=e[n],s=t?t[n]:null;return null===i||null===s?null:(i-s)/(e.timestamp-t.timestamp)*1e3}(e,t,n)}function _(e){if(!e.entries)return e;const t={};return e.forEach((function(e,n){t[n]=e})),t}function w(e,t,n={}){if(!e)return null;let i={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};n.remote&&(i.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const t of e.values())switch(t.type){case"outbound-rtp":{const n=t.mediaType||t.kind,s={};let o={};if(!["audio","video"].includes(n))continue;if(t.codecId){const n=e.get(t.codecId);n&&(s.clockRate=n.clockRate,s.mimeType=n.mimeType,s.payloadType=n.payloadType)}o=e.get(t.mediaSourceId)||e.get(t.trackId)||{},i[n].outbound.push({...t,...s,track:{...o}});break}case"inbound-rtp":{let n=t.mediaType||t.kind,s={};const o={};if(!["audio","video"].includes(n))if(t.id.includes("Video"))n="video";else{if(!t.id.includes("Audio"))continue;n="audio"}if(t.codecId){const n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}if(!i.connection.id&&t.transportId){const n=e.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=e.get(n.selectedCandidatePairId);i.connection=b(t,e)}}s=e.get(t.mediaSourceId)||e.get(t.trackId)||{},i[n].inbound.push({...t,...o,track:{...s}});break}case"peer-connection":i.connection.dataChannelsClosed=t.dataChannelsClosed,i.connection.dataChannelsOpened=t.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!n.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 n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}if(!i.connection.id&&t.transportId){const n=e.get(t.transportId);if(n&&n.selectedCandidatePairId){const t=e.get(n.selectedCandidatePairId);i.connection=b(t,e)}}i.remote[s].inbound.push({...t,...o});break}case"remote-outbound-rtp":{if(!n.remote)break;const s=t.mediaType||t.kind,o={};if(!["audio","video"].includes(s))continue;if(t.codecId){const n=e.get(t.codecId);n&&(o.clockRate=n.clockRate,o.mimeType=n.mimeType,o.payloadType=n.payloadType)}i.remote[s].outbound.push({...t,...o});break}}if(!i.connection.id)for(const t of e.values())"candidate-pair"===t.type&&t.nominated&&"succeeded"===t.state&&(i.connection=b(t,e));return i=function(e,t){return t?(e.audio.inbound.map((e=>{let n=t.audio.inbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesReceived"),e.packetRate=y(e,n,"packetsReceived")})),e.audio.outbound.map((e=>{let n=t.audio.outbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesSent"),e.packetRate=y(e,n,"packetsSent")})),e.video.inbound.map((e=>{let n=t.video.inbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesReceived"),e.packetRate=y(e,n,"packetsReceived")})),e.video.outbound.map((e=>{let n=t.video.outbound.find((t=>t.id===e.id));e.bitrate=y(e,n,"bytesSent"),e.packetRate=y(e,n,"packetsSent")})),e):e}(i,t),i}let S,I={},C=[];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:n}=e;let{connectionId:i,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(!n)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[n]){if(i&&i in this.peersToMonitor[n])throw new Error(`We are already monitoring connection with id ${i}.`);for(let e in this.peersToMonitor[n]){const i=this.peersToMonitor[n][e];if(i.pc===t)throw new Error(`We are already monitoring peer with id ${n}.`);"closed"===i.pc.connectionState&&this.removeConnection({pc:i.pc})}}const o=t.getConfiguration();return o.iceServers&&o.iceServers.forEach((function(e){delete e.credential})),i||(i=m()),this.emitEvent({event:"addConnection",tag:"peer",peerId:n,connectionId:i,data:{options:e,peerConfiguration:o}}),this.monitorPeer({peerId:n,connectionId:i,pc:t,remote:s}),{connectionId:i}}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:n,pc:i}=e;if(!i&&!n)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(n){if("string"!=typeof n)throw new Error("connectionId must be a string.");for(let e in this.peersToMonitor)n in this.peersToMonitor[e]&&(i=this.peersToMonitor[e][n].pc,t=e)}else if(i){if(!(i 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===i&&(n=s,t=e)}if(!i||!n)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(n,i),delete this.peersToMonitor[t][n],0===Object.values(this.peersToMonitor[t]).length&&delete this.peersToMonitor[t],{connectionId:n}}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 n=this.peersToMonitor[e][t].pc;this.removePeerConnectionEventListeners(t,n)}delete this.peersToMonitor[e]}}destroy(){this.removeAllPeers(),C.forEach((e=>{this.removeTrackEventListeners(e)})),C=[],this.shouldWrapGetUserMedia&&S&&(navigator.mediaDevices.getUserMedia=S)}monitorPeer(e){let{peerId:t,connectionId:n,pc:i,remote:s}=e;if(!i)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const o={pc:i,connectionId:n,stream:null,stats:{parsed:null,raw:null},options:{remote:s}};if(this.peersToMonitor[t]){if(n in this.peersToMonitor[t])return void this.logger.warn(`Already watching connection with ID ${n}`);this.peersToMonitor[t][n]=o}else this.peersToMonitor[t]={[n]:o};this.addPeerConnectionEventListeners(t,n,i),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 n=[];for(const e in t)for(const i in t[e]){const s=t[e][i],o=s.pc;if(o&&!this.checkIfConnectionIsClosed(e,i,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=w(o,s.stats.parsed,d),u={event:"stats",tag:"stats",peerId:e,connectionId:i,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)),n.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 n}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval((()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const e in this.peersToMonitor)for(const t in this.peersToMonitor[e]){const n=this.peersToMonitor[e][t].pc;this.checkIfConnectionIsClosed(e,t,n)}}),this.connectionMonitoringInterval)}checkIfConnectionIsClosed(e,t,n){const i=this.isConnectionClosed(n);if(i){this.removeConnection({pc:n});let i="closed"===n.connectionState?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:i,peerId:e,connectionId:t,tag:"connection",data:"closed"})}return i}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."),S=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const e=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=function(){return e({constraints:arguments[0]}),S.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 n=t[e];this.statsToMonitor.includes(n.type)||delete t[e]}return t}get peerConnectionListeners(){return{icecandidate:(e,t,n,i)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",i),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:e,connectionId:t,data:i.candidate})},track:(e,t,n,i)=>{this.logger.debug(`[pc-event] track | peerId: ${e}`,i);const s=i.track,o=i.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:i.track.kind+":"+i.track.id+" "+i.streams.map((function(e){return"stream:"+e.id}))}})},signalingstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${e}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:e,connectionId:t,data:{signalingState:n.signalingState,localDescription:n.localDescription,remoteDescription:n.remoteDescription}})},iceconnectionstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${e}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:n.iceConnectionState})},icegatheringstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${e}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:e,connectionId:t,data:n.iceGatheringState})},icecandidateerror:(e,t,n,i)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${e}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:e,connectionId:t,error:{errorCode:i.errorCode}})},connectionstatechange:(e,t,n)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${e}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:e,connectionId:t,data:n.connectionState})},negotiationneeded:(e,t,n)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${e}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:e,connectionId:t})},datachannel:(e,t,n,i)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${e}`,i),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:e,connectionId:t,data:i.channel})}}}addPeerConnectionEventListeners(e,t,n){this.logger.debug(`Adding event listeners for peer ${e} and connection ${t}.`),I[t]={},Object.keys(this.peerConnectionListeners).forEach((i=>{I[t][i]=this.peerConnectionListeners[i].bind(this,e,t,n),n.addEventListener(i,I[t][i],!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),C.push(e)}))),this.emitEvent(t)}catch(e){}}parseStream(e){const t={audio:[],video:[]};return e.getTracks().forEach((e=>{t[e.kind].push(this.getMediaTrackDetails(e))})),t}getMediaTrackDetails(e){return{enabled:e.enabled,id:e.id,contentHint:e.contentHint,kind:e.kind,label:e.label,muted:e.muted,readyState:e.readyState,constructorName:e.constructor.name,capabilities:e.getCapabilities?e.getCapabilities():{},constraints:e.getConstraints?e.getConstraints():{},settings:e.getSettings?e.getSettings():{},_track:e}}getStreamDetails(e){return{active:e.active,id:e.id,_stream:e}}getTrackEventObject(e){return{mute:t=>{this.emitEvent({event:"mute",tag:"track",connectionId:e,data:{event:t}})},unmute:t=>{this.emitEvent({event:"unmute",tag:"track",connectionId:e,data:{event:t}})},overconstrained:t=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:e,data:{event:t}})},ended:t=>{this.emitEvent({event:"ended",tag:"track",connectionId:e,data:{event:t}}),this.removeTrackEventListeners(t.target)}}}addTrackEventListeners(e,t){I[e.id]={};const n=this.getTrackEventObject(t);Object.keys(n).forEach((t=>{I[e.id][t]=n[t].bind(this),e.addEventListener(t,I[e.id][t])})),I[e.id].readyState=setInterval((()=>{if("ended"===e.readyState){let t=new CustomEvent("ended",{detail:{check:"readyState"}});e.dispatchEvent(t)}}),1e3)}removeTrackEventListeners(e){if(e.id in I){const t=this.getTrackEventObject();Object.keys(t).forEach((t=>{e.removeEventListener(t,I[e.id][t])})),clearInterval(I[e.id].readyState),delete I[e.id]}}addToTimeline(e){this.timeline.push(e),this.emit("timeline",e)}emitEvent(e){const t={...e,timestamp:new Date};this.addToTimeline(t),t.tag&&this.emit(t.tag,t)}set getStatsInterval(e){if(!Number.isInteger(e))throw new Error(`getStatsInterval should be an integer, got: ${e}`);this._getStatsInterval=e,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(e,t){e in I&&(Object.keys(this.peerConnectionListeners).forEach((n=>{t.removeEventListener(n,I[e][n],!1)})),delete I[e]),t.getSenders().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)})),t.getReceivers().forEach((e=>{e.track&&this.removeTrackEventListeners(e.track)}))}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const e=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const t=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),n=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=n.bind(navigator.mediaDevices)}}}}));(Ze=et)&&Ze.__esModule&&Object.prototype.hasOwnProperty.call(Ze,"default")&&Ze.default;var tt=et.WebRTCStats;class nt extends ie{constructor(e){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1})}}class it extends ie{constructor(e){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1})}}class st extends ie{constructor(e,t){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:t})}}class ot{constructor(e,n,i){this.type=e,this.options=n,this.onSdpReadyTwice=null,this._negotiating=!1,this.handleConnectionStateChange=e=>t(this,void 0,void 0,(function*(){const{connectionState:e}=this.instance;if(console.log(`[${(new Date).toISOString()}] Connection State`,e),"failed"===e||"disconnected"===e){const e=()=>{this.instance.restartIce(),this._session._closeConnection(),this._session.connect(),window.removeEventListener("online",e)};if(navigator.onLine)return e();window.addEventListener("online",e)}})),this._handleIceConnectionStateChange=e=>{console.log(`[${(new Date).toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=e=>{console.log(`[${(new Date).toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setAudioCodec=e=>{if(this.options.preferred_codecs&&0!==this.options.preferred_codecs.length)return e.setCodecPreferences?e.setCodecPreferences(this.options.preferred_codecs):void 0},this._onDebugReportMessage=e=>t(this,void 0,void 0,(function*(){this.options.debug&&("stats"===e.event&&U(m.StatsFrame,function({data:e}){var t,n,i,s,o,r,a,c;const{audio:d,remote:l}=e,{audio:u}=l,h=null!==(n=null===(t=u.inbound[0])||void 0===t?void 0:t.jitter)&&void 0!==n?n:1/0,p=null!==(s=null===(i=u.inbound[0])||void 0===i?void 0:i.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,f=null!==(c=null===(a=d.inbound[0])||void 0===a?void 0:a.packetsLost)&&void 0!==c?c:-1,v=Qe({jitter:1e3*h,rtt:1e3*p,packetsLost:f,packetsReceived:g});return{jitter:h,rtt:p,mos:v,quality:Xe(v),inboundAudio:d.inbound[0],outboundAudio:d.outbound[0],remoteInboundAudio:u.inbound[0],remoteOutboundAudio:u.outbound[0]}}(e),this._session.uuid),yield this._session.execute(this._webrtcStatsReporter.reportDataMessage(e)))})),u.info("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!0},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=i,this._init()}get isOffer(){return this.type===$.Offer}get isAnswer(){return this.type===$.Answer}startNegotiation(){this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}startDebugger(){return t(this,void 0,void 0,(function*(){this.options.debug&&(this._webrtcStatsReporter=function(){const e=a(),t=new tt({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,wrapGetUserMedia:!0,debug:!1,logLevel:"warn"});return{reportDataMessage:t=>new st(e,t),start:()=>new nt(e),stop:()=>new it(e),reportId:e,debuggerInstance:t}}(),yield this._session.execute(this._webrtcStatsReporter.start()),this._webrtcStatsReporter.debuggerInstance.on("timeline",this._onDebugReportMessage),yield new Promise((e=>setTimeout(e,500))),this._webrtcStatsReporter.debuggerInstance.addConnection({pc:this.instance,peerId:this.options.id,connectionId:this.options.telnyxSessionId}))}))}stopDebugger(){this.options.debug&&(U(m.StatsReport,this._webrtcStatsReporter.debuggerInstance.getTimeline()),this._session.execute(this._webrtcStatsReporter.stop()),this._webrtcStatsReporter.debuggerInstance.destroy())}_logTransceivers(){u.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach(((e,t)=>{u.info(`>> Transceiver [${t}]:`,e.mid,e.direction,e.stopped),u.info(`>> Sender Params [${t}]:`,JSON.stringify(e.sender.getParameters(),null,2))}))}handleSignalingStateChangeEvent(e){switch(u.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":this.instance=null;break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){u.info("Negotiation needed event"),"stable"===this.instance.signalingState&&this.startNegotiation()}handleTrackEvent(e){const{streams:[t]}=e,{remoteElement:n,screenShare:i}=this.options;let{remoteStream:s}=this.options;s=t,!1===i&&ue(n,s)}createPeerConnection(){return t(this,void 0,void 0,(function*(){var e;this.instance=(e=this._config(),new window.RTCPeerConnection(e)),yield this.startDebugger(),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.options.localStream=yield this._retrieveLocalStream().catch((e=>(U(m.MediaError,e,this.options.id),null)))}))}_init(){return t(this,void 0,void 0,(function*(){yield this.createPeerConnection();const{localElement:e,localStream:t=null,screenShare:n=!1}=this.options;if(le(t)){const i=t.getAudioTracks();u.info("Local audio tracks: ",i);const s=t.getVideoTracks();if(u.info("Local video tracks: ",s),this.isOffer&&"function"==typeof this.instance.addTransceiver){const e={direction:"sendrecv",streams:[t]};i.forEach((t=>{this.options.userVariables.microphoneLabel=t.label;const n=this.instance.addTransceiver(t,e);this._setAudioCodec(n)})),console.debug("Applying video transceiverParams",e),s.forEach((t=>{this.options.userVariables.cameraLabel=t.label,this.instance.addTransceiver(t,e)}))}else"function"==typeof this.instance.addTrack?(i.forEach((e=>{this.options.userVariables.microphoneLabel=e.label,this.instance.addTrack(e,t)})),this.instance.getTransceivers().forEach((e=>this._setAudioCodec(e))),s.forEach((e=>{this.options.userVariables.cameraLabel=e.label,this.instance.addTrack(e,t)}))):this.instance.addStream(t);!1===n&&((e=>{const t=S(e);t&&(t.muted=!0)})(e),ue(e,t))}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this.startNegotiation(),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);u.info("Add transceiver",e,t)}}_createOffer(){this._isOffer()&&(this._constraints.offerToReceiveAudio=Boolean(this.options.audio),this._constraints.offerToReceiveVideo=Boolean(this.options.video),u.info("_createOffer - this._constraints",this._constraints),this.instance.createOffer(this._constraints).then(this._setLocalDescription.bind(this)).then(this._sdpReady).catch((e=>u.error("Peer _createOffer error:",e))))}_setRemoteDescription(e){this.options.useStereo&&(e.sdp=we(e.sdp)),this.instance.localDescription&&(e.sdp=Ce(e.sdp,this.instance.localDescription.sdp));const t=e;return u.info("REMOTE SDP \n",`Type: ${e.type}`,"\n\n",e.sdp),this.instance.setRemoteDescription(t)}_createAnswer(){return t(this,void 0,void 0,(function*(){if(!this._isAnswer())return;if("stable"!==this.instance.signalingState)return console.log(" - 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:$.Offer})]));yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:$.Offer}),this._logTransceivers();const e=yield this.instance.createAnswer();yield this._setLocalDescription(e)}))}_setLocalDescription(e){const{useStereo:t,googleMaxBitrate:n,googleMinBitrate:i,googleStartBitrate:s,mediaSettings:o}=this.options;return t&&(e.sdp=we(e.sdp)),n&&i&&s&&(e.sdp=((e,t,n,i)=>{const s=e.split("\r\n");return s.forEach(((e,o)=>{/^a=fmtp:\d*/.test(e)?s[o]+=`;x-google-max-bitrate=${t};x-google-min-bitrate=${n};x-google-start-bitrate=${i}`:/^a=mid:(1|video)/.test(e)&&(s[o]+=`\r\nb=AS:${t}`)})),s.join("\r\n")})(e.sdp,n,i,s)),o&&o.useSdpASBandwidthKbps&&null!==o.sdpASBandwidthKbps&&(e.sdp=((e,t)=>{let n="AS",i=t;!navigator.userAgent.match(/firefox/gim)||navigator.userAgent.match(/OPR\/[0-9]{2}/gi)||navigator.userAgent.match(/edg/gim)||(n="TIAS",i=1e3*(t>>>0));return-1===e.indexOf("b="+n+":")?e.replace(/c=IN (.*)\r\n/,"c=IN $1\r\nb="+n+":"+i+"\r\n"):e.replace(new RegExp("b="+n+":.*\r\n"),"b="+n+":"+i+"\r\n")})(e.sdp,o.sdpASBandwidthKbps)),this.instance.setLocalDescription(e)}_sdpReady(){w(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return t(this,void 0,void 0,(function*(){if(le(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,t(void 0,void 0,void 0,(function*(){let{audio:e=!0,micId:t}=n;const{micLabel:i=""}=n;t&&(t=yield be(t,i,K.AudioIn).catch((e=>null)),t&&("boolean"==typeof e&&(e={}),e.deviceId={exact:t}));let{camId:s}=n,o=n.video;const{camLabel:r=""}=n;return s&&(s=yield be(s,r,K.Video).catch((e=>null)),s&&("boolean"==typeof o&&(o={}),o.deviceId={exact:s})),{audio:e,video:o}})));var n;return fe(e)}))}_isOffer(){return this.type===$.Offer}_isAnswer(){return this.type===$.Answer}_config(){const{iceServers:e=[],prefetchIceCandidates:t,forceRelayCandidate:n}=this.options,i={bundlePolicy:"max-compat",iceCandidatePoolSize:t?10:0,iceServers:e,iceTransportPolicy:n?"relay":"all"};return u.info("RTC config",i),i}close(){if(this.options.debug){if("file"===this.options.debugOutput){!function(e,t){const n=new Blob([JSON.stringify(e)],{type:"application/json"}),i=URL.createObjectURL(n),s=document.createElement("a");s.href=i,s.download=`${t}.json`,s.click(),URL.revokeObjectURL(i)}(this._webrtcStatsReporter.debuggerInstance.getTimeline(),this.options.telnyxSessionId)}this.stopDebugger()}}}const rt=Ue;class at{constructor(e,t){this.session=e,this.id="",this.state=H[H.New],this.prevState="",this.channels=[],this.role=W.Participant,this.extension=null,this._state=H.New,this._prevState=H.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._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(var n in t.constraints)if(t.constraints.hasOwnProperty(n)&&t.constraints[n]!==e[n])return;t.callback(e)}}))}))}))};const{iceServers:n,speaker:i,micId:s,micLabel:o,camId:r,camLabel:a,localElement:c,remoteElement:d,mediaConstraints:{audio:l,video:u},ringtoneFile:h,ringbackFile:p}=e;this.options=Object.assign({},F,{audio:l,video:u,iceServers:n,localElement:c,remoteElement:d,micId:s,micLabel:o,camId:r,camLabel:a,speakerId:i,ringtoneFile:h,ringbackFile:p},t),this._onMediaError=this._onMediaError.bind(this),this._init(),this.options&&(this._ringtone=De(this.options.ringtoneFile,"_ringtone"),this._ringback=De(this.options.ringbackFile,"_ringback"))}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}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}`}invite(){this.direction=V.Outbound,this.peer=new ot($.Offer,this.options,this.session),this._registerPeerEvents()}answer(e={}){var t,n,i,s;this.stopRingtone(),this.options.video=null!==(n=null!==(t=e.video)&&void 0!==t?t:this.options.video)&&void 0!==n&&n,this.direction=V.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})),(null===(s=e.preferred_codecs)||void 0===s?void 0:s.length)>0&&(this.options.preferred_codecs=e.preferred_codecs),this.peer=new ot($.Answer,this.options,this.session),this._registerPeerEvents()}playRingtone(){Ne(this._ringtone)}stopRingtone(){Oe(this._ringtone)}playRingback(){Ne(this._ringback)}stopRingback(){Oe(this._ringback)}hangup(e,t){var n,i,s;let o=e||{},r=!1!==t;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!==(n=this.options.customHeaders)&&void 0!==n?n:[],...null!==(s=null===(i=null==o?void 0:o.dialogParams)||void 0===i?void 0:i.customHeaders)&&void 0!==s?s:[]],this.setState(H.Hangup);const a=()=>{var e;return null===(e=this.peer)||void 0===e||e.close(),this.setState(H.Destroy)};if(this.stopRingtone(),this.stopRingback(),r){const e=new Fe({sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(e).catch((e=>{u.error("telnyx_rtc.bye failed!",e),U(m.Error,{error:e,sessionId:this.session.sessionid},this.session.uuid)})).then(a.bind(this))}else a()}hold(){const e=new He({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 He({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 He({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 We({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(t)}message(e,t){const n={from:this.session.options.login,to:e,body:t},i=new We({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(i)}muteAudio(){xe(this.options.localStream)}unmuteAudio(){Re(this.options.localStream)}toggleAudioMute(){Me(this.options.localStream)}setAudioInDevice(e){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}}}),i=t.getAudioTracks()[0];n.replaceTrack(i),this.options.micId=e;const{localStream:s}=this.options;s.getAudioTracks().forEach((e=>e.stop())),s.getVideoTracks().forEach((e=>t.addTrack(e))),this.options.localStream=t}}))}muteVideo(){var e;e=this.options.localStream,Te(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Te(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Te(e,"video",null)}setVideoDevice(e){return t(this,void 0,void 0,(function*(){const{instance:t}=this.peer,n=t.getSenders().find((({track:{kind:e}})=>"video"===e));if(n){const t=yield de({video:{deviceId:{exact:e}}}),i=t.getVideoTracks()[0];n.replaceTrack(i);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(){xe(this.options.remoteStream)}undeaf(){Re(this.options.remoteStream)}toggleDeaf(){Me(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return t(this,void 0,void 0,(function*(){if(!this||!this.peer)return void u.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,i=t.getSenders();if(!i)return void u.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=i.find((({track:{kind:e}})=>e===n));if(s){const t=s.getParameters();t.encodings||(t.encodings=[{rid:"h"}]),u.info("Parameters: ",t),u.info("Setting max ","audio"===n?"audio":"video"," bandwidth to: ",e," [bps]"),t.encodings[0].maxBitrate=e,yield s.setParameters(t).then((()=>{u.info("audio"===n?"New audio":"New video"," bandwidth settings in use: ",s.getParameters())})).catch((e=>console.error(e)))}else u.error("Could not set bandwidth (reason: no "+n+" 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 n={callback:e,constraints:t};if(this._statsBindings.push(n),!this._statsIntervalId){const e=2e3;this._startStats(e)}}setState(e){switch(this._prevState=this._state,this._state=e,this.state=H[this._state].toLowerCase(),this.prevState=H[this._prevState].toLowerCase(),u.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:B.callUpdate,call:this}),e){case H.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case H.Active:setTimeout((()=>{const{remoteElement:e,speakerId:t}=this.options;e&&t&&he(e,t)}),0);break;case H.Destroy:this._finalize()}}handleMessage(e){const{method:t,params:n}=e;switch(t){case G.Answer:if(this.gotAnswer=!0,this._state>=H.Active)return;this._state>=H.Early&&this.setState(H.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case G.Media:if(this._state>=H.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case G.Display:case G.Attach:{const{display_name:e,display_number:i,display_direction:s}=n;this.extension=i;const o=s===V.Inbound?V.Outbound:V.Inbound,r={type:B[t],call:this,displayName:e,displayNumber:i,displayDirection:o};U(m.Notification,r,this.id)||U(m.Notification,r,this.session.uuid);break}case G.Info:case G.Event:{const e=Object.assign(Object.assign({},n),{type:B.generic,call:this});U(m.Notification,e,this.id)||U(m.Notification,e,this.session.uuid);break}case G.Ringing:this.playRingback(),n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id);break;case G.Bye:const e=n.client_state||n.clientState;e&&(this.options.clientState=e),this.stopRingback(),this.stopRingtone(),this.hangup(n,!1)}}handleConferenceUpdate(e,n){return t(this,void 0,void 0,(function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return u.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:t,data:i,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}=n;this._dispatchConferenceUpdate({action:q.Join,conferenceName:o,participantId:Number(r),role:a}),e&&(yield this._subscribeConferenceChat(e)),t&&(yield this._subscribeConferenceInfo(t)),s&&a===W.Moderator&&(yield this._subscribeConferenceModerator(s));const c=[];for(const e in i)c.push(Object.assign({callId:i[e][0],index:Number(e)},y(i[e][1])));this._dispatchConferenceUpdate({action:q.Bootstrap,participants:c});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:q.Add,callId:s,index:o},y(i)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:q.Modify,callId:s,index:o},y(i)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:q.Delete,callId:s,index:o},y(i)));break;case"clear":this._dispatchConferenceUpdate({action:q.Clear});break;default:this._dispatchConferenceUpdate({action:t,data:i,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:n,fromDisplay:i,message:s,type:o}=e.data;this._dispatchConferenceUpdate({action:q.ChatMessage,direction:t,participantNumber:n,participantName:i,messageText:s,messageType:o,messageId:e.eventSerno})}},n=yield this.session.vertoSubscribe(t).catch((e=>{u.error("ConfChat subscription error:",e)}));ke(n,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(t,n)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:t,type:n}})}}}))}))}_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,ze(this.session,t);else u.error("Conference-Info unknown contentType",e)}},n=yield this.session.vertoSubscribe(t).catch((e=>{u.error("ConfInfo subscription error:",e)}));ke(n,e)&&this._addChannel(e)}))}_confControl(e,t={}){const n=Object.assign({application:"conf-control",callID:this.id,value:null},t);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:n})}_subscribeConferenceModerator(e){return t(this,void 0,void 0,(function*(){const t=(t,n=null,i=null)=>{const s=parseInt(n)||null;this._confControl(e,{command:t,id:s,value:i})},n=()=>{const{video:e}=this.options;if("boolean"==typeof e&&!e||"object"==typeof e&&b(e))throw`Conference ${this.id} has no video!`},i={nodeId:this.nodeId,channels:[e],handler:e=>{const{data:t}=e;if("list-videoLayouts"===t["conf-command"]){if(t.responseData){const e=JSON.stringify(t.responseData).replace(/IDS"/g,'Ids"');this._dispatchConferenceUpdate({action:q.LayoutList,layouts:JSON.parse(e)})}}else this._dispatchConferenceUpdate({action:q.ModCmdResponse,command:t["conf-command"],response:t.response})}},s=yield this.session.vertoSubscribe(i).catch((e=>{u.error("ConfMod subscription error:",e)}));ke(s,e)&&(this.role=W.Moderator,this._addChannel(e),Object.defineProperties(this,{listVideoLayouts:{configurable:!0,value:()=>{t("list-videoLayouts")}},playMedia:{configurable:!0,value:e=>{t("play",null,e)}},stopMedia:{configurable:!0,value:()=>{t("stop",null,"all")}},deaf:{configurable:!0,value:e=>{t("deaf",e)}},undeaf:{configurable:!0,value:e=>{t("undeaf",e)}},startRecord:{configurable:!0,value:e=>{t("recording",null,["start",e])}},stopRecord:{configurable:!0,value:()=>{t("recording",null,["stop","all"])}},snapshot:{configurable:!0,value:e=>{n(),t("vid-write-png",null,e)}},setVideoLayout:{configurable:!0,value:(e,i)=>{n();t("vid-layout",null,i?[e,i]:e)}},kick:{configurable:!0,value:e=>{t("kick",e)}},muteMic:{configurable:!0,value:e=>{t("tmute",e)}},muteVideo:{configurable:!0,value:e=>{n(),t("tvmute",e)}},presenter:{configurable:!0,value:e=>{n(),t("vid-res-id",e,"presenter")}},videoFloor:{configurable:!0,value:e=>{n(),t("vid-floor",e,"force")}},banner:{configurable:!0,value:(e,i)=>{n(),t("vid-banner",e,encodeURI(i))}},volumeDown:{configurable:!0,value:e=>{t("volume_out",e,"down")}},volumeUp:{configurable:!0,value:e=>{t("volume_out",e,"up")}},gainDown:{configurable:!0,value:e=>{t("volume_in",e,"down")}},gainUp:{configurable:!0,value:e=>{t("volume_in",e,"up")}},transfer:{configurable:!0,value:(e,n)=>{t("transfer",e,n)}}}))}))}_handleChangeHoldStateSuccess(e){return"active"===e.holdState?this.setState(H.Active):this.setState(H.Held),!0}_handleChangeHoldStateError(e){return u.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){let t=Ce(e,this.peer.instance.localDescription.sdp);this.options.useStereo&&(t=we(t));const n={sdp:t,type:$.Answer};this.peer.instance.setRemoteDescription(n).then((()=>{this.gotEarly&&this.setState(H.Early),this.gotAnswer&&this.setState(H.Active)})).catch((e=>{u.error("Call setRemoteDescription Error: ",e),this.hangup()}))}_requestAnotherLocalDescription(){w(this.peer.onSdpReadyTwice)?U(m.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,n;this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:i,type:s}=e;if(-1===i.indexOf("candidate"))return u.info("No candidate - retry \n"),void this._requestAnotherLocalDescription();null===(n=null===(t=this.peer)||void 0===t?void 0:t.instance)||void 0===n||n.removeEventListener("icecandidate",this._onIce);let o=null;const r={sessid:this.session.sessionid,sdp:i,dialogParams:this.options,"User-Agent":`Web-${rt}`};switch(s){case $.Offer:this.setState(H.Requesting),o=new Ve(r);break;case $.Answer:this.setState(H.Answering),o=!0===this.options.attach?new Be(r):new Ge(r);break;default:return u.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}this._execute(o).then((e=>{const{node_id:t=null}=e;this._targetNodeId=t,s===$.Offer?this.setState(H.Trying):this.setState(H.Active)})).catch((e=>{u.error(`${this.id} - Sending ${s} error:`,e),this.hangup()})),console.timeEnd(p)}_onIce(e){const{instance:t}=this.peer;null===this._iceTimeout&&(this._iceTimeout=setTimeout((()=>this._onIceSdp(t.localDescription)),1e3)),e.candidate?u.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(t.localDescription)}_registerPeerEvents(){const{instance:e}=this.peer;this._iceDone=!1,e.onicecandidate=e=>{this._iceDone||this._onIce(e)},e.addEventListener("addstream",(e=>{this.options.remoteStream=e.stream})),e.addEventListener("track",(e=>{this.options.remoteStream=e.streams[0];const{remoteElement:t,remoteStream:n,screenShare:i}=this.options;!1===i&&ue(t,n)}))}_onMediaError(e){this._dispatchNotification({type:B.userMediaError,error:e}),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:B.conferenceUpdate,call:this},e))}_dispatchNotification(e){!0!==this.options.screenShare&&(U(m.Notification,e,this.id,!1)||U(m.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:n,onNotification:i}=this.options;e||(this.options.id=a()),this.id=this.options.id,t&&!b(t)||(this.options.userVariables=this.session.options.userVariables||{}),n||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,N(m.MediaError,this._onMediaError,this.id),w(i)&&N(m.Notification,i.bind(this),this.id),this.setState(H.New),u.info("New Call with Options:",this.options)}_finalize(){this._stopStats(),this.peer&&this.peer.instance&&(this.peer.instance.close(),this.peer=null);const{remoteStream:e,localStream:t}=this.options;ge(e),ge(t),P(m.MediaError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),u.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),u.info("Stats stopped")}}at.setStateTelnyx=e=>{if(e){switch(e._state){case H.Requesting:case H.Recovering:case H.Trying:case H.Early:e.state="connecting";break;case H.Active:e.state="active";break;case H.Held:e.state="held";break;case H.Hangup:case H.Destroy:e.state="done";break;case H.Answering:e.state="ringing";break;case H.New:e.state="new"}return e}};class ct extends at{constructor(){super(...arguments),this._statsInterval=null}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(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;t.getTracks().forEach((e=>{e.addEventListener("ended",(()=>{this.screenShare&&this.screenShare.hangup()}))}));const{remoteCallerName:i,remoteCallerNumber:s,callerName:o,callerNumber:r}=this.options,a=Object.assign({screenShare:!0,localStream:t,destinationNumber:`${this.extension}-screen`,remoteCallerName:i,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:n}=this.options;return!(!t||!n)&&he(t,n)}))}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(!1===e)return clearInterval(this._statsInterval);u.setLevel(2),this._statsInterval=window.setInterval((()=>t(this,void 0,void 0,(function*(){const e=yield this.peer.instance.getStats(null);let t="";const n=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],i=["id","type","timestamp"];e.forEach((e=>{n.includes(e.type)||(t+=`\n${e.type}\n`,Object.keys(e).forEach((n=>{i.includes(n)||(t+=`\t${n}: ${e[n]}\n`)})))})),u.info(t)}))),2e3)}}class dt extends ce{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile}get reconnectDelay(){return 1e3}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,n=!0){return t(this,void 0,void 0,(function*(){try{const t=yield fe({audio:e,video:n});return ge(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(H.Purge))),this.calls={},yield e.disconnect.call(this)}))}speedTest(e){return new Promise(((t,n)=>{if(O(m.SpeedTest,(n=>{const{upDur:i,downDur:s}=n,o=s?8*e/(s/1e3)/1024:0;t({upDur:i,downDur:s,upKps:(i?8*e/(i/1e3)/1024:0).toFixed(0),downKps:o.toFixed(0)})}),this.uuid),!(e=Number(e)))return n(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let i=e/1024;e%1024&&i++;const s=".".repeat(1024);for(let e=0;e<i;e++)this.executeRaw(`#SPB ${s}`);this.executeRaw("#SPE")}))}getDevices(){return ve().catch((e=>(U(m.MediaError,e,this.uuid),[])))}getVideoDevices(){return ve(K.Video).catch((e=>(U(m.MediaError,e,this.uuid),[])))}getAudioInDevices(){return ve(K.AudioIn).catch((e=>(U(m.MediaError,e,this.uuid),[])))}getAudioOutDevices(){return ve(K.AudioOut).catch((e=>(console.error("getAudioOutDevices",e),U(m.MediaError,e,this.uuid),[])))}validateDeviceId(e,t,n){return be(e,t,n)}getDeviceResolutions(e){return t(this,void 0,void 0,(function*(){try{return yield(e=>t(void 0,void 0,void 0,(function*(){const t=[],n=yield fe({video:{deviceId:{exact:e}}}),i=n.getVideoTracks()[0];for(let e=0;e<me.length;e++){const[n,s]=me[e];(yield i.applyConstraints({width:{exact:n},height:{exact:s}}).then((()=>!0)).catch((()=>!1)))&&t.push({resolution:`${n}x${s}`,width:n,height:s})}return ge(n),t})))(e)}catch(e){throw e}}))}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(n){return t(this,void 0,void 0,(function*(){if(!n)throw new Error("You need to provide the settings object");const{micId:t,micLabel:i}=n,s=e(n,["micId","micLabel"]);return ye(s),this._audioConstraints=yield _e(t,i,"audioinput",s),this.micId=t,this.micLabel=i,this._audioConstraints}))}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}setVideoSettings(n){return t(this,void 0,void 0,(function*(){if(!n)throw new Error("You need to provide the settings object");const{camId:t,camLabel:i}=n,s=e(n,["camId","camLabel"]);return ye(s),this._videoConstraints=yield _e(t,i,"videoinput",s),this.camId=t,this.camLabel=i,this._videoConstraints}))}disableWebcam(){this._videoConstraints=!1}enableWebcam(){this._videoConstraints=!0}set iceServers(e){const t={urls:["stun:stun.l.google.com:19302"]};this._iceServers="boolean"==typeof e?e?[t]:[]:e||[v,f,t]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=S(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=S(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:t="",data:n}){if(!t)throw new Error(`Invalid channel for broadcast: ${t}`);const i=new qe({sessid:this.sessionid,eventChannel:t,data:n});e&&(i.targetNodeId=e),this.execute(i).catch((e=>e))}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return t(this,void 0,void 0,(function*(){if(!(n=n.filter((e=>e&&!this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new Ke({sessid:this.sessionid,eventChannel:n});e&&(t.targetNodeId=e);const s=yield this.execute(t),{unauthorized:o=[],subscribed:r=[]}=Ee(s);return o.length&&o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),r.forEach((e=>this._addSubscription(this.relayProtocol,i,e))),s}))}vertoUnsubscribe({nodeId:e,channels:n=[]}){return t(this,void 0,void 0,(function*(){if(!(n=n.filter((e=>e&&this._existsSubscription(this.relayProtocol,e)))).length)return{};const t=new Je({sessid:this.sessionid,eventChannel:n});e&&(t.targetNodeId=e);const i=yield this.execute(t),{unsubscribed:s=[],notSubscribed:o=[]}=Ee(i);return s.forEach((e=>this._removeSubscription(this.relayProtocol,e))),o.forEach((e=>this._removeSubscription(this.relayProtocol,e))),i}))}static telnyxStateCall(e){return ct.setStateTelnyx(e)}}class lt{constructor(e,t){this.code=t,this.message=e}}class ut extends oe{constructor(){super(),this.method=G.Ping;this.buildRequest({method:this.method,params:{}})}}class ht{constructor(e){this.session=e}_ack(e,t){const n=new $e(e,t);this.nodeId&&(n.targetNodeId=this.nodeId),this.session.execute(n)}reconnectDelay(){return 1e3*k(2,6)}handleMessage(e){const{session:t}=this,{id:n,method:i,params:s={}}=e,o=null==s?void 0:s.callID,r=null==s?void 0:s.eventChannel,a=null==s?void 0:s.eventType,c=i===G.Attach;if("channelPvtData"===a)return this._handlePvtEvent(s.pvtData);if(o&&t.calls.hasOwnProperty(o)){if(!c)return t.calls[o].handleMessage(e),void this._ack(n,i);t.calls[o].hangup({},!1)}const d=()=>{var e,n,i,r;const a={id:o,remoteSdp:s.sdp,destinationNumber:s.callee_id_number,remoteCallerName:s.caller_id_name,remoteCallerNumber:s.caller_id_number,callerName:s.callee_id_name,callerNumber:s.callee_id_number,attach:c,mediaSettings:s.mediaSettings,debug:null!==(e=t.options.debug)&&void 0!==e&&e,debugOutput:null!==(n=t.options.debugOutput)&&void 0!==n?n:"socket",prefetchIceCandidates:null!==(i=t.options.prefetchIceCandidates)&&void 0!==i&&i,forceRelayCandidate:null!==(r=t.options.forceRelayCandidate)&&void 0!==r&&r};s.telnyx_call_control_id&&(a.telnyxCallControlId=s.telnyx_call_control_id),s.telnyx_session_id&&(a.telnyxSessionId=s.telnyx_session_id),s.telnyx_leg_id&&(a.telnyxLegId=s.telnyx_leg_id),s.client_state&&(a.clientState=s.client_state),s.dialogParams&&s.dialogParams.custom_headers&&s.dialogParams.custom_headers.length&&(a.customHeaders=s.dialogParams.custom_headers);const d=new ct(t,a);return d.nodeId=this.nodeId,d},l=new re,h=new ut;switch(i){case G.Ping:this.session.execute(h);break;case G.Punt:t.disconnect();break;case G.Invite:{const e=d();e.playRingtone(),e.setState(H.Ringing),e.direction=V.Inbound,this._ack(n,i);break}case G.Attach:{const t=d();this.session.autoRecoverCalls?t.answer():t.setState(H.Recovering),t.handleMessage(e);break}case G.Event:case"webrtc.event":if(!r)return void u.error("Verto received an unknown event:",s);const o=t.relayProtocol,a=r.split(".")[0];t._existsSubscription(o,r)?U(o,s,r):r===t.sessionid?this._handleSessionEvent(s.eventData):t._existsSubscription(o,a)?U(o,s,a):t.calls.hasOwnProperty(r)?t.calls[r].handleMessage(e):U(m.Notification,s,t.uuid);break;case G.Info:s.type=B.generic,U(m.Notification,s,t.uuid);break;case G.ClientReady:this.session.execute(l);break;default:{const n=T(e);if(n){switch(n){case J.REGISTER:case J.REGED:t.connection.previousGatewayState!==J.REGED&&t.connection.previousGatewayState!==J.REGISTER&&(ht.retriedRegister=0,s.type=B.vertoClientReady,U(m.Ready,s,t.uuid));break;case J.UNREGED:case J.NOREG:if(ht.retriedRegister+=1,5===ht.retriedRegister){ht.retriedRegister=0,U(m.Error,{error:new lt("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:t.sessionid},t.uuid);break}setTimeout((()=>{this.session.execute(l)}),this.reconnectDelay());break;case J.FAILED:case J.FAIL_WAIT:if(t.connection.previousGatewayState!==J.FAILED&&t.connection.previousGatewayState!==J.FAIL_WAIT){if(!this.session.hasAutoReconnect()){ht.retriedConnect=0,U(m.Error,{error:new lt("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:t.sessionid},t.uuid);break}if(ht.retriedConnect+=1,5===ht.retriedConnect){ht.retriedConnect=0,U(m.Error,{error:new Error("Connection Retry Failed"),sessionId:t.sessionid},t.uuid);break}setTimeout((()=>{this.session.disconnect().then((()=>{this.session.clearConnection(),this.session.connect()}))}),this.reconnectDelay())}break;default:u.warn("GatewayState message unknown method:",e)}break}u.warn("Verto message unknown method:",e);break}}}_retrieveCallId(e,t){const n=Object.keys(this.session.calls);if("bootObj"!==e.action)return n.find((e=>this.session.calls[e].channels.includes(t)));{const t=e.data.find((e=>n.includes(e[0])));if(t instanceof Array)return t[0]}}_handlePvtEvent(e){return t(this,void 0,void 0,(function*(){const{session:t}=this,n=t.relayProtocol,{action:i,laChannel:s,laName:o,chatChannel:r,infoChannel:a,modChannel:c,conferenceMemberID:d,role:l,callID:h}=e;switch(i){case"conference-liveArray-join":{const n=()=>{t.vertoBroadcast({nodeId:this.nodeId,channel:s,data:{liveArray:{command:"bootstrap",context:s,name:o}}})},i={nodeId:this.nodeId,channels:[s],handler:({data:i})=>{const r=h||this._retrieveCallId(i,s);if(r&&t.calls.hasOwnProperty(r)){const a=t.calls[r];a._addChannel(s),a.extension=o,a.handleConferenceUpdate(i,e).then((e=>{"INVALID_PACKET"===e&&n()}))}}},r=yield t.vertoSubscribe(i).catch((e=>{u.error("liveArray subscription error:",e)}));ke(r,s)&&n();break}case"conference-liveArray-part":{let e=null;if(s&&t._existsSubscription(n,s)){const{callId:i=null}=t.subscriptions[n][s];if(e=t.calls[i]||null,null!==i){const n={type:B.conferenceUpdate,action:q.Leave,conferenceName:o,participantId:Number(d),role:l};U(m.Notification,n,i,!1)||U(m.Notification,n,t.uuid),null===e&&P(m.Notification,null,i)}}const i=[s,r,a,c];t.vertoUnsubscribe({nodeId:this.nodeId,channels:i}).then((({unsubscribedChannels:t=[]})=>{e&&(e.channels=e.channels.filter((e=>!t.includes(e))))})).catch((e=>{u.error("liveArray unsubscribe error:",e)}));break}}}))}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":ze(this.session,e);break;case"logo-info":{const t={type:B.conferenceUpdate,action:q.LogoInfo,logo:e.logoURL};U(m.Notification,t,this.session.uuid);break}}}}ht.retriedConnect=0,ht.retriedRegister=0;class pt extends dt{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,window.addEventListener("beforeunload",(e=>{this.calls&&Object.keys(this.calls).forEach((e=>{this.calls[e]&&this.calls[e].hangup({},!0)}))}))}validateOptions(){return E(this.options)}newCall(e){if(!e||!e.destinationNumber)throw new Error("Verto.newCall() error: destinationNumber is required.");console.time(p);const t=new ct(this,e);return t.invite(),t}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}_onSocketOpen(){return t(this,void 0,void 0,(function*(){this._idle=!1;const{login:e,password:t,passwd:n,login_token:i,userVariables:s,autoReconnect:o=!0}=this.options,r=new je(e,t||n,i,this.sessionid,s,!!Y()),a=yield this.execute(r).catch(this._handleLoginError);a&&(this._autoReconnect=o,this.sessionid=a.sessid)}))}_onSocketMessage(e){new ht(this).handleMessage(e)}}class gt extends pt{constructor(e){super(e),console.log(`SDK version: ${Pe}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Le()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",supported:Ae.not_supported},{browserName:"Edge",supported:Ae.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Ae.not_supported},{browserName:"Firefox",supported:Ae.not_supported},{browserName:"Safari",features:["video","audio"],supported:Ae.full},{browserName:"Edge",supported:Ae.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",supported:Ae.not_supported},{browserName:"Edge",supported:Ae.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",features:["video","audio"],supported:Ae.full},{browserName:"Edge",features:["audio"],supported:Ae.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",supported:Ae.not_supported},{browserName:"Edge",features:["audio"],supported:Ae.partial}]}]}}class ft{static run(e){return t(this,void 0,void 0,(function*(){const t=R({}),n=R({}),i=new gt(e.credentials);yield i.connect(),i.on(m.Ready,t.resolve),i.on(m.Error,t.reject),i.on(m.MediaError,t.reject),i.on(m.MediaError,t.reject),i.on(m.Notification,(e=>{e.call&&e.call.sipCode>=400&&n.reject(new Error(e.call.sipReason))})),N(m.StatsReport,(e=>{n.resolve(ft.mapReport(e))})),yield t.promise,yield i.newCall({destinationNumber:e.texMLApplicationNumber,debug:!0});const s=yield n.promise;return yield i.disconnect(),s}))}static mapReport(e){var t,n,i,s,o,r,a,c,d,l,u,h,p;const g=[],f=[];for(const t of e)switch(t.event){case"onicecandidate":t.data&&g.push(t.data);break;case"stats":f.push(t.data)}let v=0,m=1/0,b=-1/0,y=0,_=1/0,w=-1/0,S=0;f.forEach((e=>{var t,n,i;if(!(null===(t=e.remote.audio.inbound)||void 0===t?void 0:t[0]))return;v+=1;const s=null!==(n=e.remote.audio.inbound[0].jitter)&&void 0!==n?n:0,o=null!==(i=e.remote.audio.inbound[0].roundTripTime)&&void 0!==i?i:0;y+=s,S+=o,b=Math.max(b,s),m=Math.min(m,s),w=Math.max(w,o),_=Math.min(_,o)}));const I=S/v,C=y/v,k=f[f.length-1],E=Qe({jitter:1e3*C,rtt:1e3*I,packetsReceived:null!==(i=null===(n=null===(t=k.audio.inbound)||void 0===t?void 0:t[0])||void 0===n?void 0:n.packetsReceived)&&void 0!==i?i: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:f[f.length-1].connection,summaryStats:{mos:E,jitter:{average:C,max:b,min:m},rtt:{average:I,max:w,min:_},quality:Xe(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{ft as PreCallDiagnosis,m as SwEvent,gt as TelnyxRTC};
@@ -22,6 +22,8 @@ export declare enum SwEvent {
22
22
  Ready = "telnyx.ready",
23
23
  Error = "telnyx.error",
24
24
  Notification = "telnyx.notification",
25
+ StatsFrame = "telnyx.stats.frame",
26
+ StatsReport = "telnyx.stats.report",
25
27
  Messages = "telnyx.messages",
26
28
  Calls = "telnyx.calls",
27
29
  MediaError = "telnyx.rtc.mediaError"
@@ -62,6 +62,7 @@ export interface AnswerParams {
62
62
  value: string;
63
63
  }>;
64
64
  preferred_codecs?: Array<RTCRtpCodecCapability>;
65
+ video?: boolean;
65
66
  }
66
67
  export interface IWebRTCCall {
67
68
  id: string;
@@ -0,0 +1,55 @@
1
+ import { Quality } from './utils/mos';
2
+ export interface TelnyxIDs {
3
+ telnyxCallControlId?: string;
4
+ telnyxSessionId?: string;
5
+ telnyxLegId?: string;
6
+ }
7
+ export interface RTCIceCandidateStats {
8
+ address: RTCIceCandidate['address'];
9
+ candidateType: RTCIceCandidate['type'];
10
+ deleted: boolean;
11
+ id: string;
12
+ port: RTCIceCandidate['port'];
13
+ priority: RTCIceCandidate['priority'];
14
+ protocol: RTCIceCandidate['protocol'];
15
+ relayProtocol?: 'tcp' | 'udp' | 'tls';
16
+ timestamp: DOMHighResTimeStamp;
17
+ transportId: string;
18
+ type: string;
19
+ url: string;
20
+ }
21
+ export interface MinMaxAverage {
22
+ min: number;
23
+ max: number;
24
+ average: number;
25
+ }
26
+ export interface Report {
27
+ iceCandidateStats: RTCIceCandidateStats[];
28
+ iceCandidatePairStats: RTCIceCandidatePairStats;
29
+ summaryStats: {
30
+ jitter: MinMaxAverage;
31
+ rtt: MinMaxAverage;
32
+ mos: number;
33
+ quality: Quality;
34
+ };
35
+ sessionStats: {
36
+ packetsReceived: number;
37
+ packetsLost: number;
38
+ packetsSent: number;
39
+ bytesSent: number;
40
+ bytesReceived: number;
41
+ };
42
+ }
43
+ export interface PreCallDiagnosisOptions {
44
+ texMLApplicationNumber: string;
45
+ credentials: {
46
+ login?: string;
47
+ password?: string;
48
+ loginToken?: string;
49
+ };
50
+ }
51
+ export declare class PreCallDiagnosis {
52
+ static run(options: PreCallDiagnosisOptions): Promise<Report>;
53
+ private static mapReport;
54
+ getTelnyxIds(): TelnyxIDs;
55
+ }
@@ -1,3 +1,5 @@
1
1
  import TelnyxRTC from './TelnyxRTC';
2
2
  import { ICall, IClientOptions, ICallOptions, ICredentials, INotification, MessageEvents, ISIPClientOptions, ISIPCallOptions } from './utils/interfaces';
3
- export { TelnyxRTC, ICall, IClientOptions, ICallOptions, ICredentials, INotification, MessageEvents, ISIPClientOptions, ISIPCallOptions, };
3
+ import { SwEvent } from './Modules/Verto/util/constants';
4
+ export { TelnyxRTC, ICall, IClientOptions, ICallOptions, ICredentials, INotification, MessageEvents, ISIPClientOptions, ISIPCallOptions, SwEvent, };
5
+ export * from './PreCallDiagnosis';
@@ -0,0 +1,8 @@
1
+ export declare function calculateMOS(data: {
2
+ jitter: number;
3
+ rtt: number;
4
+ packetsReceived: number;
5
+ packetsLost: number;
6
+ }): number;
7
+ export declare type Quality = 'excellent' | 'good' | 'fair' | 'poor' | 'bad';
8
+ export declare function getQuality(mos: number): Quality | null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telnyx/webrtc",
3
- "version": "2.22.5",
3
+ "version": "2.22.7",
4
4
  "description": "Telnyx WebRTC Client",
5
5
  "keywords": [
6
6
  "telnyx",