@telnyx/react-native-voice-sdk
Version:
Telnyx React Native Voice SDK
2 lines (1 loc) • 28.3 kB
JavaScript
var Ke=Object.create;var Q=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Ve=Object.getOwnPropertyNames;var Je=Object.getPrototypeOf,Qe=Object.prototype.hasOwnProperty;var $e=(n,e,t)=>e in n?Q(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var oe=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var H=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Ze=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ve(e))!Qe.call(n,o)&&o!==t&&Q(n,o,{get:()=>e[o],enumerable:!(i=We(e,o))||i.enumerable});return n};var x=(n,e,t)=>(t=n!=null?Ke(Je(n)):{},Ze(e||!n||!n.__esModule?Q(t,"default",{value:n,enumerable:!0}):t,n));var r=(n,e,t)=>$e(n,typeof e!="symbol"?e+"":e,t);var le=H((at,$)=>{"use strict";var ze=Object.prototype.hasOwnProperty,w="~";function D(){}Object.create&&(D.prototype=Object.create(null),new D().__proto__||(w=!1));function Ye(n,e,t){this.fn=n,this.context=e,this.once=t||!1}function ae(n,e,t,i,o){if(typeof t!="function")throw new TypeError("The listener must be a function");var a=new Ye(t,i||n,o),d=w?w+e:e;return n._events[d]?n._events[d].fn?n._events[d]=[n._events[d],a]:n._events[d].push(a):(n._events[d]=a,n._eventsCount++),n}function G(n,e){--n._eventsCount===0?n._events=new D:delete n._events[e]}function y(){this._events=new D,this._eventsCount=0}y.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)ze.call(t,i)&&e.push(w?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};y.prototype.listeners=function(e){var t=w?w+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var o=0,a=i.length,d=new Array(a);o<a;o++)d[o]=i[o].fn;return d};y.prototype.listenerCount=function(e){var t=w?w+e:e,i=this._events[t];return i?i.fn?1:i.length:0};y.prototype.emit=function(e,t,i,o,a,d){var p=w?w+e:e;if(!this._events[p])return!1;var s=this._events[p],c=arguments.length,C,h;if(s.fn){switch(s.once&&this.removeListener(e,s.fn,void 0,!0),c){case 1:return s.fn.call(s.context),!0;case 2:return s.fn.call(s.context,t),!0;case 3:return s.fn.call(s.context,t,i),!0;case 4:return s.fn.call(s.context,t,i,o),!0;case 5:return s.fn.call(s.context,t,i,o,a),!0;case 6:return s.fn.call(s.context,t,i,o,a,d),!0}for(h=1,C=new Array(c-1);h<c;h++)C[h-1]=arguments[h];s.fn.apply(s.context,C)}else{var N=s.length,S;for(h=0;h<N;h++)switch(s[h].once&&this.removeListener(e,s[h].fn,void 0,!0),c){case 1:s[h].fn.call(s[h].context);break;case 2:s[h].fn.call(s[h].context,t);break;case 3:s[h].fn.call(s[h].context,t,i);break;case 4:s[h].fn.call(s[h].context,t,i,o);break;default:if(!C)for(S=1,C=new Array(c-1);S<c;S++)C[S-1]=arguments[S];s[h].fn.apply(s[h].context,C)}}return!0};y.prototype.on=function(e,t,i){return ae(this,e,t,i,!1)};y.prototype.once=function(e,t,i){return ae(this,e,t,i,!0)};y.prototype.removeListener=function(e,t,i,o){var a=w?w+e:e;if(!this._events[a])return this;if(!t)return G(this,a),this;var d=this._events[a];if(d.fn)d.fn===t&&(!o||d.once)&&(!i||d.context===i)&&G(this,a);else{for(var p=0,s=[],c=d.length;p<c;p++)(d[p].fn!==t||o&&!d[p].once||i&&d[p].context!==i)&&s.push(d[p]);s.length?this._events[a]=s.length===1?s[0]:s:G(this,a)}return this};y.prototype.removeAllListeners=function(e){var t;return e?(t=w?w+e:e,this._events[t]&&G(this,t)):(this._events=new D,this._eventsCount=0),this};y.prototype.off=y.prototype.removeListener;y.prototype.addListener=y.prototype.on;y.prefixed=w;y.EventEmitter=y;typeof $<"u"&&($.exports=y)});var _=H((ge,U)=>{(function(n,e){"use strict";typeof define=="function"&&define.amd?define(e):typeof U=="object"&&U.exports?U.exports=e():n.log=e()})(ge,function(){"use strict";var n=function(){},e="undefined",t=typeof window!==e&&typeof window.navigator!==e&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],o={},a=null;function d(u,m){var l=u[m];if(typeof l.bind=="function")return l.bind(u);try{return Function.prototype.bind.call(l,u)}catch{return function(){return Function.prototype.apply.apply(l,[u,arguments])}}}function p(){console.log&&(console.log.apply||Function.prototype.apply.apply(console.log,[console,arguments]))}function s(u){return u==="debug"&&(u="log"),typeof console===e?!1:u==="trace"&&t?p:console[u]!==void 0?d(console,u):console.log!==void 0?d(console,"log"):n}function c(){for(var u=this.getLevel(),m=0;m<i.length;m++){var l=i[m];this[l]=m<u?n:this.methodFactory(l,u,this.name)}if(this.log=this.debug,typeof console===e&&u<this.levels.SILENT)return"No console available for logging"}function C(u){return function(){typeof console!==e&&(c.call(this),this[u].apply(this,arguments))}}function h(u,m,l){return s(u)||C.apply(this,arguments)}function N(u,m){var l=this,B,J,k,I="loglevel";typeof u=="string"?I+=":"+u:typeof u=="symbol"&&(I=void 0);function Ge(g){var v=(i[g]||"silent").toUpperCase();if(!(typeof window===e||!I)){try{window.localStorage[I]=v;return}catch{}try{window.document.cookie=encodeURIComponent(I)+"="+v+";"}catch{}}}function ie(){var g;if(!(typeof window===e||!I)){try{g=window.localStorage[I]}catch{}if(typeof g===e)try{var v=window.document.cookie,F=encodeURIComponent(I),se=v.indexOf(F+"=");se!==-1&&(g=/^([^;]+)/.exec(v.slice(se+F.length+1))[1])}catch{}return l.levels[g]===void 0&&(g=void 0),g}}function Ue(){if(!(typeof window===e||!I)){try{window.localStorage.removeItem(I)}catch{}try{window.document.cookie=encodeURIComponent(I)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function A(g){var v=g;if(typeof v=="string"&&l.levels[v.toUpperCase()]!==void 0&&(v=l.levels[v.toUpperCase()]),typeof v=="number"&&v>=0&&v<=l.levels.SILENT)return v;throw new TypeError("log.setLevel() called with invalid level: "+g)}l.name=u,l.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},l.methodFactory=m||h,l.getLevel=function(){return k??J??B},l.setLevel=function(g,v){return k=A(g),v!==!1&&Ge(k),c.call(l)},l.setDefaultLevel=function(g){J=A(g),ie()||l.setLevel(g,!1)},l.resetLevel=function(){k=null,Ue(),c.call(l)},l.enableAll=function(g){l.setLevel(l.levels.TRACE,g)},l.disableAll=function(g){l.setLevel(l.levels.SILENT,g)},l.rebuild=function(){if(a!==l&&(B=A(a.getLevel())),c.call(l),a===l)for(var g in o)o[g].rebuild()},B=A(a?a.getLevel():"WARN");var re=ie();re!=null&&(k=A(re)),c.call(l)}a=new N,a.getLogger=function(m){if(typeof m!="symbol"&&typeof m!="string"||m==="")throw new TypeError("You must supply a name when creating a logger.");var l=o[m];return l||(l=o[m]=new N(m,a.methodFactory)),l};var S=typeof window!==e?window.log:void 0;return a.noConflict=function(){return typeof window!==e&&window.log===a&&(window.log=S),a},a.getLoggers=function(){return o},a.default=a,a})});var he=H(()=>{});var L=H((Ct,Z)=>{"use strict";(function(){var n,e=0,t=[],i;for(i=0;i<256;i++)t[i]=(i+256).toString(16).substr(1);p.BUFFER_SIZE=4096,p.bin=d,p.clearBuffer=function(){n=null,e=0},p.test=function(s){return typeof s=="string"?/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(s):!1};var o;typeof crypto<"u"?o=crypto:typeof window<"u"&&typeof window.msCrypto<"u"&&(o=window.msCrypto),typeof Z<"u"&&typeof oe=="function"?(o=o||he(),Z.exports=p):typeof window<"u"&&(window.uuid=p),p.randomBytes=function(){if(o){if(o.randomBytes)return o.randomBytes;if(o.getRandomValues)return typeof Uint8Array.prototype.slice!="function"?function(s){var c=new Uint8Array(s);return o.getRandomValues(c),Array.from(c)}:function(s){var c=new Uint8Array(s);return o.getRandomValues(c),c}}return function(s){var c,C=[];for(c=0;c<s;c++)C.push(Math.floor(Math.random()*256));return C}}();function a(s){return(!n||e+s>p.BUFFER_SIZE)&&(e=0,n=p.randomBytes(p.BUFFER_SIZE)),n.slice(e,e+=s)}function d(){var s=a(16);return s[6]=s[6]&15|64,s[8]=s[8]&63|128,s}function p(){var s=d();return t[s[0]]+t[s[1]]+t[s[2]]+t[s[3]]+"-"+t[s[4]]+t[s[5]]+"-"+t[s[6]]+t[s[7]]+"-"+t[s[8]]+t[s[9]]+"-"+t[s[10]]+t[s[11]]+t[s[12]]+t[s[13]]+t[s[14]]+t[s[15]]}})()});var E=x(le(),1);var ce=E.default;var de="0.0.0";var pe="wss://rtc.telnyx.com";var P=de;function ue(n){let e=n;return!e||typeof e!="object"?!1:!!e.id&&e.jsonrpc==="2.0"}function tt(n,e){let t;return(...i)=>{clearTimeout(t),t=setTimeout(()=>n(...i),e)}}var R=(n=0)=>{let e,t;return{promise:new Promise((o,a)=>{e=n>0?tt(o,n):o,t=a}),resolve:e,reject:t}};var q=x(_(),1);var O=class extends E.default{constructor(){super();r(this,"socket");r(this,"transactions");r(this,"messageQueue");r(this,"send",t=>{if(!this.isConnected){this.messageQueue.push(t);return}q.default.debug("Sending message to gateway",t),this.socket.send(JSON.stringify(t))});r(this,"sendAndWait",t=>{let i=R();return this.transactions.set(t.id,i),this.send(t),i.promise});r(this,"close",()=>{this.socket.close(),this.socket.removeEventListener("open",this.onOpen),this.socket.removeEventListener("error",this.onError),this.socket.removeEventListener("close",this.onClose),this.socket.removeEventListener("message",this.onMessage),this.removeAllListeners(),this.transactions.clear(),this.messageQueue=[]});r(this,"onOpen",()=>{this.emit("telnyx.socket.open"),this.flushMessageQueue()});r(this,"flushMessageQueue",()=>{this.messageQueue.length!==0&&(this.messageQueue.forEach(t=>this.send(t)),this.messageQueue=[])});r(this,"onClose",()=>this.emit("telnyx.socket.close"));r(this,"safeParseMessage",t=>{try{return JSON.parse(t)}catch(i){return q.default.error("Failed to parse message:",t,i),t}});r(this,"onError",t=>{this.emit("telnyx.socket.error",t)});r(this,"onMessage",t=>{let i=this.safeParseMessage(t.data);return q.default.debug("Received message:",i),ue(i)&&(this.transactions.get(i.id)?.resolve(i),this.transactions.delete(i.id)),this.emit("telnyx.socket.message",i)});this.socket=new WebSocket(pe),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket.addEventListener("message",this.onMessage),this.transactions=new Map,this.messageQueue=[]}get isConnected(){return this.socket.readyState===WebSocket.OPEN}};var b=x(_(),1);var ye=x(_(),1);var fe=x(L(),1);function me(n){if(!n)return!1;let e=n;return e.method==="telnyx_rtc.ping"&&e.params?.serno!==void 0}function ve(){return{id:(0,fe.default)(),jsonrpc:"2.0",method:"telnyx_rtc.ping"}}var K=class extends E.default{constructor(t){super();r(this,"connection");r(this,"start",()=>{this.connection.addListener("telnyx.socket.message",this.onSocketMessage)});r(this,"stop",()=>{this.connection.removeListener("telnyx.socket.message",this.onSocketMessage)});r(this,"onSocketMessage",async t=>{me(t)&&(ye.default.debug("[KeepAliveHandler]: Received keep-alive ping",t),await this.connection.sendAndWait(ve()))});this.connection=t}};var Y=x(_(),1);import{Platform as nt}from"react-native";var we=x(L(),1);function Ce(n){return n?n?.method==="telnyx_rtc.clientReady":!1}function xe(){return{jsonrpc:"2.0",id:(0,we.default)(),method:"telnyx_rtc.gatewayState",params:{}}}function Ie(n){return n?n.result?.params?.state==="REGED":!1}var z=x(L(),1);function Ee({login:n,password:e,reconnection:t=!1,userVariables:i}){return{id:(0,z.default)(),jsonrpc:"2.0",method:"login",params:{userVariables:i,login:n,passwd:e,reconnection:t,"User-Agent":{sdkVersion:P,platform:"react-native"}}}}function be({login_token:n,userVariables:e,reconnection:t=!1}){return{id:(0,z.default)(),jsonrpc:"2.0",method:"login",params:{userVariables:e,login_token:n,reconnection:t,"User-Agent":{sdkVersion:P,platform:"react-native"}}}}function Se(n){if(!n)return!1;let e=n;return!!e.result?.message&&!!e.result?.sessid&&e.result.message==="logged in"}var W=class{constructor(e){r(this,"connection");r(this,"clientIsReady");r(this,"login",async e=>{let t=this.createLoginMessage(e);this.clientIsReady=R();let i=await this.connection.sendAndWait(t);if(!Se(i))return Y.default.error("Login failed. Please check your credentials and try again."),null;await this.clientIsReady.promise;let o=await this.connection.sendAndWait(xe());return Ie(o)?o.result.sessid:(Y.default.error("Invalid gateway state response"),null)});r(this,"createLoginMessage",e=>{let t={push_device_token:e.pushNotificationDeviceToken,push_notification_provider:nt.OS,push_notification_environment:"production"};if(e.login&&e.password)return Ee({login:e.login,password:e.password,reconnection:!1,userVariables:t});if(e.login_token)return be({login_token:e.login_token,userVariables:t});throw new Error("Login credentials are required. Please provide either login and password or a login token.")});r(this,"onSocketMessage",e=>{Ce(e)&&this.clientIsReady?.resolve(!0)});this.connection=e,this.connection.addListener("telnyx.socket.message",this.onSocketMessage),this.clientIsReady=null}};var te=x(_(),1),Fe=x(L(),1);var T=x(L(),1);function _e({sdp:n,sessionId:e,attach:t,callId:i,callOptions:o}){return{id:(0,T.default)(),jsonrpc:"2.0",method:"telnyx_rtc.invite",params:{sessid:e,sdp:n,"User-Agent":`react-native-${P}`,dialogParams:{attach:t,callID:i,audio:o.audio,prefetchIceCandidates:o.peerConnectionOptions?.prefetchIceCandidates,destination_number:o.destinationNumber,remote_caller_id_name:o.remoteCallerIdName,remote_caller_id_number:o.remoteCallerIdNumber,caller_id_name:o.callerIdName,caller_id_number:o.callerIdNumber,custom_headers:o.customHeaders,clientState:o.clientState}}}}function ke(n){if(!n)return!1;let e=n;return!!e.result?.callID&&!!e.result?.sessid&&e.result?.message==="CALL CREATED"}function Pe(n){if(!n)return!1;let e=n;return e.method==="telnyx_rtc.ringing"&&!!e.params?.callID&&!!e.params?.telnyx_leg_id&&!!e.params?.telnyx_session_id}function Re(n){return{id:n,jsonrpc:"2.0",result:{method:"telnyx_rtc.ringing"}}}function Le(n){if(!n)return!1;let e=n;return e.method==="telnyx_rtc.answer"&&!!e.params?.callID&&!!e.params?.sdp}function Te(n){return{id:n,jsonrpc:"2.0",result:{method:"telnyx_rtc.answer"}}}function Me(n){if(!n)return!1;let e=n;return e.method==="telnyx_rtc.bye"&&!!e.params?.callID&&!!e.params?.cause}function Ae({cause:n,causeCode:e,sessionId:t,callId:i,telnyxLegId:o,telnyxSessionId:a}){return{id:(0,T.default)(),jsonrpc:"2.0",method:"telnyx_rtc.bye",params:{sessid:t,cause:n,causeCode:e,dialogParams:{telnyxSessionId:a,telnyxLegId:o,callID:i}}}}function De(n){return{id:n,jsonrpc:"2.0",result:{method:"telnyx_rtc.invite"}}}function Oe(n){if(!n)return!1;let e=n;return e.method==="telnyx_rtc.invite"&&!!e.params?.callID&&!!e.params?.sdp}function je({dialogParams:n,sdp:e,sessionId:t,callId:i,telnyxLegId:o,telnyxSessionId:a}){return{id:(0,T.default)(),jsonrpc:"2.0",method:"telnyx_rtc.answer",params:{sessid:t,sdp:e,dialogParams:{callID:i,telnyxLegId:o,telnyxSessionId:a,...n},"User-Agent":`react-native-${P}`}}}function X({sessionId:n,action:e,callId:t}){return{jsonrpc:"2.0",id:(0,T.default)(),method:"telnyx_rtc.modify",params:{sessid:n,action:e,dialogParams:{callId:t}}}}function ee(n){if(!n)return!1;let e=n;return!!e.result?.callID&&!!e.result?.sessid&&(e.result?.holdState==="held"||e.result?.holdState==="unheld")}function Ne({digits:n,sessionId:e}){return{id:(0,T.default)(),jsonrpc:"2.0",method:"telnyx_rtc.info",params:{sessid:e,dtmf:n}}}function Be(n){if(!n)return!1;let e=n;return e.result?.message==="SENT"&&!!e.result?.sessid}var f=x(_(),1);import{mediaDevices as it,RTCPeerConnection as rt,RTCSessionDescription as st}from"react-native-webrtc";var V=class V{constructor(e){r(this,"mediaConstraints");r(this,"instance");r(this,"options");r(this,"iceGatheringComplete");r(this,"close",()=>(f.default.debug("[Peer] Closing peer connection"),this.instance&&(this.instance.close(),this.instance=null),this.iceGatheringComplete?.reject(new Error("Peer connection closed")),this.iceGatheringComplete=null,this.options.localStream?.getTracks().forEach(e=>{e.stop()}),this.options.localStream=void 0,this.options.remoteStream?.getTracks().forEach(e=>{e.stop()}),this.options.remoteStream=void 0,this));r(this,"setRemoteDescription",async e=>{if(!this.instance)throw new Error("[Peer] Peer connection not created");return f.default.debug("[Peer] Setting remote description",e),await this.instance.setRemoteDescription(new st(e)).catch(t=>{f.default.error("[Peer] Error setting remote description",t)}),this});r(this,"createPeerConnection",()=>{f.default.debug("[Peer] Creating peer connection"),this.iceGatheringComplete=R(1e3);let e=new rt({bundlePolicy:this.options.peerConnectionOptions?.bundlePolicy||"max-compat",iceServers:this.getIceServers(),iceTransportPolicy:this.options.peerConnectionOptions?.iceTransportPolicy||"all",rtcpMuxPolicy:this.options.peerConnectionOptions?.rtcpMuxPolicy||"require",iceCandidatePoolSize:this.options.peerConnectionOptions?.prefetchIceCandidates?10:0});return this.instance=e,this.instance.addEventListener("icecandidate",this.onIceCandidate),this.instance.addEventListener("icecandidateerror",this.onIceCandidateError),this.instance.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this.instance.addEventListener("connectionstatechange",this.onConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.instance.addEventListener("signalingstatechange",this.onSignalingStateChange),this.instance.addEventListener("track",this.onTrackEvent),this});r(this,"createAnswer",async()=>{if(!this.instance)throw new Error("[Peer] Cannot create answer before peer connection");let e=await this.instance.createAnswer();return await this.instance.setLocalDescription(e).catch(t=>{f.default.error("[Peer] Error setting local description",t)}),this});r(this,"createOffer",async()=>{if(!this.instance)throw new Error("[Peer] Cannot create offer before peer connection");let e=await this.instance.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!1});return await this.instance.setLocalDescription(e).catch(t=>{f.default.error("[Peer] Error setting local description",t)}),this});r(this,"attachLocalStream",async e=>{if(f.default.debug("[Peer] Attaching local stream",e),!this.instance)throw new Error("[Peer] Peer connection not created");return this.mediaConstraints=e,this.options.localStream==null&&(this.options.localStream=await it.getUserMedia(e)),this.options.localStream.getTracks().forEach(t=>{f.default.debug("[Peer] Adding track",t),this.instance?.addTrack(t,this.options.localStream)}),this});r(this,"waitForIceGatheringComplete",async()=>{if(!this.iceGatheringComplete)throw new Error("Ice gathering not started");return await this.iceGatheringComplete.promise,f.default.debug("[Peer] ICE gathering complete"),this});r(this,"setMediaStreamState",(e,t)=>{if(f.default.debug("[Peer] Setting media stream state",{enabled:t,stream:e}),!e)throw new Error("[Peer] No media stream to set state");return e.getTracks().forEach(i=>{f.default.debug("[Peer] Track state set",{track:i,enabled:t}),i.enabled=t}),this});r(this,"onIceGatheringStateChange",()=>{this.instance?.iceGatheringState==="complete"&&(f.default.debug("[Peer] ICE gathering complete"),this.iceGatheringComplete?.resolve(!0),this.iceGatheringComplete=null)});r(this,"onIceCandidate",e=>{f.default.debug("[Peer] ICE candidate end",e),this.iceGatheringComplete?.resolve(!0)});r(this,"onIceCandidateError",e=>{f.default.error("[Peer] ICE candidate error",e)});r(this,"onTrackEvent",e=>{f.default.debug("[Peer] Remote track event",e),e.streams&&e.streams.length>0&&(this.options.remoteStream=e.streams[0])});r(this,"onSignalingStateChange",()=>{f.default.debug("[Peer] Signaling state change",this.instance?.signalingState)});r(this,"onIceConnectionStateChange",()=>{f.default.debug("[Peer] ICE connection state change",this.instance?.iceConnectionState)});r(this,"onConnectionStateChange",()=>{f.default.debug("[Peer] Connection state change",this.instance?.connectionState)});this.instance=null,this.iceGatheringComplete=null,this.mediaConstraints={audio:!0,video:!1},this.options=e}get remoteDescription(){if(!this.instance)throw new Error("[Peer] Peer connection not created");return this.instance.remoteDescription}get localDescription(){if(!this.instance)throw new Error("[Peer] Peer connection not created");return this.instance.localDescription}getIceServers(){return this.options.peerConnectionOptions?.iceServers&&this.options.peerConnectionOptions?.iceServers.length>0?this.options.peerConnectionOptions.iceServers:[{urls:"stun:stun.l.google.com:19302"}]}};r(V,"createOffer",async e=>await new V(e).createPeerConnection().attachLocalStream({audio:!0,video:!1}).then(i=>i.createOffer()).then(i=>i.waitForIceGatheringComplete()));var j=V;var M=class n extends E.default{constructor({connection:t,options:i,sessionId:o,direction:a,callId:d,telnyxLegId:p,telnyxSessionId:s,telnyxCallControlId:c=null,callState:C="new"}){super();r(this,"direction");r(this,"callId");r(this,"telnyxSessionId");r(this,"telnyxCallControlId");r(this,"telnyxLegId");r(this,"state");r(this,"connection");r(this,"options");r(this,"peer");r(this,"sessionId");r(this,"answer",async()=>{if(!this.peer)throw new Error("[Call] Peer is not created");await this.peer.attachLocalStream({audio:!0,video:!1}).then(t=>t.createAnswer()).then(t=>t.waitForIceGatheringComplete()),await this.connection.sendAndWait(je({callId:this.callId,dialogParams:{},sdp:this.peer.localDescription.sdp,telnyxLegId:this.telnyxLegId,telnyxSessionId:this.telnyxSessionId,sessionId:this.sessionId})),this.setState("active")});r(this,"hangup",()=>{this.connection.send(Ae({callId:this.callId,telnyxLegId:this.telnyxLegId,telnyxSessionId:this.telnyxSessionId,cause:"USER_BUSY",causeCode:17,sessionId:this.sessionId})),this.peer?.close(),this.setState("ended")});r(this,"hold",async()=>{let t=X({action:"hold",callId:this.callId,sessionId:this.sessionId}),i=await this.connection.sendAndWait(t);if(!ee(i))throw new Error(`[Call] Invalid hold response received: ${JSON.stringify(i)}`);if(i.result.holdState!=="held")throw new Error(`[Call] Hold action failed: ${JSON.stringify(i)}`);this.setState("held")});r(this,"unhold",async()=>{let t=X({action:"unhold",sessionId:this.sessionId,callId:this.callId}),i=await this.connection.sendAndWait(t);if(!ee(i))throw new Error(`[Call] Invalid hold response received: ${JSON.stringify(i)}`);if(i.result.holdState!=="held")throw new Error(`[Call] Hold action failed: ${JSON.stringify(i)}`);this.setState("active")});r(this,"dtmf",async t=>{let i=Ne({digits:t,sessionId:this.sessionId,callId:this.callId}),o=await this.connection.sendAndWait(i);if(!Be(o))throw new Error(`[Call] Invalid DTMF response received: ${JSON.stringify(o)}`);return o.result});r(this,"mute",()=>{if(!this.peer)throw new Error("[Call] Peer not created");if(!this.options.localStream)throw new Error("[Call] Local stream not set");this.peer.setMediaStreamState(this.options.localStream,!1)});r(this,"unmute",()=>{if(!this.peer)throw new Error("[Call] Peer not created");if(!this.options.localStream)throw new Error("[Call] Local stream not set");this.peer.setMediaStreamState(this.options.localStream,!0)});r(this,"deaf",()=>{if(!this.peer)throw new Error("[Call] Peer not created");if(!this.options.remoteStream)throw new Error("[Call] Remote stream not set");this.peer.setMediaStreamState(this.options.remoteStream,!1)});r(this,"undeaf",()=>{if(!this.peer)throw new Error("[Call] Peer not created");if(!this.options.remoteStream)throw new Error("[Call] Remote stream not set");this.peer.setMediaStreamState(this.options.remoteStream,!0)});r(this,"invite",async()=>{this.peer=await j.createOffer(this.options);let t=await this.connection.sendAndWait(_e({attach:!1,callOptions:this.options,sessionId:this.sessionId,callId:this.callId,sdp:this.peer.localDescription.sdp}));if(!ke(t))throw new Error(`[Call] Invalid invite ACK message received: ${JSON.stringify(t)}`);this.callId=t.result.callID});r(this,"setState",t=>{this.state=t,this.emit("telnyx.call.state",this,t)});r(this,"onSocketMessage",t=>{if(Pe(t)&&t.params.callID===this.callId)return this.handleRingingEvent(t);if(Le(t)&&t.params.callID===this.callId)return this.handleAnswerEvent(t);if(Me(t)&&t.params.callID===this.callId)return this.handleHangupEvent(t)});r(this,"handleRingingEvent",t=>{te.default.debug("[Call] Ringing event received",t),this.setState("ringing"),this.telnyxLegId=t.params.telnyx_leg_id,this.telnyxSessionId=t.params.telnyx_session_id,this.connection.send(Re(t.id))});r(this,"handleAnswerEvent",async t=>{if(!this.peer)throw new Error("[Call] Peer not created");await this.peer.setRemoteDescription({type:"answer",sdp:t.params.sdp}),this.connection.send(Te(t.id)),this.setState("active")});r(this,"handleHangupEvent",t=>{te.default.debug("[Call] Hangup event received",t),this.setState("ended"),this.peer?.close()});this.connection=t,this.options=i,this.sessionId=o,this.callId=d??(0,Fe.default)(),this.direction=a,this.state=C,this.telnyxLegId=p,this.telnyxSessionId=s,this.telnyxCallControlId=c,this.peer=null,this.connection.addListener("telnyx.socket.message",this.onSocketMessage)}static async createInboundCall({connection:t,options:i,remoteSDP:o,sessionId:a,telnyxLegId:d,telnyxSessionId:p,callId:s}){let c=new n({connection:t,options:i,sessionId:a,direction:"inbound",telnyxLegId:d,telnyxSessionId:p,callId:s,callState:"ringing"});return c.peer=new j(i),c.peer.createPeerConnection(),c.peer.setRemoteDescription({type:"offer",sdp:o}),c.setState("ringing"),c}get remoteStream(){return this.options.remoteStream}get localStream(){return this.options.localStream}get telnyxIds(){return{telnyxSessionId:this.telnyxSessionId,telnyxLegId:this.telnyxLegId,telnyxCallControlId:this.telnyxCallControlId}}};var He=new ce;var ne=class extends E.default{constructor(t){super();r(this,"options");r(this,"call");r(this,"sessionId");r(this,"connection");r(this,"loginHandler");r(this,"keepAliveHandler");r(this,"newCall",async t=>{if(!this.connection)throw b.default.error("[TelnyxRTC] No connection exists. Please connect first."),new Error("[TelnyxRTC] No connection exists. Please connect first.");if(!this.sessionId)throw b.default.error("[TelnyxRTC] No session ID exists. Please connect first."),new Error("[TelnyxRTC] No session ID exists. Please connect first.");return this.call=new M({connection:this.connection,direction:"outbound",sessionId:this.sessionId,telnyxSessionId:null,telnyxLegId:null,callId:null,options:t}),await this.call.invite(),this.call});r(this,"onSocketMessage",t=>{if(Oe(t))return this.handleCallInvite(t)});r(this,"handleCallInvite",async t=>{if(!this.connection)throw b.default.error("[TelnyxRTC] No connection exists. Please connect first."),new Error("[TelnyxRTC] Cannot receive calls without connection.");if(!this.sessionId)throw new Error("[TelnyxRTC] Cannot receive calls without session ID.");this.connection?.send(De(t.id)),this.call=await M.createInboundCall({connection:this.connection,remoteSDP:t.params.sdp,sessionId:this.sessionId,callId:t.params.callID,telnyxLegId:t.params.telnyx_leg_id,telnyxSessionId:t.params.telnyx_session_id,options:{destinationNumber:t.params.caller_id_number}}),this.emit("telnyx.call.incoming",this.call,t),He.emit("telnyx.notification",{type:"callUpdate",call:this.call})});this.options=t,this.connection=null,this.sessionId=null,this.loginHandler=null,this.keepAliveHandler=null,this.call=null,b.default.setLevel(t.logLevel||"warn")}async connect(){if(this.connection){b.default.warn("A connection already exists. Please close it before creating a new one.");return}if(this.connection=new O,this.connection.addListener("telnyx.socket.message",this.onSocketMessage),this.loginHandler=new W(this.connection),this.keepAliveHandler=new K(this.connection),this.keepAliveHandler.start(),this.sessionId=await this.loginHandler.login(this.options),!this.sessionId)throw b.default.error("Login failed. Please check your credentials and try again."),new Error("Login failed. Please check your credentials and try again.");this.emit("telnyx.client.ready")}disconnect(){if(!this.connection){b.default.warn("No connection exists.");return}this.connection.close(),this.connection=null,this.removeAllListeners()}get connected(){return this.connection!==null&&this.connection.isConnected}};export{M as Call,O as Connection,ne as TelnyxRTC};