@telnyx/ai-agent-widget 0.15.0 → 0.16.0
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/dist/bundle.min.js +2 -2
- package/package.json +2 -2
package/dist/bundle.min.js
CHANGED
|
@@ -97,7 +97,7 @@
|
|
|
97
97
|
`,JSON.stringify(r,null,2),`
|
|
98
98
|
`),Rt[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!J(r.id,r)){const l=Dr(r);J(V.SocketMessage,r,this.session.uuid),l&&(this.previousGatewayState=l)}}else this._handleStringResponse(r)}}sendRawText(t){this._wsClient.send(t)}send(t){const{request:n}=t,i=new Promise((s,o)=>{if(n.hasOwnProperty("result"))return s();ju(n.id,r=>{const{result:a,error:l}=Nu(r);return l?o(l):s(a)})});return B.debug(`SEND:
|
|
99
99
|
`,JSON.stringify(n,null,2),`
|
|
100
|
-
`),this._wsClient.send(JSON.stringify(n)),i}close(){this._wsClient&&(ln(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close()),this._wsClient=null}_unsetTimer(t){clearTimeout(this._timers[t]),delete this._timers[t]}_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(V.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else B.warn("Unknown message from socket",t)}}class qn{buildRequest(t){this.request=Object.assign({jsonrpc:"2.0",id:an()},t)}}const Uu={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class Dt extends qn{constructor(t={}){if(super(),t.hasOwnProperty("dialogParams")){const n=Mr(t.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const i in Uu)i&&n.hasOwnProperty(i)&&(n[Uu[i]]=n[i],delete n[i]);t.dialogParams=n}this.buildRequest({method:this.toString(),params:t})}}class Gu extends Dt{constructor(){super(),this.method=nt.GatewayState,this.buildRequest({method:this.method,params:{}})}}class zv{constructor(t){this.pendingRequestId=null,this.onSocketMessage=n=>G(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Dr(n))}),this.getIsRegistered=()=>G(this,void 0,void 0,function*(){const n=new Gu;this.pendingRequestId=n.request.id,this.gatewayStateTask=Fu({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[Rt.REGISTER,Rt.REGED].includes(i)}),this.session=t,this.gatewayStateTask=Fu({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Wv{constructor(t){if(this.options=t,this.uuid=an(),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 $u(this),this.registerAgent=new zv(this)}get __logger(){return B}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*Vu(2,6)}execute(t){return this._idle?new Promise(n=>this._executeQueue.push({resolve:n,msg:t})):this.connected?this.connection.send(t):new Promise(n=>{this._executeQueue.push({resolve:n,msg:t}),this.connect()})}executeRaw(t){this._idle?this._executeQueue.push({msg:t}):this.connection.sendRawText(t)}validateOptions(){return Lr(this.options)||Oi(this.options)}broadcast(t){}disconnect(){return G(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(t,n){return un(t,n,this.uuid),this}off(t,n){return dn(t,n,this.uuid),this}connect(){return G(this,void 0,void 0,function*(){this.connection||(this.connection=new $u(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()})}_handleLoginError(t){J(V.Error,{error:t,sessionId:this.sessionid},this.uuid)}_onSocketOpen(){return G(this,void 0,void 0,function*(){})}onNetworkClose(){this.relayProtocol&&Vr(this.relayProtocol);for(const t in this.subscriptions)Vr(t);this.subscriptions={},this.contexts=[],this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>this.connect(),this.reconnectDelay))}_onSocketMessage(t){}_removeSubscription(t,n){this._existsSubscription(t,n)&&(n?(delete this.subscriptions[t][n],dn(t,null,n)):(delete this.subscriptions[t],Vr(t)))}_addSubscription(t,n=null,i){this._existsSubscription(t,i)||(this._existsSubscription(t)||(this.subscriptions[t]={}),this.subscriptions[t][i]={},ln(n)&&un(t,n,i))}_existsSubscription(t,n){return!(!this.subscriptions.hasOwnProperty(t)||!(!n||n&&this.subscriptions[t].hasOwnProperty(n)))}_attachListeners(){this._detachListeners(),this.on(V.SocketOpen,this._onSocketOpen),this.on(V.SocketClose,this.onNetworkClose),this.on(V.SocketError,this.onNetworkClose),this.on(V.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(V.SocketOpen,this._onSocketOpen),this.off(V.SocketClose,this.onNetworkClose),this.off(V.SocketError,this.onNetworkClose),this.off(V.SocketMessage,this._onSocketMessage)}_emptyExecuteQueues(){this._executeQueue.forEach(({resolve:t,msg:n})=>{typeof n=="string"?this.executeRaw(n):t(this.execute(n))})}_closeConnection(){this._idle=!0,clearTimeout(this._keepAliveTimeout),this.connection&&this.connection.close()}_keepAlive(){this._doKeepAlive===!0&&(this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._keepAlive(),3e4))}static on(t,n){un(t,n)}static off(t){dn(t)}static uuid(){return an()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}getIsRegistered(){return this.registerAgent.getIsRegistered()}}const Fr=e=>navigator.mediaDevices.getUserMedia(e),Ni=e=>e&&e instanceof MediaStream,Vi=(e,t)=>{const n=Hn(e);n!==null&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=t)},Hu=(e,t)=>G(void 0,void 0,void 0,function*(){const n=Hn(e);if(n===null)return B.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof t!="string")return B.info(`Invalid speaker deviceId: '${t}'`),!1;try{return yield n.setSinkId(t),!0}catch{return!1}}),qv=e=>{e&&e.readyState==="live"&&e.stop()},Kn=e=>{Ni(e)&&e.getTracks().forEach(qv),e=null},Fi=e=>G(void 0,void 0,void 0,function*(){B.info("RTCService.getUserMedia",e);const{audio:t,video:n}=e;if(!t&&!n)return null;try{return yield Fr(e)}catch(i){throw B.error("getUserMedia error: ",i),i}}),Xn=(e=null,t=!1)=>G(void 0,void 0,void 0,function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===le.AudioIn||s===le.AudioOut,video:!s||s===le.Video}))(e)).catch(s=>(console.error(s),null));if(i){if(Kn(i),n=yield navigator.mediaDevices.enumerateDevices(),e&&(n=n.filter(o=>o.kind===e)),t===!0)return n;const s=[];n=n.filter(o=>{if(!o.groupId)return!0;const r=`${o.kind}-${o.groupId}`;return!s.includes(r)&&(s.push(r),!0)})}return n}),zu=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Bi=(e,t,n)=>G(void 0,void 0,void 0,function*(){const i=yield Xn(n,!0);for(let s=0;s<i.length;s++){const{deviceId:o,label:r}=i[s];if(e===o||t===r)return o}return null}),Wu=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map(n=>{t.hasOwnProperty(n)&&e[n]!==null&&e[n]!==void 0||delete e[n]})},qu=(e,t,n,i)=>G(void 0,void 0,void 0,function*(){const{deviceId:s}=i;if(s===void 0&&(e||t)){const o=yield Bi(e,t,n).catch(r=>null);o&&(i.deviceId={exact:o})}return i}),ji=(e,t)=>{if(!e)return!1;const{subscribed:n,alreadySubscribed:i}=Br(e);return n.includes(t)||i.includes(t)},Br=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach(n=>{t[n]=e[`${n}Channels`]||[]}),t},hn=(e,t=null,n=null)=>{if(!Ni(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(s=>{switch(n){case"on":case!0:s.enabled=!0;break;case"off":case!1:s.enabled=!1;break;default:s.enabled=!s.enabled}})},Ku=e=>{hn(e,"audio",!0)},Xu=e=>{hn(e,"audio",!1)},Yu=e=>{hn(e,"audio",null)};function Kv(){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 d=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),u=d[0],p=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:p,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const d=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),u=d[0],p=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:p,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const d=navigator.userAgent.match(/safari/gim)[0],u=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),p=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:p,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const d=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),u=d[0],p=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:p,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,l=window.navigator&&window.navigator.mediaDevices,c=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:e,browserName:t,browserVersion:n,supportWebRTC:!!(o&&r&&a&&l&&c),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!Fi}}catch(e){return e.message}}var vt;function Zu(e,t){const n=document.getElementById(t);if(n)return n;if(e&&t){const i=document.createElement("audio");return i.id=t,i.loop=!0,i.src=e,i.preload="auto",i.load(),document.body.appendChild(i),i}return null}function Ju(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 Qu(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"})(vt||(vt={}));var td="2.22.14",jr=td;class Xv extends Dt{constructor(t,n,i,s,o={},r){super(),this.method="login";const a={login:t,passwd:n,login_token:i,userVariables:o,reconnection:r,loginParams:{},"User-Agent":{sdkVersion:jr,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class Yv extends Dt{constructor(t,n){super(),this.buildRequest({id:t,result:{method:n}})}}class Zv extends Dt{toString(){return nt.Invite}}class Jv extends Dt{toString(){return nt.Answer}}class Qv extends Dt{toString(){return nt.Attach}}class t_ extends Dt{toString(){return nt.Bye}}class $r extends Dt{toString(){return nt.Modify}}class ed extends Dt{toString(){return nt.Info}}class e_ extends Dt{toString(){return nt.Broadcast}}class n_ extends Dt{toString(){return nt.Subscribe}}class i_ extends Dt{toString(){return nt.Unsubscribe}}class s_ extends qn{constructor(t){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:an(),type:"message",role:"user",content:[{type:"input_text",text:t}]}}})}}const nd=(e,t)=>{const{contentType:n,canvasType:i,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&i!=="mcu-personal-canvas"&&delete o.memberID;const a={type:ae.conferenceUpdate,call:e.calls[s],canvasInfo:r_(o),currentLayerIdx:r};switch(n){case"layer-info":{const l=Object.assign({action:At.LayerInfo},a);J(V.Notification,l,e.uuid);break}case"layout-info":{const l=Object.assign({action:At.LayoutInfo},a);J(V.Notification,l,e.uuid);break}}},r_=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Ou(t)};var $i,id=Lu(function(e,t){var n;function i(){}function s(){s.init.call(this)}function o(f){return f._maxListeners===void 0?s.defaultMaxListeners:f._maxListeners}function r(f,m,h,v){var T,R,E;if(typeof h!="function")throw new TypeError('"listener" argument must be a function');if((R=f._events)?(R.newListener&&(f.emit("newListener",m,h.listener?h.listener:h),R=f._events),E=R[m]):(R=f._events=new i,f._eventsCount=0),E){if(typeof E=="function"?E=R[m]=v?[h,E]:[E,h]:v?E.unshift(h):E.push(h),!E.warned&&(T=o(f))&&0<T&&E.length>T){E.warned=!0;var M=new Error("Possible EventEmitter memory leak detected. "+E.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");M.name="MaxListenersExceededWarning",M.emitter=f,M.type=m,M.count=E.length,function(I){typeof console.warn=="function"?console.warn(I):console.log(I)}(M)}}else E=R[m]=h,++f._eventsCount;return f}function a(f,m,h){function v(){f.removeListener(m,v),T||(T=!0,h.apply(f,arguments))}var T=!1;return v.listener=h,v}function l(f){var m=this._events;if(m){var h=m[f];if(typeof h=="function")return 1;if(h)return h.length}return 0}function c(f,m){for(var h=Array(m);m--;)h[m]=f[m];return h}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(f){if(typeof f!="number"||0>f||isNaN(f))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=f,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(f){var m,h,v,T,R,E,M,I=f==="error";if(E=this._events)I=I&&E.error==null;else if(!I)return!1;if(M=this.domain,I){if(m=arguments[1],!M){if(m instanceof Error)throw m;var N=new Error('Uncaught, unspecified "error" event. ('+m+")");throw N.context=m,N}return m||(m=new Error('Uncaught, unspecified "error" event')),m.domainEmitter=this,m.domain=M,m.domainThrown=!1,M.emit("error",m),!1}if(!(h=E[f]))return!1;var K=typeof h=="function";switch(v=arguments.length){case 1:(function(F,rt,Q){if(rt)F.call(Q);else for(var j=F.length,lt=c(F,j),z=0;z<j;++z)lt[z].call(Q)})(h,K,this);break;case 2:(function(F,rt,Q,j){if(rt)F.call(Q,j);else for(var lt=F.length,z=c(F,lt),Y=0;Y<lt;++Y)z[Y].call(Q,j)})(h,K,this,arguments[1]);break;case 3:(function(F,rt,Q,j,lt){if(rt)F.call(Q,j,lt);else for(var z=F.length,Y=c(F,z),Z=0;Z<z;++Z)Y[Z].call(Q,j,lt)})(h,K,this,arguments[1],arguments[2]);break;case 4:(function(F,rt,Q,j,lt,z){if(rt)F.call(Q,j,lt,z);else for(var Y=F.length,Z=c(F,Y),tt=0;tt<Y;++tt)Z[tt].call(Q,j,lt,z)})(h,K,this,arguments[1],arguments[2],arguments[3]);break;default:for(T=Array(v-1),R=1;R<v;R++)T[R-1]=arguments[R];(function(F,rt,Q,j){if(rt)F.apply(Q,j);else for(var lt=F.length,z=c(F,lt),Y=0;Y<lt;++Y)z[Y].apply(Q,j)})(h,K,this,T)}return!0},s.prototype.addListener=function(f,m){return r(this,f,m,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(f,m){return r(this,f,m,!0)},s.prototype.once=function(f,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.on(f,a(this,f,m)),this},s.prototype.prependOnceListener=function(f,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(f,a(this,f,m)),this},s.prototype.removeListener=function(f,m){var h,v,T,R,E;if(typeof m!="function")throw new TypeError('"listener" argument must be a function');if(!(v=this._events))return this;if(!(h=v[f]))return this;if(h===m||h.listener&&h.listener===m)--this._eventsCount==0?this._events=new i:(delete v[f],v.removeListener&&this.emit("removeListener",f,h.listener||m));else if(typeof h!="function"){for(T=-1,R=h.length;0<R--;)if(h[R]===m||h[R].listener&&h[R].listener===m){E=h[R].listener,T=R;break}if(0>T)return this;if(h.length===1){if(h[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete v[f]}else(function(M,I){for(var N=I,K=N+1,F=M.length;K<F;N+=1,K+=1)M[N]=M[K];M.pop()})(h,T);v.removeListener&&this.emit("removeListener",f,E||m)}return this},s.prototype.removeAllListeners=function(f){var m,h;if(!(h=this._events))return this;if(!h.removeListener)return arguments.length===0?(this._events=new i,this._eventsCount=0):h[f]&&(--this._eventsCount==0?this._events=new i:delete h[f]),this;if(arguments.length===0){for(var v,T=Object.keys(h),R=0;R<T.length;++R)(v=T[R])!=="removeListener"&&this.removeAllListeners(v);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(m=h[f])=="function")this.removeListener(f,m);else if(m)do this.removeListener(f,m[m.length-1]);while(m[0]);return this},s.prototype.listeners=function(f){var m,h,v=this._events;return v?h=(m=v[f])?typeof m=="function"?[m.listener||m]:function(T){for(var R=Array(T.length),E=0;E<R.length;++E)R[E]=T[E].listener||T[E];return R}(m):[]:h=[],h},s.listenerCount=function(f,m){return typeof f.listenerCount=="function"?f.listenerCount(m):l.call(f,m)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var d,u=new Uint8Array(16);function p(){if(!d&&!(d=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return d(u)}for(var g=/^(?:[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,_=[],w=0;256>w;++w)_.push((w+256).toString(16).substr(1));function b(f){var m=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,h=(_[f[m+0]]+_[f[m+1]]+_[f[m+2]]+_[f[m+3]]+"-"+_[f[m+4]]+_[f[m+5]]+"-"+_[f[m+6]]+_[f[m+7]]+"-"+_[f[m+8]]+_[f[m+9]]+"-"+_[f[m+10]]+_[f[m+11]]+_[f[m+12]]+_[f[m+13]]+_[f[m+14]]+_[f[m+15]]).toLowerCase();if(!function(v){return typeof v=="string"&&g.test(v)}(h))throw TypeError("Stringified UUID is invalid");return h}function y(f,m,h){var v=(f=f||{}).random||(f.rng||p)();return v[6]=64|15&v[6],v[8]=128|63&v[8],b(v)}function S(f,m){if(!f||!m)return{};const h={...f};if(h.localCandidateId){const v=m.get(h.localCandidateId);h.local={...v}}if(h.remoteCandidateId){const v=m.get(h.remoteCandidateId);h.remote={...v}}return h}function C(f,m,h){return 8*function(v,T,R){const E=v[R],M=T?T[R]:null;return E===null||M===null?null:(E-M)/(v.timestamp-T.timestamp)*1e3}(f,m,h)}function P(f){if(!f.entries)return f;const m={};return f.forEach(function(h,v){m[v]=h}),m}function L(f,m,h={}){if(!f)return null;let v={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};h.remote&&(v.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const T of f.values())switch(T.type){case"outbound-rtp":{const R=T.mediaType||T.kind,E={};let M={};if(!["audio","video"].includes(R))continue;if(T.codecId){const I=f.get(T.codecId);I&&(E.clockRate=I.clockRate,E.mimeType=I.mimeType,E.payloadType=I.payloadType)}M=f.get(T.mediaSourceId)||f.get(T.trackId)||{},v[R].outbound.push({...T,...E,track:{...M}});break}case"inbound-rtp":{let R=T.mediaType||T.kind,E={};const M={};if(!["audio","video"].includes(R))if(T.id.includes("Video"))R="video";else{if(!T.id.includes("Audio"))continue;R="audio"}if(T.codecId){const I=f.get(T.codecId);I&&(M.clockRate=I.clockRate,M.mimeType=I.mimeType,M.payloadType=I.payloadType)}if(!v.connection.id&&T.transportId){const I=f.get(T.transportId);if(I&&I.selectedCandidatePairId){const N=f.get(I.selectedCandidatePairId);v.connection=S(N,f)}}E=f.get(T.mediaSourceId)||f.get(T.trackId)||{},v[R].inbound.push({...T,...M,track:{...E}});break}case"peer-connection":v.connection.dataChannelsClosed=T.dataChannelsClosed,v.connection.dataChannelsOpened=T.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!h.remote)break;let R=T.mediaType||T.kind;const E={};if(!["audio","video"].includes(R))if(T.id.includes("Video"))R="video";else{if(!T.id.includes("Audio"))continue;R="audio"}if(T.codecId){const M=f.get(T.codecId);M&&(E.clockRate=M.clockRate,E.mimeType=M.mimeType,E.payloadType=M.payloadType)}if(!v.connection.id&&T.transportId){const M=f.get(T.transportId);if(M&&M.selectedCandidatePairId){const I=f.get(M.selectedCandidatePairId);v.connection=S(I,f)}}v.remote[R].inbound.push({...T,...E});break}case"remote-outbound-rtp":{if(!h.remote)break;const R=T.mediaType||T.kind,E={};if(!["audio","video"].includes(R))continue;if(T.codecId){const M=f.get(T.codecId);M&&(E.clockRate=M.clockRate,E.mimeType=M.mimeType,E.payloadType=M.payloadType)}v.remote[R].outbound.push({...T,...E});break}}if(!v.connection.id)for(const T of f.values())T.type==="candidate-pair"&&T.nominated&&T.state==="succeeded"&&(v.connection=S(T,f));return v=function(T,R){return R&&(T.audio.inbound.map(E=>{let M=R.audio.inbound.find(I=>I.id===E.id);E.bitrate=C(E,M,"bytesReceived"),E.packetRate=C(E,M,"packetsReceived")}),T.audio.outbound.map(E=>{let M=R.audio.outbound.find(I=>I.id===E.id);E.bitrate=C(E,M,"bytesSent"),E.packetRate=C(E,M,"packetsSent")}),T.video.inbound.map(E=>{let M=R.video.inbound.find(I=>I.id===E.id);E.bitrate=C(E,M,"bytesReceived"),E.packetRate=C(E,M,"packetsReceived")}),T.video.outbound.map(E=>{let M=R.video.outbound.find(I=>I.id===E.id);E.bitrate=C(E,M,"bytesSent"),E.packetRate=C(E,M,"packetsSent")})),T}(v,m),v}let D,x={},k=[];t.WebRTCStats=class extends s{constructor(f){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"],typeof window>"u")throw new Error("WebRTCStats only works in browser");const m={...f};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=m.getStatsInterval||1e3,this.rawStats=!!m.rawStats,this.statsObject=!!m.statsObject,this.filteredStats=!!m.filteredStats,this.shouldWrapGetUserMedia=!!m.wrapGetUserMedia,typeof m.remote=="boolean"&&(this.remote=m.remote),this.debug=!!m.debug,this.logLevel=m.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(f,m){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:f,pc:m})}async addConnection(f){const{pc:m,peerId:h}=f;let{connectionId:v,remote:T}=f;if(T=typeof T=="boolean"?T:this.remote,!(m&&m instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!h)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[h]){if(v&&v in this.peersToMonitor[h])throw new Error(`We are already monitoring connection with id ${v}.`);for(let E in this.peersToMonitor[h]){const M=this.peersToMonitor[h][E];if(M.pc===m)throw new Error(`We are already monitoring peer with id ${h}.`);M.pc.connectionState==="closed"&&this.removeConnection({pc:M.pc})}}const R=m.getConfiguration();return R.iceServers&&R.iceServers.forEach(function(E){delete E.credential}),v||(v=y()),this.emitEvent({event:"addConnection",tag:"peer",peerId:h,connectionId:v,data:{options:f,peerConfiguration:R}}),this.monitorPeer({peerId:h,connectionId:v,pc:m,remote:T}),{connectionId:v}}getTimeline(f){return this.timeline=this.timeline.sort((m,h)=>m.timestamp.getTime()-h.timestamp.getTime()),f?this.timeline.filter(m=>m.tag===f):this.timeline}get logger(){const f=m=>{const h=["none","error","warn","info","debug"];return h.slice(0,h.indexOf(this.logLevel)+1).indexOf(m)>-1};return{error(...m){this.debug&&f("error")&&console.error("[webrtc-stats][error] ",...m)},warn(...m){this.debug&&f("warn")&&console.warn("[webrtc-stats][warn] ",...m)},info(...m){this.debug&&f("info")&&console.log("[webrtc-stats][info] ",...m)},debug(...m){this.debug&&f("debug")&&console.debug("[webrtc-stats][debug] ",...m)}}}removeConnection(f){let m,{connectionId:h,pc:v}=f;if(!v&&!h)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(h){if(typeof h!="string")throw new Error("connectionId must be a string.");for(let T in this.peersToMonitor)h in this.peersToMonitor[T]&&(v=this.peersToMonitor[T][h].pc,m=T)}else if(v){if(!(v instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let T in this.peersToMonitor)for(let R in this.peersToMonitor[T])this.peersToMonitor[T][R].pc===v&&(h=R,m=T)}if(!v||!h)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(h,v),delete this.peersToMonitor[m][h],Object.values(this.peersToMonitor[m]).length===0&&delete this.peersToMonitor[m],{connectionId:h}}removeAllPeers(){for(let f in this.peersToMonitor)this.removePeer(f)}removePeer(f){if(this.logger.info(`Removing PeerConnection with id ${f}.`),this.peersToMonitor[f]){for(let m in this.peersToMonitor[f]){let h=this.peersToMonitor[f][m].pc;this.removePeerConnectionEventListeners(m,h)}delete this.peersToMonitor[f]}}destroy(){this.removeAllPeers(),k.forEach(f=>{this.removeTrackEventListeners(f)}),k=[],this.shouldWrapGetUserMedia&&D&&(navigator.mediaDevices.getUserMedia=D)}monitorPeer(f){let{peerId:m,connectionId:h,pc:v,remote:T}=f;if(!v)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const R={pc:v,connectionId:h,stream:null,stats:{parsed:null,raw:null},options:{remote:T}};if(this.peersToMonitor[m]){if(h in this.peersToMonitor[m])return void this.logger.warn(`Already watching connection with ID ${h}`);this.peersToMonitor[m][h]=R}else this.peersToMonitor[m]={[h]:R};this.addPeerConnectionEventListeners(m,h,v),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(f=>{f.forEach(m=>{this.emitEvent(m)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(f=null){this.logger.info(f?`Getting stats from peer ${f}`:"Getting stats from all peers");let m={};if(f){if(!this.peersToMonitor[f])throw new Error(`Cannot get stats. Peer with id ${f} does not exist`);m[f]=this.peersToMonitor[f]}else m=this.peersToMonitor;let h=[];for(const v in m)for(const T in m[v]){const R=m[v][T],E=R.pc;if(E&&!this.checkIfConnectionIsClosed(v,T,E))try{const M=this.getTimestamp(),I=E.getStats(null);if(I){const N=await I,K=this.getTimestamp(),F=P(N),rt={remote:R.options.remote},Q=L(N,R.stats.parsed,rt),j={event:"stats",tag:"stats",peerId:v,connectionId:T,timeTaken:K-M,data:Q};this.rawStats===!0&&(j.rawStats=N),this.statsObject===!0&&(j.statsObject=F),this.filteredStats===!0&&(j.filteredStats=this.filteroutStats(F)),h.push(j),R.stats.parsed=Q}else this.logger.error(`PeerConnection from peer ${v} did not return any stats data`)}catch(M){this.logger.error(M)}}return h}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const f in this.peersToMonitor)for(const m in this.peersToMonitor[f]){const h=this.peersToMonitor[f][m].pc;this.checkIfConnectionIsClosed(f,m,h)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(f,m,h){const v=this.isConnectionClosed(h);if(v){this.removeConnection({pc:h});let T=h.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:T,peerId:f,connectionId:m,tag:"connection",data:"closed"})}return v}isConnectionClosed(f){return f.connectionState==="closed"||f.iceConnectionState==="closed"}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."),D=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const f=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return f({constraints:arguments[0]}),D.apply(navigator.mediaDevices,arguments).then(m=>(f({stream:m}),m),m=>(f({error:m}),Promise.reject(m)))}).bind(navigator.mediaDevices)}filteroutStats(f={}){const m={...f};for(const v in m){var h=m[v];this.statsToMonitor.includes(h.type)||delete m[v]}return m}get peerConnectionListeners(){return{icecandidate:(f,m,h,v)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",v),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:f,connectionId:m,data:v.candidate})},track:(f,m,h,v)=>{this.logger.debug(`[pc-event] track | peerId: ${f}`,v);const T=v.track,R=v.streams[0];f in this.peersToMonitor&&m in this.peersToMonitor[f]&&(this.peersToMonitor[f][m].stream=R),this.addTrackEventListeners(T,m),this.emitEvent({event:"ontrack",tag:"track",peerId:f,connectionId:m,data:{stream:R?this.getStreamDetails(R):null,track:T?this.getMediaTrackDetails(T):null,title:v.track.kind+":"+v.track.id+" "+v.streams.map(function(E){return"stream:"+E.id})}})},signalingstatechange:(f,m,h)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${f}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:f,connectionId:m,data:{signalingState:h.signalingState,localDescription:h.localDescription,remoteDescription:h.remoteDescription}})},iceconnectionstatechange:(f,m,h)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${f}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:f,connectionId:m,data:h.iceConnectionState})},icegatheringstatechange:(f,m,h)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${f}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:f,connectionId:m,data:h.iceGatheringState})},icecandidateerror:(f,m,h,v)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${f}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:f,connectionId:m,error:{errorCode:v.errorCode}})},connectionstatechange:(f,m,h)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${f}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:f,connectionId:m,data:h.connectionState})},negotiationneeded:(f,m,h)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${f}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:f,connectionId:m})},datachannel:(f,m,h,v)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${f}`,v),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:f,connectionId:m,data:v.channel})}}}addPeerConnectionEventListeners(f,m,h){this.logger.debug(`Adding event listeners for peer ${f} and connection ${m}.`),x[m]={},Object.keys(this.peerConnectionListeners).forEach(v=>{x[m][v]=this.peerConnectionListeners[v].bind(this,f,m,h),h.addEventListener(v,x[m][v],!1)})}parseGetUserMedia(f){try{const m={event:"getUserMedia",tag:"getUserMedia",data:{...f}};f.stream&&(m.data.details=this.parseStream(f.stream),f.stream.getTracks().map(h=>{this.addTrackEventListeners(h),k.push(h)})),this.emitEvent(m)}catch{}}parseStream(f){const m={audio:[],video:[]};return f.getTracks().forEach(h=>{m[h.kind].push(this.getMediaTrackDetails(h))}),m}getMediaTrackDetails(f){return{enabled:f.enabled,id:f.id,contentHint:f.contentHint,kind:f.kind,label:f.label,muted:f.muted,readyState:f.readyState,constructorName:f.constructor.name,capabilities:f.getCapabilities?f.getCapabilities():{},constraints:f.getConstraints?f.getConstraints():{},settings:f.getSettings?f.getSettings():{},_track:f}}getStreamDetails(f){return{active:f.active,id:f.id,_stream:f}}getTrackEventObject(f){return{mute:m=>{this.emitEvent({event:"mute",tag:"track",connectionId:f,data:{event:m}})},unmute:m=>{this.emitEvent({event:"unmute",tag:"track",connectionId:f,data:{event:m}})},overconstrained:m=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:f,data:{event:m}})},ended:m=>{this.emitEvent({event:"ended",tag:"track",connectionId:f,data:{event:m}}),this.removeTrackEventListeners(m.target)}}}addTrackEventListeners(f,m){x[f.id]={};const h=this.getTrackEventObject(m);Object.keys(h).forEach(v=>{x[f.id][v]=h[v].bind(this),f.addEventListener(v,x[f.id][v])}),x[f.id].readyState=setInterval(()=>{if(f.readyState==="ended"){let v=new CustomEvent("ended",{detail:{check:"readyState"}});f.dispatchEvent(v)}},1e3)}removeTrackEventListeners(f){if(f.id in x){const m=this.getTrackEventObject();Object.keys(m).forEach(h=>{f.removeEventListener(h,x[f.id][h])}),clearInterval(x[f.id].readyState),delete x[f.id]}}addToTimeline(f){this.timeline.push(f),this.emit("timeline",f)}emitEvent(f){const m={...f,timestamp:new Date};this.addToTimeline(m),m.tag&&this.emit(m.tag,m)}set getStatsInterval(f){if(!Number.isInteger(f))throw new Error(`getStatsInterval should be an integer, got: ${f}`);this._getStatsInterval=f,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(f,m){f in x&&(Object.keys(this.peerConnectionListeners).forEach(h=>{m.removeEventListener(h,x[f][h],!1)}),delete x[f]),m.getSenders().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)}),m.getReceivers().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const f=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const m=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),h=function(){return f.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),m.apply(navigator.mediaDevices,arguments).then(function(v){return v},function(v){return f.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,v.name),Promise.reject(v)})};navigator.mediaDevices.getDisplayMedia=h.bind(navigator.mediaDevices)}}}});($i=id)&&$i.__esModule&&Object.prototype.hasOwnProperty.call($i,"default")&&$i.default;var o_=id.WebRTCStats;function a_(e){const{packetsLost:t,packetsReceived:n,jitter:i,rtt:s}=e,o=function(c){const{jitter:d,rtt:u}=c,p=d+u/2;return .024*p+.11*(p-177.3)*(p>177.3?1:0)}({rtt:s,jitter:i}),r=function(c){const{packetsLost:d,packetsReceived:u}=c,p=d/(u+d)*100;return 20*Math.log(1+p)}({packetsLost:t,packetsReceived:n}),a=93.2-o-r+0,l=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(l,1),5)}function l_(e){return isNaN(e)?null:e>4.2?"excellent":e>=4.1&&e<=4.2?"good":e>=3.7&&e<=4?"fair":e>=3.1&&e<=3.6?"poor":"bad"}class c_ extends qn{constructor(t){super(),this.buildRequest({type:"debug_report_start",debug_report_id:t,debug_report_version:1})}}class u_ extends qn{constructor(t){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:t,debug_report_version:1})}}class d_ extends qn{constructor(t,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:t,debug_report_version:1,debug_report_data:n})}}function h_(e){const t=an(),n=new o_({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),i=s=>G(this,void 0,void 0,function*(){s.event==="stats"&&J(V.StatsFrame,function({data:o}){var r,a,l,c,d,u,p,g;const{audio:_,remote:w}=o,{audio:b}=w,y=(a=(r=b.inbound[0])===null||r===void 0?void 0:r.jitter)!==null&&a!==void 0?a:1/0,S=(c=(l=b.inbound[0])===null||l===void 0?void 0:l.roundTripTime)!==null&&c!==void 0?c:1/0,C=(u=(d=_.inbound[0])===null||d===void 0?void 0:d.packetsReceived)!==null&&u!==void 0?u:-1,P=(g=(p=_.inbound[0])===null||p===void 0?void 0:p.packetsLost)!==null&&g!==void 0?g:-1,L=a_({jitter:1e3*y,rtt:1e3*S,packetsLost:P,packetsReceived:C});return{jitter:y,rtt:S,mos:L,quality:l_(L),inboundAudio:_.inbound[0],outboundAudio:_.outbound[0],remoteInboundAudio:b.inbound[0],remoteOutboundAudio:b.outbound[0]}}(s),e.uuid),yield e.execute(new d_(t,s))});return{start:(s,o,r)=>G(this,void 0,void 0,function*(){yield e.execute(new c_(t)),n.on("timeline",i),yield new Promise(a=>setTimeout(a,500)),n.addConnection({pc:s,peerId:o,connectionId:r})}),stop:s=>G(this,void 0,void 0,function*(){const o=n.getTimeline();J(V.StatsReport,o,e.uuid),s==="file"&&function(r,a){const l=new Blob([JSON.stringify(r)],{type:"application/json"}),c=URL.createObjectURL(l),d=document.createElement("a");d.href=c,d.download=`${a}.json`,d.click(),URL.revokeObjectURL(c)}(o,`webrtc-stats-${t}-${Date.now()}`),yield e.execute(new u_(t)),n.removeAllPeers(),n.destroy()})}}class sd{constructor(t,n,i){this.type=t,this.options=n,this.onSdpReadyTwice=null,this.statsReporter=null,this._negotiating=!1,this.handleConnectionStateChange=s=>G(this,void 0,void 0,function*(){const{connectionState:o}=this.instance;if(console.log(`[${new Date().toISOString()}] Connection State`,o),o==="failed"||o==="disconnected"){const r=()=>{this.instance.restartIce(),this._session._closeConnection(),this._session.connect(),window.removeEventListener("online",r)};if(navigator.onLine)return r();window.addEventListener("online",r)}}),this._handleIceConnectionStateChange=s=>{console.log(`[${new Date().toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=s=>{console.log(`[${new Date().toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setAudioCodec=s=>{if(this.options.preferred_codecs&&this.options.preferred_codecs.length!==0)return s.setCodecPreferences?s.setCodecPreferences(this.options.preferred_codecs):void 0},B.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(),this.isDebugEnabled&&(this.statsReporter=h_(i))}get isOffer(){return this.type===Vt.Offer}get isAnswer(){return this.type===Vt.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}startNegotiation(){this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}_logTransceivers(){B.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((t,n)=>{B.info(`>> Transceiver [${n}]:`,t.mid,t.direction,t.stopped),B.info(`>> Sender Params [${n}]:`,JSON.stringify(t.sender.getParameters(),null,2))})}handleSignalingStateChangeEvent(t){switch(B.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(){B.info("Negotiation needed event"),this.instance.signalingState==="stable"&&this.startNegotiation()}handleTrackEvent(t){const{streams:[n]}=t,{remoteElement:i,screenShare:s}=this.options;let{remoteStream:o}=this.options;o=n,s===!1&&Vi(i,o)}createPeerConnection(){return G(this,void 0,void 0,function*(){var t;this.instance=(t=this._config(),new window.RTCPeerConnection(t)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),this.options.localStream=yield this._retrieveLocalStream().catch(n=>(J(V.MediaError,n,this.options.id),null))})}_init(){var t;return G(this,void 0,void 0,function*(){yield this.createPeerConnection(),yield(t=this.statsReporter)===null||t===void 0?void 0:t.start(this.instance,this._session.sessionid,this._session.sessionid);const{localElement:n,localStream:i=null,screenShare:s=!1}=this.options;if(Ni(i)){const o=i.getAudioTracks();B.info("Local audio tracks: ",o);const r=i.getVideoTracks();if(B.info("Local video tracks: ",r),this.isOffer&&typeof this.instance.addTransceiver=="function"){const a={direction:"sendrecv",streams:[i]};o.forEach(l=>{this.options.userVariables.microphoneLabel=l.label;const c=this.instance.addTransceiver(l,a);this._setAudioCodec(c)}),console.debug("Applying video transceiverParams",a),r.forEach(l=>{this.options.userVariables.cameraLabel=l.label,this.instance.addTransceiver(l,a)})}else typeof this.instance.addTrack=="function"?(o.forEach(a=>{this.options.userVariables.microphoneLabel=a.label,this.instance.addTrack(a,i)}),this.instance.getTransceivers().forEach(a=>this._setAudioCodec(a)),r.forEach(a=>{this.options.userVariables.cameraLabel=a.label,this.instance.addTrack(a,i)})):this.instance.addStream(i);s===!1&&((a=>{const l=Hn(a);l&&(l.muted=!0)})(n),Vi(n,i))}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this.startNegotiation(),this._logTransceivers()})}_getSenderByKind(t){return this.instance.getSenders().find(({track:n})=>n&&n.kind===t)}_checkMediaToNegotiate(t){if(!this._getSenderByKind(t)){const n=this.instance.addTransceiver(t);B.info("Add transceiver",t,n)}}_createOffer(){return G(this,void 0,void 0,function*(){this._isOffer()&&(this._constraints.offerToReceiveAudio=!!this.options.audio,this._constraints.offerToReceiveVideo=!!this.options.video,B.info("_createOffer - this._constraints",this._constraints),yield this.instance.createOffer(this._constraints).then(this._setLocalDescription.bind(this)).then(this._sdpReady).catch(t=>B.error("Peer _createOffer error:",t)))})}_setRemoteDescription(t){return G(this,void 0,void 0,function*(){yield this.instance.setRemoteDescription(t)})}_createAnswer(){return G(this,void 0,void 0,function*(){if(!this._isAnswer())return;if(this.instance.signalingState!=="stable")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:Vt.Offer})]));yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Vt.Offer}),this._logTransceivers();const t=yield this.instance.createAnswer();yield this._setLocalDescription(t)})}_setLocalDescription(t){return G(this,void 0,void 0,function*(){const{useStereo:n,googleMaxBitrate:i,googleMinBitrate:s,googleStartBitrate:o,mediaSettings:r}=this.options;n&&(t.sdp=(a=>{const l=`\r
|
|
100
|
+
`),this._wsClient.send(JSON.stringify(n)),i}close(){this._wsClient&&(ln(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close()),this._wsClient=null}_unsetTimer(t){clearTimeout(this._timers[t]),delete this._timers[t]}_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(V.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else B.warn("Unknown message from socket",t)}}class qn{buildRequest(t){this.request=Object.assign({jsonrpc:"2.0",id:an()},t)}}const Uu={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class Dt extends qn{constructor(t={}){if(super(),t.hasOwnProperty("dialogParams")){const n=Mr(t.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const i in Uu)i&&n.hasOwnProperty(i)&&(n[Uu[i]]=n[i],delete n[i]);t.dialogParams=n}this.buildRequest({method:this.toString(),params:t})}}class Gu extends Dt{constructor(){super(),this.method=nt.GatewayState,this.buildRequest({method:this.method,params:{}})}}class zv{constructor(t){this.pendingRequestId=null,this.onSocketMessage=n=>G(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Dr(n))}),this.getIsRegistered=()=>G(this,void 0,void 0,function*(){const n=new Gu;this.pendingRequestId=n.request.id,this.gatewayStateTask=Fu({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[Rt.REGISTER,Rt.REGED].includes(i)}),this.session=t,this.gatewayStateTask=Fu({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Wv{constructor(t){if(this.options=t,this.uuid=an(),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 $u(this),this.registerAgent=new zv(this)}get __logger(){return B}get connected(){return this.connection&&this.connection.connected}get reconnectDelay(){return 1e3*Vu(2,6)}execute(t){return this._idle?new Promise(n=>this._executeQueue.push({resolve:n,msg:t})):this.connected?this.connection.send(t):new Promise(n=>{this._executeQueue.push({resolve:n,msg:t}),this.connect()})}executeRaw(t){this._idle?this._executeQueue.push({msg:t}):this.connection.sendRawText(t)}validateOptions(){return Lr(this.options)||Oi(this.options)}broadcast(t){}disconnect(){return G(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(t,n){return un(t,n,this.uuid),this}off(t,n){return dn(t,n,this.uuid),this}connect(){return G(this,void 0,void 0,function*(){this.connection||(this.connection=new $u(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()})}_handleLoginError(t){J(V.Error,{error:t,sessionId:this.sessionid},this.uuid)}_onSocketOpen(){return G(this,void 0,void 0,function*(){})}onNetworkClose(){this.relayProtocol&&Vr(this.relayProtocol);for(const t in this.subscriptions)Vr(t);this.subscriptions={},this.contexts=[],this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>this.connect(),this.reconnectDelay))}_onSocketMessage(t){}_removeSubscription(t,n){this._existsSubscription(t,n)&&(n?(delete this.subscriptions[t][n],dn(t,null,n)):(delete this.subscriptions[t],Vr(t)))}_addSubscription(t,n=null,i){this._existsSubscription(t,i)||(this._existsSubscription(t)||(this.subscriptions[t]={}),this.subscriptions[t][i]={},ln(n)&&un(t,n,i))}_existsSubscription(t,n){return!(!this.subscriptions.hasOwnProperty(t)||!(!n||n&&this.subscriptions[t].hasOwnProperty(n)))}_attachListeners(){this._detachListeners(),this.on(V.SocketOpen,this._onSocketOpen),this.on(V.SocketClose,this.onNetworkClose),this.on(V.SocketError,this.onNetworkClose),this.on(V.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(V.SocketOpen,this._onSocketOpen),this.off(V.SocketClose,this.onNetworkClose),this.off(V.SocketError,this.onNetworkClose),this.off(V.SocketMessage,this._onSocketMessage)}_emptyExecuteQueues(){this._executeQueue.forEach(({resolve:t,msg:n})=>{typeof n=="string"?this.executeRaw(n):t(this.execute(n))})}_closeConnection(){this._idle=!0,clearTimeout(this._keepAliveTimeout),this.connection&&this.connection.close()}_keepAlive(){this._doKeepAlive===!0&&(this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._keepAlive(),3e4))}static on(t,n){un(t,n)}static off(t){dn(t)}static uuid(){return an()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}getIsRegistered(){return this.registerAgent.getIsRegistered()}}const Fr=e=>navigator.mediaDevices.getUserMedia(e),Ni=e=>e&&e instanceof MediaStream,Vi=(e,t)=>{const n=Hn(e);n!==null&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=t)},Hu=(e,t)=>G(void 0,void 0,void 0,function*(){const n=Hn(e);if(n===null)return B.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof t!="string")return B.info(`Invalid speaker deviceId: '${t}'`),!1;try{return yield n.setSinkId(t),!0}catch{return!1}}),qv=e=>{e&&e.readyState==="live"&&e.stop()},Kn=e=>{Ni(e)&&e.getTracks().forEach(qv),e=null},Fi=e=>G(void 0,void 0,void 0,function*(){B.info("RTCService.getUserMedia",e);const{audio:t,video:n}=e;if(!t&&!n)return null;try{return yield Fr(e)}catch(i){throw B.error("getUserMedia error: ",i),i}}),Xn=(e=null,t=!1)=>G(void 0,void 0,void 0,function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===le.AudioIn||s===le.AudioOut,video:!s||s===le.Video}))(e)).catch(s=>(console.error(s),null));if(i){if(Kn(i),n=yield navigator.mediaDevices.enumerateDevices(),e&&(n=n.filter(o=>o.kind===e)),t===!0)return n;const s=[];n=n.filter(o=>{if(!o.groupId)return!0;const r=`${o.kind}-${o.groupId}`;return!s.includes(r)&&(s.push(r),!0)})}return n}),zu=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Bi=(e,t,n)=>G(void 0,void 0,void 0,function*(){const i=yield Xn(n,!0);for(let s=0;s<i.length;s++){const{deviceId:o,label:r}=i[s];if(e===o||t===r)return o}return null}),Wu=e=>{const t=navigator.mediaDevices.getSupportedConstraints();Object.keys(e).map(n=>{t.hasOwnProperty(n)&&e[n]!==null&&e[n]!==void 0||delete e[n]})},qu=(e,t,n,i)=>G(void 0,void 0,void 0,function*(){const{deviceId:s}=i;if(s===void 0&&(e||t)){const o=yield Bi(e,t,n).catch(r=>null);o&&(i.deviceId={exact:o})}return i}),ji=(e,t)=>{if(!e)return!1;const{subscribed:n,alreadySubscribed:i}=Br(e);return n.includes(t)||i.includes(t)},Br=e=>{const t={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(t).forEach(n=>{t[n]=e[`${n}Channels`]||[]}),t},hn=(e,t=null,n=null)=>{if(!Ni(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(s=>{switch(n){case"on":case!0:s.enabled=!0;break;case"off":case!1:s.enabled=!1;break;default:s.enabled=!s.enabled}})},Ku=e=>{hn(e,"audio",!0)},Xu=e=>{hn(e,"audio",!1)},Yu=e=>{hn(e,"audio",null)};function Kv(){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 d=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),u=d[0],p=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:p,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const d=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),u=d[0],p=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:p,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const d=navigator.userAgent.match(/safari/gim)[0],u=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),p=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:p,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const d=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),u=d[0],p=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:p,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,l=window.navigator&&window.navigator.mediaDevices,c=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:e,browserName:t,browserVersion:n,supportWebRTC:!!(o&&r&&a&&l&&c),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!Fi}}catch(e){return e.message}}var vt;function Zu(e,t){const n=document.getElementById(t);if(n)return n;if(e&&t){const i=document.createElement("audio");return i.id=t,i.loop=!0,i.src=e,i.preload="auto",i.load(),document.body.appendChild(i),i}return null}function Ju(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 Qu(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"})(vt||(vt={}));var td="2.22.15",jr=td;class Xv extends Dt{constructor(t,n,i,s,o={},r){super(),this.method="login";const a={login:t,passwd:n,login_token:i,userVariables:o,reconnection:r,loginParams:{},"User-Agent":{sdkVersion:jr,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class Yv extends Dt{constructor(t,n){super(),this.buildRequest({id:t,result:{method:n}})}}class Zv extends Dt{toString(){return nt.Invite}}class Jv extends Dt{toString(){return nt.Answer}}class Qv extends Dt{toString(){return nt.Attach}}class t_ extends Dt{toString(){return nt.Bye}}class $r extends Dt{toString(){return nt.Modify}}class ed extends Dt{toString(){return nt.Info}}class e_ extends Dt{toString(){return nt.Broadcast}}class n_ extends Dt{toString(){return nt.Subscribe}}class i_ extends Dt{toString(){return nt.Unsubscribe}}class s_ extends qn{constructor(t){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:an(),type:"message",role:"user",content:[{type:"input_text",text:t}]}}})}}const nd=(e,t)=>{const{contentType:n,canvasType:i,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=t;o&&i!=="mcu-personal-canvas"&&delete o.memberID;const a={type:ae.conferenceUpdate,call:e.calls[s],canvasInfo:r_(o),currentLayerIdx:r};switch(n){case"layer-info":{const l=Object.assign({action:At.LayerInfo},a);J(V.Notification,l,e.uuid);break}case"layout-info":{const l=Object.assign({action:At.LayoutInfo},a);J(V.Notification,l,e.uuid);break}}},r_=e=>{const t=JSON.stringify(e).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Ou(t)};var $i,id=Lu(function(e,t){var n;function i(){}function s(){s.init.call(this)}function o(f){return f._maxListeners===void 0?s.defaultMaxListeners:f._maxListeners}function r(f,m,h,v){var T,R,E;if(typeof h!="function")throw new TypeError('"listener" argument must be a function');if((R=f._events)?(R.newListener&&(f.emit("newListener",m,h.listener?h.listener:h),R=f._events),E=R[m]):(R=f._events=new i,f._eventsCount=0),E){if(typeof E=="function"?E=R[m]=v?[h,E]:[E,h]:v?E.unshift(h):E.push(h),!E.warned&&(T=o(f))&&0<T&&E.length>T){E.warned=!0;var M=new Error("Possible EventEmitter memory leak detected. "+E.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");M.name="MaxListenersExceededWarning",M.emitter=f,M.type=m,M.count=E.length,function(I){typeof console.warn=="function"?console.warn(I):console.log(I)}(M)}}else E=R[m]=h,++f._eventsCount;return f}function a(f,m,h){function v(){f.removeListener(m,v),T||(T=!0,h.apply(f,arguments))}var T=!1;return v.listener=h,v}function l(f){var m=this._events;if(m){var h=m[f];if(typeof h=="function")return 1;if(h)return h.length}return 0}function c(f,m){for(var h=Array(m);m--;)h[m]=f[m];return h}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(f){if(typeof f!="number"||0>f||isNaN(f))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=f,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(f){var m,h,v,T,R,E,M,I=f==="error";if(E=this._events)I=I&&E.error==null;else if(!I)return!1;if(M=this.domain,I){if(m=arguments[1],!M){if(m instanceof Error)throw m;var N=new Error('Uncaught, unspecified "error" event. ('+m+")");throw N.context=m,N}return m||(m=new Error('Uncaught, unspecified "error" event')),m.domainEmitter=this,m.domain=M,m.domainThrown=!1,M.emit("error",m),!1}if(!(h=E[f]))return!1;var K=typeof h=="function";switch(v=arguments.length){case 1:(function(F,rt,Q){if(rt)F.call(Q);else for(var j=F.length,lt=c(F,j),z=0;z<j;++z)lt[z].call(Q)})(h,K,this);break;case 2:(function(F,rt,Q,j){if(rt)F.call(Q,j);else for(var lt=F.length,z=c(F,lt),Y=0;Y<lt;++Y)z[Y].call(Q,j)})(h,K,this,arguments[1]);break;case 3:(function(F,rt,Q,j,lt){if(rt)F.call(Q,j,lt);else for(var z=F.length,Y=c(F,z),Z=0;Z<z;++Z)Y[Z].call(Q,j,lt)})(h,K,this,arguments[1],arguments[2]);break;case 4:(function(F,rt,Q,j,lt,z){if(rt)F.call(Q,j,lt,z);else for(var Y=F.length,Z=c(F,Y),tt=0;tt<Y;++tt)Z[tt].call(Q,j,lt,z)})(h,K,this,arguments[1],arguments[2],arguments[3]);break;default:for(T=Array(v-1),R=1;R<v;R++)T[R-1]=arguments[R];(function(F,rt,Q,j){if(rt)F.apply(Q,j);else for(var lt=F.length,z=c(F,lt),Y=0;Y<lt;++Y)z[Y].apply(Q,j)})(h,K,this,T)}return!0},s.prototype.addListener=function(f,m){return r(this,f,m,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(f,m){return r(this,f,m,!0)},s.prototype.once=function(f,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.on(f,a(this,f,m)),this},s.prototype.prependOnceListener=function(f,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(f,a(this,f,m)),this},s.prototype.removeListener=function(f,m){var h,v,T,R,E;if(typeof m!="function")throw new TypeError('"listener" argument must be a function');if(!(v=this._events))return this;if(!(h=v[f]))return this;if(h===m||h.listener&&h.listener===m)--this._eventsCount==0?this._events=new i:(delete v[f],v.removeListener&&this.emit("removeListener",f,h.listener||m));else if(typeof h!="function"){for(T=-1,R=h.length;0<R--;)if(h[R]===m||h[R].listener&&h[R].listener===m){E=h[R].listener,T=R;break}if(0>T)return this;if(h.length===1){if(h[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete v[f]}else(function(M,I){for(var N=I,K=N+1,F=M.length;K<F;N+=1,K+=1)M[N]=M[K];M.pop()})(h,T);v.removeListener&&this.emit("removeListener",f,E||m)}return this},s.prototype.removeAllListeners=function(f){var m,h;if(!(h=this._events))return this;if(!h.removeListener)return arguments.length===0?(this._events=new i,this._eventsCount=0):h[f]&&(--this._eventsCount==0?this._events=new i:delete h[f]),this;if(arguments.length===0){for(var v,T=Object.keys(h),R=0;R<T.length;++R)(v=T[R])!=="removeListener"&&this.removeAllListeners(v);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(m=h[f])=="function")this.removeListener(f,m);else if(m)do this.removeListener(f,m[m.length-1]);while(m[0]);return this},s.prototype.listeners=function(f){var m,h,v=this._events;return v?h=(m=v[f])?typeof m=="function"?[m.listener||m]:function(T){for(var R=Array(T.length),E=0;E<R.length;++E)R[E]=T[E].listener||T[E];return R}(m):[]:h=[],h},s.listenerCount=function(f,m){return typeof f.listenerCount=="function"?f.listenerCount(m):l.call(f,m)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var d,u=new Uint8Array(16);function p(){if(!d&&!(d=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return d(u)}for(var g=/^(?:[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,_=[],w=0;256>w;++w)_.push((w+256).toString(16).substr(1));function b(f){var m=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,h=(_[f[m+0]]+_[f[m+1]]+_[f[m+2]]+_[f[m+3]]+"-"+_[f[m+4]]+_[f[m+5]]+"-"+_[f[m+6]]+_[f[m+7]]+"-"+_[f[m+8]]+_[f[m+9]]+"-"+_[f[m+10]]+_[f[m+11]]+_[f[m+12]]+_[f[m+13]]+_[f[m+14]]+_[f[m+15]]).toLowerCase();if(!function(v){return typeof v=="string"&&g.test(v)}(h))throw TypeError("Stringified UUID is invalid");return h}function y(f,m,h){var v=(f=f||{}).random||(f.rng||p)();return v[6]=64|15&v[6],v[8]=128|63&v[8],b(v)}function S(f,m){if(!f||!m)return{};const h={...f};if(h.localCandidateId){const v=m.get(h.localCandidateId);h.local={...v}}if(h.remoteCandidateId){const v=m.get(h.remoteCandidateId);h.remote={...v}}return h}function C(f,m,h){return 8*function(v,T,R){const E=v[R],M=T?T[R]:null;return E===null||M===null?null:(E-M)/(v.timestamp-T.timestamp)*1e3}(f,m,h)}function P(f){if(!f.entries)return f;const m={};return f.forEach(function(h,v){m[v]=h}),m}function L(f,m,h={}){if(!f)return null;let v={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};h.remote&&(v.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const T of f.values())switch(T.type){case"outbound-rtp":{const R=T.mediaType||T.kind,E={};let M={};if(!["audio","video"].includes(R))continue;if(T.codecId){const I=f.get(T.codecId);I&&(E.clockRate=I.clockRate,E.mimeType=I.mimeType,E.payloadType=I.payloadType)}M=f.get(T.mediaSourceId)||f.get(T.trackId)||{},v[R].outbound.push({...T,...E,track:{...M}});break}case"inbound-rtp":{let R=T.mediaType||T.kind,E={};const M={};if(!["audio","video"].includes(R))if(T.id.includes("Video"))R="video";else{if(!T.id.includes("Audio"))continue;R="audio"}if(T.codecId){const I=f.get(T.codecId);I&&(M.clockRate=I.clockRate,M.mimeType=I.mimeType,M.payloadType=I.payloadType)}if(!v.connection.id&&T.transportId){const I=f.get(T.transportId);if(I&&I.selectedCandidatePairId){const N=f.get(I.selectedCandidatePairId);v.connection=S(N,f)}}E=f.get(T.mediaSourceId)||f.get(T.trackId)||{},v[R].inbound.push({...T,...M,track:{...E}});break}case"peer-connection":v.connection.dataChannelsClosed=T.dataChannelsClosed,v.connection.dataChannelsOpened=T.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!h.remote)break;let R=T.mediaType||T.kind;const E={};if(!["audio","video"].includes(R))if(T.id.includes("Video"))R="video";else{if(!T.id.includes("Audio"))continue;R="audio"}if(T.codecId){const M=f.get(T.codecId);M&&(E.clockRate=M.clockRate,E.mimeType=M.mimeType,E.payloadType=M.payloadType)}if(!v.connection.id&&T.transportId){const M=f.get(T.transportId);if(M&&M.selectedCandidatePairId){const I=f.get(M.selectedCandidatePairId);v.connection=S(I,f)}}v.remote[R].inbound.push({...T,...E});break}case"remote-outbound-rtp":{if(!h.remote)break;const R=T.mediaType||T.kind,E={};if(!["audio","video"].includes(R))continue;if(T.codecId){const M=f.get(T.codecId);M&&(E.clockRate=M.clockRate,E.mimeType=M.mimeType,E.payloadType=M.payloadType)}v.remote[R].outbound.push({...T,...E});break}}if(!v.connection.id)for(const T of f.values())T.type==="candidate-pair"&&T.nominated&&T.state==="succeeded"&&(v.connection=S(T,f));return v=function(T,R){return R&&(T.audio.inbound.map(E=>{let M=R.audio.inbound.find(I=>I.id===E.id);E.bitrate=C(E,M,"bytesReceived"),E.packetRate=C(E,M,"packetsReceived")}),T.audio.outbound.map(E=>{let M=R.audio.outbound.find(I=>I.id===E.id);E.bitrate=C(E,M,"bytesSent"),E.packetRate=C(E,M,"packetsSent")}),T.video.inbound.map(E=>{let M=R.video.inbound.find(I=>I.id===E.id);E.bitrate=C(E,M,"bytesReceived"),E.packetRate=C(E,M,"packetsReceived")}),T.video.outbound.map(E=>{let M=R.video.outbound.find(I=>I.id===E.id);E.bitrate=C(E,M,"bytesSent"),E.packetRate=C(E,M,"packetsSent")})),T}(v,m),v}let D,x={},k=[];t.WebRTCStats=class extends s{constructor(f){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"],typeof window>"u")throw new Error("WebRTCStats only works in browser");const m={...f};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=m.getStatsInterval||1e3,this.rawStats=!!m.rawStats,this.statsObject=!!m.statsObject,this.filteredStats=!!m.filteredStats,this.shouldWrapGetUserMedia=!!m.wrapGetUserMedia,typeof m.remote=="boolean"&&(this.remote=m.remote),this.debug=!!m.debug,this.logLevel=m.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(f,m){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:f,pc:m})}async addConnection(f){const{pc:m,peerId:h}=f;let{connectionId:v,remote:T}=f;if(T=typeof T=="boolean"?T:this.remote,!(m&&m instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!h)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[h]){if(v&&v in this.peersToMonitor[h])throw new Error(`We are already monitoring connection with id ${v}.`);for(let E in this.peersToMonitor[h]){const M=this.peersToMonitor[h][E];if(M.pc===m)throw new Error(`We are already monitoring peer with id ${h}.`);M.pc.connectionState==="closed"&&this.removeConnection({pc:M.pc})}}const R=m.getConfiguration();return R.iceServers&&R.iceServers.forEach(function(E){delete E.credential}),v||(v=y()),this.emitEvent({event:"addConnection",tag:"peer",peerId:h,connectionId:v,data:{options:f,peerConfiguration:R}}),this.monitorPeer({peerId:h,connectionId:v,pc:m,remote:T}),{connectionId:v}}getTimeline(f){return this.timeline=this.timeline.sort((m,h)=>m.timestamp.getTime()-h.timestamp.getTime()),f?this.timeline.filter(m=>m.tag===f):this.timeline}get logger(){const f=m=>{const h=["none","error","warn","info","debug"];return h.slice(0,h.indexOf(this.logLevel)+1).indexOf(m)>-1};return{error(...m){this.debug&&f("error")&&console.error("[webrtc-stats][error] ",...m)},warn(...m){this.debug&&f("warn")&&console.warn("[webrtc-stats][warn] ",...m)},info(...m){this.debug&&f("info")&&console.log("[webrtc-stats][info] ",...m)},debug(...m){this.debug&&f("debug")&&console.debug("[webrtc-stats][debug] ",...m)}}}removeConnection(f){let m,{connectionId:h,pc:v}=f;if(!v&&!h)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(h){if(typeof h!="string")throw new Error("connectionId must be a string.");for(let T in this.peersToMonitor)h in this.peersToMonitor[T]&&(v=this.peersToMonitor[T][h].pc,m=T)}else if(v){if(!(v instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let T in this.peersToMonitor)for(let R in this.peersToMonitor[T])this.peersToMonitor[T][R].pc===v&&(h=R,m=T)}if(!v||!h)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(h,v),delete this.peersToMonitor[m][h],Object.values(this.peersToMonitor[m]).length===0&&delete this.peersToMonitor[m],{connectionId:h}}removeAllPeers(){for(let f in this.peersToMonitor)this.removePeer(f)}removePeer(f){if(this.logger.info(`Removing PeerConnection with id ${f}.`),this.peersToMonitor[f]){for(let m in this.peersToMonitor[f]){let h=this.peersToMonitor[f][m].pc;this.removePeerConnectionEventListeners(m,h)}delete this.peersToMonitor[f]}}destroy(){this.removeAllPeers(),k.forEach(f=>{this.removeTrackEventListeners(f)}),k=[],this.shouldWrapGetUserMedia&&D&&(navigator.mediaDevices.getUserMedia=D)}monitorPeer(f){let{peerId:m,connectionId:h,pc:v,remote:T}=f;if(!v)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const R={pc:v,connectionId:h,stream:null,stats:{parsed:null,raw:null},options:{remote:T}};if(this.peersToMonitor[m]){if(h in this.peersToMonitor[m])return void this.logger.warn(`Already watching connection with ID ${h}`);this.peersToMonitor[m][h]=R}else this.peersToMonitor[m]={[h]:R};this.addPeerConnectionEventListeners(m,h,v),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(f=>{f.forEach(m=>{this.emitEvent(m)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(f=null){this.logger.info(f?`Getting stats from peer ${f}`:"Getting stats from all peers");let m={};if(f){if(!this.peersToMonitor[f])throw new Error(`Cannot get stats. Peer with id ${f} does not exist`);m[f]=this.peersToMonitor[f]}else m=this.peersToMonitor;let h=[];for(const v in m)for(const T in m[v]){const R=m[v][T],E=R.pc;if(E&&!this.checkIfConnectionIsClosed(v,T,E))try{const M=this.getTimestamp(),I=E.getStats(null);if(I){const N=await I,K=this.getTimestamp(),F=P(N),rt={remote:R.options.remote},Q=L(N,R.stats.parsed,rt),j={event:"stats",tag:"stats",peerId:v,connectionId:T,timeTaken:K-M,data:Q};this.rawStats===!0&&(j.rawStats=N),this.statsObject===!0&&(j.statsObject=F),this.filteredStats===!0&&(j.filteredStats=this.filteroutStats(F)),h.push(j),R.stats.parsed=Q}else this.logger.error(`PeerConnection from peer ${v} did not return any stats data`)}catch(M){this.logger.error(M)}}return h}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const f in this.peersToMonitor)for(const m in this.peersToMonitor[f]){const h=this.peersToMonitor[f][m].pc;this.checkIfConnectionIsClosed(f,m,h)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(f,m,h){const v=this.isConnectionClosed(h);if(v){this.removeConnection({pc:h});let T=h.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:T,peerId:f,connectionId:m,tag:"connection",data:"closed"})}return v}isConnectionClosed(f){return f.connectionState==="closed"||f.iceConnectionState==="closed"}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."),D=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const f=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return f({constraints:arguments[0]}),D.apply(navigator.mediaDevices,arguments).then(m=>(f({stream:m}),m),m=>(f({error:m}),Promise.reject(m)))}).bind(navigator.mediaDevices)}filteroutStats(f={}){const m={...f};for(const v in m){var h=m[v];this.statsToMonitor.includes(h.type)||delete m[v]}return m}get peerConnectionListeners(){return{icecandidate:(f,m,h,v)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",v),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:f,connectionId:m,data:v.candidate})},track:(f,m,h,v)=>{this.logger.debug(`[pc-event] track | peerId: ${f}`,v);const T=v.track,R=v.streams[0];f in this.peersToMonitor&&m in this.peersToMonitor[f]&&(this.peersToMonitor[f][m].stream=R),this.addTrackEventListeners(T,m),this.emitEvent({event:"ontrack",tag:"track",peerId:f,connectionId:m,data:{stream:R?this.getStreamDetails(R):null,track:T?this.getMediaTrackDetails(T):null,title:v.track.kind+":"+v.track.id+" "+v.streams.map(function(E){return"stream:"+E.id})}})},signalingstatechange:(f,m,h)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${f}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:f,connectionId:m,data:{signalingState:h.signalingState,localDescription:h.localDescription,remoteDescription:h.remoteDescription}})},iceconnectionstatechange:(f,m,h)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${f}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:f,connectionId:m,data:h.iceConnectionState})},icegatheringstatechange:(f,m,h)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${f}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:f,connectionId:m,data:h.iceGatheringState})},icecandidateerror:(f,m,h,v)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${f}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:f,connectionId:m,error:{errorCode:v.errorCode}})},connectionstatechange:(f,m,h)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${f}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:f,connectionId:m,data:h.connectionState})},negotiationneeded:(f,m,h)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${f}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:f,connectionId:m})},datachannel:(f,m,h,v)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${f}`,v),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:f,connectionId:m,data:v.channel})}}}addPeerConnectionEventListeners(f,m,h){this.logger.debug(`Adding event listeners for peer ${f} and connection ${m}.`),x[m]={},Object.keys(this.peerConnectionListeners).forEach(v=>{x[m][v]=this.peerConnectionListeners[v].bind(this,f,m,h),h.addEventListener(v,x[m][v],!1)})}parseGetUserMedia(f){try{const m={event:"getUserMedia",tag:"getUserMedia",data:{...f}};f.stream&&(m.data.details=this.parseStream(f.stream),f.stream.getTracks().map(h=>{this.addTrackEventListeners(h),k.push(h)})),this.emitEvent(m)}catch{}}parseStream(f){const m={audio:[],video:[]};return f.getTracks().forEach(h=>{m[h.kind].push(this.getMediaTrackDetails(h))}),m}getMediaTrackDetails(f){return{enabled:f.enabled,id:f.id,contentHint:f.contentHint,kind:f.kind,label:f.label,muted:f.muted,readyState:f.readyState,constructorName:f.constructor.name,capabilities:f.getCapabilities?f.getCapabilities():{},constraints:f.getConstraints?f.getConstraints():{},settings:f.getSettings?f.getSettings():{},_track:f}}getStreamDetails(f){return{active:f.active,id:f.id,_stream:f}}getTrackEventObject(f){return{mute:m=>{this.emitEvent({event:"mute",tag:"track",connectionId:f,data:{event:m}})},unmute:m=>{this.emitEvent({event:"unmute",tag:"track",connectionId:f,data:{event:m}})},overconstrained:m=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:f,data:{event:m}})},ended:m=>{this.emitEvent({event:"ended",tag:"track",connectionId:f,data:{event:m}}),this.removeTrackEventListeners(m.target)}}}addTrackEventListeners(f,m){x[f.id]={};const h=this.getTrackEventObject(m);Object.keys(h).forEach(v=>{x[f.id][v]=h[v].bind(this),f.addEventListener(v,x[f.id][v])}),x[f.id].readyState=setInterval(()=>{if(f.readyState==="ended"){let v=new CustomEvent("ended",{detail:{check:"readyState"}});f.dispatchEvent(v)}},1e3)}removeTrackEventListeners(f){if(f.id in x){const m=this.getTrackEventObject();Object.keys(m).forEach(h=>{f.removeEventListener(h,x[f.id][h])}),clearInterval(x[f.id].readyState),delete x[f.id]}}addToTimeline(f){this.timeline.push(f),this.emit("timeline",f)}emitEvent(f){const m={...f,timestamp:new Date};this.addToTimeline(m),m.tag&&this.emit(m.tag,m)}set getStatsInterval(f){if(!Number.isInteger(f))throw new Error(`getStatsInterval should be an integer, got: ${f}`);this._getStatsInterval=f,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(f,m){f in x&&(Object.keys(this.peerConnectionListeners).forEach(h=>{m.removeEventListener(h,x[f][h],!1)}),delete x[f]),m.getSenders().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)}),m.getReceivers().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const f=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const m=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),h=function(){return f.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),m.apply(navigator.mediaDevices,arguments).then(function(v){return v},function(v){return f.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,v.name),Promise.reject(v)})};navigator.mediaDevices.getDisplayMedia=h.bind(navigator.mediaDevices)}}}});($i=id)&&$i.__esModule&&Object.prototype.hasOwnProperty.call($i,"default")&&$i.default;var o_=id.WebRTCStats;function a_(e){const{packetsLost:t,packetsReceived:n,jitter:i,rtt:s}=e,o=function(c){const{jitter:d,rtt:u}=c,p=d+u/2;return .024*p+.11*(p-177.3)*(p>177.3?1:0)}({rtt:s,jitter:i}),r=function(c){const{packetsLost:d,packetsReceived:u}=c,p=d/(u+d)*100;return 20*Math.log(1+p)}({packetsLost:t,packetsReceived:n}),a=93.2-o-r+0,l=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(l,1),5)}function l_(e){return isNaN(e)?null:e>4.2?"excellent":e>=4.1&&e<=4.2?"good":e>=3.7&&e<=4?"fair":e>=3.1&&e<=3.6?"poor":"bad"}class c_ extends qn{constructor(t){super(),this.buildRequest({type:"debug_report_start",debug_report_id:t,debug_report_version:1})}}class u_ extends qn{constructor(t){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:t,debug_report_version:1})}}class d_ extends qn{constructor(t,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:t,debug_report_version:1,debug_report_data:n})}}function h_(e){const t=an(),n=new o_({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),i=s=>G(this,void 0,void 0,function*(){s.event==="stats"&&J(V.StatsFrame,function({data:o}){var r,a,l,c,d,u,p,g;const{audio:_,remote:w}=o,{audio:b}=w,y=(a=(r=b.inbound[0])===null||r===void 0?void 0:r.jitter)!==null&&a!==void 0?a:1/0,S=(c=(l=b.inbound[0])===null||l===void 0?void 0:l.roundTripTime)!==null&&c!==void 0?c:1/0,C=(u=(d=_.inbound[0])===null||d===void 0?void 0:d.packetsReceived)!==null&&u!==void 0?u:-1,P=(g=(p=_.inbound[0])===null||p===void 0?void 0:p.packetsLost)!==null&&g!==void 0?g:-1,L=a_({jitter:1e3*y,rtt:1e3*S,packetsLost:P,packetsReceived:C});return{jitter:y,rtt:S,mos:L,quality:l_(L),inboundAudio:_.inbound[0],outboundAudio:_.outbound[0],remoteInboundAudio:b.inbound[0],remoteOutboundAudio:b.outbound[0]}}(s),e.uuid),yield e.execute(new d_(t,s))});return{start:(s,o,r)=>G(this,void 0,void 0,function*(){yield e.execute(new c_(t)),n.on("timeline",i),yield new Promise(a=>setTimeout(a,500)),n.addConnection({pc:s,peerId:o,connectionId:r})}),stop:s=>G(this,void 0,void 0,function*(){const o=n.getTimeline();J(V.StatsReport,o,e.uuid),s==="file"&&function(r,a){const l=new Blob([JSON.stringify(r)],{type:"application/json"}),c=URL.createObjectURL(l),d=document.createElement("a");d.href=c,d.download=`${a}.json`,d.click(),URL.revokeObjectURL(c)}(o,`webrtc-stats-${t}-${Date.now()}`),yield e.execute(new u_(t)),n.removeAllPeers(),n.destroy()})}}class sd{constructor(t,n,i){this.type=t,this.options=n,this.onSdpReadyTwice=null,this.statsReporter=null,this._negotiating=!1,this.handleConnectionStateChange=s=>G(this,void 0,void 0,function*(){const{connectionState:o}=this.instance;if(console.log(`[${new Date().toISOString()}] Connection State`,o),o==="failed"||o==="disconnected"){const r=()=>{this.instance.restartIce(),this._session._closeConnection(),this._session.connect(),window.removeEventListener("online",r)};if(navigator.onLine)return r();window.addEventListener("online",r)}}),this._handleIceConnectionStateChange=s=>{console.log(`[${new Date().toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=s=>{console.log(`[${new Date().toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setAudioCodec=s=>{if(this.options.preferred_codecs&&this.options.preferred_codecs.length!==0)return s.setCodecPreferences?s.setCodecPreferences(this.options.preferred_codecs):void 0},B.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(),this.isDebugEnabled&&(this.statsReporter=h_(i))}get isOffer(){return this.type===Vt.Offer}get isAnswer(){return this.type===Vt.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}startNegotiation(){this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}_logTransceivers(){B.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((t,n)=>{B.info(`>> Transceiver [${n}]:`,t.mid,t.direction,t.stopped),B.info(`>> Sender Params [${n}]:`,JSON.stringify(t.sender.getParameters(),null,2))})}handleSignalingStateChangeEvent(t){switch(B.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(){B.info("Negotiation needed event"),this.instance.signalingState==="stable"&&this.startNegotiation()}handleTrackEvent(t){const{streams:[n]}=t,{remoteElement:i,screenShare:s}=this.options;let{remoteStream:o}=this.options;o=n,s===!1&&Vi(i,o)}createPeerConnection(){return G(this,void 0,void 0,function*(){var t;this.instance=(t=this._config(),new window.RTCPeerConnection(t)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),this.options.localStream=yield this._retrieveLocalStream().catch(n=>(J(V.MediaError,n,this.options.id),null))})}_init(){var t;return G(this,void 0,void 0,function*(){yield this.createPeerConnection(),yield(t=this.statsReporter)===null||t===void 0?void 0:t.start(this.instance,this._session.sessionid,this._session.sessionid);const{localElement:n,localStream:i=null,screenShare:s=!1}=this.options;if(Ni(i)){const o=i.getAudioTracks();B.info("Local audio tracks: ",o);const r=i.getVideoTracks();if(B.info("Local video tracks: ",r),this.isOffer&&typeof this.instance.addTransceiver=="function"){const a={direction:"sendrecv",streams:[i]};o.forEach(l=>{this.options.userVariables.microphoneLabel=l.label;const c=this.instance.addTransceiver(l,a);this._setAudioCodec(c)}),console.debug("Applying video transceiverParams",a),r.forEach(l=>{this.options.userVariables.cameraLabel=l.label,this.instance.addTransceiver(l,a)})}else typeof this.instance.addTrack=="function"?(o.forEach(a=>{this.options.userVariables.microphoneLabel=a.label,this.instance.addTrack(a,i)}),this.instance.getTransceivers().forEach(a=>this._setAudioCodec(a)),r.forEach(a=>{this.options.userVariables.cameraLabel=a.label,this.instance.addTrack(a,i)})):this.instance.addStream(i);s===!1&&((a=>{const l=Hn(a);l&&(l.muted=!0)})(n),Vi(n,i))}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this.startNegotiation(),this._logTransceivers()})}_getSenderByKind(t){return this.instance.getSenders().find(({track:n})=>n&&n.kind===t)}_checkMediaToNegotiate(t){if(!this._getSenderByKind(t)){const n=this.instance.addTransceiver(t);B.info("Add transceiver",t,n)}}_createOffer(){return G(this,void 0,void 0,function*(){this._isOffer()&&(this._constraints.offerToReceiveAudio=!!this.options.audio,this._constraints.offerToReceiveVideo=!!this.options.video,B.info("_createOffer - this._constraints",this._constraints),yield this.instance.createOffer(this._constraints).then(this._setLocalDescription.bind(this)).then(this._sdpReady).catch(t=>B.error("Peer _createOffer error:",t)))})}_setRemoteDescription(t){return G(this,void 0,void 0,function*(){yield this.instance.setRemoteDescription(t)})}_createAnswer(){return G(this,void 0,void 0,function*(){if(!this._isAnswer())return;if(this.instance.signalingState!=="stable")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:Vt.Offer})]));yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Vt.Offer}),this._logTransceivers();const t=yield this.instance.createAnswer();yield this._setLocalDescription(t)})}_setLocalDescription(t){return G(this,void 0,void 0,function*(){const{useStereo:n,googleMaxBitrate:i,googleMinBitrate:s,googleStartBitrate:o,mediaSettings:r}=this.options;n&&(t.sdp=(a=>{const l=`\r
|
|
101
101
|
`,c=a.split(l),d=c.findIndex(_=>/^a=rtpmap/.test(_)&&/opus\/48000/.test(_));if(d<0)return a;const u=(_=>{const w=new RegExp("a=rtpmap:(\\d+) \\w+\\/\\d+"),b=_.match(w);return b&&b.length==2?b[1]:null})(c[d]),p=new RegExp(`a=fmtp:${u}`),g=c.findIndex(_=>p.test(_));return g>=0?/stereo=1;/.test(c[g])||(c[g]+="; stereo=1; sprop-stereo=1"):c[d]+=`${l}a=fmtp:${u} stereo=1; sprop-stereo=1`,c.join(l)})(t.sdp)),i&&s&&o&&(t.sdp=((a,l,c,d)=>{const u=a.split(`\r
|
|
102
102
|
`);return u.forEach((p,g)=>{/^a=fmtp:\d*/.test(p)?u[g]+=`;x-google-max-bitrate=${l};x-google-min-bitrate=${c};x-google-start-bitrate=${d}`:/^a=mid:(1|video)/.test(p)&&(u[g]+=`\r
|
|
103
103
|
b=AS:${l}`)}),u.join(`\r
|
|
@@ -109,4 +109,4 @@ b=`+c+":"+d+`\r
|
|
|
109
109
|
`),void this._requestAnotherLocalDescription();(i=(n=this.peer)===null||n===void 0?void 0:n.instance)===null||i===void 0||i.removeEventListener("icecandidate",this._onIce);let r=null;const a={sessid:this.session.sessionid,sdp:s,dialogParams:this.options,"User-Agent":`Web-${f_}`};switch(o){case Vt.Offer:this.setState(X.Requesting),r=new Zv(a);break;case Vt.Answer:this.setState(X.Answering),r=this.options.attach===!0?new Qv(a):new Jv(a);break;default:return B.error(`${this.id} - Unknown local SDP type:`,t),this.hangup({},!1)}this._execute(r).then(l=>{const{node_id:c=null}=l;this._targetNodeId=c,o===Vt.Offer?this.setState(X.Trying):this.setState(X.Active)}).catch(l=>{B.error(`${this.id} - Sending ${o} error:`,l),this.hangup()}),console.timeEnd(Iu)}_onIce(t){const{instance:n}=this.peer;this._iceTimeout===null&&(this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),1e3)),t.candidate?B.debug("RTCPeer Candidate:",t.candidate):this._onIceSdp(n.localDescription)}_registerPeerEvents(){const{instance:t}=this.peer;this._iceDone=!1,t.onicecandidate=n=>{this._iceDone||this._onIce(n)},t.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),t.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:o}=this.options;o===!1&&Vi(i,s)})}_onMediaError(t){this._dispatchNotification({type:ae.userMediaError,error:t}),this.hangup({},!1)}_dispatchConferenceUpdate(t){this._dispatchNotification(Object.assign({type:ae.conferenceUpdate,call:this},t))}_dispatchNotification(t){this.options.screenShare!==!0&&(J(V.Notification,t,this.id,!1)||J(V.Notification,t,this.session.uuid))}_execute(t){return this.nodeId&&(t.targetNodeId=this.nodeId),this.session.execute(t)}_init(){const{id:t,userVariables:n,remoteCallerNumber:i,onNotification:s}=this.options;t||(this.options.id=an()),this.id=this.options.id,n&&!Du(n)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,un(V.MediaError,this._onMediaError,this.id),ln(s)&&un(V.Notification,s.bind(this),this.id),this.setState(X.New),B.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;Kn(t),Kn(n),dn(V.MediaError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(t){this._statsIntervalId=setInterval(this._doStats,t),B.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),B.info("Stats stopped")}}rd.setStateTelnyx=e=>{if(e){switch(e._state){case X.Requesting:case X.Recovering:case X.Trying:case X.Early:e.state="connecting";break;case X.Active:e.state="active";break;case X.Held:e.state="held";break;case X.Hangup:case X.Destroy:e.state="done";break;case X.Answering:e.state="ringing";break;case X.New:e.state="new"}return e}};class Ve extends rd{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=t=>this.session.execute(new s_(t))}hangup(t={},n=!0){this.screenShare instanceof Ve&&this.screenShare.hangup(t,n),super.hangup(t,n)}startScreenShare(t){return G(this,void 0,void 0,function*(){const n=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;n.getTracks().forEach(c=>{c.addEventListener("ended",()=>{this.screenShare&&this.screenShare.hangup()})});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:n,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${a} (Screen)`},t);return this.screenShare=new Ve(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){this.screenShare instanceof Ve&&this.screenShare.hangup()}setAudioOutDevice(t){return G(this,void 0,void 0,function*(){this.options.speakerId=t;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&Hu(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(t=!0){if(t===!1)return clearInterval(this._statsInterval);B.setLevel(2),this._statsInterval=window.setInterval(()=>G(this,void 0,void 0,function*(){const n=yield this.peer.instance.getStats(null);let i="";const s=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],o=["id","type","timestamp"];n.forEach(r=>{s.includes(r.type)||(i+=`
|
|
110
110
|
${r.type}
|
|
111
111
|
`,Object.keys(r).forEach(a=>{o.includes(a)||(i+=` ${a}: ${r[a]}
|
|
112
|
-
`)}))}),B.info(i)}),2e3)}}class p_ extends Wv{constructor(t){super(t),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=t.iceServers,this.ringtoneFile=t.ringtoneFile,this.ringbackFile=t.ringbackFile}get reconnectDelay(){return 1e3}connect(){const t=Object.create(null,{connect:{get:()=>super.connect}});return G(this,void 0,void 0,function*(){t.connect.call(this)})}checkPermissions(t=!0,n=!0){return G(this,void 0,void 0,function*(){try{const i=yield Fi({audio:t,video:n});return Kn(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const t=Object.create(null,{disconnect:{get:()=>super.disconnect}});return G(this,void 0,void 0,function*(){Object.keys(this.calls).forEach(n=>this.calls[n].setState(X.Purge)),this.calls={},yield t.disconnect.call(this)})}speedTest(t){return new Promise((n,i)=>{if(ju(V.SpeedTest,r=>{const{upDur:a,downDur:l}=r,c=l?8*t/(l/1e3)/1024:0;n({upDur:a,downDur:l,upKps:(a?8*t/(a/1e3)/1024:0).toFixed(0),downKps:c.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 r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")})}getDevices(){return Xn().catch(t=>(J(V.MediaError,t,this.uuid),[]))}getVideoDevices(){return Xn(le.Video).catch(t=>(J(V.MediaError,t,this.uuid),[]))}getAudioInDevices(){return Xn(le.AudioIn).catch(t=>(J(V.MediaError,t,this.uuid),[]))}getAudioOutDevices(){return Xn(le.AudioOut).catch(t=>(console.error("getAudioOutDevices",t),J(V.MediaError,t,this.uuid),[]))}validateDeviceId(t,n,i){return Bi(t,n,i)}getDeviceResolutions(t){return G(this,void 0,void 0,function*(){try{return yield(n=>G(void 0,void 0,void 0,function*(){const i=[],s=yield Fi({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<zu.length;r++){const[a,l]=zu[r];(yield o.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${l}`,width:a,height:l})}return Kn(s),i}))(t)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(t){return G(this,void 0,void 0,function*(){if(!t)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=t,s=Mr(t,["micId","micLabel"]);return Wu(s),this._audioConstraints=yield qu(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}setVideoSettings(t){return G(this,void 0,void 0,function*(){if(!t)throw new Error("You need to provide the settings object");const{camId:n,camLabel:i}=t,s=Mr(t,["camId","camLabel"]);return Wu(s),this._videoConstraints=yield qu(n,i,"videoinput",s),this.camId=n,this.camLabel=i,this._videoConstraints})}disableWebcam(){this._videoConstraints=!1}enableWebcam(){this._videoConstraints=!0}set iceServers(t){const n={urls:["stun:stun.l.google.com:19302"]};this._iceServers=typeof t=="boolean"?t?[n]:[]:t||[Mu,Lv,n]}get iceServers(){return this._iceServers}set speaker(t){this._speaker=t}get speaker(){return this._speaker}set localElement(t){this._localElement=Hn(t)}get localElement(){return this._localElement}set remoteElement(t){this._remoteElement=Hn(t)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:t,channel:n="",data:i}){if(!n)throw new Error(`Invalid channel for broadcast: ${n}`);const s=new e_({sessid:this.sessionid,eventChannel:n,data:i});t&&(s.targetNodeId=t),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:t,channels:n=[],handler:i}){return G(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new n_({sessid:this.sessionid,eventChannel:n});t&&(s.targetNodeId=t);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=Br(o);return r.length&&r.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,i,l)),o})}vertoUnsubscribe({nodeId:t,channels:n=[]}){return G(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new i_({sessid:this.sessionid,eventChannel:n});t&&(i.targetNodeId=t);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=Br(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}static telnyxStateCall(t){return Ve.setStateTelnyx(t)}}class od{constructor(t,n){this.code=n,this.message=t}}class m_ extends Dt{constructor(){super(),this.method=nt.Ping,this.buildRequest({method:this.method,params:{}})}}class zt{constructor(t){this.session=t}_ack(t,n){const i=new Yv(t,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*Vu(2,6)}handleMessage(t){const{session:n}=this,{id:i,method:s,params:o={}}=t,r=o==null?void 0:o.callID,a=o==null?void 0:o.eventChannel,l=o==null?void 0:o.eventType,c=s===nt.Attach;if(l==="channelPvtData")return this._handlePvtEvent(o.pvtData);if(r&&n.calls.hasOwnProperty(r)){if(!c)return n.calls[r].handleMessage(t),void this._ack(i,s);n.calls[r].hangup({},!1)}const d=()=>{var g,_,w,b;const y={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:c,mediaSettings:o.mediaSettings,debug:(g=n.options.debug)!==null&&g!==void 0&&g,debugOutput:(_=n.options.debugOutput)!==null&&_!==void 0?_:"socket",prefetchIceCandidates:(w=n.options.prefetchIceCandidates)!==null&&w!==void 0&&w,forceRelayCandidate:(b=n.options.forceRelayCandidate)!==null&&b!==void 0&&b};o.telnyx_call_control_id&&(y.telnyxCallControlId=o.telnyx_call_control_id),o.telnyx_session_id&&(y.telnyxSessionId=o.telnyx_session_id),o.telnyx_leg_id&&(y.telnyxLegId=o.telnyx_leg_id),o.client_state&&(y.clientState=o.client_state),o.dialogParams&&o.dialogParams.custom_headers&&o.dialogParams.custom_headers.length&&(y.customHeaders=o.dialogParams.custom_headers);const S=new Ve(n,y);return S.nodeId=this.nodeId,S},u=new Gu,p=new m_;switch(s){case nt.Ping:this.session.execute(p);break;case nt.Punt:n.disconnect();break;case nt.Invite:{const w=d();w.playRingtone(),w.setState(X.Ringing),w.direction=xe.Inbound,this._ack(i,s);break}case nt.Attach:{const w=d();this.session.autoRecoverCalls?w.answer():w.setState(X.Recovering),w.handleMessage(t);break}case nt.Event:case"webrtc.event":if(!a)return void B.error("Verto received an unknown event:",o);const g=n.relayProtocol,_=a.split(".")[0];n._existsSubscription(g,a)?J(g,o,a):a===n.sessionid?this._handleSessionEvent(o.eventData):n._existsSubscription(g,_)?J(g,o,_):n.calls.hasOwnProperty(a)?n.calls[a].handleMessage(t):J(V.Notification,o,n.uuid);break;case nt.Info:o.type=ae.generic,J(V.Notification,o,n.uuid);break;case nt.ClientReady:this.session.execute(u);break;default:{const w=Dr(t);if(w){switch(w){case Rt.REGISTER:case Rt.REGED:n.connection.previousGatewayState!==Rt.REGED&&n.connection.previousGatewayState!==Rt.REGISTER&&(zt.retriedRegister=0,o.type=ae.vertoClientReady,J(V.Ready,o,n.uuid));break;case Rt.UNREGED:case Rt.NOREG:if(zt.retriedRegister+=1,zt.retriedRegister===5){zt.retriedRegister=0,J(V.Error,{error:new od("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 Rt.FAILED:case Rt.FAIL_WAIT:if(n.connection.previousGatewayState!==Rt.FAILED&&n.connection.previousGatewayState!==Rt.FAIL_WAIT){if(!this.session.hasAutoReconnect()){zt.retriedConnect=0,J(V.Error,{error:new od("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:n.sessionid},n.uuid);break}if(zt.retriedConnect+=1,zt.retriedConnect===5){zt.retriedConnect=0,J(V.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:B.warn("GatewayState message unknown method:",t)}break}B.debug("Verto message unknown method:",t);break}}}_retrieveCallId(t,n){const i=Object.keys(this.session.calls);if(t.action!=="bootObj")return i.find(s=>this.session.calls[s].channels.includes(n));{const s=t.data.find(o=>i.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(t){return G(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:d,role:u,callID:p}=t;switch(s){case"conference-liveArray-join":{const g=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},_={nodeId:this.nodeId,channels:[o],handler:({data:b})=>{const y=p||this._retrieveCallId(b,o);if(y&&n.calls.hasOwnProperty(y)){const S=n.calls[y];S._addChannel(o),S.extension=r,S.handleConferenceUpdate(b,t).then(C=>{C==="INVALID_PACKET"&&g()})}}},w=yield n.vertoSubscribe(_).catch(b=>{B.error("liveArray subscription error:",b)});ji(w,o)&&g();break}case"conference-liveArray-part":{let g=null;if(o&&n._existsSubscription(i,o)){const{callId:w=null}=n.subscriptions[i][o];if(g=n.calls[w]||null,w!==null){const b={type:ae.conferenceUpdate,action:At.Leave,conferenceName:r,participantId:Number(d),role:u};J(V.Notification,b,w,!1)||J(V.Notification,b,n.uuid),g===null&&dn(V.Notification,null,w)}}const _=[o,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:_}).then(({unsubscribedChannels:w=[]})=>{g&&(g.channels=g.channels.filter(b=>!w.includes(b)))}).catch(w=>{B.error("liveArray unsubscribe error:",w)});break}}})}_handleSessionEvent(t){switch(t.contentType){case"layout-info":case"layer-info":nd(this.session,t);break;case"logo-info":{const n={type:ae.conferenceUpdate,action:At.LogoInfo,logo:t.logoURL};J(V.Notification,n,this.session.uuid);break}}}}zt.retriedConnect=0,zt.retriedRegister=0;class g_ extends Dt{constructor(t,n,i,s={},o){super(),this.method="anonymous_login";const r={target_type:t,target_id:n,userVariables:s,reconnection:o,"User-Agent":{sdkVersion:jr,data:navigator.userAgent}};i&&(r.sessid=i),this.buildRequest({method:this.method,params:r})}}class v_ extends p_{constructor(t){super(t),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>G(this,void 0,void 0,function*(){this._idle=!1;const{login:n,password:i,passwd:s,login_token:o,userVariables:r,autoReconnect:a=!0}=this.options,l=new Xv(n,i||s,o,this.sessionid,r,!!Nr()),c=yield this.execute(l).catch(this._handleLoginError);c&&(this._autoReconnect=a,this.sessionid=c.sessid)}),this.handleAnonymousLoginOnSocketOpen=()=>G(this,void 0,void 0,function*(){this._idle=!1;const{anonymous_login:n}=this.options,{target_type:i,target_id:s}=n,o=new g_(i,s,this.sessionid,this.options.userVariables,!!Nr()),r=yield this.execute(o).catch(this._handleLoginError);r&&(this.sessionid=r.sessid)}),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&this.calls[i].hangup({},!0)})})}validateOptions(){return Lr(this.options)||Oi(this.options)}newCall(t){if(!this.validateCallOptions(t))throw new Error("Verto.newCall() error: destinationNumber is required.");console.time(Iu);const n=new Ve(this,t);return n.invite(),n}broadcast(t){return this.vertoBroadcast(t)}subscribe(t){return this.vertoSubscribe(t)}unsubscribe(t){return this.vertoUnsubscribe(t)}validateCallOptions(t){return!!Oi(this.options)||!!t.destinationNumber}_onSocketOpen(){return G(this,void 0,void 0,function*(){return Lr(this.options)?this.handleLoginOnSocketOpen():Oi(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(t){new zt(this).handleMessage(t)}}class __ extends v_{constructor(t){super(t),console.log(`SDK version: ${td}`)}newCall(t){return super.newCall(t)}static webRTCInfo(){return Kv()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:vt.full},{browserName:"Firefox",features:["audio"],supported:vt.partial},{browserName:"Safari",supported:vt.not_supported},{browserName:"Edge",supported:vt.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:vt.not_supported},{browserName:"Firefox",supported:vt.not_supported},{browserName:"Safari",features:["video","audio"],supported:vt.full},{browserName:"Edge",supported:vt.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:vt.full},{browserName:"Firefox",features:["audio"],supported:vt.partial},{browserName:"Safari",supported:vt.not_supported},{browserName:"Edge",supported:vt.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:vt.full},{browserName:"Firefox",features:["audio"],supported:vt.partial},{browserName:"Safari",features:["video","audio"],supported:vt.full},{browserName:"Edge",features:["audio"],supported:vt.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:vt.full},{browserName:"Firefox",features:["audio"],supported:vt.partial},{browserName:"Safari",supported:vt.not_supported},{browserName:"Edge",features:["audio"],supported:vt.partial}]}]}}function y_(e){if(!e||typeof e!="object")return!1;const t=e;return t.method==="ai_conversation"&&typeof t.params=="object"}function b_(e){if(!e||typeof e!="object")return!1;const t=e;return t.params.type!=="response.text.delta"?!1:!!t.params.delta}function w_(e){if(!e||typeof e!="object")return!1;const t=e;return t.params.type!=="conversation.item.created"?!1:!!t.params.item.content}function x_(e){return b_(e)?{id:e.params.item_id,role:"assistant",content:e.params.delta,timestamp:new Date}:null}function S_(e){return!w_(e)||e.params.item.role!=="user"||e.params.item.status!=="completed"?null:{id:e.params.item.id,role:e.params.item.role,content:e.params.item.content.map(t=>t.transcript).join(" "),timestamp:new Date}}function C_(e){const[t,n]=ee([]),[,i]=Zc();return Kt(()=>{if(!e)return;const s=o=>{if(y_(o))switch(o.params.type){case"response.text.delta":{const r=x_(o);r&&n(a=>[...a,r]),i("waiting");return}case"conversation.item.created":{const r=S_(o);r&&(i("thinking"),n(a=>[...a,r]));return}}};return e.on(V.SocketMessage,s),()=>{e.off(V.SocketMessage,s)}},[e,i]),t}const k_=({call:e,client:t})=>{const n=Ne(),[i,s]=ee(n.default_state),o=()=>s("expanded"),r=()=>s("collapsed"),a=C_(t);switch(i){case"collapsed":return A(Eu,{onExpand:o,call:e,client:t});case"expanded":return A(Rv,{transcript:a,onCollapse:r,call:e});default:return A(Eu,{onExpand:o,call:e,client:t})}},Ur=()=>A(Bn.div,{layoutId:Ci,className:"bg-[#FEFDF5] text-black dark:bg-black gap-3 dark:text-white w-[240px] max-w-full rounded-4xl p-4 text-center flex items-center justify-center flex-col shadow-lg shadow-[#38383878]",children:A("div",{className:"rounded-full animate-spin",children:A(pv,{})})}),T_=({call:e,client:t})=>{switch(e==null?void 0:e.state){case"new":case"trying":case"requesting":return A(Ur,{});case"done":case"purged":case"destroy":return null;case"active":return A(k_,{client:t,call:e});default:return A(Ur,{})}},E_=(e,t)=>{const[n,i]=ee(null);return Kt(()=>{if(!e)return;const s=new __({env:t||"production",anonymous_login:{target_id:e,target_type:"ai_assistant"}});i(s)},[e,t]),n},A_=(e,{onReady:t,onNotification:n,onError:i,onSocketMessage:s})=>(Kt(()=>{if(e)return e.connect().then().catch(console.error),e.on(V.Ready,t),e.on(V.Notification,n),e.on(V.Error,i),e.on(V.SocketMessage,s),()=>{e.off(V.Ready,t),e.off(V.Notification,n),e.off(V.Error,i),e.off(V.SocketMessage,s),e.disconnect()}},[e]),null),R_=({className:e})=>A("svg",{className:e,width:"236",height:"211",viewBox:"0 0 236 211",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[A("g",{clipPath:"url(#:R5lfm:)",children:[A("path",{d:"M231.927 194.514C235.881 187.393 237.006 179.067 235.083 171.168C234.531 168.984 233.769 166.858 232.806 164.819C232.502 164.15 232.156 163.501 231.771 162.874L200.418 104.252H168.341L201.143 165.69C202.172 167.475 202.714 169.496 202.714 171.552C202.714 173.608 202.172 175.628 201.143 177.414C200.139 179.082 198.715 180.464 197.01 181.424C195.305 182.385 193.378 182.89 191.416 182.892H154.009C153.595 188.612 151.801 194.15 148.776 199.041C145.751 203.931 141.584 208.033 136.625 211H205.385C209.975 210.698 214.443 209.405 218.475 207.211C224.164 204.438 228.859 200.007 231.927 194.514Z",fill:"currentColor"}),A("path",{d:"M56.0698 65.9049H88.1473L104.134 36.466C105.487 33.9253 107.515 31.7984 109.999 30.3146C112.484 28.8309 115.331 28.0467 118.233 28.0467C121.135 28.0467 123.982 28.8309 126.466 30.3146C128.951 31.7984 130.979 33.9253 132.331 36.466L147.853 65.9049H179.93L157.166 23.3081C153.391 16.2702 147.751 10.3822 140.851 6.27586C133.951 2.16956 126.052 0 118 0C109.948 0 102.049 2.16956 95.1487 6.27586C88.2488 10.3822 82.6089 16.2702 78.8345 23.3081L56.0698 65.9049Z",fill:"currentColor"}),A("path",{d:"M81.9387 99.1324C82.275 93.4362 83.9987 87.9051 86.9627 83.0107C89.9266 78.1164 94.0429 74.0041 98.9604 71.0247H36.875V99.1324H81.9387Z",fill:"currentColor"}),A("path",{d:"M87.0591 101.18V177.977H101.649C104.692 177.944 107.64 176.924 110.041 175.075C112.443 173.226 114.165 170.648 114.946 167.738C115.26 166.621 115.416 165.467 115.411 164.308V118.229C115.425 113.227 117.432 108.432 120.997 104.885C124.561 101.338 129.396 99.3264 134.451 99.286H199.382V71.0247H117.481C109.408 71.0382 101.67 74.2213 95.9663 79.8751C90.2626 85.5289 87.0591 93.1914 87.0591 101.18Z",fill:"currentColor"}),A("path",{d:"M3.1927 164.819C2.23008 166.858 1.46775 168.984 0.916237 171.168C-1.00574 179.084 0.119328 187.425 4.07225 194.565C7.14854 200.039 11.8422 204.452 17.5241 207.211C21.5555 209.405 26.0233 210.698 30.6138 211H117.999C126.232 211 134.128 207.764 139.949 202.003C145.771 196.242 149.042 188.428 149.042 180.281V104.201H134.245C130.607 104.294 127.148 105.782 124.6 108.352C122.051 110.922 120.611 114.372 120.586 117.973V164.051C120.572 169.053 118.555 173.845 114.976 177.377C111.397 180.909 106.549 182.892 101.495 182.892H44.8417C42.8798 182.89 40.9521 182.385 39.2471 181.424C37.5421 180.464 36.1182 179.082 35.1149 177.414C34.0855 175.619 33.5443 173.59 33.5443 171.526C33.5443 169.462 34.0855 167.434 35.1149 165.638L67.9167 104.201H35.5806L4.22746 162.823C3.86529 163.539 3.50313 164.154 3.1927 164.819Z",fill:"currentColor"})]}),A("defs",{children:A("clipPath",{id:":R5lfm:",children:A("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function I_(){const e=Ne();return e.logo_icon_url?A("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:A("img",{src:e.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):A(R_,{className:"w-8 h-8 mr-2"})}const P_=({client:e,versionId:t})=>{const n=Ne(),i=()=>{var a;if(!e){console.error("Client is not initialized.");return}const s=(a=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:a.codecs,o=s==null?void 0:s.find(l=>l.mimeType.toLowerCase().includes("opus")),r=t?[{name:"X-AI-Assistant-Version-ID",value:t}]:void 0;e.newCall({destinationNumber:"xxx",preferred_codecs:[o],customHeaders:r})};return A(Bn.button,{layoutId:Ci,onClick:i,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer dark:bg-black dark:text-white ",children:[A(I_,{}),n.start_call_text]})},M_='@layer components;/*! tailwindcss v4.1.11 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-font-weight:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-400:oklch(70.4% .191 22.216);--color-green-400:oklch(79.2% .209 151.711);--color-black:#000;--color-white:#fff;--spacing:.25rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-xl:1.25rem;--text-xl--line-height:calc(1.75/1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--font-weight-medium:500;--font-weight-semibold:600;--radius-md:.375rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--radius-4xl:2rem;--animate-spin:spin 1s linear infinite;--blur-xs:4px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing)*0)}.top-0{top:calc(var(--spacing)*0)}.right-0{right:calc(var(--spacing)*0)}.bottom-0{bottom:calc(var(--spacing)*0)}.left-0{left:calc(var(--spacing)*0)}.z-10{z-index:10}.z-\\[9999\\]{z-index:9999}.mt-2{margin-top:calc(var(--spacing)*2)}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.ml-4{margin-left:calc(var(--spacing)*4)}.ml-auto{margin-left:auto}.flex{display:flex}.hidden{display:none}.inline-flex{display:inline-flex}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-8{height:calc(var(--spacing)*8)}.h-\\[72px\\]{height:72px}.h-\\[144px\\]{height:144px}.h-\\[300px\\]{height:300px}.h-full{height:100%}.min-h-\\[180px\\]{min-height:180px}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-8{width:calc(var(--spacing)*8)}.w-\\[200px\\]{width:200px}.w-\\[240px\\]{width:240px}.w-\\[250px\\]{width:250px}.w-\\[344px\\]{width:344px}.w-full{width:100%}.max-w-full{max-width:100%}.flex-1{flex:1}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing)*1)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-\\[\\#3D3D46\\]>:not(:last-child)){border-color:#3d3d46}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-3xl{border-radius:var(--radius-3xl)}.rounded-4xl{border-radius:var(--radius-4xl)}.rounded-full{border-radius:3.40282e38px}.rounded-md{border-radius:var(--radius-md)}.rounded-t-3xl{border-top-left-radius:var(--radius-3xl);border-top-right-radius:var(--radius-3xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-solid{--tw-border-style:solid;border-style:solid}.border-\\[\\#969696\\]{border-color:#969696}.bg-\\[\\#E6E3D3\\]{background-color:#e6e3d3}.bg-\\[\\#F36666\\]{background-color:#f36666}.bg-\\[\\#FEFDF5\\]{background-color:#fefdf5}.bg-\\[\\#FEFDF599\\]{background-color:#fefdf599}.object-cover{object-fit:cover}.object-center{object-position:center}.p-2{padding:calc(var(--spacing)*2)}.p-4{padding:calc(var(--spacing)*4)}.px-2\\.5{padding-inline:calc(var(--spacing)*2.5)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-2{padding-block:calc(var(--spacing)*2)}.py-3{padding-block:calc(var(--spacing)*3)}.text-center{text-align:center}.text-left{text-align:left}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-\\[\\#969696\\]{color:#969696}.text-black{color:var(--color-black)}.text-green-400{color:var(--color-green-400)}.text-red-400{color:var(--color-red-400)}.text-white{color:var(--color-white)}.underline{text-decoration-line:underline}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[\\#38383878\\]{--tw-shadow-color:#38383878}@supports (color:color-mix(in lab,red,red)){.shadow-\\[\\#38383878\\]{--tw-shadow-color:color-mix(in oklab,#38383878 var(--tw-shadow-alpha),transparent)}}.backdrop-blur-xs{--tw-backdrop-blur:blur(var(--blur-xs));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}@media (min-width:40rem){.sm\\:h-\\[386px\\]{height:386px}.sm\\:w-\\[400px\\]{width:400px}.sm\\:rounded-3xl{border-radius:var(--radius-3xl)}}@media (min-width:48rem){.md\\:right-10{right:calc(var(--spacing)*10)}.md\\:bottom-10{bottom:calc(var(--spacing)*10)}}.dark\\:border-\\[\\#3D3D46\\]:where(.dark,.dark *){border-color:#3d3d46}.dark\\:bg-\\[\\#3C3C3C\\]:where(.dark,.dark *){background-color:#3c3c3c}.dark\\:bg-\\[\\#38383C96\\]:where(.dark,.dark *){background-color:#38383c96}.dark\\:bg-\\[\\#38383C\\]:where(.dark,.dark *){background-color:#38383c}.dark\\:bg-\\[\\#222227\\]:where(.dark,.dark *){background-color:#222227}.dark\\:bg-\\[\\#750000\\]:where(.dark,.dark *){background-color:#750000}.dark\\:bg-black:where(.dark,.dark *){background-color:var(--color-black)}.dark\\:text-black:where(.dark,.dark *){color:var(--color-black)}.dark\\:text-white:where(.dark,.dark *){color:var(--color-white)}}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:0 0}::-webkit-scrollbar-thumb{background-color:#888;background-clip:content-box;border:2px solid #0000;border-radius:4px}::-webkit-scrollbar-thumb:hover{background-color:#555}html{scrollbar-width:thin;scrollbar-color:#888 transparent}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}',L_=({children:e})=>A("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:A("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:e})}),D_={duration:.1,ease:"circOut"},O_=({children:e,position:t="fixed"})=>{const n=Ne(),s=(t??n.position??"fixed")==="fixed"?A(L_,{children:e}):e;return A("div",{className:Oe(n.theme==="dark"&&"dark"),children:A(Wf,{transition:D_,children:[A("style",{children:M_}),s]})})},N_=e=>A(Bn.div,{layoutId:Ci,className:"bg-[#FEFDF5] text-black dark:bg-black rounded-2xl p-4 flex flex-col items-center justify-center dark:text-white w-[344px] max-w-full",children:[A(hv,{className:"w-8 h-8 text-red-400"}),A("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),A("ul",{className:"gap-4 ml-4 text-sm list-disc",children:[A("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),A("li",{children:["Make sure that the"," ",A("a",{href:`https://portal.telnyx.com/#/ai/assistants/edit/${e.agentId}?tab=telephony`,className:"inline-flex items-center gap-1 font-medium text-green-400 underline",target:"_blank",rel:"noopener noreferrer",children:["Support Unauthenticated Web Calls"," ",A(yv,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function V_(e){return Object.keys(e).length===0}function ad(e){var n;if(typeof e!="object"||e===null)return!1;const t=e;return t.method==="ai_conversation"&&((n=t.params)==null?void 0:n.type)==="widget_settings"&&typeof t.params.widget_settings=="object"}const F_=({client:e})=>{const t=Bg();return es(()=>{if(!e)return;const n=i=>{if(ad(i)&&!V_(i.params.widget_settings)){const s=i.params.widget_settings;t(s)}};return e.on(V.SocketMessage,n),()=>{e.off(V.SocketMessage,n)}},[e,t]),null};function B_({"agent-id":e,environment:t,position:n="fixed","version-id":i}){const s=E_(e,t),[o,r]=ee(null),[a,l]=ee(!1),[c,d]=ee(!1),[u,p]=ee(!1);return A_(s,{onReady:()=>l(!1),onNotification:S=>{var C;if(((C=S.call)==null?void 0:C.state)==="destroy")return r(null);r(S)},onError:()=>{l(!1),d(!0)},onSocketMessage:S=>{ad(S)&&p(!0)}}),A(Qt,{children:[A(O_,{position:n,children:e?c?A(N_,{agentId:e}):a?A(Ur,{}):o!=null&&o.call?A(T_,{call:o.call,client:s}):u?A(P_,{versionId:i,client:s}):null:A("div",{children:"Please provide an assistant ID."})}),A(F_,{client:s})]})}Cd(B_,"telnyx-ai-agent",Sg,{shadow:!0})})();
|
|
112
|
+
`)}))}),B.info(i)}),2e3)}}class p_ extends Wv{constructor(t){super(t),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=t.iceServers,this.ringtoneFile=t.ringtoneFile,this.ringbackFile=t.ringbackFile}get reconnectDelay(){return 1e3}connect(){const t=Object.create(null,{connect:{get:()=>super.connect}});return G(this,void 0,void 0,function*(){t.connect.call(this)})}checkPermissions(t=!0,n=!0){return G(this,void 0,void 0,function*(){try{const i=yield Fi({audio:t,video:n});return Kn(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const t=Object.create(null,{disconnect:{get:()=>super.disconnect}});return G(this,void 0,void 0,function*(){Object.keys(this.calls).forEach(n=>this.calls[n].setState(X.Purge)),this.calls={},yield t.disconnect.call(this)})}speedTest(t){return new Promise((n,i)=>{if(ju(V.SpeedTest,r=>{const{upDur:a,downDur:l}=r,c=l?8*t/(l/1e3)/1024:0;n({upDur:a,downDur:l,upKps:(a?8*t/(a/1e3)/1024:0).toFixed(0),downKps:c.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 r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")})}getDevices(){return Xn().catch(t=>(J(V.MediaError,t,this.uuid),[]))}getVideoDevices(){return Xn(le.Video).catch(t=>(J(V.MediaError,t,this.uuid),[]))}getAudioInDevices(){return Xn(le.AudioIn).catch(t=>(J(V.MediaError,t,this.uuid),[]))}getAudioOutDevices(){return Xn(le.AudioOut).catch(t=>(console.error("getAudioOutDevices",t),J(V.MediaError,t,this.uuid),[]))}validateDeviceId(t,n,i){return Bi(t,n,i)}getDeviceResolutions(t){return G(this,void 0,void 0,function*(){try{return yield(n=>G(void 0,void 0,void 0,function*(){const i=[],s=yield Fi({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<zu.length;r++){const[a,l]=zu[r];(yield o.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${l}`,width:a,height:l})}return Kn(s),i}))(t)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(t){return G(this,void 0,void 0,function*(){if(!t)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=t,s=Mr(t,["micId","micLabel"]);return Wu(s),this._audioConstraints=yield qu(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}setVideoSettings(t){return G(this,void 0,void 0,function*(){if(!t)throw new Error("You need to provide the settings object");const{camId:n,camLabel:i}=t,s=Mr(t,["camId","camLabel"]);return Wu(s),this._videoConstraints=yield qu(n,i,"videoinput",s),this.camId=n,this.camLabel=i,this._videoConstraints})}disableWebcam(){this._videoConstraints=!1}enableWebcam(){this._videoConstraints=!0}set iceServers(t){const n={urls:["stun:stun.l.google.com:19302"]};this._iceServers=typeof t=="boolean"?t?[n]:[]:t||[Mu,Lv,n]}get iceServers(){return this._iceServers}set speaker(t){this._speaker=t}get speaker(){return this._speaker}set localElement(t){this._localElement=Hn(t)}get localElement(){return this._localElement}set remoteElement(t){this._remoteElement=Hn(t)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:t,channel:n="",data:i}){if(!n)throw new Error(`Invalid channel for broadcast: ${n}`);const s=new e_({sessid:this.sessionid,eventChannel:n,data:i});t&&(s.targetNodeId=t),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:t,channels:n=[],handler:i}){return G(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new n_({sessid:this.sessionid,eventChannel:n});t&&(s.targetNodeId=t);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=Br(o);return r.length&&r.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,i,l)),o})}vertoUnsubscribe({nodeId:t,channels:n=[]}){return G(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new i_({sessid:this.sessionid,eventChannel:n});t&&(i.targetNodeId=t);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=Br(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}static telnyxStateCall(t){return Ve.setStateTelnyx(t)}}class od{constructor(t,n){this.code=n,this.message=t}}class m_ extends Dt{constructor(){super(),this.method=nt.Ping,this.buildRequest({method:this.method,params:{}})}}class zt{constructor(t){this.session=t}_ack(t,n){const i=new Yv(t,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*Vu(2,6)}handleMessage(t){const{session:n}=this,{id:i,method:s,params:o={}}=t,r=o==null?void 0:o.callID,a=o==null?void 0:o.eventChannel,l=o==null?void 0:o.eventType,c=s===nt.Attach;if(l==="channelPvtData")return this._handlePvtEvent(o.pvtData);if(r&&n.calls.hasOwnProperty(r)){if(!c)return n.calls[r].handleMessage(t),void this._ack(i,s);n.calls[r].hangup({},!1)}const d=()=>{var g,_,w,b;const y={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:c,mediaSettings:o.mediaSettings,debug:(g=n.options.debug)!==null&&g!==void 0&&g,debugOutput:(_=n.options.debugOutput)!==null&&_!==void 0?_:"socket",prefetchIceCandidates:(w=n.options.prefetchIceCandidates)!==null&&w!==void 0&&w,forceRelayCandidate:(b=n.options.forceRelayCandidate)!==null&&b!==void 0&&b};o.telnyx_call_control_id&&(y.telnyxCallControlId=o.telnyx_call_control_id),o.telnyx_session_id&&(y.telnyxSessionId=o.telnyx_session_id),o.telnyx_leg_id&&(y.telnyxLegId=o.telnyx_leg_id),o.client_state&&(y.clientState=o.client_state),o.dialogParams&&o.dialogParams.custom_headers&&o.dialogParams.custom_headers.length&&(y.customHeaders=o.dialogParams.custom_headers);const S=new Ve(n,y);return S.nodeId=this.nodeId,S},u=new Gu,p=new m_;switch(s){case nt.Ping:this.session.execute(p);break;case nt.Punt:n.disconnect();break;case nt.Invite:{const w=d();w.playRingtone(),w.setState(X.Ringing),w.direction=xe.Inbound,this._ack(i,s);break}case nt.Attach:{const w=d();this.session.autoRecoverCalls?w.answer():w.setState(X.Recovering),w.handleMessage(t);break}case nt.Event:case"webrtc.event":if(!a)return void B.error("Verto received an unknown event:",o);const g=n.relayProtocol,_=a.split(".")[0];n._existsSubscription(g,a)?J(g,o,a):a===n.sessionid?this._handleSessionEvent(o.eventData):n._existsSubscription(g,_)?J(g,o,_):n.calls.hasOwnProperty(a)?n.calls[a].handleMessage(t):J(V.Notification,o,n.uuid);break;case nt.Info:o.type=ae.generic,J(V.Notification,o,n.uuid);break;case nt.ClientReady:this.session.execute(u);break;default:{const w=Dr(t);if(w){switch(w){case Rt.REGISTER:case Rt.REGED:n.connection.previousGatewayState!==Rt.REGED&&n.connection.previousGatewayState!==Rt.REGISTER&&(zt.retriedRegister=0,o.type=ae.vertoClientReady,J(V.Ready,o,n.uuid));break;case Rt.UNREGED:case Rt.NOREG:if(zt.retriedRegister+=1,zt.retriedRegister===5){zt.retriedRegister=0,J(V.Error,{error:new od("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 Rt.FAILED:case Rt.FAIL_WAIT:if(n.connection.previousGatewayState!==Rt.FAILED&&n.connection.previousGatewayState!==Rt.FAIL_WAIT){if(!this.session.hasAutoReconnect()){zt.retriedConnect=0,J(V.Error,{error:new od("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:n.sessionid},n.uuid);break}if(zt.retriedConnect+=1,zt.retriedConnect===5){zt.retriedConnect=0,J(V.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:B.warn("GatewayState message unknown method:",t)}break}B.debug("Verto message unknown method:",t);break}}}_retrieveCallId(t,n){const i=Object.keys(this.session.calls);if(t.action!=="bootObj")return i.find(s=>this.session.calls[s].channels.includes(n));{const s=t.data.find(o=>i.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(t){return G(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:d,role:u,callID:p}=t;switch(s){case"conference-liveArray-join":{const g=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},_={nodeId:this.nodeId,channels:[o],handler:({data:b})=>{const y=p||this._retrieveCallId(b,o);if(y&&n.calls.hasOwnProperty(y)){const S=n.calls[y];S._addChannel(o),S.extension=r,S.handleConferenceUpdate(b,t).then(C=>{C==="INVALID_PACKET"&&g()})}}},w=yield n.vertoSubscribe(_).catch(b=>{B.error("liveArray subscription error:",b)});ji(w,o)&&g();break}case"conference-liveArray-part":{let g=null;if(o&&n._existsSubscription(i,o)){const{callId:w=null}=n.subscriptions[i][o];if(g=n.calls[w]||null,w!==null){const b={type:ae.conferenceUpdate,action:At.Leave,conferenceName:r,participantId:Number(d),role:u};J(V.Notification,b,w,!1)||J(V.Notification,b,n.uuid),g===null&&dn(V.Notification,null,w)}}const _=[o,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:_}).then(({unsubscribedChannels:w=[]})=>{g&&(g.channels=g.channels.filter(b=>!w.includes(b)))}).catch(w=>{B.error("liveArray unsubscribe error:",w)});break}}})}_handleSessionEvent(t){switch(t.contentType){case"layout-info":case"layer-info":nd(this.session,t);break;case"logo-info":{const n={type:ae.conferenceUpdate,action:At.LogoInfo,logo:t.logoURL};J(V.Notification,n,this.session.uuid);break}}}}zt.retriedConnect=0,zt.retriedRegister=0;class g_ extends Dt{constructor(t){super(),this.method="anonymous_login";const{target_type:n,target_id:i,target_version_id:s,userVariables:o,sessionId:r,reconnection:a}=t,l={target_type:n,target_id:i,userVariables:o,reconnection:a,"User-Agent":{sdkVersion:jr,data:navigator.userAgent}};r&&(l.sessid=r),s&&(l.target_version_id=s),this.buildRequest({method:this.method,params:l})}}class v_ extends p_{constructor(t){super(t),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>G(this,void 0,void 0,function*(){this._idle=!1;const{login:n,password:i,passwd:s,login_token:o,userVariables:r,autoReconnect:a=!0}=this.options,l=new Xv(n,i||s,o,this.sessionid,r,!!Nr()),c=yield this.execute(l).catch(this._handleLoginError);c&&(this._autoReconnect=a,this.sessionid=c.sessid)}),this.handleAnonymousLoginOnSocketOpen=()=>G(this,void 0,void 0,function*(){this._idle=!1;const{anonymous_login:n}=this.options,i=new g_({target_id:n.target_id,target_type:n.target_type,target_version_id:n.target_version_id,sessionId:this.sessionid,userVariables:this.options.userVariables,reconnection:!!Nr()}),s=yield this.execute(i).catch(this._handleLoginError);s&&(this.sessionid=s.sessid)}),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&this.calls[i].hangup({},!0)})})}validateOptions(){return Lr(this.options)||Oi(this.options)}newCall(t){if(!this.validateCallOptions(t))throw new Error("Verto.newCall() error: destinationNumber is required.");console.time(Iu);const n=new Ve(this,t);return n.invite(),n}broadcast(t){return this.vertoBroadcast(t)}subscribe(t){return this.vertoSubscribe(t)}unsubscribe(t){return this.vertoUnsubscribe(t)}validateCallOptions(t){return!!Oi(this.options)||!!t.destinationNumber}_onSocketOpen(){return G(this,void 0,void 0,function*(){return Lr(this.options)?this.handleLoginOnSocketOpen():Oi(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(t){new zt(this).handleMessage(t)}}class __ extends v_{constructor(t){super(t),console.log(`SDK version: ${td}`)}newCall(t){return super.newCall(t)}static webRTCInfo(){return Kv()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:vt.full},{browserName:"Firefox",features:["audio"],supported:vt.partial},{browserName:"Safari",supported:vt.not_supported},{browserName:"Edge",supported:vt.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:vt.not_supported},{browserName:"Firefox",supported:vt.not_supported},{browserName:"Safari",features:["video","audio"],supported:vt.full},{browserName:"Edge",supported:vt.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:vt.full},{browserName:"Firefox",features:["audio"],supported:vt.partial},{browserName:"Safari",supported:vt.not_supported},{browserName:"Edge",supported:vt.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:vt.full},{browserName:"Firefox",features:["audio"],supported:vt.partial},{browserName:"Safari",features:["video","audio"],supported:vt.full},{browserName:"Edge",features:["audio"],supported:vt.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:vt.full},{browserName:"Firefox",features:["audio"],supported:vt.partial},{browserName:"Safari",supported:vt.not_supported},{browserName:"Edge",features:["audio"],supported:vt.partial}]}]}}function y_(e){if(!e||typeof e!="object")return!1;const t=e;return t.method==="ai_conversation"&&typeof t.params=="object"}function b_(e){if(!e||typeof e!="object")return!1;const t=e;return t.params.type!=="response.text.delta"?!1:!!t.params.delta}function w_(e){if(!e||typeof e!="object")return!1;const t=e;return t.params.type!=="conversation.item.created"?!1:!!t.params.item.content}function x_(e){return b_(e)?{id:e.params.item_id,role:"assistant",content:e.params.delta,timestamp:new Date}:null}function S_(e){return!w_(e)||e.params.item.role!=="user"||e.params.item.status!=="completed"?null:{id:e.params.item.id,role:e.params.item.role,content:e.params.item.content.map(t=>t.transcript).join(" "),timestamp:new Date}}function C_(e){const[t,n]=ee([]),[,i]=Zc();return Kt(()=>{if(!e)return;const s=o=>{if(y_(o))switch(o.params.type){case"response.text.delta":{const r=x_(o);r&&n(a=>[...a,r]),i("waiting");return}case"conversation.item.created":{const r=S_(o);r&&(i("thinking"),n(a=>[...a,r]));return}}};return e.on(V.SocketMessage,s),()=>{e.off(V.SocketMessage,s)}},[e,i]),t}const k_=({call:e,client:t})=>{const n=Ne(),[i,s]=ee(n.default_state),o=()=>s("expanded"),r=()=>s("collapsed"),a=C_(t);switch(i){case"collapsed":return A(Eu,{onExpand:o,call:e,client:t});case"expanded":return A(Rv,{transcript:a,onCollapse:r,call:e});default:return A(Eu,{onExpand:o,call:e,client:t})}},Ur=()=>A(Bn.div,{layoutId:Ci,className:"bg-[#FEFDF5] text-black dark:bg-black gap-3 dark:text-white w-[240px] max-w-full rounded-4xl p-4 text-center flex items-center justify-center flex-col shadow-lg shadow-[#38383878]",children:A("div",{className:"rounded-full animate-spin",children:A(pv,{})})}),T_=({call:e,client:t})=>{switch(e==null?void 0:e.state){case"new":case"trying":case"requesting":return A(Ur,{});case"done":case"purged":case"destroy":return null;case"active":return A(k_,{client:t,call:e});default:return A(Ur,{})}},E_=(e,t,n)=>{const[i,s]=ee(null);return Kt(()=>{if(!e)return;const o=new __({env:t||"production",anonymous_login:{target_id:e,target_type:"ai_assistant",target_version_id:n}});s(o)},[e,t,n]),i},A_=(e,{onReady:t,onNotification:n,onError:i,onSocketMessage:s})=>(Kt(()=>{if(e)return e.connect().then().catch(console.error),e.on(V.Ready,t),e.on(V.Notification,n),e.on(V.Error,i),e.on(V.SocketMessage,s),()=>{e.off(V.Ready,t),e.off(V.Notification,n),e.off(V.Error,i),e.off(V.SocketMessage,s),e.disconnect()}},[e]),null),R_=({className:e})=>A("svg",{className:e,width:"236",height:"211",viewBox:"0 0 236 211",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[A("g",{clipPath:"url(#:R5lfm:)",children:[A("path",{d:"M231.927 194.514C235.881 187.393 237.006 179.067 235.083 171.168C234.531 168.984 233.769 166.858 232.806 164.819C232.502 164.15 232.156 163.501 231.771 162.874L200.418 104.252H168.341L201.143 165.69C202.172 167.475 202.714 169.496 202.714 171.552C202.714 173.608 202.172 175.628 201.143 177.414C200.139 179.082 198.715 180.464 197.01 181.424C195.305 182.385 193.378 182.89 191.416 182.892H154.009C153.595 188.612 151.801 194.15 148.776 199.041C145.751 203.931 141.584 208.033 136.625 211H205.385C209.975 210.698 214.443 209.405 218.475 207.211C224.164 204.438 228.859 200.007 231.927 194.514Z",fill:"currentColor"}),A("path",{d:"M56.0698 65.9049H88.1473L104.134 36.466C105.487 33.9253 107.515 31.7984 109.999 30.3146C112.484 28.8309 115.331 28.0467 118.233 28.0467C121.135 28.0467 123.982 28.8309 126.466 30.3146C128.951 31.7984 130.979 33.9253 132.331 36.466L147.853 65.9049H179.93L157.166 23.3081C153.391 16.2702 147.751 10.3822 140.851 6.27586C133.951 2.16956 126.052 0 118 0C109.948 0 102.049 2.16956 95.1487 6.27586C88.2488 10.3822 82.6089 16.2702 78.8345 23.3081L56.0698 65.9049Z",fill:"currentColor"}),A("path",{d:"M81.9387 99.1324C82.275 93.4362 83.9987 87.9051 86.9627 83.0107C89.9266 78.1164 94.0429 74.0041 98.9604 71.0247H36.875V99.1324H81.9387Z",fill:"currentColor"}),A("path",{d:"M87.0591 101.18V177.977H101.649C104.692 177.944 107.64 176.924 110.041 175.075C112.443 173.226 114.165 170.648 114.946 167.738C115.26 166.621 115.416 165.467 115.411 164.308V118.229C115.425 113.227 117.432 108.432 120.997 104.885C124.561 101.338 129.396 99.3264 134.451 99.286H199.382V71.0247H117.481C109.408 71.0382 101.67 74.2213 95.9663 79.8751C90.2626 85.5289 87.0591 93.1914 87.0591 101.18Z",fill:"currentColor"}),A("path",{d:"M3.1927 164.819C2.23008 166.858 1.46775 168.984 0.916237 171.168C-1.00574 179.084 0.119328 187.425 4.07225 194.565C7.14854 200.039 11.8422 204.452 17.5241 207.211C21.5555 209.405 26.0233 210.698 30.6138 211H117.999C126.232 211 134.128 207.764 139.949 202.003C145.771 196.242 149.042 188.428 149.042 180.281V104.201H134.245C130.607 104.294 127.148 105.782 124.6 108.352C122.051 110.922 120.611 114.372 120.586 117.973V164.051C120.572 169.053 118.555 173.845 114.976 177.377C111.397 180.909 106.549 182.892 101.495 182.892H44.8417C42.8798 182.89 40.9521 182.385 39.2471 181.424C37.5421 180.464 36.1182 179.082 35.1149 177.414C34.0855 175.619 33.5443 173.59 33.5443 171.526C33.5443 169.462 34.0855 167.434 35.1149 165.638L67.9167 104.201H35.5806L4.22746 162.823C3.86529 163.539 3.50313 164.154 3.1927 164.819Z",fill:"currentColor"})]}),A("defs",{children:A("clipPath",{id:":R5lfm:",children:A("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function I_(){const e=Ne();return e.logo_icon_url?A("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:A("img",{src:e.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):A(R_,{className:"w-8 h-8 mr-2"})}const P_=({client:e,versionId:t})=>{const n=Ne(),i=()=>{var a;if(!e){console.error("Client is not initialized.");return}const s=(a=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:a.codecs,o=s==null?void 0:s.find(l=>l.mimeType.toLowerCase().includes("opus")),r=t?[{name:"X-AI-Assistant-Version-ID",value:t}]:void 0;e.newCall({destinationNumber:"xxx",preferred_codecs:[o],customHeaders:r})};return A(Bn.button,{layoutId:Ci,onClick:i,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer dark:bg-black dark:text-white ",children:[A(I_,{}),n.start_call_text]})},M_='@layer components;/*! tailwindcss v4.1.11 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-font-weight:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-400:oklch(70.4% .191 22.216);--color-green-400:oklch(79.2% .209 151.711);--color-black:#000;--color-white:#fff;--spacing:.25rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-xl:1.25rem;--text-xl--line-height:calc(1.75/1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--font-weight-medium:500;--font-weight-semibold:600;--radius-md:.375rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--radius-4xl:2rem;--animate-spin:spin 1s linear infinite;--blur-xs:4px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing)*0)}.top-0{top:calc(var(--spacing)*0)}.right-0{right:calc(var(--spacing)*0)}.bottom-0{bottom:calc(var(--spacing)*0)}.left-0{left:calc(var(--spacing)*0)}.z-10{z-index:10}.z-\\[9999\\]{z-index:9999}.mt-2{margin-top:calc(var(--spacing)*2)}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.ml-4{margin-left:calc(var(--spacing)*4)}.ml-auto{margin-left:auto}.flex{display:flex}.hidden{display:none}.inline-flex{display:inline-flex}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-8{height:calc(var(--spacing)*8)}.h-\\[72px\\]{height:72px}.h-\\[144px\\]{height:144px}.h-\\[300px\\]{height:300px}.h-full{height:100%}.min-h-\\[180px\\]{min-height:180px}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-8{width:calc(var(--spacing)*8)}.w-\\[200px\\]{width:200px}.w-\\[240px\\]{width:240px}.w-\\[250px\\]{width:250px}.w-\\[344px\\]{width:344px}.w-full{width:100%}.max-w-full{max-width:100%}.flex-1{flex:1}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing)*1)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-\\[\\#3D3D46\\]>:not(:last-child)){border-color:#3d3d46}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-3xl{border-radius:var(--radius-3xl)}.rounded-4xl{border-radius:var(--radius-4xl)}.rounded-full{border-radius:3.40282e38px}.rounded-md{border-radius:var(--radius-md)}.rounded-t-3xl{border-top-left-radius:var(--radius-3xl);border-top-right-radius:var(--radius-3xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-solid{--tw-border-style:solid;border-style:solid}.border-\\[\\#969696\\]{border-color:#969696}.bg-\\[\\#E6E3D3\\]{background-color:#e6e3d3}.bg-\\[\\#F36666\\]{background-color:#f36666}.bg-\\[\\#FEFDF5\\]{background-color:#fefdf5}.bg-\\[\\#FEFDF599\\]{background-color:#fefdf599}.object-cover{object-fit:cover}.object-center{object-position:center}.p-2{padding:calc(var(--spacing)*2)}.p-4{padding:calc(var(--spacing)*4)}.px-2\\.5{padding-inline:calc(var(--spacing)*2.5)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-2{padding-block:calc(var(--spacing)*2)}.py-3{padding-block:calc(var(--spacing)*3)}.text-center{text-align:center}.text-left{text-align:left}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-\\[\\#969696\\]{color:#969696}.text-black{color:var(--color-black)}.text-green-400{color:var(--color-green-400)}.text-red-400{color:var(--color-red-400)}.text-white{color:var(--color-white)}.underline{text-decoration-line:underline}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[\\#38383878\\]{--tw-shadow-color:#38383878}@supports (color:color-mix(in lab,red,red)){.shadow-\\[\\#38383878\\]{--tw-shadow-color:color-mix(in oklab,#38383878 var(--tw-shadow-alpha),transparent)}}.backdrop-blur-xs{--tw-backdrop-blur:blur(var(--blur-xs));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}@media (min-width:40rem){.sm\\:h-\\[386px\\]{height:386px}.sm\\:w-\\[400px\\]{width:400px}.sm\\:rounded-3xl{border-radius:var(--radius-3xl)}}@media (min-width:48rem){.md\\:right-10{right:calc(var(--spacing)*10)}.md\\:bottom-10{bottom:calc(var(--spacing)*10)}}.dark\\:border-\\[\\#3D3D46\\]:where(.dark,.dark *){border-color:#3d3d46}.dark\\:bg-\\[\\#3C3C3C\\]:where(.dark,.dark *){background-color:#3c3c3c}.dark\\:bg-\\[\\#38383C96\\]:where(.dark,.dark *){background-color:#38383c96}.dark\\:bg-\\[\\#38383C\\]:where(.dark,.dark *){background-color:#38383c}.dark\\:bg-\\[\\#222227\\]:where(.dark,.dark *){background-color:#222227}.dark\\:bg-\\[\\#750000\\]:where(.dark,.dark *){background-color:#750000}.dark\\:bg-black:where(.dark,.dark *){background-color:var(--color-black)}.dark\\:text-black:where(.dark,.dark *){color:var(--color-black)}.dark\\:text-white:where(.dark,.dark *){color:var(--color-white)}}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:0 0}::-webkit-scrollbar-thumb{background-color:#888;background-clip:content-box;border:2px solid #0000;border-radius:4px}::-webkit-scrollbar-thumb:hover{background-color:#555}html{scrollbar-width:thin;scrollbar-color:#888 transparent}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}',L_=({children:e})=>A("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:A("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:e})}),D_={duration:.1,ease:"circOut"},O_=({children:e,position:t="fixed"})=>{const n=Ne(),s=(t??n.position??"fixed")==="fixed"?A(L_,{children:e}):e;return A("div",{className:Oe(n.theme==="dark"&&"dark"),children:A(Wf,{transition:D_,children:[A("style",{children:M_}),s]})})},N_=e=>A(Bn.div,{layoutId:Ci,className:"bg-[#FEFDF5] text-black dark:bg-black rounded-2xl p-4 flex flex-col items-center justify-center dark:text-white w-[344px] max-w-full",children:[A(hv,{className:"w-8 h-8 text-red-400"}),A("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),A("ul",{className:"gap-4 ml-4 text-sm list-disc",children:[A("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),A("li",{children:["Make sure that the"," ",A("a",{href:`https://portal.telnyx.com/#/ai/assistants/edit/${e.agentId}?tab=telephony`,className:"inline-flex items-center gap-1 font-medium text-green-400 underline",target:"_blank",rel:"noopener noreferrer",children:["Support Unauthenticated Web Calls"," ",A(yv,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function V_(e){return Object.keys(e).length===0}function ad(e){var n;if(typeof e!="object"||e===null)return!1;const t=e;return t.method==="ai_conversation"&&((n=t.params)==null?void 0:n.type)==="widget_settings"&&typeof t.params.widget_settings=="object"}const F_=({client:e})=>{const t=Bg();return es(()=>{if(!e)return;const n=i=>{if(ad(i)&&!V_(i.params.widget_settings)){const s=i.params.widget_settings;t(s)}};return e.on(V.SocketMessage,n),()=>{e.off(V.SocketMessage,n)}},[e,t]),null};function B_({"agent-id":e,environment:t,position:n="fixed","version-id":i}){const s=E_(e,t,i),[o,r]=ee(null),[a,l]=ee(!1),[c,d]=ee(!1),[u,p]=ee(!1);return A_(s,{onReady:()=>l(!1),onNotification:S=>{var C;if(((C=S.call)==null?void 0:C.state)==="destroy")return r(null);r(S)},onError:()=>{l(!1),d(!0)},onSocketMessage:S=>{ad(S)&&p(!0)}}),A(Qt,{children:[A(O_,{position:n,children:e?c?A(N_,{agentId:e}):a?A(Ur,{}):o!=null&&o.call?A(T_,{call:o.call,client:s}):u?A(P_,{versionId:i,client:s}):null:A("div",{children:"Please provide an assistant ID."})}),A(F_,{client:s})]})}Cd(B_,"telnyx-ai-agent",Sg,{shadow:!0})})();
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@telnyx/ai-agent-widget",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.16.0",
|
|
5
5
|
"description": "A widget for Telnyx AI Agent",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"author": "Telnyx",
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
23
|
"@fontsource/inter": "^5.2.6",
|
|
24
|
-
"@telnyx/webrtc": "^2.22.
|
|
24
|
+
"@telnyx/webrtc": "^2.22.15",
|
|
25
25
|
"audiomotion-analyzer": "^4.5.1",
|
|
26
26
|
"clsx": "^2.1.1",
|
|
27
27
|
"jotai": "^2.12.5",
|